ab_direct_io_file/lib.rs
1//! Cross-platform APIs for working with files using direct I/O.
2//!
3//! Depending on OS, this will use direct I/O, unbuffered, uncaches passthrough file reads/writes,
4//! bypassing as much of OS machinery as possible.
5//!
6//! NOTE: There are major alignment requirements described here:
7//! <https://learn.microsoft.com/en-us/windows/win32/fileio/file-buffering#alignment-and-file-access-requirements>
8//! <https://man7.org/linux/man-pages/man2/open.2.html>
9//!
10//! APIs deliberately only take page-aligned buffers ([`OwnedPages`]) or buffers that are as
11//! unaligned in memory as the offset is in the file, so whole pages go to and from disk without
12//! copies and there is no need to handle arbitrarily aligned input. Only partially written pages at
13//! the edges of a write are copied, see [`DirectIoFile::write_at()`].
14
15#![feature(core_io_borrowed_buf)]
16#![cfg_attr(unix, feature(read_buf_at))]
17#![cfg_attr(windows, feature(seek_read_exact_seek_write_all))]
18
19// TODO: Windows shims are incomplete under Miri: https://github.com/rust-lang/miri/issues/3482
20#[cfg(all(test, not(all(miri, windows))))]
21mod tests;
22
23use ab_aligned_buffer::alignment::{Align1, Align4096};
24use ab_aligned_buffer::{AlignedBuffer, AllocationError, OwnedAlignedBuffer, SharedAlignedBuffer};
25use parking_lot::Mutex;
26use std::fs::{File, OpenOptions};
27use std::io::BorrowedBuf;
28#[cfg(unix)]
29use std::os::unix::fs::FileExt;
30#[cfg(windows)]
31use std::os::windows::fs::FileExt;
32use std::path::Path;
33use std::{io, mem};
34
35/// Page of memory aligned to its size, used for read-modify-write of partially written pages
36#[repr(C, align(4096))]
37struct Page([u8; OwnedPages::ALIGN as usize]);
38
39const _: () = {
40 assert!(align_of::<Page>() == OwnedPages::ALIGN as usize);
41};
42
43/// Owned buffer of pages, which are the unit of direct I/O.
44///
45/// The size of a page is the alignment of the buffer, [`OwnedPages::ALIGN`] bytes. 4096 bytes is a
46/// relatively safe size due to sector size on SSDs commonly being 512 or 4096 bytes.
47pub type OwnedPages = OwnedAlignedBuffer<Align4096>;
48/// Shared buffer of pages, see [`OwnedPages`]
49pub type SharedPages = SharedAlignedBuffer<Align4096>;
50
51/// Error of a direct I/O operation
52#[derive(Debug, thiserror::Error)]
53pub enum DirectIoError {
54 /// Failed to allocate a buffer
55 #[error("Failed to allocate a buffer: {0}")]
56 AllocationFailed(#[from] AllocationError),
57 /// I/O error
58 #[error("I/O error: {0}")]
59 Io(#[from] io::Error),
60}
61
62impl From<DirectIoError> for io::Error {
63 #[inline]
64 fn from(error: DirectIoError) -> Self {
65 match error {
66 DirectIoError::AllocationFailed(_) => io::Error::new(io::ErrorKind::OutOfMemory, error),
67 DirectIoError::Io(error) => error,
68 }
69 }
70}
71
72/// Error of an operation that takes a buffer by value, which is returned back, so that its
73/// allocation can be reused
74#[derive(Debug, thiserror::Error)]
75#[error("{error}")]
76pub struct IoBufError<B> {
77 /// Low-level error
78 pub error: DirectIoError,
79 /// Buffer that was given to the operation
80 pub buffer: B,
81}
82
83impl<B> From<IoBufError<B>> for io::Error {
84 #[inline]
85 fn from(error: IoBufError<B>) -> Self {
86 error.error.into()
87 }
88}
89
90/// Wrapper data structure for direct/unbuffered/uncached I/O.
91///
92/// Depending on OS, this will use direct I/O, unbuffered, uncaches passthrough file reads/writes,
93/// bypassing as much of OS machinery as possible.
94///
95/// NOTE: There are major alignment requirements described here:
96/// <https://learn.microsoft.com/en-us/windows/win32/fileio/file-buffering#alignment-and-file-access-requirements>
97/// <https://man7.org/linux/man-pages/man2/open.2.html>
98#[derive(Debug)]
99pub struct DirectIoFile {
100 file: File,
101 /// Serializes read-modify-write of partially written pages
102 partial_pages: Mutex<()>,
103}
104
105impl DirectIoFile {
106 /// Open a file with basic open options at the specified path for direct/unbuffered I/O for
107 /// reads and writes.
108 ///
109 /// `options` allows configuring things like read/write/create/truncate, but custom options
110 /// will be overridden internally.
111 ///
112 /// This is especially important on Windows to prevent huge memory usage.
113 #[inline]
114 pub fn open<P>(
115 #[cfg(any(target_os = "linux", windows))] mut options: OpenOptions,
116 #[cfg(not(any(target_os = "linux", windows)))] options: OpenOptions,
117 path: P,
118 ) -> io::Result<Self>
119 where
120 P: AsRef<Path>,
121 {
122 // Direct I/O on Linux
123 #[cfg(target_os = "linux")]
124 // TODO: Unlock under Miri once supported: https://github.com/rust-lang/miri/issues/4462
125 if !cfg!(miri) {
126 use std::os::unix::fs::OpenOptionsExt;
127
128 options.custom_flags(libc::O_DIRECT);
129 }
130 // Unbuffered write-through on Windows
131 #[cfg(windows)]
132 // TODO: Unlock under Miri once supported: https://github.com/rust-lang/miri/issues/4462
133 if !cfg!(miri) {
134 use std::os::windows::fs::OpenOptionsExt;
135
136 options.custom_flags(
137 windows::Win32::Storage::FileSystem::FILE_FLAG_WRITE_THROUGH.0
138 | windows::Win32::Storage::FileSystem::FILE_FLAG_NO_BUFFERING.0,
139 );
140 }
141 let file = options.open(path)?;
142
143 // Disable caching on macOS
144 #[cfg(target_os = "macos")]
145 // TODO: Unlock under Miri once supported: https://github.com/rust-lang/miri/issues/4462
146 if !cfg!(miri) {
147 use std::os::unix::io::AsRawFd;
148
149 // SAFETY: FFI call with correct file descriptor and arguments
150 if unsafe { libc::fcntl(file.as_raw_fd(), libc::F_NOCACHE, 1) } != 0 {
151 return Err(io::Error::last_os_error());
152 }
153 }
154
155 Ok(Self {
156 file,
157 partial_pages: Mutex::new(()),
158 })
159 }
160
161 /// Get file size, which is the size of the whole device for a block device (see
162 /// [`Self::is_block_device()`])
163 #[inline]
164 pub fn len(&self) -> io::Result<u64> {
165 cfg_select! {
166 unix => {
167 use std::os::unix::fs::FileTypeExt;
168
169 let metadata = self.file.metadata()?;
170 if metadata.file_type().is_block_device() {
171 self.block_device_len()
172 } else {
173 Ok(metadata.len())
174 }
175 }
176 windows => {
177 match self.file.metadata() {
178 Ok(metadata) => Ok(metadata.len()),
179 // File information is not available for disks, volumes and partitions
180 Err(_error) => self.block_device_len(),
181 }
182 }
183 _ => {
184 compile_error!("Unsupported platform (consider contributing)")
185 }
186 }
187 }
188
189 /// Returns `Ok(true)` if the file is a block device.
190 ///
191 /// On Windows these are disks, volumes and partitions opened with paths like
192 /// `\\.\PhysicalDrive0` or `\\.\C:`. A block device has a fixed size, it can't be allocated or
193 /// resized.
194 #[inline]
195 pub fn is_block_device(&self) -> io::Result<bool> {
196 cfg_select! {
197 unix => {
198 use std::os::unix::fs::FileTypeExt;
199
200 Ok(self.file.metadata()?.file_type().is_block_device())
201 }
202 windows => {
203 match self.file.metadata() {
204 Ok(_metadata) => Ok(false),
205 // File information is not available for disks, volumes and partitions
206 Err(_error) => self.block_device_len().map(|_len| true),
207 }
208 }
209 _ => {
210 compile_error!("Unsupported platform (consider contributing)")
211 }
212 }
213 }
214
215 /// Get the size of a block device
216 fn block_device_len(&self) -> io::Result<u64> {
217 cfg_select! {
218 target_os = "linux" => {
219 use std::io::{Seek, SeekFrom};
220
221 // The end of a block device is its size. The position in the file doesn't matter,
222 // reads and writes are positional.
223 (&self.file).seek(SeekFrom::End(0))
224 }
225 target_os = "macos" => {
226 use std::os::unix::io::AsRawFd;
227
228 // `_IOR('d', 24, uint32_t)` and `_IOR('d', 25, uint64_t)` from `<sys/disk.h>`
229 const DKIOCGETBLOCKSIZE: libc::c_ulong = 0x4004_6418;
230 const DKIOCGETBLOCKCOUNT: libc::c_ulong = 0x4008_6419;
231
232 let mut block_size = 0_u32;
233 // SAFETY: The file descriptor is open while `self.file` is alive, the request
234 // writes a `u32` into the location of a local `u32`
235 if unsafe {
236 libc::ioctl(
237 self.file.as_raw_fd(),
238 DKIOCGETBLOCKSIZE,
239 &raw mut block_size,
240 )
241 } != 0
242 {
243 return Err(io::Error::last_os_error());
244 }
245 let mut block_count = 0_u64;
246 // SAFETY: The file descriptor is open while `self.file` is alive, the request
247 // writes a `u64` into the location of a local `u64`
248 if unsafe {
249 libc::ioctl(
250 self.file.as_raw_fd(),
251 DKIOCGETBLOCKCOUNT,
252 &raw mut block_count,
253 )
254 } != 0
255 {
256 return Err(io::Error::last_os_error());
257 }
258
259 block_count
260 .checked_mul(u64::from(block_size))
261 .ok_or_else(|| {
262 io::Error::new(
263 io::ErrorKind::InvalidData,
264 "Block device size overflows `u64`",
265 )
266 })
267 }
268 windows => {
269 use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
270 use windows::Win32::Foundation::{ERROR_IO_PENDING, HANDLE, WIN32_ERROR};
271 use windows::Win32::System::IO::{
272 DeviceIoControl, GetOverlappedResult, OVERLAPPED,
273 };
274 use windows::Win32::System::Ioctl::{
275 GET_LENGTH_INFORMATION, IOCTL_DISK_GET_LENGTH_INFO,
276 };
277 use windows::Win32::System::Threading::CreateEventW;
278
279 // Checked at compile time, the structure is 8 bytes
280 const LENGTH_INFO_SIZE: u32 = {
281 assert!(u32::MAX as usize >= size_of::<GET_LENGTH_INFORMATION>());
282 size_of::<GET_LENGTH_INFORMATION>() as u32
283 };
284
285 // `io::Error::from()` would keep the `HRESULT` instead of the Win32 error code
286 let to_io_error =
287 |error: windows::core::Error| match WIN32_ERROR::from_error(&error) {
288 Some(code) => io::Error::from_raw_os_error(code.0.cast_signed()),
289 None => io::Error::other(error),
290 };
291
292 let handle = HANDLE(self.file.as_raw_handle());
293
294 // A request through a handle opened for overlapped I/O completes asynchronously,
295 // it is waited for with a dedicated event, such that other requests through the
296 // same handle don't end the wait early
297 // SAFETY: FFI call without pointers that creates a new event
298 let event =
299 unsafe { CreateEventW(None, true, false, None) }.map_err(to_io_error)?;
300 // SAFETY: The event was just created and is owned by nothing else
301 let _event = unsafe { OwnedHandle::from_raw_handle(event.0) };
302 let mut overlapped = OVERLAPPED {
303 hEvent: event,
304 ..OVERLAPPED::default()
305 };
306 let mut length_info = GET_LENGTH_INFORMATION::default();
307 let mut bytes_returned = 0_u32;
308
309 // SAFETY: The file handle and the event are open until the end of this function.
310 // The output buffer is a local `GET_LENGTH_INFORMATION` of the size given, which is
311 // what the request writes. `overlapped` and the output buffer outlive the request:
312 // it either completes before `DeviceIoControl()` returns or is waited for below.
313 let result = unsafe {
314 DeviceIoControl(
315 handle,
316 IOCTL_DISK_GET_LENGTH_INFO,
317 None,
318 0,
319 Some((&raw mut length_info).cast()),
320 LENGTH_INFO_SIZE,
321 Some(&raw mut bytes_returned),
322 Some(&raw mut overlapped),
323 )
324 };
325 if let Err(error) = result {
326 if error.code() != ERROR_IO_PENDING.to_hresult() {
327 return Err(to_io_error(error));
328 }
329
330 // SAFETY: The file handle and the event are open until the end of this
331 // function, `overlapped` is the one the pending request was started with.
332 // With `bWait` the function doesn't return until the request has completed.
333 unsafe {
334 GetOverlappedResult(
335 handle,
336 &raw const overlapped,
337 &raw mut bytes_returned,
338 true,
339 )
340 }
341 .map_err(to_io_error)?;
342 }
343
344 u64::try_from(length_info.Length)
345 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
346 }
347 _ => Err(io::Error::from(io::ErrorKind::Unsupported)),
348 }
349 }
350
351 /// Returns `Ok(true)` if the file is empty
352 #[inline]
353 pub fn is_empty(&self) -> io::Result<bool> {
354 Ok(self.len()? == 0)
355 }
356
357 /// Truncates or extends the underlying file, updating the size of this file to become `len`.
358 ///
359 /// Note if `len` is larger than the previous file size, it will result in a sparse file. To
360 /// allocate space on disk, use a crate like `fs4` with [`Self::file()`], which may be followed
361 /// by this method to truncate the file if the new file size is smaller than the previous
362 /// (allocation doesn't truncate the file).
363 #[inline(always)]
364 pub fn set_len(&self, len: u64) -> io::Result<()> {
365 self.file.set_len(len)
366 }
367
368 /// The file direct I/O happens on, for operations this type doesn't wrap, like locking or
369 /// allocation of disk space.
370 ///
371 /// Reads and writes through it bypass the alignment handling of this type.
372 #[inline(always)]
373 pub fn file(&self) -> &File {
374 &self.file
375 }
376
377 /// Read `len` bytes at `offset` into `buffer`, replacing its contents.
378 ///
379 /// Whole pages that cover the requested bytes are read into the buffer, which grows if it
380 /// doesn't have enough capacity. Existing contents are discarded, so they are never copied.
381 /// The returned buffer contains exactly the requested bytes, which start at
382 /// `offset % OwnedPages::ALIGN` from the beginning of the data region of its page-aligned
383 /// allocation, see [`OwnedAlignedBuffer::into_empty()`] for reusing it for the next read.
384 ///
385 /// All pages that cover the requested bytes must exist in the file. The buffer is returned
386 /// back on error too.
387 #[inline]
388 pub fn read_at(
389 &self,
390 mut buffer: OwnedPages,
391 len: u32,
392 offset: u64,
393 ) -> Result<OwnedAlignedBuffer<Align1>, IoBufError<OwnedPages>> {
394 if len == 0 {
395 buffer.truncate(0);
396 return Ok(buffer.into_start_align());
397 }
398
399 let head = u32::try_from(offset % u64::from(OwnedPages::ALIGN))
400 .expect("Smaller than the size of a page; qed");
401 let Some((end, span)) = head
402 .checked_add(len)
403 .and_then(|end| Some((end, end.checked_next_multiple_of(OwnedPages::ALIGN)?)))
404 else {
405 return Err(IoBufError {
406 error: AllocationError::CapacityOverflow.into(),
407 buffer,
408 });
409 };
410
411 if let Err(error) = self.read_pages_into(&mut buffer, span, offset - u64::from(head)) {
412 return Err(IoBufError { error, buffer });
413 }
414
415 let mut buffer = buffer.into_start_align::<Align1>();
416 buffer.truncate(end);
417 if !buffer.set_offset(head) {
418 unreachable!(
419 "Contents are `head + len` bytes at the beginning of the data region; qed"
420 );
421 }
422 Ok(buffer)
423 }
424
425 /// Read `num_pages` pages at `page_offset` (in pages) into `buffer`, replacing its contents.
426 ///
427 /// The buffer grows if it doesn't have enough capacity. Existing contents are discarded, so
428 /// they are never copied. All pages must exist in the file. The buffer is returned back on
429 /// error too.
430 #[inline]
431 pub fn read_pages_at(
432 &self,
433 mut buffer: OwnedPages,
434 num_pages: u32,
435 page_offset: u64,
436 ) -> Result<OwnedPages, IoBufError<OwnedPages>> {
437 let Some(len) = num_pages.checked_mul(OwnedPages::ALIGN) else {
438 return Err(IoBufError {
439 error: AllocationError::CapacityOverflow.into(),
440 buffer,
441 });
442 };
443 let Some(offset) = page_offset.checked_mul(u64::from(OwnedPages::ALIGN)) else {
444 return Err(IoBufError {
445 error: io::Error::from(io::ErrorKind::InvalidInput).into(),
446 buffer,
447 });
448 };
449
450 match self.read_pages_into(&mut buffer, len, offset) {
451 Ok(()) => Ok(buffer),
452 Err(error) => Err(IoBufError { error, buffer }),
453 }
454 }
455
456 /// Write the contents of `buffer` at `offset`.
457 ///
458 /// The contents must be as unaligned in memory as `offset` is in the file, both must have the
459 /// same offset within a page, which is the case for a buffer returned by [`Self::read_at()`]
460 /// at the same offset and for page-aligned buffers written at page-aligned offsets, otherwise
461 /// [`io::ErrorKind::InvalidInput`] is returned. Whole pages are written directly from the
462 /// buffer. Partially written pages at the beginning and the end are read from the file first,
463 /// so they must exist in the file, and are written from a page on the stack, serialized with
464 /// other such writes. The buffer is returned back on error too.
465 #[inline]
466 pub fn write_at<B>(&self, buffer: B, offset: u64) -> Result<B, IoBufError<B>>
467 where
468 B: AlignedBuffer,
469 {
470 match self.write_bytes(&buffer, offset) {
471 Ok(()) => Ok(buffer),
472 Err(error) => Err(IoBufError {
473 error: error.into(),
474 buffer,
475 }),
476 }
477 }
478
479 /// Read `len` bytes (whole pages) at page-aligned `offset` into `buffer`, replacing its
480 /// contents
481 fn read_pages_into(
482 &self,
483 buffer: &mut OwnedPages,
484 len: u32,
485 offset: u64,
486 ) -> Result<(), DirectIoError> {
487 // Content is replaced and moved to the beginning of the data region, so nothing is copied
488 // if the buffer has to grow
489 *buffer = mem::take(buffer).into_empty();
490 buffer.try_ensure_capacity(len)?;
491
492 self.read_exact(
493 BorrowedBuf::from(&mut buffer.spare_capacity_mut()[..len as usize]),
494 offset,
495 )?;
496 // SAFETY: `len` bytes were just read
497 unsafe {
498 buffer.set_len(len);
499 }
500
501 Ok(())
502 }
503
504 /// Read exactly the capacity of `buf` at `offset`, `buf` and `offset` are page-aligned and the
505 /// capacity of `buf` is a multiple of the page size
506 fn read_exact(&self, mut buf: BorrowedBuf<'_, u8>, offset: u64) -> io::Result<()> {
507 debug_assert!(
508 offset.is_multiple_of(u64::from(OwnedPages::ALIGN))
509 && buf.capacity().is_multiple_of(OwnedPages::ALIGN as usize)
510 && buf
511 .filled()
512 .as_ptr()
513 .addr()
514 .is_multiple_of(OwnedPages::ALIGN as usize),
515 "Direct I/O requires page alignment"
516 );
517
518 cfg_select! {
519 unix => self.file.read_buf_exact_at(buf.unfilled(), offset),
520 windows => self.file.seek_read_buf_exact(buf.unfilled(), offset),
521 _ => {
522 compile_error!("Unsupported platform (consider contributing)")
523 }
524 }
525 }
526
527 /// Write `bytes` at `offset`, both have the same offset within a page
528 fn write_bytes(&self, mut bytes: &[u8], mut offset: u64) -> io::Result<()> {
529 if bytes.is_empty() {
530 return Ok(());
531 }
532
533 let page = OwnedPages::ALIGN as usize;
534 let head = usize::try_from(offset % u64::from(OwnedPages::ALIGN))
535 .expect("Smaller than the size of a page; qed");
536 if bytes.as_ptr().addr() % page != head {
537 return Err(io::Error::new(
538 io::ErrorKind::InvalidInput,
539 "Bytes have a different offset within a page than the file offset",
540 ));
541 }
542
543 // Offsets are only advanced after a successful write at a smaller offset, which the OS
544 // only accepts far below `u64::MAX`, so they don't overflow
545 if head != 0 {
546 let prefix;
547 (prefix, bytes) = bytes.split_at((page - head).min(bytes.len()));
548 let page_offset = offset - offset % u64::from(OwnedPages::ALIGN);
549 self.write_partial_page(prefix, page_offset, head)?;
550 offset = page_offset + u64::from(OwnedPages::ALIGN);
551 }
552
553 let middle;
554 (middle, bytes) = bytes.split_at(bytes.len() - bytes.len() % page);
555 if !middle.is_empty() {
556 self.write_pages(middle, offset)?;
557 offset += u64::try_from(middle.len()).expect("Buffers are smaller than 4 GiB; qed");
558 }
559
560 if !bytes.is_empty() {
561 self.write_partial_page(bytes, offset, 0)?;
562 }
563
564 Ok(())
565 }
566
567 /// Write whole pages at page-aligned `offset`, `bytes` are page-aligned in memory
568 fn write_pages(&self, bytes: &[u8], offset: u64) -> io::Result<()> {
569 debug_assert!(
570 offset.is_multiple_of(u64::from(OwnedPages::ALIGN))
571 && bytes.len().is_multiple_of(OwnedPages::ALIGN as usize)
572 && bytes
573 .as_ptr()
574 .addr()
575 .is_multiple_of(OwnedPages::ALIGN as usize),
576 "Direct I/O requires page alignment"
577 );
578
579 cfg_select! {
580 unix => self.file.write_all_at(bytes, offset),
581 windows => self.file.seek_write_all(bytes, offset),
582 _ => {
583 compile_error!("Unsupported platform (consider contributing)")
584 }
585 }
586 }
587
588 /// Write `bytes` at `start` within the page at page-aligned `page_offset`, the rest of the
589 /// page is read from the file first
590 fn write_partial_page(&self, bytes: &[u8], page_offset: u64, start: usize) -> io::Result<()> {
591 let mut page = Page([0; _]);
592
593 // Read-modify-write of pages is serialized, such that concurrent writes to different bytes
594 // of the same page don't overwrite each other
595 let _guard = self.partial_pages.lock();
596
597 self.read_exact(BorrowedBuf::from(page.0.as_mut_slice()), page_offset)?;
598 page.0[start..][..bytes.len()].copy_from_slice(bytes);
599 self.write_pages(&page.0, page_offset)
600 }
601}