fsys 0.9.3

Adaptive file and directory IO for Rust — fast, hardware-aware, multi-strategy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! macOS-specific IO primitives.
//!
//! Uses `F_NOCACHE` for Direct IO and `F_FULLFSYNC` for durability.
//! Regular `fsync(2)` on macOS only flushes to the drive's write cache —
//! `F_FULLFSYNC` is required to guarantee media durability.

#![cfg(target_os = "macos")]

use crate::{Error, Result};
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::path::Path;

// ──────────────────────────────────────────────────────────────────────────────
// File opening
// ──────────────────────────────────────────────────────────────────────────────

pub(crate) fn open_write_new(path: &Path, use_direct: bool) -> Result<(File, bool)> {
    let path_cstr = path_to_cstr(path)?;
    let flags = libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC;

    // SAFETY: path_cstr is a valid NUL-terminated string; flags and mode are
    // valid open(2) arguments.
    let fd = unsafe { libc::open(path_cstr.as_ptr(), flags, 0o600_i32) };
    if fd < 0 {
        return Err(Error::Io(std::io::Error::last_os_error()));
    }

    if use_direct {
        // F_NOCACHE disables the page cache for this fd.
        // SAFETY: fd is a valid open file descriptor.
        let ret = unsafe { libc::fcntl(fd, libc::F_NOCACHE, 1_i32) };
        if ret < 0 {
            // F_NOCACHE failure is rare (some HFS+ configurations). Proceed
            // without it but still use F_FULLFSYNC for durability. The caller
            // will observe the fallback via the returned false flag.
            // TODO(0.3.0): emit a metrics event for this fallback.
            // SAFETY: fd is valid and owned.
            let file = unsafe { File::from_raw_fd(fd) };
            return Ok((file, false));
        }
    }

    // SAFETY: fd is a valid, open file descriptor owned by us.
    Ok((unsafe { File::from_raw_fd(fd) }, use_direct))
}

pub(crate) fn open_read(path: &Path, use_direct: bool) -> Result<(File, bool)> {
    let path_cstr = path_to_cstr(path)?;
    let flags = libc::O_RDONLY | libc::O_CLOEXEC;

    // SAFETY: path_cstr and flags are valid.
    let fd = unsafe { libc::open(path_cstr.as_ptr(), flags, 0) };
    if fd < 0 {
        return Err(Error::Io(std::io::Error::last_os_error()));
    }

    if use_direct {
        // SAFETY: fd is valid and open.
        let ret = unsafe { libc::fcntl(fd, libc::F_NOCACHE, 1_i32) };
        if ret < 0 {
            // F_NOCACHE failed; proceed without it.
            // SAFETY: fd is valid.
            let file = unsafe { File::from_raw_fd(fd) };
            return Ok((file, false));
        }
    }

    // SAFETY: fd is valid and owned.
    Ok((unsafe { File::from_raw_fd(fd) }, use_direct))
}

pub(crate) fn open_append(path: &Path) -> Result<File> {
    OpenOptions::new()
        .append(true)
        .create(true)
        .open(path)
        .map_err(Error::Io)
}

pub(crate) fn open_write_at(path: &Path) -> Result<File> {
    OpenOptions::new()
        .write(true)
        .create(true)
        .open(path)
        .map_err(Error::Io)
}

// ──────────────────────────────────────────────────────────────────────────────
// Writing
// ──────────────────────────────────────────────────────────────────────────────

pub(crate) fn write_all(file: &File, data: &[u8]) -> Result<()> {
    let fd = file.as_raw_fd();
    let mut written = 0usize;
    while written < data.len() {
        // SAFETY: fd is a valid open file descriptor; the slice is valid.
        let n = unsafe {
            libc::write(
                fd,
                data[written..].as_ptr().cast::<libc::c_void>(),
                data.len() - written,
            )
        };
        if n < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(Error::Io(err));
        }
        written += n as usize;
    }
    Ok(())
}

