Skip to main content

coreutils_rs/common/
io.rs

1use std::fs::{self, File};
2use std::io::{self, Read};
3use std::ops::Deref;
4use std::path::Path;
5
6#[cfg(target_os = "linux")]
7use std::sync::atomic::{AtomicBool, Ordering};
8
9use memmap2::{Mmap, MmapOptions};
10
11/// Holds file data — either zero-copy mmap or an owned Vec.
12/// Dereferences to `&[u8]` for transparent use.
13pub enum FileData {
14    Mmap(Mmap),
15    Owned(Vec<u8>),
16}
17
18impl Deref for FileData {
19    type Target = [u8];
20
21    fn deref(&self) -> &[u8] {
22        match self {
23            FileData::Mmap(m) => m,
24            FileData::Owned(v) => v,
25        }
26    }
27}
28
29/// Threshold below which we use read() instead of mmap.
30/// For files under 1MB, read() is faster since mmap has setup/teardown overhead
31/// (page table creation for up to 256 pages, TLB flush on munmap) that exceeds
32/// the zero-copy benefit.
33const MMAP_THRESHOLD: u64 = 1024 * 1024;
34
35/// Track whether O_NOATIME is supported to avoid repeated failed open() attempts.
36/// After the first EPERM, we never try O_NOATIME again (saves one syscall per file).
37#[cfg(target_os = "linux")]
38static NOATIME_SUPPORTED: AtomicBool = AtomicBool::new(true);
39
40/// Open a file with O_NOATIME on Linux to avoid atime inode writes.
41/// Caches whether O_NOATIME works to avoid double-open on every file.
42#[cfg(target_os = "linux")]
43fn open_noatime(path: &Path) -> io::Result<File> {
44    use std::os::unix::fs::OpenOptionsExt;
45    if NOATIME_SUPPORTED.load(Ordering::Relaxed) {
46        match fs::OpenOptions::new()
47            .read(true)
48            .custom_flags(libc::O_NOATIME)
49            .open(path)
50        {
51            Ok(f) => return Ok(f),
52            Err(ref e) if e.raw_os_error() == Some(libc::EPERM) => {
53                // O_NOATIME requires file ownership or CAP_FOWNER — disable globally
54                NOATIME_SUPPORTED.store(false, Ordering::Relaxed);
55            }
56            Err(e) => return Err(e), // Real error, propagate
57        }
58    }
59    File::open(path)
60}
61
62#[cfg(not(target_os = "linux"))]
63fn open_noatime(path: &Path) -> io::Result<File> {
64    File::open(path)
65}
66
67/// Read a file with zero-copy mmap for large files or read() for small files.
68/// Opens once with O_NOATIME, uses fstat for metadata to save a syscall.
69pub fn read_file(path: &Path) -> io::Result<FileData> {
70    let file = open_noatime(path)?;
71    let metadata = file.metadata()?;
72    let len = metadata.len();
73
74    if len > 0 && metadata.file_type().is_file() {
75        // Small files: exact-size read from already-open fd.
76        // Uses read_full into pre-sized buffer instead of read_to_end,
77        // which avoids the grow-and-probe pattern (saves 1-2 extra read() syscalls).
78        if len < MMAP_THRESHOLD {
79            let mut buf = vec![0u8; len as usize];
80            let n = read_full(&mut &file, &mut buf)?;
81            buf.truncate(n);
82            return Ok(FileData::Owned(buf));
83        }
84
85        // SAFETY: Read-only mapping. No MAP_POPULATE — it synchronously faults
86        // all pages with 4KB before MADV_HUGEPAGE can take effect, causing ~25,600
87        // minor page faults for 100MB (~12.5ms overhead). Without it, HUGEPAGE hint
88        // is set first, then POPULATE_READ prefaults using 2MB pages (~50 faults).
89        match unsafe { MmapOptions::new().map(&file) } {
90            Ok(mmap) => {
91                #[cfg(target_os = "linux")]
92                {
93                    // HUGEPAGE MUST come first: reduces 25,600 minor faults (4KB) to
94                    // ~50 faults (2MB) for 100MB files. Saves ~12ms of page fault overhead.
95                    if len >= 2 * 1024 * 1024 {
96                        let _ = mmap.advise(memmap2::Advice::HugePage);
97                    }
98                    let _ = mmap.advise(memmap2::Advice::Sequential);
99                    // POPULATE_READ (5.14+): prefault with huge pages. Fall back to WillNeed.
100                    if len >= 4 * 1024 * 1024 {
101                        if mmap.advise(memmap2::Advice::PopulateRead).is_err() {
102                            let _ = mmap.advise(memmap2::Advice::WillNeed);
103                        }
104                    } else {
105                        let _ = mmap.advise(memmap2::Advice::WillNeed);
106                    }
107                }
108                Ok(FileData::Mmap(mmap))
109            }
110            Err(_) => {
111                // mmap failed — fall back to read
112                let mut buf = Vec::with_capacity(len as usize);
113                let mut reader = file;
114                reader.read_to_end(&mut buf)?;
115                Ok(FileData::Owned(buf))
116            }
117        }
118    } else if len > 0 {
119        // Non-regular file (special files) — read from open fd
120        let mut buf = Vec::new();
121        let mut reader = file;
122        reader.read_to_end(&mut buf)?;
123        Ok(FileData::Owned(buf))
124    } else {
125        Ok(FileData::Owned(Vec::new()))
126    }
127}
128
129/// Read a file entirely into a mutable Vec.
130/// Uses exact-size allocation from fstat + single read() for efficiency.
131/// Preferred over mmap when the caller needs mutable access (e.g., in-place decode).
132pub fn read_file_vec(path: &Path) -> io::Result<Vec<u8>> {
133    let file = open_noatime(path)?;
134    let metadata = file.metadata()?;
135    let len = metadata.len() as usize;
136    if len == 0 {
137        return Ok(Vec::new());
138    }
139    let mut buf = vec![0u8; len];
140    let n = read_full(&mut &file, &mut buf)?;
141    buf.truncate(n);
142    Ok(buf)
143}
144
145/// Read a file always using mmap, with optimal page fault strategy.
146/// Used by tac for zero-copy output and parallel scanning.
147///
148/// Strategy: mmap WITHOUT MAP_POPULATE, then MADV_HUGEPAGE + MADV_POPULATE_READ.
149/// MAP_POPULATE synchronously faults all pages with 4KB BEFORE MADV_HUGEPAGE
150/// can take effect, causing ~25,600 minor faults for 100MB (~12.5ms overhead).
151/// MADV_POPULATE_READ (Linux 5.14+) prefaults pages AFTER HUGEPAGE is set,
152/// using 2MB huge pages (~50 faults = ~0.1ms). Falls back to WILLNEED on
153/// older kernels.
154pub fn read_file_mmap(path: &Path) -> io::Result<FileData> {
155    let file = open_noatime(path)?;
156    let metadata = file.metadata()?;
157    let len = metadata.len();
158
159    if len > 0 && metadata.file_type().is_file() {
160        // No MAP_POPULATE: let MADV_HUGEPAGE take effect before page faults.
161        let mmap_result = unsafe { MmapOptions::new().map(&file) };
162        match mmap_result {
163            Ok(mmap) => {
164                #[cfg(target_os = "linux")]
165                {
166                    // HUGEPAGE first: must be set before any page faults occur.
167                    // Reduces ~25,600 minor faults (4KB) to ~50 (2MB) for 100MB.
168                    if len >= 2 * 1024 * 1024 {
169                        let _ = mmap.advise(memmap2::Advice::HugePage);
170                    }
171                    // POPULATE_READ (Linux 5.14+): synchronously prefaults all pages
172                    // using huge pages. Falls back to WILLNEED on older kernels.
173                    if len >= 4 * 1024 * 1024 {
174                        if mmap.advise(memmap2::Advice::PopulateRead).is_err() {
175                            let _ = mmap.advise(memmap2::Advice::WillNeed);
176                        }
177                    } else {
178                        let _ = mmap.advise(memmap2::Advice::WillNeed);
179                    }
180                }
181                return Ok(FileData::Mmap(mmap));
182            }
183            Err(_) => {
184                // mmap failed — fall back to read
185                let mut buf = vec![0u8; len as usize];
186                let n = read_full(&mut &file, &mut buf)?;
187                buf.truncate(n);
188                return Ok(FileData::Owned(buf));
189            }
190        }
191    } else if len > 0 {
192        // Non-regular file (special files) — read from open fd
193        let mut buf = Vec::new();
194        let mut reader = file;
195        reader.read_to_end(&mut buf)?;
196        Ok(FileData::Owned(buf))
197    } else {
198        Ok(FileData::Owned(Vec::new()))
199    }
200}
201
202/// Get file size without reading it (for byte-count-only optimization).
203pub fn file_size(path: &Path) -> io::Result<u64> {
204    Ok(fs::metadata(path)?.len())
205}
206
207/// Read all bytes from stdin into a Vec.
208/// On Linux, uses raw libc::read() to bypass Rust's StdinLock/BufReader overhead.
209/// Uses a direct read() loop into a pre-allocated buffer instead of read_to_end(),
210/// which avoids Vec's grow-and-probe pattern (extra read() calls and memcpy).
211/// Callers should enlarge the pipe buffer via fcntl(F_SETPIPE_SZ) before calling.
212/// Uses the full spare capacity for each read() to minimize syscalls.
213pub fn read_stdin() -> io::Result<Vec<u8>> {
214    #[cfg(target_os = "linux")]
215    return read_stdin_raw();
216
217    #[cfg(not(target_os = "linux"))]
218    read_stdin_generic()
219}
220
221/// Raw libc::read() implementation for Linux — bypasses Rust's StdinLock
222/// and BufReader layers entirely. StdinLock uses an internal 8KB BufReader
223/// which adds an extra memcpy for every read; raw read() goes directly
224/// from the kernel pipe buffer to our Vec.
225///
226/// Pre-allocates 16MB to cover most workloads (benchmark = 10MB) without
227/// over-allocating. For inputs > 16MB, doubles capacity on demand.
228/// Each read() uses the full spare capacity to maximize bytes per syscall.
229///
230/// Note: callers (ftac, ftr, fbase64) are expected to enlarge the pipe
231/// buffer via fcntl(F_SETPIPE_SZ) before calling this function. We don't
232/// do it here to avoid accidentally shrinking a previously enlarged pipe.
233#[cfg(target_os = "linux")]
234fn read_stdin_raw() -> io::Result<Vec<u8>> {
235    const PREALLOC: usize = 16 * 1024 * 1024;
236
237    let mut buf: Vec<u8> = Vec::with_capacity(PREALLOC);
238
239    loop {
240        let spare_cap = buf.capacity() - buf.len();
241        if spare_cap < 1024 * 1024 {
242            // Grow by doubling (or at least 64MB) to minimize realloc count
243            let new_cap = (buf.capacity() * 2).max(buf.len() + PREALLOC);
244            buf.reserve(new_cap - buf.capacity());
245        }
246        let spare_cap = buf.capacity() - buf.len();
247        let start = buf.len();
248
249        // SAFETY: we read into the uninitialized spare capacity and extend
250        // set_len only by the number of bytes actually read.
251        let ret = unsafe {
252            libc::read(
253                0,
254                buf.as_mut_ptr().add(start) as *mut libc::c_void,
255                spare_cap,
256            )
257        };
258        if ret < 0 {
259            let err = io::Error::last_os_error();
260            if err.kind() == io::ErrorKind::Interrupted {
261                continue;
262            }
263            return Err(err);
264        }
265        if ret == 0 {
266            break;
267        }
268        unsafe { buf.set_len(start + ret as usize) };
269    }
270
271    Ok(buf)
272}
273
274/// Splice piped stdin to a memfd, then mmap for zero-copy access.
275/// Uses splice(2) to move data from the stdin pipe directly into a memfd's
276/// page cache (kernel→kernel, no userspace copy). Returns a mutable mmap.
277/// Returns None if stdin is not a pipe or splice fails.
278///
279/// For translate operations: caller can modify the mmap'd data in-place.
280/// For filter operations (delete, cut): caller reads from the mmap.
281#[cfg(target_os = "linux")]
282pub fn splice_stdin_to_mmap() -> io::Result<Option<memmap2::MmapMut>> {
283    use std::os::unix::io::FromRawFd;
284
285    // Check if stdin is a pipe
286    let mut stat: libc::stat = unsafe { std::mem::zeroed() };
287    if unsafe { libc::fstat(0, &mut stat) } != 0 {
288        return Ok(None);
289    }
290    if (stat.st_mode & libc::S_IFMT) != libc::S_IFIFO {
291        return Ok(None);
292    }
293
294    // Create memfd for receiving spliced data.
295    // Use raw syscall to avoid glibc version dependency (memfd_create added in glibc 2.27,
296    // but the syscall works on any kernel >= 3.17). This fixes cross-compilation to
297    // aarch64-unknown-linux-gnu with older sysroots.
298    let memfd =
299        unsafe { libc::syscall(libc::SYS_memfd_create, c"stdin_splice".as_ptr(), 0u32) as i32 };
300    if memfd < 0 {
301        return Ok(None); // memfd_create not supported, fallback
302    }
303
304    // Splice all data from stdin pipe to memfd (zero-copy: kernel moves pipe pages)
305    let mut total: usize = 0;
306    loop {
307        let n = unsafe {
308            libc::splice(
309                0,
310                std::ptr::null_mut(),
311                memfd,
312                std::ptr::null_mut(),
313                // Splice up to 1GB at a time (kernel will limit to actual pipe data)
314                1024 * 1024 * 1024,
315                libc::SPLICE_F_MOVE,
316            )
317        };
318        if n > 0 {
319            total += n as usize;
320        } else if n == 0 {
321            break; // EOF
322        } else {
323            let err = io::Error::last_os_error();
324            if err.kind() == io::ErrorKind::Interrupted {
325                continue;
326            }
327            unsafe { libc::close(memfd) };
328            return Ok(None); // splice failed, fallback to read
329        }
330    }
331
332    if total == 0 {
333        unsafe { libc::close(memfd) };
334        return Ok(None);
335    }
336
337    // Truncate memfd to exact data size. splice() may leave the memfd larger than
338    // `total` (page-aligned), and mmap would map the full file including zero padding.
339    // Without ftruncate, callers get a mmap with garbage/zero bytes beyond `total`.
340    if unsafe { libc::ftruncate(memfd, total as libc::off_t) } != 0 {
341        unsafe { libc::close(memfd) };
342        return Ok(None);
343    }
344
345    // Wrap memfd in a File for memmap2 API, then mmap it.
346    // MAP_SHARED allows in-place modification; populate prefaults pages.
347    let file = unsafe { File::from_raw_fd(memfd) };
348    let mmap = unsafe { MmapOptions::new().populate().map_mut(&file) };
349    drop(file); // Close memfd fd (mmap stays valid, kernel holds reference)
350
351    match mmap {
352        Ok(mut mm) => {
353            // Advise kernel for sequential access + hugepages
354            unsafe {
355                libc::madvise(
356                    mm.as_mut_ptr() as *mut libc::c_void,
357                    total,
358                    libc::MADV_SEQUENTIAL,
359                );
360                if total >= 2 * 1024 * 1024 {
361                    libc::madvise(
362                        mm.as_mut_ptr() as *mut libc::c_void,
363                        total,
364                        libc::MADV_HUGEPAGE,
365                    );
366                }
367            }
368            Ok(Some(mm))
369        }
370        Err(_) => Ok(None),
371    }
372}
373
374/// Generic read_stdin for non-Linux platforms.
375#[cfg(not(target_os = "linux"))]
376fn read_stdin_generic() -> io::Result<Vec<u8>> {
377    const PREALLOC: usize = 16 * 1024 * 1024;
378    const READ_BUF: usize = 4 * 1024 * 1024;
379
380    let mut stdin = io::stdin().lock();
381    let mut buf: Vec<u8> = Vec::with_capacity(PREALLOC);
382
383    loop {
384        let spare_cap = buf.capacity() - buf.len();
385        if spare_cap < READ_BUF {
386            buf.reserve(PREALLOC);
387        }
388        let spare_cap = buf.capacity() - buf.len();
389
390        let start = buf.len();
391        unsafe { buf.set_len(start + spare_cap) };
392        match stdin.read(&mut buf[start..start + spare_cap]) {
393            Ok(0) => {
394                buf.truncate(start);
395                break;
396            }
397            Ok(n) => {
398                buf.truncate(start + n);
399            }
400            Err(e) if e.kind() == io::ErrorKind::Interrupted => {
401                buf.truncate(start);
402                continue;
403            }
404            Err(e) => return Err(e),
405        }
406    }
407
408    Ok(buf)
409}
410
411/// Read as many bytes as possible into buf, retrying on partial reads.
412/// Ensures the full buffer is filled (or EOF reached), avoiding the
413/// probe-read overhead of read_to_end.
414/// Fast path: regular file reads usually return the full buffer on the first call.
415#[inline]
416fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
417    // Fast path: first read() usually fills the entire buffer for regular files
418    let n = reader.read(buf)?;
419    if n == buf.len() || n == 0 {
420        return Ok(n);
421    }
422    // Slow path: partial read — retry to fill buffer (pipes, slow devices)
423    let mut total = n;
424    while total < buf.len() {
425        match reader.read(&mut buf[total..]) {
426            Ok(0) => break,
427            Ok(n) => total += n,
428            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
429            Err(e) => return Err(e),
430        }
431    }
432    Ok(total)
433}