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
//! Per-platform IO primitives.
//!
//! This module provides a uniform `pub(crate)` interface over the
//! platform-specific IO operations that fsys needs: direct-IO file opening,
//! positioned read/write, durability flushes, atomic rename, parent-directory
//! sync, optimised file copy, and sector-size probing.
//!
//! Each submodule implements the same set of functions for its target OS.
//! The active submodule is aliased to `imp` and its symbols are re-exported
//! from this module so callers can write `crate::platform::open_write_new(…)`
//! without knowing which platform is active.
//!
//! # Platform-specific behavior
//!
//! - **Linux** (`platform/linux.rs`): `O_DIRECT`, `pwrite`/`pread`,
//! `fdatasync`, `fsync`, `copy_file_range`, `renameat2`-with-fallback.
//! - **macOS** (`platform/macos.rs`): `F_NOCACHE`, `pwrite`/`pread`,
//! `F_FULLFSYNC`, `clonefile`-with-fallback.
//! - **Windows** (`platform/windows.rs`): `CreateFileW` with
//! `FILE_FLAG_NO_BUFFERING|WRITE_THROUGH`, `ReadFile`/`WriteFile`,
//! `FlushFileBuffers`, `MoveFileExW`.
//! - **Unknown** (`platform/unknown.rs`): pure `std::fs` fallback.
use linux as imp;
// io_uring wrapper — Linux only. Lazy-init per-Handle ring used by
// `Method::Direct`'s elite path (locked decision #1 in
// `.dev/DECISIONS-0.5.0.md`). Falls back to `pwrite` + `fdatasync`
// when `io_uring_setup(2)` is unavailable.
pub
// io_uring kernel-feature probe — Linux only. Runs a single
// process-wide probe (cached via OnceLock) for the elite setup
// flags COOP_TASKRUN / SINGLE_ISSUER / DEFER_TASKRUN, then
// applies the supported subset to every ring built by the
// crate. New in 0.9.4.
pub
use macos as imp;
use windows as imp;
// Windows NVMe passthrough flush via `IOCTL_STORAGE_PROTOCOL_COMMAND`
// (locked decision D-2 in `.dev/DECISIONS-0.6.0.md`). Capability
// detection at first Direct op; falls back to
// `FILE_FLAG_WRITE_THROUGH` when the IOCTL is unavailable.
pub
use unknown as imp;
// ──────────────────────────────────────────────────────────────────────────────
// Aligned-buffer utility for Direct IO.
//
// Direct IO requires that buffer address, length, and file offset are all
// multiples of the logical sector size (typically 512 or 4096 bytes).
// When the caller's data does not meet these requirements, fsys allocates a
// heap-aligned scratch buffer, copies the data in, and writes from the aligned
// address.
//
// Allocation cost: one `alloc + dealloc` per Direct IO operation on
// unaligned input. The 64 KiB stack-buffer optimisation is deferred to
// 0.5.0; all Direct IO alignment uses heap allocation in 0.3.0.
// ──────────────────────────────────────────────────────────────────────────────
use ;
use NonNull;
/// Heap-allocated buffer with a guaranteed minimum alignment.
///
/// Wraps a raw allocation so the memory is freed on drop even if the
/// operation fails part-way through.
pub
// SAFETY: `AlignedBuf` owns its allocation exclusively (the
// pointer is never duplicated; `Drop` is the only deallocator),
// so transferring ownership across threads is sound — same
// reasoning as `Vec<u8>`. `NonNull<u8>` is `!Send + !Sync` by
// default only because it might in general represent an aliased
// pointer; here it does not.
unsafe
// SAFETY: shared `&AlignedBuf` access is read-only via
// `as_slice`, which is the same access shape as `&[u8]`. No
// interior mutability is possible.
unsafe
/// Rounds `n` up to the next multiple of `align`.
///
/// `align` must be a power of two and non-zero.
pub
// ──────────────────────────────────────────────────────────────────────────────
// Public(crate) cross-platform API — delegates to the active platform module.
// ──────────────────────────────────────────────────────────────────────────────
/// Opens `path` for writing as a new (must-not-exist) file.
///
/// Returns the file and a flag indicating whether Direct IO was actually
/// activated. When `use_direct` is `true` but the filesystem rejects it
/// (e.g. tmpfs on Linux), the file is re-opened without Direct IO and the
/// returned flag is `false`.
///
/// # Platform-specific behavior
///
/// - Linux: `O_WRONLY|O_CREAT|O_EXCL`, optionally `|O_DIRECT`.
/// - macOS: standard create-new open, then `fcntl(F_NOCACHE, 1)` when
/// `use_direct` is true.
/// - Windows: `CreateFileW(CREATE_NEW)`, optionally with
/// `FILE_FLAG_NO_BUFFERING|FILE_FLAG_WRITE_THROUGH`.
/// - Unknown: `std::fs::OpenOptions` create-new.
pub
/// Opens `path` for reading.
///
/// Returns the file and a flag indicating whether Direct IO is active.
///
/// # Platform-specific behavior
///
/// Same Direct IO semantics as [`open_write_new`], but with read-only access.
pub
/// Opens `path` for appending (creates if missing).
///
/// Always uses standard (non-Direct) IO. `O_APPEND` / `FILE_APPEND_DATA`
/// ensures OS-level atomicity for writes up to `PIPE_BUF` bytes on POSIX.
pub
/// Opens `path` for random-access writing (existing file, no truncation).
///
/// Used by [`crate::Handle::write_at`]. Direct IO is **not** used here
/// because arbitrary offsets would require a costly read-modify-write cycle
/// on every unaligned access. See the `write_at` doc comment for details.
pub
/// Writes `data` to `file` using standard (buffered) IO.
///
/// Used when Direct IO is not active.
pub
/// Writes `data` to `file` using Direct IO, with internal alignment handling.
///
/// If `data` length is not a multiple of `sector_size`, the remainder is
/// zero-padded in an aligned scratch buffer before the write. This matches
/// the kernel's requirement that every `O_DIRECT` write is sector-aligned.
///
/// # Platform-specific behavior
///
/// - Linux: `pwrite(2)` with an aligned buffer; offset 0.
/// - macOS: standard `write(2)` on an `F_NOCACHE` fd; alignment handled by
/// zero-padding to sector boundary.
/// - Windows: `WriteFile` through a `FILE_FLAG_NO_BUFFERING` handle with an
/// aligned buffer.
/// - Unknown: delegates to [`write_all`] (no Direct IO on unknown platforms).
pub
/// Writes `data` to `file` at `offset` bytes using standard IO.
///
/// Uses `pwrite(2)` on Unix and `SetFilePointerEx` + `WriteFile` on
/// Windows. This is **not** crash-atomic — a power failure mid-write
/// may leave the file in a partially updated state. Callers that need
/// crash safety should use [`crate::Handle::write`] instead.
pub
/// Sector-aligned positioned write for Direct IO file handles.
///
/// **Pre-conditions** (caller-enforced — not validated here on the
/// hot path; violations surface as kernel `EINVAL`):
/// - `data.as_ptr()` is sector-aligned.
/// - `data.len()` is a multiple of the underlying device's sector size.
/// - `offset` is a multiple of the sector size.
///
/// Used by the direct-IO journal log buffer (`JournalOptions::direct(true)`),
/// which owns an `AlignedBuf` and flushes only at sector boundaries.
pub
/// Reads the entire content of `file` into a `Vec<u8>`.
pub
/// Reads the entire content of `file` into a `Vec<u8>` using Direct IO.
///
/// Allocates an aligned buffer of `file_size` rounded up to the next
/// sector boundary, reads, then trims to `file_size`.
pub
/// Reads `len` bytes from `file` starting at `offset`.
pub
/// Flushes data-only (equivalent of `fdatasync`).
///
/// On platforms without `fdatasync` (macOS, Windows), falls back to a
/// full flush. The caller is responsible for updating `active_method()`
/// when this fallback occurs.
pub
/// Full file flush (equivalent of `fsync` / `F_FULLFSYNC`).
pub
/// 0.9.4 — Sets the per-file NVMe write-lifetime hint
/// (`F_SET_RW_HINT` on Linux).
///
/// `hint_ordinal` is the 0-based discriminant of
/// [`crate::WriteLifetimeHint`]:
/// `0 = Short`, `1 = Medium`, `2 = Long`, `3 = Extreme`.
///
/// **Platforms:**
/// - **Linux**: applies the `F_SET_RW_HINT` fcntl. Failure
/// (older kernels, drives without multi-stream, FS rejection)
/// returns `Err` — the journal-open path swallows the error
/// because the hint is advisory.
/// - **macOS / Windows / unknown**: silent no-op. The hint
/// primitive doesn't exist; returning `Ok(())` is the honest
/// answer (we successfully did nothing).
pub
/// 0.9.4 — Barrier-grade sync. Cheaper than [`sync_full`]
/// where the platform supports it.
///
/// **Platform mapping:**
/// - **macOS:** `fcntl(F_BARRIERFSYNC)` — ordering guarantee
/// without forcing the drive to flush its write cache to
/// media. Crash-safe **only** on drives with PLP (or when
/// paired with an eventual `sync_full` at a commit
/// boundary). Dramatically cheaper than `F_FULLFSYNC` on
/// Apple Silicon NVMe.
/// - **Linux:** `fdatasync(2)` — already barrier-grade by
/// default; same as `sync_data`.
/// - **Windows:** no-op. `FILE_FLAG_WRITE_THROUGH` already
/// provides durable-on-return semantics for every write;
/// there is no separate barrier primitive to call.
/// - **Unknown:** falls back to `sync_data`.
///
/// **Used internally** by [`crate::JournalHandle::sync_through`]
/// when the journal was opened with
/// `JournalOptions::sync_mode(SyncMode::Barrier)`. The default
/// `SyncMode::Full` retains the pre-0.9.4 behaviour (every
/// `sync_through` calls `sync_data` → `fsync`/`F_FULLFSYNC`).
pub
/// Atomically renames `from` to `to`, replacing `to` if it exists.
///
/// # Platform-specific behavior
///
/// - Unix: POSIX `rename(2)`, which is atomic within the same filesystem.
/// - Windows: `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING |
/// MOVEFILE_WRITE_THROUGH`.
pub
/// Opens the parent directory and calls `fsync` on it.
///
/// Required on Linux and macOS after an atomic rename to guarantee that the
/// directory entry update is durable. No-op on Windows (directory durability
/// is implicit with `WRITE_THROUGH`) and on unknown platforms.
pub
/// Copies `src` to `dst` using the best available platform primitive.
///
/// # Platform-specific behavior
///
/// - Linux: `copy_file_range(2)` for same-filesystem copies; `std::fs::copy`
/// fallback.
/// - macOS: `clonefile(2)` when available; `std::fs::copy` fallback.
/// - Windows/Unknown: `std::fs::copy`.
pub
/// Probes the logical sector / block size for the filesystem hosting `path`.
///
/// Returns a conservative default of `512` when the probe is unavailable.
/// The sector size is used to set up aligned scratch buffers for Direct IO.
pub
/// Returns `true` when Direct IO is potentially available on this platform.
///
/// A `true` result means the kernel-level API exists; actual availability
/// depends on the filesystem and is confirmed at file-open time.
pub
// ─────────────────────────────────────────────────────────────────────────
// Storage-engine primitives — extent preallocation + access-pattern hints
// ─────────────────────────────────────────────────────────────────────────
/// Pre-allocates `len` bytes of disk space for `file` starting at
/// `offset`. Reserves filesystem extents up-front so subsequent writes
/// don't trigger allocation in the IO hot path. Critical for
/// high-throughput WAL workloads where allocation jitter creates
/// long-tail latency.
///
/// # Platform-specific behavior
///
/// - **Linux:** `fallocate(fd, FALLOC_FL_KEEP_SIZE, offset, len)` —
/// reserves extents without changing the logical file size. The
/// journal can then write into the pre-allocated region knowing the
/// filesystem won't need to allocate blocks mid-write. On
/// filesystems that don't support fallocate (some FUSE, network),
/// falls back to `posix_fallocate` which writes zeros.
/// - **macOS:** `fcntl(fd, F_PREALLOCATE, ...)` with
/// `F_ALLOCATECONTIG | F_ALLOCATEALL` flags. Falls back to
/// `F_ALLOCATEALL` alone if contiguous allocation fails.
/// - **Windows:** `SetEndOfFile` to extend the logical size. True
/// physical preallocation requires `SetFileValidData` which
/// needs the `SE_MANAGE_VOLUME_NAME` privilege; we use it only
/// when the privilege is detected (caller running as
/// administrator). Without the privilege the kernel allocates
/// on the first write — same as not calling preallocate.
/// - **Unknown:** no-op (succeeds; the OS allocates on write).
///
/// # Errors
///
/// - [`Error::Io`](crate::Error::Io) on the underlying syscall failure.
pub
/// Hints the kernel about how `file` will be accessed in the
/// `[offset, offset+len)` byte range. The kernel uses these hints
/// to drive page-cache pre-fetch, eviction, and read-ahead policy.
///
/// `len = 0` means "the rest of the file from `offset` onward."
///
/// See [`Advice`] for the available hint variants.
pub