pub(crate) fn write_all_direct(file: &File, data: &[u8], sector_size: u32) -> Result<()> {
    use super::{round_up, AlignedBuf};

    // Empty input — no-op. See linux.rs::write_all_direct for the
    // rationale (AlignedBuf::new rejects size=0).
    if data.is_empty() {
        return Ok(());
    }

    // macOS F_NOCACHE does not require strict sector alignment from the
    // application (the kernel handles alignment internally), but we still
    // pad to the sector boundary for consistency with the Linux path.
    let ss = sector_size as usize;
    let aligned_len = round_up(data.len(), ss);
    let mut buf = AlignedBuf::new(aligned_len, ss)?;
    buf.as_mut_slice()[..data.len()].copy_from_slice(data);

    let fd = file.as_raw_fd();
    let base = buf.as_slice().as_ptr();

    // Loop on partial writes. See linux.rs::write_all_direct for
    // the rationale — `pwrite` may return less than requested on
    // EINTR or short-write conditions; without a loop a Direct
    // write of a large payload can silently truncate.
    let mut written = 0usize;
    while written < aligned_len {
        // SAFETY: fd is valid; buf is sector-aligned and has
        // aligned_len bytes available; the offset (written) and
        // length (aligned_len - written) stay within bounds.
        let n = unsafe {
            libc::pwrite(
                fd,
                base.add(written).cast::<libc::c_void>(),
                aligned_len - written,
                written as libc::off_t,
            )
        };
        if n < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(Error::Io(err));
        }
        if n == 0 {
            return Err(Error::Io(std::io::Error::other(
                "pwrite returned 0 in write_all_direct (no progress)",
            )));
        }
        written += n as usize;
    }
    Ok(())
}

pub(crate) fn write_at(file: &File, offset: u64, data: &[u8]) -> Result<()> {
    let fd = file.as_raw_fd();
    let mut written = 0usize;
    while written < data.len() {
        let off = (offset as i64).checked_add(written as i64).ok_or_else(|| {
            Error::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "write_at: offset overflow",
            ))
        })?;
        // SAFETY: fd is valid; the slice is valid for the duration.
        let n = unsafe {
            libc::pwrite(
                fd,
                data[written..].as_ptr().cast::<libc::c_void>(),
                data.len() - written,
                off as libc::off_t,
            )
        };
        if n < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(Error::Io(err));
        }
        written += n as usize;
    }
    Ok(())
}

/// Sector-aligned positioned write for `F_NOCACHE` files. See
/// `linux.rs::write_at_direct` for the pre-condition contract.
pub(crate) fn write_at_direct(file: &File, offset: u64, data: &[u8]) -> Result<()> {
    write_at(file, offset, data)
}

// ──────────────────────────────────────────────────────────────────────────────
// Reading
// ──────────────────────────────────────────────────────────────────────────────

pub(crate) fn read_all(file: &File) -> Result<Vec<u8>> {
    let mut buf = Vec::new();
    // `read_to_end` returns the byte count, redundant with `buf.len()`
    // once the call returns; explicit `_` discard satisfies
    // `unused_results`.
    let _ = (&*file).read_to_end(&mut buf).map_err(Error::Io)?;
    Ok(buf)
}

pub(crate) fn read_all_direct(file: &File, file_size: u64, sector_size: u32) -> Result<Vec<u8>> {
    use super::{round_up, AlignedBuf};

    if file_size == 0 {
        return Ok(Vec::new());
    }

    let ss = sector_size as usize;
    let aligned_len = round_up(file_size as usize, ss);
    let mut buf = AlignedBuf::new(aligned_len, ss)?;

    let fd = file.as_raw_fd();
    let ptr = buf.as_mut_slice().as_mut_ptr().cast::<libc::c_void>();
    // SAFETY: fd is valid; buf is aligned and has aligned_len bytes; offset 0.
    let n = unsafe { libc::pread(fd, ptr, aligned_len, 0) };
    if n < 0 {
        return Err(Error::Io(std::io::Error::last_os_error()));
    }

    let trimmed = usize::min(n as usize, file_size as usize);
    Ok(buf.as_slice()[..trimmed].to_vec())
}

