Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / mem_s1.rs

mem_s1.rs125 lines · 5.3 KiBRaw
1/// Ask the filesystem to store an EMPTY scratch file uncompressed. Best effort: a no-op
2/// anywhere but Linux, and any refusal (not btrfs, flag unsupported, file already has
3/// data) is ignored -- the file then behaves exactly as it did before.
4///
5/// Why this exists: the build box mounts btrfs with `compress-force=zstd:3`, which
6/// compresses every extent in 128 KiB units regardless of whether the data shrinks. For
7/// `nodeloc`'s 83 GB coordinate table (planet) the data does not shrink (`compsize`: 94%)
8/// and the access is random 8-byte reads through a mapping, so every 4 KiB page fault that
9/// misses the page cache inflates a whole 128 KiB extent: ~32x read amplification and a
10/// zstd decode per fault. Measured on the Nov 10 planet build, the lane-inheritance scan
11/// ran at 4-5 cores with ~190 threads in `D` state on those faults.
12///
13/// btrfs only skips compression (even under `compress-force`) for a NOCOW inode
14/// (`FS_NOCOW_FL`, `chattr +C`), and NOCOW only takes on a file with no data yet -- so
15/// call this right after `create`/`truncate`, before the first write. Scratch only: NOCOW
16/// also drops data checksums, which is fine for a file the same process deletes.
17///
18/// Bytes read back are identical either way; this changes only how the filesystem stores
19/// them.
20/// Where named scratch files go: `MAPS_SCRATCH_DIR` if set, else the directory a tool set with
21/// [`set_scratch_dir`] (mamaps_build: the build's own scratch directory, next to its spills),
22/// else the system temp dir. Path only: nothing written there is observable in any output.
23pub fn scratch_dir() -> std::path::PathBuf {
24 if let Some(dir) = std::env::var_os("MAPS_SCRATCH_DIR").filter(|d| !d.is_empty()) {
25 return std::path::PathBuf::from(dir);
26 }
27 SCRATCH_DIR.lock().expect("the scratch dir setting").clone().unwrap_or_else(std::env::temp_dir)
28}
29
30/// Set the default for [`scratch_dir`] (the `MAPS_SCRATCH_DIR` override still wins).
31pub fn set_scratch_dir(dir: Option<std::path::PathBuf>) {
32 *SCRATCH_DIR.lock().expect("the scratch dir setting") = dir;
33}
34
35static SCRATCH_DIR: std::sync::Mutex<Option<std::path::PathBuf>> = std::sync::Mutex::new(None);
36
37/// Unlink a scratch file the caller keeps open (and possibly mapped), so the kernel frees its
38/// blocks when the last handle closes -- on any exit, a kill included -- instead of leaving it on
39/// disk. Returns whether the name is gone; on platforms that cannot delete an open file (Windows)
40/// it does nothing and returns `false`, and the caller keeps deleting the file on drop.
41pub fn unlink_open_scratch(path: &std::path::Path) -> bool {
42 #[cfg(unix)]
43 {
44 std::fs::remove_file(path).is_ok()
45 }
46 #[cfg(not(unix))]
47 {
48 let _ = path;
49 false
50 }
51}
52
53pub fn mark_scratch_uncompressed(file: &std::fs::File) {
54 #[cfg(target_os = "linux")]
55 {
56 use std::os::fd::AsRawFd;
57 const FS_NOCOW_FL: libc::c_long = 0x0080_0000;
58 let fd = file.as_raw_fd();
59 // `c_long` per the ioctl's declared size; the kernel reads/writes the low int.
60 let mut flags: libc::c_long = 0;
61 // SAFETY: `fd` is a live descriptor owned by `file`; both ioctls only read or write
62 // the flag word through the pointer, which outlives the calls.
63 unsafe {
64 if libc::ioctl(fd, libc::FS_IOC_GETFLAGS, &mut flags as *mut libc::c_long) != 0 {
65 return;
66 }
67 if flags & FS_NOCOW_FL != 0 {
68 return;
69 }
70 flags |= FS_NOCOW_FL;
71 let _ = libc::ioctl(fd, libc::FS_IOC_SETFLAGS, &flags as *const libc::c_long);
72 }
73 }
74 #[cfg(not(target_os = "linux"))]
75 {
76 let _ = file;
77 }
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 /// Best effort means it must never fail or disturb the file: whatever the filesystem
85 /// under the temp dir, the file stays writable and reads back what was written.
86 #[test]
87 fn marking_scratch_uncompressed_never_changes_the_bytes() {
88 use std::io::{Read, Seek, Write};
89 let path = std::env::temp_dir().join(format!("osm_nocow_test_{}.bin", std::process::id()));
90 let mut f = std::fs::OpenOptions::new()
91 .read(true)
92 .write(true)
93 .create(true)
94 .truncate(true)
95 .open(&path)
96 .unwrap();
97 mark_scratch_uncompressed(&f);
98 f.write_all(b"same bytes either way").unwrap();
99 f.rewind().unwrap();
100 let mut back = String::new();
101 f.read_to_string(&mut back).unwrap();
102 drop(f);
103 let _ = std::fs::remove_file(&path);
104 assert_eq!(back, "same bytes either way");
105 }
106
107 #[test]
108 fn vm_hwm_is_read_in_kilobytes() {
109 let status =
110 "Name:\troad_graph\nVmPeak:\t 9999999 kB\nVmHWM:\t 5212672 kB\nVmRSS:\t 12 kB\n";
111 assert_eq!(parse_vm_hwm(status), Some(5_212_672 * 1024));
112 // VmRSS must not be mistaken for the high-water mark, and a status file
113 // without the field (older kernels, or a sandbox) is absent, not zero.
114 assert_eq!(parse_vm_hwm("VmRSS:\t 12 kB\n"), None);
115 assert_eq!(parse_vm_hwm("VmHWM:\n"), None);
116 }
117
118 #[test]
119 fn the_report_is_a_string_on_every_platform() {
120 let s = peak_rss_report();
121 assert!(!s.is_empty());
122 #[cfg(target_os = "linux")]
123 assert!(s.ends_with(" GB"), "{s}");
124 }
125}