github.com/alexfalkowski/go-linux/v2/mount provides filesystem configuration contexts, owned mount handles, and structured mount discovery through the modern Linux mount API. It requires Linux 7.0+ and the Go version in go.mod. The verification guide describes the required isolation environment, commands, and verified runners.
Good for preparing filesystems and mount restrictions before making them visible in an isolated mount namespace. runc sets up mounts as part of container isolation; this package supplies mount operations while the application owns isolation and cleanup.
Call mount.Open("tmpfs") to acquire a *mount.Config, then supply parameters with SetFlag("rw") or SetString("size", "1m"). Configuration, handle ownership, and attachment have separate lifetimes:
Open -> Config --Create, Mount--> detached Handle --Attach--> attached mount
| | |
Close Close Unmount
Close Config and Handle independently. Closing an attached handle does not unmount it.
SetString(key, "") passes an empty string; it is distinct from a flag with no value. Strings are not parsed as comma-separated option lists. Names, keys, values, filesystem support, and configuration phase transitions retain kernel validation. On Linux 7.0, fsconfig keys and string values are limited to 255 bytes excluding the terminating NUL; embedded NUL bytes fail with EINVAL.
SetBinary(key, value) passes a 1-byte to 1-MiB blob. Linux copies the bytes during the call, including embedded NULs. Keep the slice unchanged until the call returns. The receiving filesystem determines which parameters accept blobs.
SetPath(key, dir, path) passes a filename parameter. The filesystem decides how to resolve it. A nil dir supplies the current working directory, and an empty path with a nonnil file selects that file itself. For example, ext4 accepts its journal_path parameter as a path relative to an open directory or as an empty path with a path-only file for the journal device.
SetFile(key, file) supplies an open file as the parameter itself. For example, OverlayFS accepts a directory file for each lowerdir+ layer. Both setters borrow their file arguments during the call. Close them normally on either outcome. The filesystem can retain its own reference after the setter returns. Nil files in SetFile and empty paths with nil files in SetPath match os.ErrInvalid.
Create can reuse a filesystem instance; it does not promise a unique superblock. Mount never calls Create implicitly. A failed acquisition returns nil and leaves no newly acquired resource to close. A failed Mount leaves the existing Config caller-owned; a kernel failure can still change its phase. A failed setter or Create likewise leaves the existing Config open, but the kernel may make a failed context unusable for later configuration. There is no rollback or legacy mount backend.
See the configuration example. It is compiled by the normal harness and executed inside the namespace integration fixture when its prerequisites are available.
Use mount.Pick(dir, path, flags) to open a Config for an existing filesystem. The target must resolve to the root of a mount. Nil dir selects the current working directory. An empty path selects the supplied open file itself. The Config remains usable after closing the borrowed lookup file. Zero flags use the kernel lookup defaults. Combine mount.PickNoFollow and mount.PickNoAutomount to suppress final-component symlink following and automounting.
Set the pending parameters, then call config.Reconfigure(). For a mounted tmpfs, setting size changes its capacity. This updates the superblock shared by other mounts of the same filesystem, possibly across namespaces. Choose a filesystem you own and use Handle.SetAttributes for per-mount restrictions.
A Config that has acquired a Handle with Mount can also reconfigure that filesystem. After a successful reconfiguration the context can accept fresh parameters for another change. A kernel failure can leave partial changes and make the context unusable. The caller still closes the Config. The reconfiguration example resizes a private tmpfs.
Attributes supports ReadOnly, NoSUID, NoDev, and NoExec. Combine restrictions with |. Zero adds no restrictions. Existing filesystem and kernel policy still apply. SetAttributes(mount.AttributeChange{Set: ..., Clear: ...}) changes explicit masks on a detached or attached handle. Set and Clear must be disjoint and contain known bits. Kernel policy can forbid clearing restrictions. Use the dedicated operations below for atime, propagation, and ID mapping.
handle.SetAtime(mount.AtimeChange{Mode: mount.RelativeAtime, Directory: mount.NoDirectoryAtime}) selects relative access-time updates and disables updates on directories. Choose NoAtime to disable updates or StrictAtime to request traditional updates. Choose UpdateDirectoryAtime to clear the directory override so it follows the selected atime policy. Zero for either field keeps that part of the policy. These choices are independent.
handle.SetPropagation(mount.Private, mount.MountTree) selects propagation on the held mount. To change an existing mount root, call mount.SetPropagation(dir, path, mode, scope). A nil directory uses the current working directory and an empty path selects the supplied directory itself. The path form follows symlink and automount defaults and borrows the supplied directory. Both forms accept one of Shared, Slave, Private, or Unbindable. Linux determines peer and master relationships. A slave request on a mount without a master can leave it private.
MountOnly is the default scope for attribute operations and affects the named mount. Select MountTree to include child mounts. Invalid masks, modes, or scopes match os.ErrInvalid. Separate calls apply in order, and a later failure does not undo an earlier change. Observe the result through structured discovery when a sequence fails.
handle.Attach(dir, path) uses move_mount to attach or move the mount. A nil directory selects the current working directory; an absolute path uses ordinary absolute lookup. A nonnil directory is borrowed for the duration of the call, protected against concurrent Close. An empty path targets that directory itself and requires a nonnil directory. Closing the directory after attachment does not invalidate the mount. Target symlinks and automounts are not followed by move_mount; component traversal remains the caller’s responsibility. These operations do not offer confined path resolution.
The caller retains the handle after either attachment success or failure. An unattached tree is released when its last reference disappears. Attached mounts remain until explicitly unmounted or their namespace is destroyed. Use mount.Unmount(path, 0) for a normal unmount, which fails with EBUSY while references keep the mount busy. mount.Unmount(path, mount.Detach) disconnects the mount immediately and defers release until references disappear. Open files and handles remain caller-owned. Unknown flags match os.ErrInvalid; other errors preserve Linux errno. Unmount follows target symlinks and kernel propagation rules, so path and namespace policy remain with the caller. The attachment example shows explicit typed cleanup.
handle.Stat() returns standard file metadata for the mount root, including while detached. handle.Attributes() queries the current four supported restrictions; other kernel flags are omitted. These are snapshots and can change through other references.
mount.Clone(dir, path, flags) uses open_tree to acquire a detached copy. Zero flags clones one mount; mount.Recursive includes child mounts. The directory/nil/empty-path rules are the same as for Attach. Clone uses open_tree’s default symlink following and automount behavior. It borrows the directory on success and failure, and returns no new owner on failure. A successful clone survives closing the source directory and must be closed independently. Clones share filesystem contents while permitting independent mount attributes; they are not data snapshots. Attach the resulting Handle explicitly when a visible mount point is needed.
To present existing files with translated owners, clone the source mount and call handle.SetIDMap(user, mount.MountOnly) before attaching the clone. Supply a *namespace.Handle for a user namespace with configured UID and GID maps. Acquire it while the namespace still exists using the namespace API. The call borrows the handle. Close it independently on either outcome. Once applied, the mount retains its mapping and uses it for ownership and permission checks against the same backing files.
Linux requires a filesystem that supports ID-mapped mounts, such as tmpfs, and CAP_SYS_ADMIN over the filesystem and the selected user namespace. The mapping must come from a namespace other than the initial user namespace or the filesystem’s owning user namespace. Each selected mount must be detached and free of existing ID mappings and active writers. To map a cloned tree, include descendants at both steps with mount.Recursive and mount.MountTree. A nil or non-user namespace matches os.ErrInvalid. Kernel rejections preserve errno. To change the mapping exposed at a path, prepare another compatible detached mount and apply its mapping before attachment.
Run root setup in a dedicated child started with Go’s os/exec and a private mount namespace. Before attaching or switching roots, set private propagation with mount.SetPropagation(nil, "/", mount.Private, mount.MountTree). Attach the prepared tree at a mount point and make an empty directory such as old-root under it.
Call mount.PivotRoot(newRoot, putOld) with the mount point and the full path to the old-root directory as seen before the switch. The kernel changes the namespace’s root mount and moves the old tree to the selected directory. The current root must satisfy the kernel’s mount-point and propagation requirements, and the caller needs CAP_SYS_ADMIN in the user namespace that owns the mount namespace. Paths follow kernel symlink resolution. Failure leaves the existing root in place and returns an *os.LinkError containing both paths and the kernel errno.
After success, call os.Chdir("/") to leave any working directory still under the old root. The switch can affect processes and threads whose root or working directory referenced the previous root itself. Keep other work out of the child until setup finishes. Detach the old tree with mount.Unmount("/old-root", mount.Detach) and remove the empty directory. Existing open files and directory handles can still reference the old tree. If changing directories or detaching fails, treat the child as already on its new root. Standard Go child chroot configuration changes pathname lookup and does not move the root mount or provide old-root detachment. See the executable root activation example.
Use mount.List(mount.ListOptions{}) to start with a page of up to 128 IDs. Set Parent to a unique mount ID to list its descendants, excluding the named mount. Zero Parent lists the mounts reachable from the selected root. Set Order: mount.DecreasingID to reverse the default increasing order. Use the last returned ID as After with the same parent, namespace, and order until the page is empty. Limit can be set to 1 through 4096. The cursor still works if its mount has disappeared.
Use mount.Stat(id, mount.StatOptions{Mask: mask}) to look up a mount. For an existing *os.File, mount.StatFile(file, mask) observes the containing mount. Use handle.Info(mask) with a mount handle. Both calls borrow the reference for the duration of the query. Results hold no kernel reference and do not keep a mount alive. Linux can omit the mount point and namespace ID when an open file keeps an unmounted mount alive. On Linux 7.0, a freshly detached handle can return ENOENT before its first attachment. Handle.Stat() continues to return standard root-inode metadata.
Zero mask requests MaskMount, which supplies identity, parentage, attributes, and propagation. Check the returned Info.Mask before reading each requested group. Use MaskSupported to learn which field bits the kernel recognizes. A recognized field may be unavailable for an individual mount. Mount and parent IDs are unique for the running system. The separate LegacyID and LegacyParentID fields match the reusable IDs in procfs mountinfo. To obtain a unique ID at a path, use file.StatAt with file.MaskUniqueMountID, check the returned mask, and convert Metadata.MountID to mount.ID.
List and Stat default to the calling thread’s mount namespace. Set Namespace: mount.NamespaceSelector{Handle: ns} to borrow a mount namespace handle, or set ID to a numeric ID obtained from Info.NamespaceID. The handle pins the namespace reference during a call. A numeric ID does not, and the kernel applies its own visibility and capability checks. Namespace IDs are separate from procfs namespace inode numbers. When the selected namespace differs from the calling thread’s namespace, Linux uses that namespace’s root for traversal and mount point paths. No namespace entry or mount mutation is involved.
Pages and records are independent observations. A concurrent attach, move, attribute change, or unmount may change later results or cause Stat to return ENOENT. Variable records grow on EOVERFLOW up to 1 MiB. Larger records return EOVERFLOW, and malformed records return EPROTO. The discovery example walks pages and handles disappearance.
When a Config command reaches its valid context descriptor and fails, it drains the kernel filesystem-context queue before another Config method can interleave, returning a *mount.Error inside normal error wrapping. This includes a failure to borrow a parameter file after reaching the context. Local argument checks and failures to access the context return ordinary wrapping and leave pending records available. Use errors.As to inspect Diagnostics and DiagnosticError. errors.Is and errors.As traverse the primary operation error only; a diagnostic read failure never replaces its errno. Errors may include warnings left by earlier successful operations. Configuration failures do not always produce diagnostic records.
Each Diagnostic contains a Severity byte, normally e, w, or i, and a Message without its framing separator or final newline. Unknown severity bytes are preserved. Unframed kernel records retain all bytes with zero Severity. Error text includes diagnostic messages for ordinary logging; use fields for structured inspection. Kernel text may contain configuration inputs, so apply caller logging policy.
config.Diagnostics() drains remaining records, returning nil/nil for an empty queue and partial records alongside retrieval errors. Messages already collected in an Error are not returned again. The kernel queue holds only the newest eight records on Linux 7.0 and can lose earlier messages. Reads grow from 4 KiB to 1 MiB on EMSGSIZE; a larger record reports EMSGSIZE and stays queued on the supported baseline. This bound controls allocation and is not a producer-size guarantee. The queue is not a lossless log.
Mount path operations wrap *os.PathError, with both paths carried by *os.LinkError for PivotRoot. Errors preserve kernel errno identity, including capability, syscall-filter, filesystem, and configuration rejections. Zero owners match os.ErrInvalid. Repeated Close and ordinary methods on closed owners match os.ErrClosed for otherwise valid arguments.
Config supports ordinary creation and reconfiguration on the Linux 7.0 mount UAPI. Exclusive superblock creation is outside its scope. Clone supplies CLONE/CLOEXEC and optional recursive selection; creating a mount namespace through open_tree is not exposed. Attach uses its documented empty-path selectors, without beneath/group-setting controls.
Handle.Attributes reports four named restrictions. Structured discovery preserves the full kernel attribute mask and can observe propagation and visible ID mappings. The attribute mutation API covers the four restrictions, access-time policies, propagation, and first-time ID mapping of a detached tree. Setting MOUNT_ATTR_NOSYMFOLLOW and replacing or clearing an ID mapping through open_tree_attr are outside this API. The package provides normal and lazy unmount. Force/expire and arbitrary legacy mount calls are outside its scope. The application supplies namespace setup, rootfs contents, and cleanup policy.
The caller supplies namespace isolation, applicable CAP_SYS_ADMIN, filesystem support, attachment/propagation policy, and unmount cleanup. The library never enters a namespace. Do not run attachment examples against host mounts. A container’s UID 0 alone does not establish the required capabilities or syscall permissions.
Both owners implement io.Closer; descriptors are atomically close-on-exec. Do not copy owners after first use. Config methods, Close, and diagnostic collection are serialized; Config.Close waits for in-flight Config methods. Handle methods pin descriptor lifetime against concurrent Close; operation sequences and path lookups are not transactions. Handle.Close can return while a protected operation is still running, with final kernel descriptor release deferred until its reference is dropped. Close provides no cancellation. Both owners keep descriptors private. There is no adoption API, I/O stream, deadline, or context support.
Run package=mount make specs for ordinary-user validation/error tests. Run package=mount make specs profile=namespaces to request isolated integration, or add required=true to fail when a prerequisite is unavailable. The mount API tests and examples run in bounded subprocesses with private mount propagation. Most use a new user namespace with UID/GID mappings. The ID-mapping fixtures that install distinct IDs retain the runner’s initial-user-namespace privileges. After the prerequisites pass, any operation or cleanup failure fails the test. See mount verification for runner requirements, including the separate XFS reflink fixture, and the design note for ownership and diagnostic tradeoffs.