pub(crate) fn read_range(file: &File, offset: u64, len: usize) -> Result<Vec<u8>> {
    let fd = file.as_raw_fd();
    let mut buf = vec![0u8; len];
    let mut total_read = 0usize;
    while total_read < len {
        let off = (offset as i64)
            .checked_add(total_read as i64)
            .ok_or_else(|| {
                Error::Io(std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "read_range: offset overflow",
                ))
            })?;
        // SAFETY: fd is valid; the slice is valid.
        let n = unsafe {
            libc::pread(
                fd,
                buf[total_read..].as_mut_ptr().cast::<libc::c_void>(),
                len - total_read,
                off as libc::off_t,
            )
        };
        if n < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(Error::Io(err));
        }
        if n == 0 {
            buf.truncate(total_read);
            break;
        }
        total_read += n as usize;
    }
    buf.truncate(total_read);
    Ok(buf)
}

// ──────────────────────────────────────────────────────────────────────────────
// Durability
//
// On macOS, regular fsync(2) only flushes to the drive's write cache and does
// NOT guarantee media durability. F_FULLFSYNC is the only correct primitive
// for crash-safe writes. This applies to ALL methods on macOS:
//   - Method::Sync:   F_FULLFSYNC
//   - Method::Data:   F_FULLFSYNC (no fdatasync on macOS)
//   - Method::Direct: F_FULLFSYNC (F_NOCACHE + F_FULLFSYNC)
// ──────────────────────────────────────────────────────────────────────────────

pub(crate) fn sync_data(file: &File) -> Result<()> {
    // macOS has no fdatasync equivalent. Use F_FULLFSYNC for correctness.
    sync_full(file)
}

