Filesystems, block storage, and networking¶
VFS and filesystem servers¶
VFS owns mount namespaces, lookup, authorization, and delegation of filesystem handles. A successful open can return a revocable, rights-limited handle to the filesystem server. That server enforces the handle’s lifetime, mount and zone policy, and file semantics. Direct calls through the delegated handle avoid a VFS round trip on each supported operation. Share page-cache objects where practical and define memory, cache ownership, coherency, and reclamation across VM and storage.
Port FreeBSD UFS, Linux FAT, and Linux ext4 into contrib/ to replace the
initial filesystem implementations, then port OpenZFS, XFS, Btrfs, and bcachefs as
native filesystem servers. Reuse on-disk format code and subsystem algorithms
where practical. Adapt integration to native VFS, VM, block I/O,
synchronization, allocation, and event interfaces. Filesystem-specific
support code is suitable for these ports. LinuxKPI serves drivers.
Preserve correctness, access control, durability, recovery, and
interoperability. Complex ports can bring up read-only access before
enabling verified writes. Coordinate OpenZFS ARC reclamation with VM
and preserve OpenZFS licensing and dependencies.
The default native disk mounts the small ext4 server read-only. The image
builder uses e2fsprogs to create a clean filesystem with 4 KiB blocks,
256-byte Linux inodes, extents, and typed directory records. It writes
guest ownership and permissions into the inodes. The reader checks
partition bounds, uses Linux’s extent validation and lookup, zero-fills
sparse file ranges, and uses the Linux directory checker for linear
directory records. The checker validates record alignment, the minimum
length, and inode numbers before VFS receives metadata. Each
nonempty child node must start at the logical block named by its parent
index. The server accepts the feature
set generated by the image builder. It also mounts clean Linux-formatted
ext4 volumes read-only with 1 KiB, 2 KiB, or 4 KiB blocks and power-of-two
inode records from 128 bytes through one filesystem block. This includes
ordinary journal-enabled volumes that need no replay, flex block groups, and
64-byte group descriptors on volumes within the 32-bit block-address limit.
The Linux CRC32C routines check superblocks,
group descriptors, inode bitmaps, inodes, external extent nodes, and both
leaf and index directory blocks. The reader rejects unrecognized feature bits
and volumes requiring orphan recovery. When the partition capability permits
writes, mount can replay a version-2 internal JBD2 journal. Recovery supports
logs with no checksums or with CRC32C v2 or v3, including committed revokes
and escaped data blocks. It validates the committed prefix and replay targets
before writing home blocks, then flushes the home blocks, empty journal,
and ext4 recovery marker in that order. The journal must fit the service’s
128 data extent, 256 index block, and 8192 revoke entry bounds. External
journals, fast commits, and orphan recovery require further support.
With a write capability and a supported, empty internal journal, the service
commits permission, owner, flag, and timestamp updates on existing inodes.
Mode and ownership changes require an inode without extended attributes.
Timestamp changes require an inode large enough for its timestamp extensions
and preserve existing attributes. Each update uses one synchronous JBD2
transaction for the inode-table block and regenerates the inode checksum. The
service flushes the journal records and the filesystem recovery flag before
activating the log. It clears the recovery flag only after checkpointing the
inode-table block and deactivating the log. A write failure disables further
mutation until remount. On the same volumes a file overwrite can update
initialized data blocks within the current length. The server checks the
whole range against the Linux allocation bitmap and excludes journal blocks,
backup superblocks, and block-group metadata. The file must have no extended
attributes or set-ID bits. fsync() flushes these data writes. A supported
journaled volume permits growth in the inode’s extent root or at the
right edge of an external extent tree. If the final extent cannot be
extended and its leaf is full, Linux’s extent split adds a right-hand
branch at the nearest index with a free entry. When the root also fills,
the server moves its entries into a newly allocated node and increases
the tree depth. The server journals the changed extent nodes together
with the inode and allocation records. A growth operation
prefers a contiguous run. If no group can
satisfy the request, it can reserve multiple runs and journal all
affected groups together. Up to 30 changed groups can participate,
within the extent leaf and transaction limits. The server verifies
each group’s block bitmap and the metadata ranges of neighboring
groups that share its flex group. For a checksummed group
whose block bitmap has not been initialized, the server reserves the
group’s metadata and bitmap padding and checks the resulting free-block
count. The first allocation journals the bitmap and clears the
uninitialized flag in the same transaction. Growth flushes initialized
blocks and zero-filled gaps before increasing the inode’s length. A write
starting at or beyond EOF on a journaled file with a hole at its old end
keeps the gap before the first written block sparse. Shrink commits the
new length and releases blocks in one JBD2 transaction, including when a
file spans block groups. The Linux extent removal walk prunes external
extent nodes and stages modified nodes with their checksums. The
transaction includes the inode, changed extent nodes, allocation bitmaps
and descriptor blocks, and superblock. Truncation is bounded by the
staging capacity of 30 changed groups and the current JBD2
transaction’s descriptor and log limits. During replay, a committed, checksummed superblock
image can validate and repair a partial superblock checkpoint. The
filesystem service calls Linux’s ext4 record insertion and deletion
routines on resident directory blocks. The service supplies the validated
slot, checksum boundary, and transaction. Deletion merges space with the
preceding record or keeps an unused first record. Linear directories
support hard-link creation into a free slot, removal, and file or
symlink rename. Rename over a closed file or symbolic link journals
both directory changes together with the victim’s link count or
reclamation. A linear directory whose extents
fit in its inode can grow to make room for a
creation, hard link, or rename. Growth initializes and flushes an empty
leaf, including Linux’s checksum tail, before a transaction publishes its
mapping. The namespace update follows in its own transaction. Creation
supports regular files, symbolic links, and directories. Short link
targets are inline. A longer native target occupies a block journaled
with its inode and directory entry. The service
starts the inode search in the parent’s group and can select any group
with a free inode. It commits the name, inode, inode bitmap, and both
free-inode counts in one JBD2 transaction. The first allocation in a
lazy group initializes its inode bitmap and, when needed, its block
bitmap. Directory creation also commits the new directory block, its
allocation, and the parent’s link count in that transaction. The new
directory’s inode and data can reside in different groups. Replay can
locate the reserved journal inode during an
interrupted checkpoint even if the inode bitmap and its descriptor belong
to different points in the transaction. The journal inode and descriptor
still undergo their own checksum checks. Last-link removal and removal
of an empty linear directory commit the
directory entry, inode and block release, and updated summaries in
one transaction. Linux’s inode allocator updates the inode bitmap and
group counts. Removal requires an inode without extended attributes
and reclaims both data and external extent blocks. It can release
storage in up to 28
block groups, subject to the JBD2 transaction limits. In indexed
directories, removal updates the leaf and preserves existing hash
boundaries. Empty directory removal can also reclaim an index. For indexed creation, hard links, and rename,
the service uses Linux’s filename hash and index search
to select an existing leaf. This supports the traditional legacy,
half-MD4, and TEA hashes with explicit signedness, and up to one
interior index level. A full leaf can split within the supported extent
growth limits. A full root can acquire an interior node. When a
full interior node splits, the root must have room for another entry.
The service flushes the new blocks, then journals the changed leaf,
index blocks, directory extent, and allocation records together.
The namespace update follows in its own transaction.
The system.writable-root boot option gives the root service a writer
capability. On a writable ext4 image, applications can overwrite an
allocated range, extend a regular file, and synchronize data with
fsync(). Growth uses the standard allocation bitmap, free-block
counts, and inline extents on the single-group root image. A write beyond
the end allocates and zero-fills the intervening range. The writer
requires allocated extents for any portion of the write inside the old
file. The service
flushes a dirty superblock before an allocation, flushes file data
before publishing the larger inode, and marks the volume clean after
the metadata is durable. An interrupted update requires an offline
filesystem check. File and directory creation allocate a standard ext4
inode and publish it in an existing free slot of a linear directory.
A new directory starts with one block holding its dot entries. When create,
rename, or link needs another slot, the writer extends the directory with a
valid empty block before publishing the entry. Growth uses the writer’s
single-group allocator and inline extent tree. The parent
requires write and search permission, and the mode follows the caller’s
umask. An exclusive open fails when the name exists. Append selects the
live end of file for each write. A write open with truncation or
ftruncate(fd, 0) can shrink a regular file to zero. The
non-journaled writer handles inode-resident extents, and the journaled
writer also handles external extent trees. truncate() follows the pathname and resizes the opened file through
the same interface as ftruncate(). The new inode becomes durable before
the blocks are returned to the allocation bitmap. fdatasync() uses the
same backing-provider flush as fsync(). Synchronizing an open directory
flushes its filesystem’s metadata.
Open descriptors read through the live inode and see the current end of
file. The service checks both requested access bits on a read-write
open. Both chmod() and fchmod() support the nine ordinary
permission bits and require the file owner or root. Root can change the
owner or group with chown() or fchown(). An ordinary owner can
change the group to one of the caller’s effective or supplementary
groups. Ownership changes clear set-user-ID and set-group-ID bits.
On writable ext4, futimens() and utimensat() update access and
modification times at nanosecond precision. utimensat() accepts
the same directory-relative paths as openat(). AT_SYMLINK_NOFOLLOW
updates a link inode. Explicit or mixed timestamp updates require ownership
or root authority. Write access also permits setting both times to the
current time. VFS derives that sample and the inode change time from the
supervisor’s boot clock reference. Real updates require a firmware wall-clock
reference. The filesystem writes the three timestamps together and flushes
the inode. A pair of UTIME_OMIT values performs no mutation.
The file owner or root can set the user flags nodump, uchg, and
uappnd on writable ext4. The server stores these flags in standard
ext4 inode bits. It checks live immutable and append-only flags even for
descriptors opened before a flag change. Immutable files and directories
reject changes. Append-only files accept only append writes, and
append-only directories allow creation while protecting existing entries.
Unlink removes regular files and symbolic links. Directory removal
requires an empty directory.
On writable ext4, link() and linkat() add a name to a regular
file or symbolic link. Root or the inode owner can create the link in
a searchable, writable directory on the same volume. link() follows
a terminal source symlink. linkat() follows it when the caller passes
AT_SYMLINK_FOLLOW. Ext4 flushes the new link count before adding the
directory entry and releases storage when the last name is removed.
Removal returns EBUSY while a filesystem handle refers to the inode.
The server makes the name unreachable before releasing the inode and
its blocks. Rename moves regular files and symbolic links between
directories on the same volume and can atomically replace a closed
file or link for filesystem clients. The source inode stays valid
for existing handles. Renames across mounts report EXDEV.
Interrupted directory updates require an offline check. The ESP uses a
separate read-only capability. The ESP server caches
a bounded set of FAT sectors for cluster-chain traversal. A positioned
read near the end of a boot bundle reuses the allocation entries for
both chain cursors while retaining cycle and bounds checks.
The image installs a sticky /tmp directory with mode 01777. Unlink and
rename in that directory require ownership of the affected entry or
directory, or an effective UID of zero. Temporary files and
directories use private modes and exclusive name creation. Account
administration uses the recoverable publication described in
Native processes, loading, and the C runtime.
The ext4 server keeps a per-mount read-through cache of 1024 sectors.
Cached reads avoid block service calls for repeated file and metadata
access. Writes invalidate the affected sector before submission.
Mounting a volume discards all entries.
Stage 2.5 replaces the in-tree ext4 server implementation with a port of Linux ext4 behind the native filesystem service interface.
See also
getfsstat() returns the mounted filesystems and their allocation
counts. statfs() selects the mount for a path. Ext4 and UFS report
block and inode counts from their superblocks. The FAT server counts free
clusters in the active allocation table once per read-only mount. It follows
Linux’s default policy for the potentially stale FAT32 FSInfo count.
The boot mount inventory reports the root, ESP, and any configured FAT data volume. /boot/core
uses the same ESP allocation counts as /boot/efi.
statvfs() and fstatvfs() expose these counts through the POSIX
structure. Its filesystem ID is the native mount ID. pathconf()
and fpathconf() report the pathname and component bounds after
checking the requested path or descriptor.
fdopendir() turns an open directory descriptor into a stream and
transfers ownership to closedir() after successful allocation.
Ext4 and UFS serve readlink() through the same permission-checked
path lookup as lstat(). It returns bytes from the terminal symbolic
link, including inline inode data, up to the caller’s buffer capacity.
On writable ext4, symlink() creates a new inode after checking write
and search permission on the parent and confirming that the name is free.
The link preserves the target spelling, including relative and dangling
targets. Ext4 uses inline storage for short targets and a data block
for longer targets, and publishes the directory entry after the inode
and any allocated block are durable.
VFS asks the filesystem to report the first symlink in a path segment
after checking search permission. It interprets absolute targets in the
mount namespace and relative targets from the link’s parent. VFS
reapplies mount policy after expansion, resolves links before consuming
a following .., and rejects a lookup after 40 expansions. Operations
that act on the link entry, including lstat(), readlink(), and
unlink(), leave the terminal link intact during lookup.
open(O_NOFOLLOW) follows links in the parent path and returns ELOOP
when the final name is a symbolic link. An exclusive create at an existing
link returns EEXIST.
openat(), fstatat(), mkdirat(), unlinkat(), renameat(),
readlinkat(), symlinkat(), utimensat(), fchmodat(),
fchownat(), and chflagsat() resolve a relative path
from a live directory descriptor or the current directory with AT_FDCWD.
Absolute paths start at the namespace root. VFS records the directory’s
resolved name when it opens the filesystem handle. The current filesystems
either mount read-only or preserve that name while the handle is open.
Directory removal returns EBUSY while the directory is open, and the ext4
writer supports rename for files and links. Any implementation that moves
open directories must also maintain their namespace references.
The filesystem checks search permission in the starting directory and
subsequent directories. VFS supplies the already reached prefix on its
private filesystem request so a later permission change above the directory
does not revoke the handle. A relative symlink retains that starting point.
An absolute target restarts at the namespace root with normal pathname
permissions. .. checks search permission on the directory it leaves
and crosses mount roots through VFS.
faccessat() checks the real IDs by default and the effective IDs when
called with AT_EACCESS. VFS uses one supervisor-provided identity and
supplementary group snapshot for traversal and the final permission check.
access() and eaccess() use the same path. The result describes
access at the time of the check and grants no handle or authority.
fchmodat(), fchownat(), and chflagsat() use the caller’s effective
identity and follow the terminal symlink by default. With
AT_SYMLINK_NOFOLLOW they address the link itself. The ext4 writer can
change a link’s owner and group. Changing a link’s mode or flags returns
ENOTSUP.
realpath() uses the FreeBSD libc fallback to resolve each component,
including a symbolic link followed by ... It uses native lookup
permissions, preserves absolute and relative link targets, and rejects
cycles after 40 link expansions.
-
int getfsstat(struct statfs *mounts, long bytes, int flags)¶
Return current allocation counts for each native mount.
-
int statfs(const char *path, struct statfs *information)¶
Return mount properties for the filesystem containing a path.
-
int statvfs(const char *path, struct statvfs *result)¶
Return the allocation counts and flags of the filesystem containing a path.
The UFS reader uses FreeBSD’s FFS superblock, inode, and directory declarations
and the standalone reader’s direct and indirect block mapping. The System
server supplies bounded, byte-order-aware 512-byte sector reads and checks
geometry and directory record bounds. It reads clean UFS1 volumes with the
4.4BSD inode format and clean UFS2 volumes in either byte order. UFS1 inode
lookup accounts for staggered cylinder groups and indirect reads use 32-bit
addresses. Unallocated regular-file blocks read as zero. UFS2 accepts the
standard primary superblock and the older placement produced by some versions
of makefs. The FreeBSD check-hash code verifies superblocks and allocated
UFS2 inodes when their metadata checksum flags are enabled. Validation uses
the original on-disk bytes. A volume flagged for an offline check is rejected.
The writable-root option also allows overwrites and fsync() on clean UFS1
and UFS2 volumes. Before writing, UFS checks the entire requested range
against the inode’s block mapping and cylinder group allocation bitmaps.
It verifies cylinder group check-hashes when enabled and excludes the
superblocks, inode tables, and cylinder summary storage. Partial sector
writes preserve the surrounding bytes. chmod(), chown(),
chflags(), and timestamp updates check the inode allocation bitmap and
flush the containing sector. UFS2 regenerates the inode check-hash when
enabled. Flag changes preserve system flags, and ownership changes clear
set-user-ID and set-group-ID bits. UFS2 can extend a dense regular file
within its direct pointers. Growth uses the already allocated tail,
extends a partial block into adjacent free fragments through FreeBSD’s
ffs_fragextend, or allocates free blocks from one or more cylinder groups. The server
first looks for a single group with enough space. If space is spread
across groups, it validates every reservation before changing the disk
and publishes all the allocation summaries before updating the inode.
When the existing partial block cannot accommodate the requested growth,
the server copies its data into a new allocation before publishing the
new inode block pointers. It returns the old fragments after the updated
inode is durable. For a single partial allocation, the port uses FreeBSD’s
ffs_alloccg and ffs_mapsearch policy to select the smallest
suitable fragment run from the cylinder group’s rotor. A final partial
block reserves only the fragments it needs. FreeBSD’s FFS cluster
accounting updates the free-cluster map and
run counts on the decoded cylinder group. The sector adapter writes them
in the volume’s byte order and accepts the little-endian run counts left
by older big-endian UFS2 image builders on groups without check-hashes.
Gaps read as zeros. The server flushes the new data before marking the
primary superblock dirty, then persists the cylinder group, free-space
summaries, and inode before marking it clean. An interruption during
allocation requires an offline check. UFS2 can also extend regular
files through single, double, and triple indirect blocks. The loader’s
block-path calculation selects the indirect entries. New data and index
blocks use full allocations. A distant write or truncate leaves intervening
blocks sparse and promotes an old direct tail fragment to a full block
before extending past it. The server flushes the new detached blocks and
persists their reservations before publishing an indirect pointer.
Writes inside a sparse UFS2 file can allocate missing direct and indirect
blocks without changing the file’s length. Bytes outside the written
range in a newly allocated block read as zeros.
Clean UFS1 and UFS2 volumes can
rename files and symlinks within and between directories that already
have room. The service checks the inode and directory allocations and
updates both names in one write when they occupy the same sector. For a
cross-sector rename, it marks the volume dirty and persists the new name
before removing the old one, so an interrupted rename leaves a reachable
name and requires an offline check. On UFS2, regular files, directories,
and symbolic links can be created. UFS2 can also move a directory to a
new name. A cross-parent move follows FreeBSD’s ancestry check and changes
the directory’s .. entry and both parent link counts while the
volume is marked dirty. Replacing an existing directory remains unsupported.
Short link targets are inline.
Longer native targets occupy a data fragment. UFS2 flushes a file’s
new link count before adding a hard link to it. If a directory has no room
for creation, the server can append an empty directory sector through
the direct block writer. The server
uses FreeBSD’s inode rotor to select a free inode, starting in the
parent’s cylinder group. It initializes any newly reached inode-table
blocks and flushes the inode, bitmap, and summaries before publishing
the name. The filesystem remains dirty until the name is durable. UFS2
also shrinks files and removes names for regular files and links.
Before releasing fragments, it flushes either the shortened inode or the
last-name removal and retired inode. The FreeBSD ffs_indirtrunc walk
detaches discarded indirect entries before returning the data and index
blocks to the cylinder group. A retained indirect data block keeps its
full allocation even when the new end of file falls within it. The
FreeBSD fragment accounting converts a fully freed fragment run into
a free block and updates the cluster summary. Last-link removal
returns the inode to its cylinder group. Directory creation and empty
directory removal also account for the directory in its cylinder
group and update the parent’s link count.
UFS2 rename can replace a file or symbolic link, including one with
other hard links. It updates the existing destination record using
FFS’s ufs_dirrewrite order, retires the source name, and then
decrements or reclaims the victim inode. A victim’s open last link
returns EBUSY. When a destination directory has no room for a new
name, UFS2 can append a directory sector within its direct pointers.
Allocation into holes inside an existing file and moving directories
require further work. Volumes with active
snapshots, journaled soft updates, GEOM journaling, or ACLs require further
write support.
The root supervisor delegates a partition-only endpoint and a read-only
sector buffer to the selected root filesystem service. A separate VFS server mediates access
to that root. It has a trusted session for the supervisor and a separate
badged, read-only session with a private shared page for each application
slot. Init temporarily uses the first application slot. The supervisor
closes remaining file handles and clears the page when its task exits.
Applications can read files and list directories on the native root
when inode permissions allow reading the object and searching
its containing directories. The root filesystem
selects the owner, group, or other permission bits using the UID and GID
bound to the badged VFS session. An owner match takes precedence over group
or other bits. The supervisor’s trusted execute request checks directory
search and file execute permissions using the launching user’s identity.
The filesystem rejects traversal components, and VFS limits handles to the
session that opened them. Each boot session supports four simultaneous open
handles.
Closing one makes it stale and leaves the other handles usable. Reusing
a slot assigns a new handle. The backend file tables have room for both
application sessions and the supervisor to reach their limits on the same
volume.
VFS enumerates the boot mounts through getfsstat(). The answer
identifies the active filesystem server and its write and execution
policy. The root and ESP are available on a native disk boot. The
additional view at /boot/core aliases the ESP and shares its mount
identity. A configured FAT data volume at /mnt has its own mount
identity. Effective UID 0 can attach or detach the configured FAT volume
at runtime. VFS rejects changes while the mount point is a working directory
or an open directory, or while the mounted volume has live file or mapping
references. Detach flushes the provider before removing the mount. The
configuration survives VFS replacement during the current boot.
VFS routes /boot/efi/ and /boot/core/ paths to the msdosfs server.
The server publishes root:wheel ownership, mode 0755 for
directories, and mode 0400 for regular files. Users can enumerate
and traverse directories. Opening a regular file requires effective UID
0. GPT selects the native root by partition
GUID. It distinguishes root and EFI block requests by the sender’s
capability badge and exports separate sector
buffers. The msdosfs service uses Linux FAT’s boot parameter block reader,
allocation-entry decoder, and VFAT slot decoder. The geometry adapter
validates 512-byte to 4 KiB logical sectors and normalizes their offsets to
the storage service’s 512-byte sectors. The reader checks cluster chains.
The directory slot decoder validates VFAT sequence numbers
and alias checksums. Directory iteration returns valid long names as UTF-8
and falls back to the short alias when a long-name sequence is damaged. Linux’s
CP437 tables convert short aliases to UTF-8 and apply the directory entry’s
lowercase flags. Lookup accepts long names and short aliases with ASCII case
folding. MS-DOS
filesystem support reads FAT12, FAT16, and FAT32 volumes with execution
disabled. With an explicit writer capability, the filesystem service can
overwrite, extend, and truncate existing files. Root can create files and
directories with native UTF-8 names. The writer emits the corresponding
VFAT slots and a unique short alias, extends cluster-backed directories when
needed, and flushes the initialized contents of new directories before
publishing their names. The FAT12 and FAT16 fixed roots have finite directory
slots. Newly created entries initially use FAT’s minimum representable date.
On the writable mount, futimens() and utimensat() update the short
entry’s access date and modification time. The service uses the Linux FAT
UTC encoding, preserves omitted fields, and bounds dates to the DOS
calendar. Access times have day resolution, and modification times
have two-second resolution.
Root can remove closed files and empty directories. Removal validates the
short entry’s VFAT slot sequence, retires the short name and associated
long-name slots, and flushes the directory before returning the chain to
the allocation table. Renaming a closed file or directory preserves its
cluster chain and updates the parent link of a moved directory. The service
checks for directory cycles and permits replacement of closed files and
empty directories. It flushes removal of the old name before publishing
the new name. After an interruption, an offline check can reclaim a chain
whose new directory entry had yet to be published. The service
rejects removal of read-only entries and nonempty directories. It updates the
active FAT and mirrors changes when the BPB enables mirroring. Growth uses
Linux’s FAT chain allocator, which walks from the previous allocation and
wraps at the end of the data-cluster range, excluding reserved terminal
cluster numbers. The Linux port also releases detached chains and counts
free entries from the active table. The server initializes the clusters and
flushes the data before publishing the directory entry. A shrink
commits the shorter entry before returning detached clusters to the table.
Chain changes mark the boot record dirty and invalidate stale FSInfo hints.
A failed chain change leaves the volume marked dirty for an offline check.
The boot supervisor delegates a read-only capability for the ESP.
The system.writable-fat-data boot option starts another FAT server
and mounts its data volume at /mnt with execution disabled. The GPT
server selects the unique Microsoft Basic Data partition named
System FAT data on the boot disk and checks that it differs from
the root partition. The data server receives its own partition-bounded
writer capability and shared buffers. Enabling this option requires a
writable disk and a mountable FAT data volume. The service publishes
directories with mode 0755 and restricts regular-file access and
mutations to effective UID 0. VFS keeps file identity, cached pages,
and record locks distinct across volumes. Storage supervision replaces
the data server alongside the other boot filesystem services.
The base system installs FreeBSD’s newfs_msdos for formatting regular
FAT12, FAT16, and FAT32 image files. With -C it creates a new file.
With -N it reports geometry without modifying the image. Formatting an
existing image requires an explicit pathname. The implementation checks the
specified image bounds and flushes the completed filesystem. FreeBSD’s
fsck_msdosfs checks regular images with -n and repairs them with
-y. On a repaired image it flushes filesystem changes before clearing
the dirty bit, with the primary boot record written last. Raw-device
formatting and repair, along with runtime selection of arbitrary data
partitions and mount points, require additional storage interfaces.
The GPT service can delegate a separate writer capability for the selected volume. It bounds sector writes to that volume and forwards flushes only when the underlying block device supports them. The ESP and ordinary read capabilities remain read-only. The current root filesystem uses a read capability by default. A filesystem that takes a writer capability must order data and metadata writes before flushing them.
Bootstrap handle reads use explicit offsets and exact lengths within a page.
The application descriptor interface assigns the lowest available descriptor
starting at 3, tracks an independent offset for every open, and shortens a
read at EOF. pread() supplies a byte offset per request and leaves the
open file description’s offset unchanged, including across shared-page
transfers. dup() creates a second descriptor for the same open file
description and therefore shares its offset. dup2() replaces an exact
descriptor in one VFS request and leaves it intact if closing its backing
handle fails. fcntl() supports retrieving and setting descriptor flags
and duplicating at or above a specified descriptor number. Close-on-exec
and close-on-fork flags are per descriptor and can be set at open or
duplication time. The initial posix_spawn() inherits descriptors at
the same numbers and skips entries with either flag. The last close
releases the backing handle.
The session limits distinct opens and descriptor numbers
independently. VFS forwards data operations to
its filesystem server and copies back from that server’s buffer. Mount
namespaces and direct delegation are later steps.
fstat() resolves a descriptor to its backing handle in the same VFS
session. The filesystem supplies metadata without advancing the file
offset. VFS assigns distinct device IDs to the native root and ESP. Inode-based root filesystems
returns inode metadata and allocation in 512-byte blocks. The ESP uses
FAT directory-entry positions for file IDs, synthetic UID and GID 0,
and mode 0444. The ESP image writer and filesystem service use UTC
for FAT timestamps. The service uses modification time for change time.
FAT allocated space is rounded to
whole clusters.
stat() checks the session’s path access and resolves regular files
and directories without opening a descriptor. The native root requires search
permission on each ancestor and exposes metadata for both readable and
unreadable final objects. A trailing slash requires a directory. FAT directory
sizes come from the validated allocation chain.
VFS keeps the canonical directory path in the process’s file session on
the read-only root. open(), stat(), opendir(), and unlink()
resolve relative paths from that directory. VFS checks search permission
on the directory being traversed before consuming . or .. and
holds traversal at the root. It snapshots the input from the shared page
and applies mount access policy throughout resolution. chdir() requires
search permission on the destination, even when directory listing is
denied. The working directory changes only after a successful lookup.
After a successful rename on the native root, VFS updates the paths of
working directories and open directory descriptors under the moved
name. It checks that the resulting paths fit before asking the
filesystem to rename the entry.
Native root directory descriptors use a directory cookie stored in the VFS open
file description. The filesystem validates each record and returns a
bounded batch of inode numbers, types, and names. VFS advances the cookie
only after a successful reply. Applications access these records through
opendir(), readdir(), and closedir(). Directory enumeration
currently covers the native root. The ESP supports directory metadata.
-
enum class native_file_request : uint64_t¶
Values:
-
enumerator open¶
-
enumerator read¶
-
enumerator close¶
-
enumerator fd_open¶
-
enumerator fd_read¶
-
enumerator fd_close¶
-
enumerator fd_seek¶
-
enumerator fd_dup¶
-
enumerator fd_dup_to¶
-
enumerator fd_get_flags¶
-
enumerator fd_set_flags¶
-
enumerator fd_stat¶
-
enumerator path_stat¶
-
enumerator fd_pread¶
-
enumerator fd_readdir¶
-
enumerator socket_pair¶
-
enumerator fd_write¶
-
enumerator fd_wait¶
-
enumerator event_queue¶
-
enumerator event_change¶
-
enumerator event_poll¶
-
enumerator fd_sendmsg¶
-
enumerator fd_recvmsg¶
-
enumerator udp_socket¶
-
enumerator udp_bind¶
-
enumerator udp_send¶
-
enumerator udp_receive¶
-
enumerator local_socket¶
-
enumerator local_bind¶
-
enumerator local_listen¶
-
enumerator local_connect¶
-
enumerator local_accept¶
-
enumerator path_unlink¶
-
enumerator tcp_socket¶
-
enumerator tcp_connect¶
-
enumerator tcp_get_stack¶
-
enumerator tcp_set_stack¶
-
enumerator sysctl_name¶
-
enumerator path_chdir¶
-
enumerator cwd_get¶
-
enumerator pipe¶
-
enumerator fd_get_status¶
-
enumerator fd_set_status¶
-
enumerator fd_sync¶
Flush the filesystem behind the descriptor in word 1.
-
enumerator path_chmod¶
Path length and mode in words 1 and 2, nofollow in word 3.
-
enumerator path_mkdir¶
Path length and mode in words 1 and 2.
-
enumerator path_rmdir¶
Path length in word 1.
-
enumerator path_rename¶
Path lengths in words 1 and 2, with the second path at native_file_path_limit.
-
enumerator fd_truncate¶
Resize the descriptor in word 1 to the signed length in word 2.
-
enumerator fd_lock¶
Descriptor and advisory lock flags in words 1 and 2.
-
enumerator fd_chmod¶
Descriptor and mode in words 1 and 2.
-
enumerator path_chown¶
Path length in word 1, packed UID and GID in word 2, nofollow in word 3.
-
enumerator fd_chown¶
-
enumerator mounts¶
Return mount records in the shared page and the count in word 1.
-
enumerator path_chflags¶
Path length and file flags in words 1 and 2, nofollow in word 3.
-
enumerator fd_chflags¶
-
enumerator socket_shutdown¶
Shut down socket directions in word 2 for the descriptor in word 1.
-
enumerator tcp_get_option¶
Read an integer TCP option named in word 2 for the descriptor in word 1.
-
enumerator tcp_set_option¶
Set the TCP option named in word 2 to the integer in word 3.
-
enumerator path_readlink¶
Path length and output capacity in words 1 and 2. Returns link bytes and length.
-
enumerator fd_get_record_lock¶
Packed descriptor, lock type, and seek base, then signed offset and length.
-
enumerator fd_set_record_lock¶
-
enumerator path_symlink¶
Destination and target lengths in words 1 and 2.
-
enumerator path_set_times¶
Path length or descriptor in word 1, no-follow flag in word 2.
-
enumerator fd_set_times¶
-
enumerator fd_wait_record_lock¶
Like fd_set_record_lock, but defer the reply while a lock conflicts.
-
enumerator path_link¶
Source and destination lengths, with a source symlink-follow flag in word 3.
-
enumerator path_access¶
Path length, permission bits, and access flags in words 1 through 3.
-
enumerator mount_fat¶
Attach or detach the configured FAT data volume at the supplied path.
-
enumerator unmount_fat¶
-
enumerator open¶
-
struct native_file_info_t¶
Filesystem metadata. The allocation count uses 512-byte blocks.
Block I/O and encryption¶
A FreeBSD GEOM-inspired userspace stack represents devices and transforms as providers and consumers. Compose device, partition, volume, encryption, mirroring, and striping layers. Export a capability-scoped block provider to a filesystem or swap service. Define graph ownership, alignment, attach and detach, hot-unplug, cleanup, and flush and discard propagation across every layer. Set queue limits and cancellation and backpressure rules. Use an asynchronous submission and completion path, batched requests, shared buffers, and scatter-gather DMA where supported. Devices must have authority for every buffer they can access. See Platforms, device drivers, and virtualization.
The writable GPT endpoint forwards explicitly requested discard ranges to VirtIO block devices that support them. GPT checks that the entire range belongs to the delegated partition and translates its offset. The device service checks capacity, the negotiated maximum sector count, and starting alignment before submission. The limits query reports the provider’s maximum, alignment, and first aligned sector in partition-relative units. Read-only and ESP capabilities cannot discard. Filesystem allocation and swap release do not currently submit discard requests. Reads of a discarded range have unspecified contents. See the VirtIO 1.2 specification.
Encryption at rest is selected independently per disk, partition, or logical volume. Different volumes can use different reviewed algorithms and modes simultaneously, with a secure default and versioned metadata recording the selected suite. Use existing cryptographic implementations. Separate key management, unlocking, recovery, and delegation from the block data path. Include encrypted root unlock and optional ephemeral encryption for swap in the design.
See also
FreeBSD GEOM, FreeBSD GELI, BitLocker, and FileVault.
Networking and event delivery¶
The VirtIO Ethernet service runs in a driver process with
one split receive queue and one split transmit queue. It exposes the
interface MAC and transfers Ethernet frames through a shared page that
is separate from the device’s pinned DMA page. On the native-disk
configuration, a PCI IOMMU restricts the device to its pinned page.
The RISC-V QEMU boot
fixture checks transmit and receive by exchanging ARP frames with the
isolated QEMU user network before and after replacing the driver.
The resident IP service consumes this interface in a separate address
space. The supervisor restarts it with the Ethernet driver when either
loses readiness. The QEMU configuration uses static addresses and
answers ARP, IPv6 neighbor solicitation, and IPv4 and IPv6 ICMP echo.
The echo handlers build FreeBSD’s ip_icmp.c and icmp6.c
for checksum and type validation. Echo requests can carry validated
IPv4 options or IPv6 extension headers. Replies use fresh IP headers.
Its Internet checksum is adapted from FreeBSD’s
stand/libsa/in_cksum.c at revision
4ba6fd2ef5a739b6fdc955890d27e07ae8794fb3 under BSD-3-Clause.
The IPv4 and IPv6 mbuf routines in in_cksum.c and
in6_cksum.c carry an odd byte across mbuf boundaries. IPv6 uses
the same pseudo-header sum for contiguous input and chains, and
Neighbor Discovery checksums its receive and transmit messages through
the mbuf interface.
The QEMU test uses an isolated Ethernet peer to verify both protocols
and their checksums.
FreeBSD IPv4, IPv6, TCP, and their selected dependencies come from one
pinned vendor/freebsd tree. Keep upstream-relative paths under
contrib/freebsd and apply System changes there after merging the
vendor revision. Xmake compiles the adapted checksum, SipHash, SACK,
and time-filter sources as C at their upstream-relative paths. The
userspace transport and compatibility code lives under
contrib/freebsd/system/inet. The service entry point, build targets,
and tests live under packages/servers/network/inet.
TCP and UDP input dispatch through the native C build of FreeBSD’s
ip_input.c and ip6_input.c. The IPv4 path validates the full
header checksum and walks options to find the transport payload. The
IPv6 path walks Hop-by-Hop and Destination Options, inactive Routing
headers, and atomic fragments in wire order. The transport checksum
uses the resulting upper-layer offset and length. The System header
views contain the wire layouts and options used by these paths.
Active source routes are rejected. For local unicast input, System builds
the reassembly paths in ip_reass.c and frag6.c. Four fragment
queues share a 60-second expiration policy and admit datagrams that fit
the Ethernet MTU after reassembly. The queues accept out-of-order
fragments, discard overlapping datagrams, preserve congestion marks,
and clear when the service resets. The IPv6 path discards fragmented
Neighbor Discovery messages in accordance with
RFC 6980. See
RFC 1122 and
RFC 8200.
Native applications can open UDP sockets in either address family.
VFS owns the descriptor and its lifetime. The IP service queues received
datagrams in FIFO order with the FreeBSD socket-buffer record operations.
Each bound port can hold four datagrams, subject to a service-wide limit
of eight records. Each record carries the source address and payload in
an owned mbuf. Closing the socket releases its queued records.
The native C build of FreeBSD’s sys/netinet/udp_usrreq.c and
sys/netinet6/udp6_usrreq.c validates ports, lengths, and checksums
before passing a payload view to the native socket service. The UDP
header exposes the wire layout, input routines, and a shared transmit
routine that builds and checksums the UDP header and payload. The native
input permits trailing IPv4 padding and an omitted IPv4 UDP checksum.
IPv6 UDP requires an exact length and a checksum.
Native UDP handles own FreeBSD sockets and protocol control blocks.
An application can bind a socket to the interface address or the
wildcard for its family. Port zero selects an ephemeral port in the
49152–65535 range. A
socket can also acquire its local port on the first connect or send.
A connected socket uses the selected peer for destination-less sends
and receives packets from that peer. An application can use
read(), write(), or sendto() and recvfrom() on
these sockets. Each receive consumes one datagram, including empty
packets, and truncates it to the caller’s buffer. A connected socket
can shut down either direction. Read shutdown clears the receive
queue and reports EOF. Write shutdown rejects fresh sends.
The IP service caches validated on-link addresses and uses ARP or
IPv6 neighbor solicitation for unresolved destinations. The upstream
protocols queue output for Ethernet transmission in a bounded service
buffer. The service retries neighbor discovery for one second before
dropping an unresolved packet. Off-link sends return
EHOSTUNREACH. Blocking reads, transmit backpressure, and
EVFILT_READ and EVFILT_WRITE use deferred waits. The VFS and
IP services exchange data on a page separate from the client and
device buffers. If the network service restarts, clients recreate
their sockets. Replacing VFS drops the sockets it owned.
Native TCP stream sockets support active connections and listeners in
both address families. Each native handle in inet owns a FreeBSD
socket and its protocol control block. Socket creation attaches the
selected protocol. Bind, connect, listen, accept, shutdown, and close
invoke that protocol through the FreeBSD socket interface. A completed
connection stays on the listener’s queue until accepted. Closing a
listener releases its queued connections. The application transfer
buffer is separate from the service’s mbufs, which hold queued send and
receive data. The upstream TCP core owns sequence generation, receive
reassembly, and send and retransmission state.
The dispatcher uses the System monotonic counter for FreeBSD callouts and for the deadlines maintained by TCP. The HPTS adapter dispatches the upstream module’s work under the PCB lock. It schedules loss recovery, pacing, and other per-connection work on a single callout queue. The Ethernet input poll provides an upper bound of one millisecond on the event loop’s wait. The IPC receive timeout can expire earlier for pending TCP work.
The IP service starts with rack as the default for new TCP sockets.
/sbin/init applies name=value settings from /etc/sysctl.conf
after networking is available and before the shell starts. To change
the running default, an administrator can use
/sbin/sysctl net.inet.tcp.functions_default=bbr.
The native disk build copies packages/boot/native-root/etc/sysctl.conf
to /etc/sysctl.conf on the root filesystem. Edit that input before
building to change the boot default in the generated image.
net.inet.tcp.functions_available lists the registered choices.
sysctlbyname() and the sysctl utility carry requests through the
application’s VFS capability. VFS checks the supervisor-provided
effective UID before writing, and the IP service owns the values.
The native interface currently exposes these two string controls.
An invalid write or a combined read and write with insufficient
output space leaves the default unchanged. A runtime change applies
to newly created sockets and lasts for the life of the IP service.
Applications can override the default with setsockopt(),
FreeBSD’s TCP_FUNCTION_BLK and tcp_function_set at level
IPPROTO_TCP.
The accepted socket inherits its listener’s choice. Getting the option
returns the selected name and its live control-block count. The
requested stack’s FreeBSD handoff hook checks whether it can take
over. A successful switch keeps the connection’s protocol state and
queued bytes. A switch during the handshake returns EAGAIN.
BBR requires SACK for an established handoff with the default
tunables and rejects connections that negotiated ECN. RACK permits
established handoff without SACK.
On RACK sockets, the integer options TCP_RACK_PACE_ALWAYS,
TCP_RACK_PACE_MAX_SEG, and TCP_RACK_PACE_RATE_CA use the
upstream socket-option handlers. Applications can use them to
enable rate-based pacing, cap segments per paced transmission, and
set the congestion-avoidance rate in bytes per second.
The RACK and BBR implementations are the upstream C function blocks registered by their module entry points. RACK uses the FreeBSD send map, loss timers, and congestion window. BBR uses the upstream delivery measurements and pacing state machine. When negotiated, timestamps protect established sockets against stale segments. The System profile drops established segments that omit the negotiated timestamp.
VFS defers accept, connect, and descriptor waits after checking the current
socket state. The IP service posts a nonblocking, coalescing badge to VFS
when a read, write, connect, or accept readiness level changes. Stock
socket-buffer and listener upcalls mark readiness work inside
inet. The dispatcher sends the badge after the callback returns
and the socket lock is released. VFS then rechecks the affected
waiters and completes only those whose conditions hold. VFS registers a waiter and checks readiness in the same dispatch
pass, so a concurrent notification remains pending until VFS can receive
it. Closing the descriptor cancels its waits. The supervisor detaches a
failed IP service from VFS before binding its replacement. The new
generation invalidates the old sockets and their waits. After VFS
replacement, the supervisor delegates a notify capability to the new VFS
endpoint, and the IP service resets the socket state of the old session.
shutdown(2) on an established TCP socket closes either direction
independently. A write shutdown rejects new writes and sends FIN
after queued stream bytes. A read shutdown discards queued bytes
and reports EOF to the caller.
The QEMU test accepts an IPv4 connection, initiates an IPv6 connection,
and exchanges stream data across an IPv6 write shutdown. The
native-disk/tcp and native-disk/tcp-bbr cases select
RACK or BBR on the IPv4 listener and accepted socket. The IPv6
client starts with BBR and switches to RACK. Both exercise
bidirectional policy handoff with queued data, rejection of a handoff
without SACK, and duplicate SACK reporting,
sequence and timestamp wrap, SACK across a gap and inside a segment,
stale or missing timestamps, handshake retransmission, multiple
segments in flight, loss recovery after SACK, a tail loss probe, a
zero receive window, and peer close. See
RFC 2018
for selective acknowledgement and
RFC 8985 for time-based recovery.
The native-disk/tcp case enables fixed-rate RACK pacing on the
accepted socket and checks the time between packets from a single
write. The native-disk/tcp-ecn case verifies ECN marking and feedback
and exercises the ECN handoff restriction.
The virtual interface uses fixed on-link addresses. The pinned
sys/netinet/tcp_stacks tree contains the RACK and BBR modules.
The compatibility layer supplies their FreeBSD socket and PCB
interfaces, runtime initialization, and tunables. The stock runtime
uses service-owned thread and CPU records.
Run xmake build inet-freebsd-tcp to build the upstream RACK and BBR
modules, their shared support files, and the FreeBSD TCP core. The same
archive builds the IPv4 and IPv6 input, output, FIB lookup, ICMP,
fragment reassembly, PCB, and UDP sources. The TCP core includes
NewReno, ECN, the SACK scoreboard, SYN cache, timers, and TIME_WAIT.
The archive selects process-owned CPU and thread records for the single
dispatcher.
Its interface adapter creates the Ethernet interface and the connected
IPv4 and IPv6 routes for FIB zero. The routes retain stable interface
addresses and reference-counted nexthops. The stock FIB lookup uses the
address and prefix configured by the service. The
inet-freebsd-route/connected-prefixes fixture checks both families,
off-link rejection, reverse-path checks, and delivery through the
attached interface’s transmit callback.
The interface ingress adapter copies IP packets out of the driver’s
transfer buffer into owned mbufs and queues them by IP family. The
dispatcher limits queued packets and runs protocol input under the
network epoch. The fixture checks queue overflow, ordering, and packet
ownership after the transfer buffer is overwritten.
The upstream IPv4 and UDP dispatch tables also run in the
inet-freebsd-udp/ipv4-datagrams RISC-V fixture. It exercises creation,
bind, connect, send, receive readiness, and close through the upstream
UDP callbacks. It verifies that a bad checksum sends no notification,
a valid datagram reaches the bound socket, and a closed port can be
bound again. The archive uses FreeBSD’s diagnostic formatter with an
optional service sink and provides rate counters for ICMP. The stock
IPv4 profile serves a single attached network. This profile omits
multicast membership, raw sockets, source routing, packet-filter hooks,
redirect-based route changes, and socket timestamps. When Limine
supplies boot entropy, inet dispatches incoming traffic through
the upstream IP, TCP, and UDP input routines after Ethernet handling.
The IPv6 port uses FreeBSD source-address selection, scope
validation, routing, and ICMPv6 error generation. Output uses the
upstream transport checksums and IP routing before the service
resolves the Ethernet neighbor and submits the frame through the
driver IPC endpoint. Closing the native handle or
resetting the VFS connection releases the upstream socket. The existing
receive and transmit readiness notifications use the stock socket’s
first queued record. The inet-freebsd-udp6/ipv6-datagrams fixture
checks zero-length IPv6 receive readiness, source addresses, and the
ICMPv6 port-unreachable response after close. The native-disk UDP test
checks that both families use the upstream backend during its
Ethernet exchange. It exercises IPv4 fragment reassembly, UDP
readiness and truncation, implicit port allocation, and IPv6
connected I/O, peer filtering, and shutdown. It verifies that a
closed descriptor’s kqueue registration cannot observe the next
socket assigned that descriptor number. The bootstrap profile
uses its earlier transport adapters
when the boot handoff supplies no entropy. The stock TCP registry starts
FreeBSD’s TCP core, NewReno, and the RACK and BBR module entry points.
The inet-freebsd-tcp-registry/registered-stacks fixture creates IPv4
and IPv6 TCP sockets, selects a registered function block through
TCP_FUNCTION_BLK, checks that an unknown name preserves the selected
block, and closes the sockets. The stock TCP startup sets bounded
reassembly, SYN-cache, and host-cache tables for the single dispatcher.
Its private build generates FreeBSD machine and driver interface headers
from the pinned tree. The archive retains the FreeBSD control-block
layout and initializes the protocols it exposes to native descriptors.
The archive provides nonblocking
UMA zones for module control blocks and send maps. The zones share a
bounded arena, enforce item limits, honor the FreeBSD object callbacks,
and return empty slabs to the arena. Allocation can fail without
blocking the dispatcher. The stock transport shares the service’s
monotonic clock and callout queue, and its counters use independent
words allocated from a service-owned zone. Its typed heap uses the
same arena and keeps FreeBSD heap symbols separate from libc. Initialize
the service clock before running FreeBSD protocol setup. Keep these
dependencies inside the IP service and retain the existing VFS and
Ethernet IPC boundaries. The upstream modules’ HPTS entry points use
absolute callouts in the TCP control blocks. They dispatch queued input
or call the transport’s output function under its PCB lock. The
inet-freebsd-hpts/dispatch fixture exercises that adapter and the
userspace PCB locks in RISC-V QEMU user mode. The locks support shared
readers, write ownership, recursion where requested, and a nonblocking
upgrade from a single read hold. Callouts can acquire and release the
adapted mutex and read/write locks. FreeBSD’s mutex, sx, and read-mostly
lock entry points also use the single dispatcher. They track ownership
and release state without parking the service. The network epoch implementation
tracks nested readers on the single dispatcher and runs reclamation
callbacks on the shared callout queue after the outermost reader exits.
The fixture also checks that a callback can queue work for a later
dispatch pass. The archive’s private sysctl tree supports dynamic
registration and context-based cleanup for imported modules. Its
socket-buffer adapter reserves bounded send and receive space
atomically, charges bytes and mbuf storage, and queues datagrams
with their sender address and ancillary records. Read and write
wakeups call the registered socket owner’s nonblocking callback
while holding the corresponding buffer lock. The callback can queue
readiness work for the dispatcher. The
inet-freebsd-runtime/socket-buffers-and-sysctls fixture exercises
the archive adapters in RISC-V QEMU user mode. It checks that the private
SYSINIT runner invokes static initializers in FreeBSD phase order and
calls a built-in module’s MOD_LOAD hook once. The socket adapter uses
a bounded, aligned allocation zone and calls the chosen protocol’s
attach and detach hooks. The listener promotes completed connections from
the pending queue and wakes its owner. Failed attachment releases socket
buffers and credentials. Closing a listener aborts the connections still
on its queues. The socket I/O adapter passes owned mbuf chains to protocol
send hooks. It copies received bytes through service-owned I/O vectors and
preserves datagram boundaries, sender addresses, peek, and truncation.
Protocol control blocks can use SMR allocation zones. Retired objects
remain readable until the dispatcher’s read section exits, and allocation
then reclaims them. The fixture exercises the socket lifetime and data
transfer paths with fixture protocols and checks delayed SMR reuse, lock
ownership, and packet tag lifetime. The
inet-freebsd-tcp-wire/passive-open-and-pacing fixture checks a
SYN-cache retransmission, connection promotion, receive delivery,
close, and paced RACK output on the service callout queue. It
advances a controlled clock and measures the interval between two
data packets emitted by a single write.
The inet-freebsd-pcb/socket-attachment fixture uses the stock PCB
allocator, bind and detach operations. It checks IPv4 and IPv6 binding,
reserved port denial, allocation failure, and release of credentials and
cached routes. Before protocol startup, the service takes a per-task seed
from the supervisor for the stock port and sequence-number generators.
Socket-option transfers operate on service-owned memory, pass transport
options to the protocol, and restrict the routing-table selector to FIB
zero.
The RISC-V kernel can allocate additional mapping and frame records
from the authorized physical memory pool. The complete FreeBSD
transport must still budget its executable, runtime storage, stack,
and shared mappings together.
The stock ingress copies Ethernet payloads into owned FreeBSD
mbuf chains before returning the driver’s shared frame. The IP service
provides bounded inline mbuf allocation, chain trimming, contiguous
header pullup, packet tags, and reference-counted external clusters.
The FreeBSD archive uses those same mbuf operations. Packet copies and
checksums share a range walker that handles offsets across chains and
propagates callback errors.
FreeBSD’s m_get(), m_gethdr(), m_getcl(), and m_free() use
the service pools. Prepending a packet header transfers its metadata and
tags to the new head. Packet tag copies own independent storage, and
the nonpersistent cleanup keeps the tags marked persistent.
The stock output paths can make a writable packet copy or extend an
exclusive mbuf chain. Extending across a gap initializes the gap to zero
and updates the packet header to match the bytes allocated.
Clones share owned cluster data and copy borrowed Ethernet data when it
must outlive dispatch. The layout and chain operations adapt FreeBSD’s
sys/sys/mbuf.h, sys/kern/uipc_mbuf.c, sys/kern/uipc_mbuf2.c,
and sys/kern/kern_mbuf.c at the same revision under BSD-3-Clause
and BSD-2-Clause. Unmapped page chains, hardware send tags, and the
remaining FreeBSD socket-buffer operations for asynchronous I/O remain
part of the full transport port.
Native applications can create connected Unix stream sockets with
socketpair(AF_UNIX, SOCK_STREAM, 0, fds). VFS owns the paired
descriptors and two bounded byte queues. Duplication shares an open file
description, and the last close on one side lets the peer drain buffered
bytes before seeing EOF. A write after peer closure returns EPIPE.
SOCK_NONBLOCK selects EAGAIN when an operation would block.
Blocking calls use a separate readiness reply, so neither side holds
the shared transfer page while waiting. Automatic signal delivery for
a broken pipe remains later work.
Unix stream sockets can also bind a name directly below /run.
VFS owns this volatile namespace and includes the socket owner’s
effective UID and GID in stat(). Connect and unlink require the
owner’s UID or an effective UID of zero. A listener queues up to four
connections. accept() can wait for a connection, and a read event on
the listener reports the pending count. Accepted streams share the
ordinary Unix stream I/O and descriptor-passing paths.
Unlinking a name leaves its listener and established streams live. Closing the listener closes any connections still in its queue and leaves a linked name until unlink. Replacing VFS clears the volatile namespace. Names support direct lookup. Directory enumeration of volatile entries and filesystem-backed socket nodes remain later work.
sendmsg() and recvmsg() pass one regular file descriptor per
control message with SCM_RIGHTS. The control record belongs to the
first byte of its message. VFS keeps the open file description alive
while the record is queued. A received descriptor shares its offset and
has independent descriptor flags. Reads that skip control data, truncated
control messages, and endpoint teardown release the queued reference.
A process can share a socket pair with a child through descriptor
inheritance. The endpoints and queued references survive the sender’s
descriptor close, and readiness wakes callers in either VFS session.
Each kqueue() descriptor holds a bounded set of registrations in its
VFS session. kevent() supports level-triggered reads on regular files,
read and write readiness on Unix stream sockets, and EVFILT_USER
triggers. It reports stream EOF and the available byte count. Closing
or replacing a watched descriptor removes its registrations. One-shot
events remove their registration upon delivery, and EV_CLEAR
resets user triggers. A wait can poll, block indefinitely, or expire at
a monotonic deadline. The client releases its transfer page before
waiting so another thread can trigger an event. Additional filters and
edge-triggered descriptor notifications remain later work.
Port FreeBSD netinet and netinet6 to native userspace networking
services. Use VirtIO for virtual network interfaces and add net80211
infrastructure as wireless support is needed. Provide sockets and Unix
domain sockets with descriptor passing. Adapt FreeBSD kqueue to native
descriptors and notifications with consistent readiness, lifetime,
wakeup, and cancellation rules across servers.
Support separate network stack instances or equivalent isolation for zones, with VNET and illumos Crossbow as references. Account for packet buffers and queues against the appropriate resource domains. Shared packet rings and buffer ownership transfer can handle a batch without a synchronous IPC per packet. Evaluate RSS and per-core queues, interrupt moderation, adaptive polling, and authorized direct access to queues. LionsOS and its seL4 Device Driver Framework provide implementation references for these data paths.
See also
Packet filtering¶
Port FreeBSD IPFW and PF from the same pinned FreeBSD tree as the IP
stack. Build the engines into the userspace inet service so packet
evaluation can use its existing mbufs and network event loop.
At most one engine filters a network stack instance. Keep engine state,
counters, and rules scoped to that instance. A switch between engines
discards the old engine’s connection state.
Run the selected engine on IPv4 and IPv6 ingress and egress, including traffic routed through the instance once IP forwarding is available. Preserve the selected engine’s ordering of filtering, state lookup, and address translation. Apply those hooks to loopback where included in the ruleset. Keep raw device and queue capabilities under device and zone policy so ordinary clients cannot route around the filters. Use the namespace and delegation rules in Resource domains and branded zones.
Port ipfw and pfctl, adapting their FreeBSD control paths to
native IPC. A capability scoped to a network instance grants inspection
or administration. Validate an entire update before publishing it and
leave the active rules untouched if validation fails. Apply the engine’s
state retention rules when replacing a ruleset. Send packet logs through
a bounded queue so an unavailable log consumer cannot stall forwarding.
Keep the last accepted policy available to the supervisor. When a
profile requires filtering, keep network traffic halted until the
configured rules are active, including after inet restarts.
Connection state lives in inet and starts empty after replacement.
Verify the forwarding and local socket paths in QEMU, including IPv4
NAT reply traffic, rejected updates, and loss of a service during active
filtering.
See also