From 74b1886da3eb578614d381466db628a697ebd203 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Wed, 25 Nov 2026 00:41:27 +0000 Subject: [PATCH] sparse: add package for walking a sparse file's data extents Add a package that lists a file's data extents, so callers can skip its holes. This is the third time we've needed this in the corp repo. The first, cmd/cihostlet/sparse.go in tailscale/corp#38151, copied VM disk images without materializing their holes, and was since deleted in tailscale/corp#42869. The second, the ci/sparse package in tailscale/corp#39248, hashed sparse ext4 images for build caching, and never landed (yet?). The third, the Tart image peer fill in tailscale/corp#52161, is a WIP with its own extent loop to send disk.img without its holes, and could use this instead. So put it here once. It is the ci/sparse package from tailscale/corp#39248 with these changes: - It works on macOS and FreeBSD as well as Linux. ci/sparse was Linux-only and hard-coded Linux's SEEK_DATA and SEEK_HOLE values, which are swapped on macOS; these come from x/sys/unix now. - It works on Windows too, with FSCTL_QUERY_ALLOCATED_RANGES, for the day cihostlet runs there. Only NTFS files marked sparse have holes; other files are one extent. - Where the file system can't report holes (EINVAL), or on other platforms, the rest of the file is reported as one extent, as both earlier versions did, so ForEachExtent is always correct, just not always sparse. - ForEachExtent now sets the file position to each extent's start, as its doc already promised, and clips extents to the given size. - Extent gets an End method. - FileHash is gone. It hashed only the data extents, as a build cache key that depends on where the file system put the holes, which is specific to that one caller; a caller that wants it can build it on ForEachExtent in a few lines. - It has tests, and an example of streaming a file with its holes, the shape that tailscale/corp#52161 needs. The tests pass on Linux, macOS (APFS), FreeBSD 15.0 (UFS), and Windows Server 2022 (NTFS). Updates tailscale/corp#51142 Co-authored-by: Sam Wronski Signed-off-by: Brad Fitzpatrick Change-Id: I4771a43e2c9f519b1fd426d7c2b59fa30f30c4c1 --- sparse/example_test.go | 34 +++++ sparse/sparse.go | 42 ++++++ sparse/sparse_notwindows_test.go | 15 ++ sparse/sparse_other.go | 23 ++++ sparse/sparse_seek.go | 56 ++++++++ sparse/sparse_test.go | 226 +++++++++++++++++++++++++++++++ sparse/sparse_windows.go | 81 +++++++++++ sparse/sparse_windows_test.go | 20 +++ 8 files changed, 497 insertions(+) create mode 100644 sparse/example_test.go create mode 100644 sparse/sparse.go create mode 100644 sparse/sparse_notwindows_test.go create mode 100644 sparse/sparse_other.go create mode 100644 sparse/sparse_seek.go create mode 100644 sparse/sparse_test.go create mode 100644 sparse/sparse_windows.go create mode 100644 sparse/sparse_windows_test.go diff --git a/sparse/example_test.go b/sparse/example_test.go new file mode 100644 index 0000000..767e001 --- /dev/null +++ b/sparse/example_test.go @@ -0,0 +1,34 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +package sparse_test + +import ( + "encoding/binary" + "io" + "os" + + "github.com/tailscale/tb/sparse" +) + +// This sends a file's size and then each data extent as an offset, a length, +// and that many bytes, so the receiver can recreate the file with its holes. +func ExampleForEachExtent() { + send := func(w io.Writer, f *os.File) error { + fi, err := f.Stat() + if err != nil { + return err + } + if err := binary.Write(w, binary.BigEndian, fi.Size()); err != nil { + return err + } + return sparse.ForEachExtent(f, fi.Size(), func(e sparse.Extent) error { + if err := binary.Write(w, binary.BigEndian, [2]int64{e.Offset, e.Length}); err != nil { + return err + } + _, err := io.Copy(w, io.NewSectionReader(f, e.Offset, e.Length)) + return err + }) + } + _ = send +} diff --git a/sparse/sparse.go b/sparse/sparse.go new file mode 100644 index 0000000..0d6705e --- /dev/null +++ b/sparse/sparse.go @@ -0,0 +1,42 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +// Package sparse lists the data extents of sparse files, so callers can +// skip their holes. +package sparse + +import "os" + +// Extent is a region of a file that holds data rather than a hole. +type Extent struct { + Offset int64 + Length int64 +} + +// End returns the offset just past the extent. +func (e Extent) End() int64 { return e.Offset + e.Length } + +// ForEachExtent calls fn for each data extent of f, in ascending order, among +// the first size bytes of f. Before each call it sets f's position to the +// extent's start, but fn may read at any offset, as with an +// io.NewSectionReader. +// +// It finds extents with SEEK_DATA and SEEK_HOLE on Linux, macOS, and +// FreeBSD, and with FSCTL_QUERY_ALLOCATED_RANGES on Windows, where only +// files marked sparse have holes. Where the file system can't report holes, +// or on other platforms, it reports the rest of the file as one extent, so +// the result is always correct, just not always sparse. +func ForEachExtent(f *os.File, size int64, fn func(Extent) error) error { + return forEachExtent(f, size, fn) +} + +// Extents returns the data extents of f among its first size bytes; see +// [ForEachExtent]. +func Extents(f *os.File, size int64) ([]Extent, error) { + var extents []Extent + err := ForEachExtent(f, size, func(e Extent) error { + extents = append(extents, e) + return nil + }) + return extents, err +} diff --git a/sparse/sparse_notwindows_test.go b/sparse/sparse_notwindows_test.go new file mode 100644 index 0000000..48ff2e5 --- /dev/null +++ b/sparse/sparse_notwindows_test.go @@ -0,0 +1,15 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !windows + +package sparse + +import ( + "os" + "testing" +) + +// makeSparse does nothing, since these file systems leave unwritten +// regions as holes. +func makeSparse(t *testing.T, f *os.File) {} diff --git a/sparse/sparse_other.go b/sparse/sparse_other.go new file mode 100644 index 0000000..cf62849 --- /dev/null +++ b/sparse/sparse_other.go @@ -0,0 +1,23 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !(linux || darwin || freebsd || windows) + +package sparse + +import ( + "io" + "os" +) + +// forEachExtent reports the whole file as one extent, since this platform +// has no SEEK_DATA. +func forEachExtent(f *os.File, size int64, fn func(Extent) error) error { + if size <= 0 { + return nil + } + if _, err := f.Seek(0, io.SeekStart); err != nil { + return err + } + return fn(Extent{Offset: 0, Length: size}) +} diff --git a/sparse/sparse_seek.go b/sparse/sparse_seek.go new file mode 100644 index 0000000..621f6a8 --- /dev/null +++ b/sparse/sparse_seek.go @@ -0,0 +1,56 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux || darwin || freebsd + +package sparse + +import ( + "errors" + "io" + "os" + + "golang.org/x/sys/unix" +) + +func forEachExtent(f *os.File, size int64, fn func(Extent) error) error { + rc, err := f.SyscallConn() + if err != nil { + return err + } + // seek runs lseek on f's descriptor. The SEEK_DATA and SEEK_HOLE values + // differ between platforms, so they come from x/sys/unix. + seek := func(off int64, whence int) (pos int64, err error) { + if cerr := rc.Control(func(fd uintptr) { pos, err = unix.Seek(int(fd), off, whence) }); cerr != nil { + return 0, cerr + } + return pos, err + } + for off := int64(0); off < size; { + start, err := seek(off, unix.SEEK_DATA) + switch { + case errors.Is(err, unix.ENXIO): + return nil // The rest of the file is a hole. + case errors.Is(err, unix.EINVAL): + start = off // The file system can't report holes. + case err != nil: + return err + } + if start >= size { + return nil + } + end, err := seek(start, unix.SEEK_HOLE) + if err != nil { + end = size + } + end = min(end, size) + if _, err := f.Seek(start, io.SeekStart); err != nil { + return err + } + if err := fn(Extent{Offset: start, Length: end - start}); err != nil { + return err + } + off = end + } + return nil +} diff --git a/sparse/sparse_test.go b/sparse/sparse_test.go new file mode 100644 index 0000000..149f881 --- /dev/null +++ b/sparse/sparse_test.go @@ -0,0 +1,226 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +package sparse + +import ( + "bytes" + "errors" + "io" + "os" + "path/filepath" + "slices" + "testing" +) + +// The test file is 64 MiB with data at these offsets and holes elsewhere, +// including at the start and the end. +const ( + testSize = 64 << 20 + chunk = 1 << 20 +) + +var dataAt = []int64{8 << 20, 9 << 20, 40 << 20} + +// writeTestFile writes the test file and returns it open for reading. +func writeTestFile(t *testing.T) *os.File { + t.Helper() + path := filepath.Join(t.TempDir(), "sparse.img") + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + makeSparse(t, f) + if err := f.Truncate(testSize); err != nil { + t.Fatal(err) + } + for i, off := range dataAt { + if _, err := f.WriteAt(bytes.Repeat([]byte{byte('a' + i)}, chunk), off); err != nil { + t.Fatal(err) + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + f, err = os.Open(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { f.Close() }) + return f +} + +func TestForEachExtent(t *testing.T) { + f := writeTestFile(t) + var covered, prevEnd int64 + err := ForEachExtent(f, testSize, func(e Extent) error { + if e.Offset < prevEnd || e.Length <= 0 || e.End() > testSize { + t.Errorf("bad extent %+v after %d", e, prevEnd) + } + // The file position is at the extent's start. + if pos, err := f.Seek(0, io.SeekCurrent); err != nil || pos != e.Offset { + t.Errorf("position %d, %v at extent %+v", pos, err, e) + } + covered += e.Length + prevEnd = e.End() + return nil + }) + if err != nil { + t.Fatal(err) + } + t.Logf("extents cover %d of %d bytes", covered, int64(testSize)) + + // Every written byte must be in an extent. Whether the holes are left + // out depends on the file system, so that's only logged. + extents, err := Extents(f, testSize) + if err != nil { + t.Fatal(err) + } + for _, off := range dataAt { + in := false + for _, e := range extents { + if e.Offset <= off && off+chunk <= e.End() { + in = true + } + } + if !in { + t.Errorf("data at %d is not inside an extent of %v", off, extents) + } + } + + // Bytes outside the extents read as zeros. + buf := make([]byte, chunk) + for off := int64(0); off < testSize; off += chunk { + inExtent := false + for _, e := range extents { + if off < e.End() && e.Offset < off+chunk { + inExtent = true + } + } + if inExtent { + continue + } + if _, err := f.ReadAt(buf, off); err != nil { + t.Fatal(err) + } + if !bytes.Equal(buf, make([]byte, chunk)) { + t.Errorf("nonzero bytes in the hole at %d", off) + } + } +} + +func TestForEachExtentSizeLimit(t *testing.T) { + f := writeTestFile(t) + // Only the first extent's region is within the limit. + limit := dataAt[0] + chunk/2 + extents, err := Extents(f, limit) + if err != nil { + t.Fatal(err) + } + for _, e := range extents { + if e.End() > limit { + t.Errorf("extent %+v goes past limit %d", e, limit) + } + } +} + +// TestManyExtents covers files with more extents than one Windows +// FSCTL_QUERY_ALLOCATED_RANGES call returns. +func TestManyExtents(t *testing.T) { + const ( + islands = 200 // more than the 64 ranges per Windows query + stride = 1 << 20 // well past NTFS's 64 KiB sparse unit + island = 4 << 10 + ) + path := filepath.Join(t.TempDir(), "islands.img") + w, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + makeSparse(t, w) + size := int64(islands * stride) + if err := w.Truncate(size); err != nil { + t.Fatal(err) + } + for i := range islands { + if _, err := w.WriteAt(bytes.Repeat([]byte{'d'}, island), int64(i)*stride); err != nil { + t.Fatal(err) + } + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + extents, err := Extents(f, size) + if err != nil { + t.Fatal(err) + } + t.Logf("%d islands in %d extents", islands, len(extents)) + for i := range islands { + off := int64(i) * stride + if !slices.ContainsFunc(extents, func(e Extent) bool { return e.Offset <= off && off+island <= e.End() }) { + t.Fatalf("island at %d is not inside an extent", off) + } + } + for i := 1; i < len(extents); i++ { + if extents[i].Offset < extents[i-1].End() { + t.Fatalf("extents %v and %v overlap or are out of order", extents[i-1], extents[i]) + } + } +} + +func TestForEachExtentStopsOnError(t *testing.T) { + f := writeTestFile(t) + errStop := errors.New("stop") + calls := 0 + err := ForEachExtent(f, testSize, func(Extent) error { + calls++ + return errStop + }) + if !errors.Is(err, errStop) || calls != 1 { + t.Errorf("err = %v after %d calls, want errStop after 1", err, calls) + } +} + +func TestDenseFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "dense") + if err := os.WriteFile(path, bytes.Repeat([]byte("x"), 3*chunk+17), 0o644); err != nil { + t.Fatal(err) + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + const size = 3*chunk + 17 + extents, err := Extents(f, size) + if err != nil { + t.Fatal(err) + } + var covered int64 + for _, e := range extents { + covered += e.Length + } + if covered != size { + t.Errorf("extents %v cover %d bytes, want all %d", extents, covered, size) + } +} + +func TestEmptyFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "empty") + if err := os.WriteFile(path, nil, 0o644); err != nil { + t.Fatal(err) + } + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if extents, err := Extents(f, 0); err != nil || len(extents) != 0 { + t.Errorf("Extents of an empty file = %v, %v", extents, err) + } +} diff --git a/sparse/sparse_windows.go b/sparse/sparse_windows.go new file mode 100644 index 0000000..50d429b --- /dev/null +++ b/sparse/sparse_windows.go @@ -0,0 +1,81 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +package sparse + +import ( + "errors" + "io" + "os" + "unsafe" + + "golang.org/x/sys/windows" +) + +// allocatedRange is FILE_ALLOCATED_RANGE_BUFFER, the input and output of +// FSCTL_QUERY_ALLOCATED_RANGES. +type allocatedRange struct { + FileOffset int64 + Length int64 +} + +// rangesPerQuery is how many ranges one FSCTL_QUERY_ALLOCATED_RANGES call +// returns at most; more need another call. +const rangesPerQuery = 64 + +// forEachExtent reports f's allocated ranges as its extents. A file that +// isn't marked sparse is allocated throughout, so it is one extent. +func forEachExtent(f *os.File, size int64, fn func(Extent) error) error { + rc, err := f.SyscallConn() + if err != nil { + return err + } + for off := int64(0); off < size; { + in := allocatedRange{FileOffset: off, Length: size - off} + var out [rangesPerQuery]allocatedRange + var n uint32 + var qerr error + if err := rc.Control(func(h uintptr) { + qerr = windows.DeviceIoControl(windows.Handle(h), windows.FSCTL_QUERY_ALLOCATED_RANGES, + (*byte)(unsafe.Pointer(&in)), uint32(unsafe.Sizeof(in)), + (*byte)(unsafe.Pointer(&out[0])), uint32(unsafe.Sizeof(out)), &n, nil) + }); err != nil { + return err + } + more := errors.Is(qerr, windows.ERROR_MORE_DATA) + switch { + case errors.Is(qerr, windows.ERROR_INVALID_FUNCTION): + // The file system can't report allocated ranges. + return emit(f, Extent{Offset: off, Length: size - off}, fn) + case qerr != nil && !more: + return qerr + } + ranges := out[:n/uint32(unsafe.Sizeof(out[0]))] + if len(ranges) == 0 { + return nil // The rest of the file is unallocated. + } + for _, r := range ranges { + start, end := max(r.FileOffset, off), min(r.FileOffset+r.Length, size) + if start >= end { + continue + } + if err := emit(f, Extent{Offset: start, Length: end - start}, fn); err != nil { + return err + } + } + if !more { + return nil + } + last := ranges[len(ranges)-1] + off = last.FileOffset + last.Length + } + return nil +} + +// emit sets f's position to e's start and calls fn with e. +func emit(f *os.File, e Extent, fn func(Extent) error) error { + if _, err := f.Seek(e.Offset, io.SeekStart); err != nil { + return err + } + return fn(e) +} diff --git a/sparse/sparse_windows_test.go b/sparse/sparse_windows_test.go new file mode 100644 index 0000000..29f2d65 --- /dev/null +++ b/sparse/sparse_windows_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +package sparse + +import ( + "os" + "testing" + + "golang.org/x/sys/windows" +) + +// makeSparse marks f sparse, without which NTFS allocates a file's holes. +func makeSparse(t *testing.T, f *os.File) { + t.Helper() + var n uint32 + if err := windows.DeviceIoControl(windows.Handle(f.Fd()), windows.FSCTL_SET_SPARSE, nil, 0, nil, 0, &n, nil); err != nil { + t.Fatalf("FSCTL_SET_SPARSE: %v", err) + } +}