Documentation
¶
Overview ¶
Package apfs provides zero-cgo Darwin APFS primitives for copy-on-write cloning, physical extent inspection, sparse hole punching, volume snapshots, buffer-cache fcntl controls, and virtual-memory madvise helpers.
CloneFile wraps Darwin's clonefile(2) system call to create instant copy-on-write clones of files and entire directory trees atomically on APFS volumes, returning an error wrapping ErrUnsupported when the underlying filesystem does not support cloning.
Extents inspects physical disk allocations via F_LOG2PHYS_EXT and SharedExtentBytes measures physical bytes shared between two extent lists.
PunchHole deallocates byte ranges inside a file via F_PUNCHHOLE without changing its logical size.
ListSnapshots, CreateSnapshot, and DeleteSnapshot manage APFS volume snapshots via fs_snapshot_list(2), fs_snapshot_create(2), and fs_snapshot_delete(2).
SetNoCache, SetReadAhead, FullSync, and BarrierSync control Darwin's F_NOCACHE, F_RDAHEAD, F_FULLFSYNC, and F_BARRIERFSYNC file-descriptor options without cgo.
Madvise wraps madvise(2) with Darwin-specific hints including FreeReusable (MADV_FREE_REUSABLE) and FreeReuse (MADV_FREE_REUSE).
OpenMapped combines mmap(2) with optional F_NOCACHE, F_RDAHEAD, and madvise(2) controls for streaming large read-only or writable files.
Basic usage:
if err := apfs.CloneFile("weights.safetensors", "checkpoint.safetensors"); err != nil {
log.Fatal(err)
}
mf, err := apfs.OpenMapped("weights.safetensors", apfs.MapOptions{
NoCache: true,
Advice: apfs.Sequential,
})
if err != nil {
log.Fatal(err)
}
defer mf.Close()
Example ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/apple/x/apfs"
)
func main() {
dir, err := os.MkdirTemp("", "apfs-example-*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
src := filepath.Join(dir, "weights.bin")
dst := filepath.Join(dir, "checkpoint.bin")
if err := os.WriteFile(src, []byte("layer0-weights"), 0o644); err != nil {
log.Fatal(err)
}
if err := apfs.CloneFile(src, dst, apfs.WithNoOwnerCopy()); err != nil {
log.Fatal(err)
}
mf, err := apfs.OpenMapped(dst, apfs.MapOptions{
NoCache: true,
Advice: apfs.Sequential,
})
if err != nil {
log.Fatal(err)
}
defer mf.Close()
fmt.Println(string(mf.Bytes()))
}
Output: layer0-weights
Index ¶
- Variables
- func BarrierSync(f *os.File) error
- func CloneFile(src, dst string, opts ...CloneOption) error
- func CreateSnapshot(mountPath, name string) error
- func DeleteSnapshot(mountPath, name string) error
- func FullSync(fd uintptr) error
- func ListSnapshots(mountPath string) ([]string, error)
- func Madvise(b []byte, advice Advice) error
- func PunchHole(f *os.File, offset, length int64) error
- func SetNoCache(fd uintptr, enable bool) error
- func SetReadAhead(fd uintptr, enable bool) error
- func SharedExtentBytes(a, b []Extent) int64
- type Advice
- type CloneOption
- type Extent
- type MapOptions
- type MappedFile
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrUnsupported = errors.New("apfs: operation not supported")
ErrUnsupported reports that the filesystem or kernel does not support the requested APFS operation (for example, clonefile(2) on a non-APFS volume or across mount points).
Functions ¶
func BarrierSync ¶
BarrierSync flushes buffered data for f and issues an ordering barrier to the underlying storage device using Darwin's F_BARRIERFSYNC fcntl. It is lighter-weight than FullSync while still guaranteeing write ordering.
func CloneFile ¶
func CloneFile(src, dst string, opts ...CloneOption) error
CloneFile creates a copy-on-write clone of src at dst using Darwin's clonefile(2) system call. dst must not already exist.
When src is a directory, clonefile(2) natively clones the entire directory tree atomically with copy-on-write sharing for every file beneath it.
If the filesystem does not support cloning or src and dst reside on different volumes, the returned error wraps ErrUnsupported.
Example ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/apple/x/apfs"
)
func main() {
dir, err := os.MkdirTemp("", "apfs-clone-*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
src := filepath.Join(dir, "model.bin")
dst := filepath.Join(dir, "model-cow.bin")
if err := os.WriteFile(src, []byte("checkpoint-v1"), 0o644); err != nil {
log.Fatal(err)
}
if err := apfs.CloneFile(src, dst); err != nil {
log.Fatal(err)
}
got, err := os.ReadFile(dst)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(got))
}
Output: checkpoint-v1
func CreateSnapshot ¶
CreateSnapshot creates a read-only APFS snapshot named name on the volume mounted at mountPath using Darwin's fs_snapshot_create(2) system call.
Creating snapshots requires superuser privileges and the appropriate entitlement; unprivileged callers receive an error wrapping syscall.EPERM. If the volume does not support snapshots, the returned error wraps ErrUnsupported.
func DeleteSnapshot ¶
DeleteSnapshot deletes the APFS snapshot named name from the volume mounted at mountPath using Darwin's fs_snapshot_delete(2) system call.
Deleting snapshots requires superuser privileges and the appropriate entitlement; unprivileged callers receive an error wrapping syscall.EPERM. If the volume does not support snapshots, the returned error wraps ErrUnsupported.
func FullSync ¶
FullSync flushes all buffered data for fd to permanent storage using Darwin's F_FULLFSYNC fcntl, issuing a drive flush barrier beyond fsync(2).
func ListSnapshots ¶
ListSnapshots returns the names of all APFS snapshots on the volume mounted at mountPath using Darwin's fs_snapshot_list(2) system call.
If the volume does not support snapshots, the returned error wraps ErrUnsupported.
func Madvise ¶
Madvise advises the Darwin VM system about expected access patterns for b using madvise(2). Passing an empty slice is a no-op. Note that XNU restricts FreeReusable and FreeReuse to writable anonymous mappings; use DontNeed to release clean pages from read-only file-backed mappings.
func PunchHole ¶
PunchHole deallocates the byte range [offset, offset+length) within f using Darwin's F_PUNCHHOLE fcntl, turning it into a sparse hole without changing the file's logical size. On APFS, offset and length are typically aligned to the filesystem block size.
If the filesystem does not support hole punching, the returned error wraps ErrUnsupported.
Example ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/apple/x/apfs"
)
func main() {
dir, err := os.MkdirTemp("", "apfs-punch-*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
f, err := os.Create(filepath.Join(dir, "data.bin"))
if err != nil {
log.Fatal(err)
}
defer f.Close()
if _, err := f.Write(make([]byte, 64*1024)); err != nil {
log.Fatal(err)
}
if err := apfs.PunchHole(f, 0, 32*1024); err != nil {
log.Fatal(err)
}
if err := apfs.BarrierSync(f); err != nil {
log.Fatal(err)
}
info, err := f.Stat()
if err != nil {
log.Fatal(err)
}
fmt.Println(info.Size())
}
Output: 65536
func SetNoCache ¶
SetNoCache toggles Darwin's F_NOCACHE fcntl on fd. When enabled, reads and writes bypass the unified buffer cache, preventing large sequential scans from evicting working memory.
func SetReadAhead ¶
SetReadAhead toggles Darwin's F_RDAHEAD fcntl on fd. Disabling read-ahead avoids speculative prefetching during random or explicitly prefetched reads.
func SharedExtentBytes ¶
SharedExtentBytes returns the total number of physical disk bytes shared between extent lists a and b. Overlapping physical ranges within either list are coalesced so shared bytes are never double-counted.
Types ¶
type Advice ¶
type Advice int
Advice is a Darwin madvise(2) memory-usage hint from <sys/mman.h>.
const ( Normal Advice = 0 // MADV_NORMAL Random Advice = 1 // MADV_RANDOM Sequential Advice = 2 // MADV_SEQUENTIAL WillNeed Advice = 3 // MADV_WILLNEED DontNeed Advice = 4 // MADV_DONTNEED Free Advice = 5 // MADV_FREE FreeReusable Advice = 7 // MADV_FREE_REUSABLE FreeReuse Advice = 8 // MADV_FREE_REUSE )
type CloneOption ¶
type CloneOption func(*cloneConfig)
CloneOption configures CloneFile.
func WithACL ¶
func WithACL() CloneOption
WithACL sets CLONE_ACL to copy access control lists from src.
func WithNoFollow ¶
func WithNoFollow() CloneOption
WithNoFollow sets CLONE_NOFOLLOW so that if src is a symbolic link, the link itself is cloned rather than its target.
func WithNoFollowAny ¶
func WithNoFollowAny() CloneOption
WithNoFollowAny sets CLONE_NOFOLLOW_ANY to reject symbolic links anywhere in the source path.
func WithNoOwnerCopy ¶
func WithNoOwnerCopy() CloneOption
WithNoOwnerCopy sets CLONE_NOOWNERCOPY so that ownership information is not copied from src.
type Extent ¶
type Extent struct {
LogicalOffset int64 // byte offset within the file
PhysicalOffset int64 // byte offset on the underlying block device
Length int64 // length of the contiguous extent in bytes
}
Extent describes a contiguous physical disk allocation for a byte range within a file.
func Extents ¶
Extents returns the allocated physical disk extents of f by walking the file from offset 0 to its logical size via Darwin's F_LOG2PHYS_EXT fcntl.
Sparse holes (unallocated regions) are omitted from the returned slice. An empty file returns a nil slice and a nil error. If the filesystem does not support F_LOG2PHYS_EXT, the returned error wraps ErrUnsupported.
type MapOptions ¶
type MapOptions struct {
// Writable opens the file read-write and maps it with PROT_READ|PROT_WRITE.
Writable bool
// NoCache applies F_NOCACHE to the file descriptor before mapping.
NoCache bool
// DisableReadAhead applies F_RDAHEAD=0 to the file descriptor before mapping.
DisableReadAhead bool
// Advice, if non-zero, is applied to the full mapping via Madvise.
Advice Advice
}
MapOptions configures OpenMapped. The zero value maps the file read-only with default kernel caching and no initial madvise hint.
type MappedFile ¶
type MappedFile struct {
// contains filtered or unexported fields
}
MappedFile holds a memory-mapped file along with its underlying descriptor. The zero value is not usable; create one with OpenMapped.
func OpenMapped ¶
func OpenMapped(path string, opts MapOptions) (*MappedFile, error)
OpenMapped opens path, applies any requested fcntl cache controls, maps the file into memory with mmap(2), and applies any initial madvise hint. Call MappedFile.Close to unmap and close the file.
Example ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/apple/x/apfs"
)
func main() {
dir, err := os.MkdirTemp("", "apfs-map-*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "shard.bin")
if err := os.WriteFile(path, []byte("hello-mmap"), 0o644); err != nil {
log.Fatal(err)
}
mf, err := apfs.OpenMapped(path, apfs.MapOptions{
NoCache: true,
Advice: apfs.WillNeed,
})
if err != nil {
log.Fatal(err)
}
defer mf.Close()
if err := mf.Madvise(apfs.DontNeed); err != nil {
log.Fatal(err)
}
fmt.Println(mf.Len(), string(mf.Bytes()))
}
Output: 10 hello-mmap
func (*MappedFile) Bytes ¶
func (m *MappedFile) Bytes() []byte
Bytes returns the mapped byte slice. The returned slice must not be used after MappedFile.Close is called.
func (*MappedFile) Close ¶
func (m *MappedFile) Close() error
Close unmaps the file and closes the underlying descriptor. Calling Close more than once is a no-op.
func (*MappedFile) Fd ¶
func (m *MappedFile) Fd() uintptr
Fd returns the underlying file descriptor, or ^uintptr(0) if closed.
func (*MappedFile) FullSync ¶
func (m *MappedFile) FullSync() error
FullSync flushes the underlying file to permanent storage via F_FULLFSYNC.
func (*MappedFile) Madvise ¶
func (m *MappedFile) Madvise(advice Advice) error
Madvise applies advice to the entire mapped region.
func (*MappedFile) MadviseRange ¶
func (m *MappedFile) MadviseRange(offset, length int, advice Advice) error
MadviseRange applies advice to the subrange [offset, offset+length).