github.com/alexfalkowski/go-linux/v2/file adds Linux open, metadata, linking and rename, allocation, access advice, synchronization, and locking controls to standard *os.File handles. Use os and os.Root for ordinary file operations. The module supports Linux 7.0+ and the Go floor in go.mod. Filesystem support and security policy can vary by operation.
Use it for controlled path lookup, extended metadata inspection, atomic file replacement or exchange, and preallocating log segments. GNU mv’s exchange mode demonstrates swapping two existing entries atomically on supporting filesystems.
Open an anchor with os.Open, then borrow it for one restricted lookup:
dir, err := os.Open("/srv/app")
if err != nil {
return err
}
defer dir.Close()
config, err := file.Open(dir, "config.json", file.OpenOptions{
Resolve: file.Beneath | file.NoSymlinks | file.NoXDev,
})
if err != nil {
return err
}
defer config.Close()
The result is an ordinary owned *os.File, ready for standard I/O or composition with mmap.Map. Close it independently of the borrowed directory. This is the deliberate standard-file boundary for this package; descriptor borrowing and Linux calls are handled internally. The executable examples include complete setup and error handling.
OpenOptions{} opens read-only with ordinary Linux resolution. Zero does not confine the lookup. Beneath rejects absolute names and escapes above the anchor; InRoot instead interprets absolute names, absolute symlinks, and parent traversal relative to that anchor for the duration of the lookup. They cannot be combined. NoSymlinks rejects traversal through any symlink, while the NoFollow open flag affects only the last component. NoMagicLinks excludes procfs-style magic-link traversal; request it explicitly with Beneath or InRoot if required. NoXDev rejects mount-point crossings, including bind mounts. Cached returns EAGAIN when lookup needs uncached work. No restriction is removed on retry, and the package performs no automatic retry.
Create and TempFile use Perm in Go os.FileMode representation, including Go’s setuid, setgid, and sticky constants. Umask and filesystem policy still apply. Set Perm to zero for other opens. All descriptors are atomically close-on-exec. A Path handle permits metadata and directory anchoring. Combine Path|NoFollow to open a final symlink itself, including under NoSymlinks or NoMagicLinks.
Names pass to Linux unchanged. Trailing slashes, empty names, symlink expansion, and .. keep kernel semantics. A live nonnil anchor is required even when an absolute path would ignore it. Blocking opens of special files can occupy an OS thread; closing the anchor does not cancel the call. The returned os.File retains standard I/O behavior, including that regular files do not support deadlines and a blocking special-file handle may lack runtime polling.
Stage a manifest or backup in its destination filesystem before exposing a name. Open a writable unnamed file with file.Open(dir, ".", file.OpenOptions{Flags: file.TempFile | file.WriteOnly, Perm: 0o600, Resolve: file.Beneath}). For TempFile, the path names the directory in which to allocate the inode. Use either WriteOnly or ReadWrite and supply the intended permissions.
Write through the returned file, then call file.Link(draft, dir, "manifest") to create the destination entry for that inode. The link fails with EEXIST if the name already exists. The destination uses ordinary path resolution on the same mount as the source. Linux checks the open-time credentials of the source or CAP_DAC_READ_SEARCH, along with destination permissions and hard-link policy. A linked entry survives closing the file. Closing the last reference to an unpublished inode discards it; add Exclusive to create a scratch file that cannot be published. If crash durability matters, synchronize the file and the containing directory at the appropriate steps. Executable publication example · Linux 7.0 link implementation
Add Direct to request O_DIRECT for a storage file. Query the open file with Stat and allocate buffers using the reported address, offset, and segment-length alignments. Check the read-specific alignment when Linux supplies one. Ordinary Go byte slices provide no filesystem-specific alignment guarantee. A misaligned operation can fail with EINVAL or use buffered I/O, depending on the filesystem and kernel. Coordinate access if the same file also has buffered I/O or mappings. Linux open documentation
Add DataSync for a journal whose writes must synchronize data and the metadata needed to retrieve it. Add Sync when writes must also synchronize other associated file metadata. These flags apply to each write. Use File.Sync or Fdatasync for an explicit flush and synchronize the containing directory separately when its entry needs to persist. Executable journal example
Stat(opened, file.MaskBasic|file.MaskBirthTime|file.MaskMountID) observes the open inode, including after unlink. StatAt(dir, name, file.StatOptions{...}) resolves a name relative to a borrowed directory. Set Flags to file.StatNoFollow to query the symlink itself, file.StatNoAutomount to suppress a final automount, or their bitwise combination. Set Sync to SyncDefault, SyncForce, or SyncDont. An empty name observes the handle itself, permitting explicit synchronization of an open file.
Metadata.Mask is the validity mask supplied by Linux. A requested field may be unavailable, and unrequested fields may be present. Check the returned bit rather than testing a field for zero. MaskBasic includes type, permission mode, link count, UID/GID, access/modification/status-change times, inode, size, and allocated 512-byte blocks. Birth time is filesystem-dependent. Times are UTC time.Time values; an unavailable timestamp is the zero Go time. Mode uses Go bits, and Linux unsigned size/identifier ranges are retained.
MaskMountID requests the reusable ID used in procfs mountinfo; MaskUniqueMountID requests the system-lifetime nonreused identity. They share Metadata.MountID, and the returned mask identifies the kind. Linux prefers the unique kind if both are requested. AttributesMask separately identifies the meaningful bits of Attributes: an unset unsupported bit does not establish a false attribute. Unknown output mask and attribute bits are preserved. BlockSize and the containing DeviceMajor/DeviceMinor are always supplied; RdevMajor/RdevMinor apply to device inodes.
For direct I/O, request MaskDirectIOAlignment|MaskDirectIOReadAlignment. The first bit validates DirectIOMemoryAlignment for buffer addresses and DirectIOOffsetAlignment for file offsets and I/O segment lengths, both in bytes. Valid zero values indicate that direct I/O is unsupported for the file. A valid, nonzero DirectIOReadOffsetAlignment supplies a separate offset and segment-length alignment for reads. Otherwise, use the general offset alignment for reads when available. The memory alignment applies to both reads and writes.
For backup traversal, request MaskSubvolumeID and use SubvolumeID to identify the containing subvolume on that filesystem. Filesystems without subvolume metadata omit the bit.
For protected direct writes, request MaskAtomicWrite. A returned bit validates the minimum and maximum write sizes in bytes, the optimized maximum size, and the maximum number of I/O vectors for one write. A valid zero minimum means the file does not support atomic writes. When atomic writes are supported, a zero optimized maximum means the ordinary maximum is the optimized limit. Check AttributesMask&file.AtomicWrite before interpreting the separate Attributes&file.AtomicWrite capability bit. These fields report kernel limits. Issuing protected writes is outside the file API.
StatAt uses ordinary Linux resolution and permits escapes, intermediate symlinks, and mount crossings. For a constrained lookup, call Open with the required restrictions and then Stat on its result. Metadata fields can reflect different instants during concurrent mutation; neither one query nor multiple queries promise an atomic snapshot.
Use keyed file.Metadata literals in tests or adapters. Positional literals written before the extended fields were added require conversion to keyed literals.
Rename(oldDir, oldName, newDir, newName, mode) accepts one named mode. Replace is the zero value. NoReplace fails with EEXIST for an existing destination, including a dangling symlink. Exchange requires both entries and atomically swaps them, even when their types differ. Final symlinks are moved themselves.
When managing an overlay’s writable layer, use Whiteout to move an entry and create a whiteout at its original name in the same operation. If both names already refer to the same inode, Whiteout succeeds as a no-op. Use WhiteoutNoReplace to protect an existing destination. An EEXIST conflict leaves both names intact. On a backing filesystem such as XFS, the whiteout is a character-device inode with device number 0:0. The modes require backing filesystem support and are subject to Linux’s permissions and security policy for whiteout creation. Linux 7.0 rename implementation · XFS whiteout implementation
Each name is relative to its matching borrowed directory, or absolute with that anchor ignored. Both anchors must remain live for admission to the operation. Rename has ordinary Linux path resolution and does not confine untrusted names. The library does not emulate modes with existence checks or multiple renames. Filesystem support failures and cross-mount errors retain errno. Entry replacement/exchange is atomic, but later lookups are separate operations; success does not promise crash durability or synchronize storage.
Reserve storage for a log segment before writing the first record. Size preservation keeps the logical end of the file at the last written record.
if err := file.Fallocate(segment, file.Allocate|file.KeepSize, 0, 64*1024); err != nil {
return err
}
Pass a writable open file, a mode, and a byte offset and length. The executable example writes a record to a preallocated segment.
| Mode | File effect |
|---|---|
Allocate (zero) |
Reserves storage and extends the file when the range ends beyond EOF. Existing data is preserved. Add KeepSize to preserve EOF. |
PunchHole with KeepSize |
Frees whole blocks and zeros partial blocks in the range. Size stays the same. |
ZeroRange |
Zeros the range and reserves storage for it. Add KeepSize to preserve EOF. |
CollapseRange |
Removes bytes, shifts later data toward the start, and shrinks the file. The range must end before EOF. |
InsertRange |
Inserts a hole, shifts later data toward the end, and grows the file. The insertion offset must be before EOF. |
UnshareRange |
Reserves storage and makes shared blocks in the range private while preserving existing data. Add KeepSize to preserve EOF. |
WriteZeroes |
Zeros the range and prepares its mappings for subsequent overwrites. Extends the file if the range ends beyond EOF. Use it alone. |
Offsets must be nonnegative and lengths positive. Invalid inputs match os.ErrInvalid. A range end outside the signed 64-bit range returns EFBIG. The filesystem checks alignment and can reject a mode with EOPNOTSUPP. Collapse and insert commonly require both offset and length to be aligned to the filesystem’s block size. KeepSize is required for hole punching and cannot be combined with collapse or insert.
Use UnshareRange|KeepSize before overwriting a range in a reflinked working copy when the logical file size must stay fixed. The filesystem determines the allocation granularity. An unaligned range can affect extent sharing at its boundary blocks while preserving their contents. The working-copy example treats the reservation as optional. See mount verification for the test on real reflinked files.
Use WriteZeroes to prepare a new or reusable database segment for in-place overwrites. On Linux 7.0, ext4 requires backing storage that advertises write zeroes with unmap and returns EOPNOTSUPP when that capability is absent. Ext4 also supports partial edge blocks and preserves bytes outside the requested range. The database segment example treats preparation as optional. Linux 7.0 ext4 implementation
Fallocate borrows the open file and preserves its current offset. Coordinate overlapping reads, writes, mappings, and range mutations at the application level. The call can block in the kernel. Errors use *os.PathError and preserve errno. The package passes the operation to Linux without fallback or rollback. Use the usual file synchronization calls for durability. Linux fallocate(2)
Set sequential advice before scanning a segment. Use readahead to request advance reads for the first part of the scan.
if err := file.Fadvise(segment, file.Sequential, 0, 0); err != nil {
return err
}
if err := file.Readahead(segment, 0, 64*1024); err != nil {
return err
}
Fadvise accepts one hint. Normal restores defaults, Random disables automatic file readahead, Sequential increases the readahead window, and NoReuse tells Linux that accesses need not protect pages from reclamation. These four hints affect the open file description and are shared by duplicated handles. WillNeed requests advance reads for the byte range, and DontNeed asks Linux to reclaim cached pages in the range. The kernel and filesystem may limit or ignore every hint. Linux 7.0 advice implementation
Readahead requires a readable handle. Linux can round requests to pages, limit the work, and block while resolving filesystem metadata. On Linux 7.0, a request for an ordinary tmpfs file can succeed without starting advance reads. Cache residency can change at any time. Linux 7.0 readahead implementation · Linux 7.0 tmpfs implementation
Both calls borrow the file and preserve its current offset. Offsets and lengths are nonnegative byte counts. A zero length requests the range through EOF. A negative offset or length matches os.ErrInvalid, and a range end above MaxInt64 returns EFBIG.
After writing a record to an existing write-ahead log, use file.Fdatasync(log) to synchronize its data and the metadata needed to retrieve it, including size changes. For broader file metadata, use the standard log.Sync(). If a new or renamed directory entry must be durable, synchronize its containing directory separately with dir.Sync().
Use file.SyncFS(dir) for an explicit filesystem-wide checkpoint. A regular file or directory handle identifies the containing filesystem. The operation can synchronize other files and report writeback errors unrelated to the supplied file. Both synchronization calls preserve the input’s offset and can block. Coordinate transaction ordering and recovery in the application. Linux 7.0 synchronization implementation
Have each cooperating writer open the shared log segment with os.O_APPEND so writes start at the end of the file. Call file.Flock(segment, file.LockExclusive|file.LockNonblock) before appending. Handle EWOULDBLOCK through errors.Is if another worker holds an incompatible lock. Readers can acquire LockShared while other readers hold shared locks. Call file.Flock(segment, file.Unlock) to release the lock and keep using the file. Pass exactly one operation, with LockNonblock optional. See the executable example.
Each open file description has one lock. Duplicated or inherited descriptors that refer to the same description share it. Unlocking through any of them releases it, as does closing the final reference. Separate opens compete even within one process. Switching between shared and exclusive mode can release the old lock before acquiring the new one. A failed conversion can leave the file unlocked. Linux 7.0 locking implementation
Blocking acquisition can occupy an OS thread. Closing the file or setting a Go deadline does not interrupt a pending call. LockNonblock prevents waiting for a conflicting lock. Local locks are advisory and require all participants to cooperate. NFS and SMB can emulate flock with whole-file byte-range locks, depending on the server and mount options. NFS can require write access for an exclusive lock, and SMB can enforce the lock on I/O through separate opens. Linux flock(2)
To update one record in a file shared by cooperating workers, open the file for writing and call file.SetRecordLock(store, file.OFDLocks, lock) with a file.RecordLock whose Type is file.LockWrite and whose Range covers the record. Use WriteAt to update that record, then set lock.Type = file.LockRelease and pass it to SetRecordLock to release those bytes. Readers with readable handles can share a range using file.LockRead. Executable example
Choose file.OFDLocks when workers need separate open file descriptions. Each separate open can contend with other opens, even in one process. Duplicates and inherited references share the locks, and the final close releases them. Choose file.POSIXLocks when cooperating with a process-associated protocol. Closing any descriptor for the inode in that process releases all of its POSIX locks on the inode. A POSIX lock survives exec unless a close releases it, and fork does not transfer the parent’s POSIX locks to the child. The two scopes can conflict with each other. Local Flock locks operate independently of record locks. Linux fcntl_locking(2)
LockRange.Whence accepts Go’s io.SeekStart, io.SeekCurrent, and io.SeekEnd. Start is signed and Linux resolves it at the time of each call without moving the file offset. A positive Length covers bytes starting at the resolved position. A negative length covers bytes preceding that position, excluding the position itself. A zero length extends through future file growth. Use absolute offsets if the file position or size can change between acquisition and release. Linux rejects resolved ranges before byte zero and preserves native overflow errors. Linux 7.0 range resolution
SetRecordLock returns EAGAIN or EACCES on contention. Use WaitRecordLock for kernel blocking acquisition. It can occupy an OS thread, and file close and Go deadlines do not interrupt that wait. The call preserves EINTR when the kernel returns it, and POSIX waits can return EDEADLK when Linux detects a cycle. Linux does not perform this deadlock check for OFD locks. Linux fcntl_locking(2)
QueryRecordLock reports one incompatible lock, if present, with an absolute range and the kernel’s owner PID. It ignores locks belonging to the selected owner and reserves no bytes. A local POSIX owner has a PID in the caller’s namespace, or zero if invisible there. An OFD conflict reports -1. Network filesystems can impose additional locking rules or lose server-side locks. Linux 7.0 owner reporting
Ordinary creation, I/O, logical resizing, and File.Sync use standard Go operations. The supported opening flags are declared in OpenFlags.
The allocation API accepts the modes in the table. sync_file_range is outside the current surface. Linux 7.0 allocation definitions
Statx accepts the named field masks above, including individual basic bits. Reflink creation, extent inspection, and device control are outside this surface. Linux 7.0 statx definitions
Every input is borrowed for one call and stays caller-owned on success and failure. Descriptor references are pinned internally against concurrent Close; operations either use the original open description or fail with os.ErrClosed. File status flags and offsets are preserved. Separate calls are safe concurrently, while logical sequences require caller coordination. No context or syscall-deadline API is promised.
Options rejected by Go validation match os.ErrInvalid before file access. Nil files match os.ErrInvalid, and closed files match os.ErrClosed. Kernel failures such as EEXIST, ELOOP, EXDEV, EAGAIN, EACCES, and ENOTDIR retain identity through errors.Is. Link and Rename use *os.LinkError to report the source and destination when available. Other operations use *os.PathError. A failed Open returns nil with nothing for the caller to clean up.
Run package=file make specs for the real-kernel race/coverage suite. The verification guide describes temporary filesystem prerequisites and the isolated metadata scenario. The design note explains API tradeoffs.