pub(crate) fn sync_full(file: &File) -> Result<()> {
    let fd = file.as_raw_fd();
    // F_FULLFSYNC forces the drive to flush its write cache to stable media.
    // This is the only durable sync primitive on macOS.
    //
    // SAFETY: fd is a valid open file descriptor.
    let ret = unsafe { libc::fcntl(fd, libc::F_FULLFSYNC, 0_i32) };
    if ret == 0 {
        Ok(())
    } else {
        Err(Error::Io(std::io::Error::last_os_error()))
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Rename, directory sync, copy
// ──────────────────────────────────────────────────────────────────────────────

pub(crate) fn atomic_rename(from: &Path, to: &Path) -> Result<()> {
    // POSIX rename(2) is atomic within the same filesystem.
    // renameatx_np(RENAME_SWAP) would swap two existing files, which is NOT
    // what we need — we want to replace the destination. Plain rename() is
    // the correct primitive. See .dev/DECISIONS-0.3.0.md.
    std::fs::rename(from, to).map_err(Error::Io)
}

pub(crate) fn sync_parent_dir(path: &Path) -> Result<()> {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let dir = File::open(parent).map_err(Error::Io)?;
    let fd = dir.as_raw_fd();
    // Use F_FULLFSYNC on the directory as well for full durability.
    // SAFETY: fd is a valid open directory file descriptor.
    let ret = unsafe { libc::fcntl(fd, libc::F_FULLFSYNC, 0_i32) };
    if ret == 0 {
        Ok(())
    } else {
        Err(Error::Io(std::io::Error::last_os_error()))
    }
}

pub(crate) fn copy_file(src: &Path, dst: &Path) -> Result<u64> {
    // TODO(0.5.0): use clonefile(2) for instant, copy-on-write file cloning
    // on APFS. Falls back to std::fs::copy for now.
    std::fs::copy(src, dst).map_err(Error::Io)
}

// ──────────────────────────────────────────────────────────────────────────────
// Probes
// ──────────────────────────────────────────────────────────────────────────────

// ──────────────────────────────────────────────────────────────────────────────
// Storage-engine primitives — preallocate + advise
// ──────────────────────────────────────────────────────────────────────────────

/// macOS preallocate via `fcntl(F_PREALLOCATE)`. Tries
/// contiguous allocation first (`F_ALLOCATECONTIG`); falls back
/// to non-contiguous (`F_ALLOCATEALL`) if the contiguous request
/// can't be satisfied.
pub(crate) fn preallocate(file: &File, offset: u64, len: u64) -> Result<()> {
    if len == 0 {
        return Ok(());
    }
    // macOS preallocation goes through `fcntl(F_PREALLOCATE)` with
    // an `fstore_t` describing the request. The `fst_posmode` field
    // selects how `fst_offset` is interpreted:
    //   - `F_PEOFPOSMODE` (3): allocate `fst_length` bytes past the
    //     current logical EOF. `fst_offset` is unused.
    //   - `F_VOLPOSMODE`  (4): allocate at a specific volume-physical
    //     offset (advanced use; typically rejected with EINVAL on
    //     ordinary files).
    //
    // For our semantic — reserve disk extents for an append-only
    // journal — `F_PEOFPOSMODE` is the correct mode. The caller's
    // `offset` parameter is interpreted as "additional bytes past
    // current EOF", which on a fresh / append-only file matches
    // the Linux `fallocate(offset, len)` behaviour for the usual
    // calling shape (`preallocate(0, total_journal_size)`).
    #[repr(C)]
    struct Fstore {
        fst_flags: u32,
        fst_posmode: i32,
        fst_offset: libc::off_t,
        fst_length: libc::off_t,
        fst_bytesalloc: libc::off_t,
    }
    const F_PREALLOCATE: libc::c_int = 42;
    const F_ALLOCATECONTIG: u32 = 0x0000_0002;
    const F_ALLOCATEALL: u32 = 0x0000_0004;
    const F_PEOFPOSMODE: i32 = 3;

    let fd = file.as_raw_fd();
    // Reserve `offset + len` bytes past current EOF — this covers
    // both the typical `preallocate(0, total)` case and the
    // less-common `preallocate(off, len)` case where the caller
    // wants extents reserved for a region they'll write later.
    let total_to_reserve = offset.saturating_add(len) as libc::off_t;
    let mut store = Fstore {
        fst_flags: F_ALLOCATECONTIG | F_ALLOCATEALL,
        fst_posmode: F_PEOFPOSMODE,
        fst_offset: 0,
        fst_length: total_to_reserve,
        fst_bytesalloc: 0,
    };
    // SAFETY: fd is valid; F_PREALLOCATE expects an `fstore_t *`
    // and reads/writes only that struct.
    let ret = unsafe { libc::fcntl(fd, F_PREALLOCATE, &mut store) };
    if ret == 0 {
        return Ok(());
    }
    // Contiguous allocation failed — retry without F_ALLOCATECONTIG.
    store.fst_flags = F_ALLOCATEALL;
    store.fst_bytesalloc = 0;
    // SAFETY: same as above.
    let ret = unsafe { libc::fcntl(fd, F_PREALLOCATE, &mut store) };
    if ret == 0 {
        Ok(())
    } else {
        Err(Error::Io(std::io::Error::last_os_error()))
    }
}

/// macOS advise — limited surface vs Linux. Sequential / WillNeed
/// map to `F_RDADVISE`; DontNeed maps to a temporary `F_NOCACHE`
/// flip; Random and Normal are best-effort no-ops.
pub(crate) fn advise(file: &File, offset: u64, len: u64, advice: crate::Advice) -> Result<()> {
    let fd = file.as_raw_fd();
    match advice {
        crate::Advice::Sequential | crate::Advice::WillNeed => {
            // F_RDADVISE: struct radvisory { off_t ra_offset; int ra_count; }
            #[repr(C)]
            struct Radvisory {
                ra_offset: libc::off_t,
                ra_count: libc::c_int,
            }
            const F_RDADVISE: libc::c_int = 44;
            let count = if len == 0 || len > i32::MAX as u64 {
                i32::MAX
            } else {
                len as i32
            };
            let mut adv = Radvisory {
                ra_offset: offset as libc::off_t,
                ra_count: count,
            };
            // SAFETY: fd is valid; F_RDADVISE expects a radvisory pointer.
            let ret = unsafe { libc::fcntl(fd, F_RDADVISE, &mut adv) };
            if ret == 0 {
                Ok(())
            } else {
                // Best-effort: failure isn't fatal.
                Ok(())
            }
        }
        crate::Advice::DontNeed => {
            // No direct equivalent on macOS; closest is
            // toggling F_NOCACHE which affects the *handle*'s
            // future reads, not a region. We accept this as a
            // best-effort no-op rather than mutating handle
            // state silently.
            let _ = (fd, offset, len);
            Ok(())
        }
        crate::Advice::Random | crate::Advice::Normal => Ok(()),
    }
}

pub(crate) fn probe_sector_size(path: &Path) -> u32 {
    use libc::statfs;

    let path_cstr = match path_to_cstr(path) {
        Ok(c) => c,
        Err(_) => return 512,
    };

    let mut st: statfs = unsafe { std::mem::zeroed() };
    // SAFETY: path_cstr is valid NUL-terminated; st is properly sized.
    let ret = unsafe { libc::statfs(path_cstr.as_ptr(), &mut st) };
    if ret == 0 && st.f_bsize > 0 {
        let bs = st.f_bsize as u64;
        if bs >= 512 && bs <= 65536 {
            return bs as u32;
        }
    }
    512
}

pub(crate) fn probe_direct_io_available() -> bool {
    // F_NOCACHE is available on all macOS versions supported by fsys.
    true
}

// ──────────────────────────────────────────────────────────────────────────────
// Internal helper
// ──────────────────────────────────────────────────────────────────────────────

fn path_to_cstr(path: &Path) -> Result<std::ffi::CString> {
    use std::os::unix::ffi::OsStrExt;
    std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(|_| Error::InvalidPath {
        path: path.to_owned(),
        reason: "path contains an interior NUL byte".into(),
    })
}

// ──────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    fn tmp_path(suffix: &str) -> std::path::PathBuf {
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!(
            "fsys_macos_{}_{}_{}",
            std::process::id(),
            n,
            suffix
        ))
    }

    struct TmpFile(std::path::PathBuf);
    impl Drop for TmpFile {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.0);
        }
    }

    #[test]
    fn test_open_write_new_creates_file() {
        let path = tmp_path("create");
        let _g = TmpFile(path.clone());
        let (f, _) = open_write_new(&path, false).expect("open");
        drop(f);
        assert!(path.exists());
    }

    #[test]
    fn test_write_read_roundtrip() {
        let path = tmp_path("rw");
        let _g = TmpFile(path.clone());
        let (f, _) = open_write_new(&path, false).expect("open");
        write_all(&f, b"macos").expect("write");
        drop(f);
        let (rf, _) = open_read(&path, false).expect("read open");
        let data = read_all(&rf).expect("read");
        assert_eq!(data, b"macos");
    }

    #[test]
    fn test_sync_full_does_not_panic() {
        let path = tmp_path("sync");
        let _g = TmpFile(path.clone());
        let (f, _) = open_write_new(&path, false).expect("open");
        write_all(&f, b"sync test").expect("write");
        sync_full(&f).expect("sync_full");
    }

    #[test]
    fn test_atomic_rename_works() {
        let src = tmp_path("ren_src");
        let dst = tmp_path("ren_dst");
        let _gs = TmpFile(src.clone());
        let _gd = TmpFile(dst.clone());
        std::fs::write(&src, b"new content").expect("write");
        atomic_rename(&src, &dst).expect("rename");
        assert!(!src.exists());
        assert_eq!(std::fs::read(&dst).expect("read"), b"new content");
    }

    #[test]
    fn test_probe_sector_size_returns_at_least_512() {
        let size = probe_sector_size(Path::new("/tmp"));
        assert!(size >= 512);
    }

    #[test]
    fn test_copy_file_produces_correct_content() {
        let src = tmp_path("cp_src");
        let dst = tmp_path("cp_dst");
        let _gs = TmpFile(src.clone());
        let _gd = TmpFile(dst.clone());
        std::fs::write(&src, b"copy content").expect("write");
        let bytes = copy_file(&src, &dst).expect("copy");
        assert_eq!(bytes, 12);
    }
}