diff --git a/Cargo.lock b/Cargo.lock index 21d755c..5d82d18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1657,6 +1657,7 @@ dependencies = [ name = "disktree-scanner" version = "1.0.0" dependencies = [ + "io-uring", "lz4_flex", "prost", "rayon", @@ -3688,6 +3689,17 @@ dependencies = [ "leaky-cow", ] +[[package]] +name = "io-uring" +version = "0.7.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "878c26bc5e45fe089ce2ca25689260c152a87ce1d7de2ca86101efeea6973932" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "libc", +] + [[package]] name = "ipnet" version = "2.12.2" diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index 1f420f3..a06a18a 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -114,6 +114,60 @@ const INSIGHT_LIMIT: usize = 6; /// Duration of the tile freshness colour fade when a square becomes fresh. const FRESHNESS_FADE_MS: f32 = 200.0; +/// Duration of smooth per-tile rectangle gliding when sizes update during a +/// live scan or background refresh. +const TILE_RECT_GLIDE_MS: f32 = 200.0; +/// Minimum interval between incremental subtree re-layouts during a background +/// scan so the treemap stays calm instead of thrashing on every checkpoint. +const LIVE_REPROJECT_BUFFER: Duration = Duration::from_millis(1200); + +#[derive(Clone, Copy, Debug)] +struct TileRectAnim { + from: Rect, + target: Rect, + started: Instant, +} + +impl TileRectAnim { + fn settled(rect: Rect, now: Instant) -> Self { + let elapsed = Duration::from_millis(250); + Self { + from: rect, + target: rect, + started: now.checked_sub(elapsed).unwrap_or(now), + } + } + + fn rects_close(a: Rect, b: Rect) -> bool { + (a.x - b.x).abs() < 0.5 + && (a.y - b.y).abs() < 0.5 + && (a.w - b.w).abs() < 0.5 + && (a.h - b.h).abs() < 0.5 + } + + fn value(&self, now: Instant) -> Rect { + if Self::rects_close(self.from, self.target) { + return self.target; + } + let elapsed_ms = + now.saturating_duration_since(self.started).as_secs_f32() * 1000.0; + let t = (elapsed_ms / TILE_RECT_GLIDE_MS).clamp(0.0, 1.0); + let eased = 1.0 - (1.0 - t).powi(3); + Rect::new( + (self.target.x - self.from.x).mul_add(eased, self.from.x), + (self.target.y - self.from.y).mul_add(eased, self.from.y), + (self.target.w - self.from.w).mul_add(eased, self.from.w), + (self.target.h - self.from.h).mul_add(eased, self.from.h), + ) + } + + fn is_running(&self, now: Instant) -> bool { + !Self::rects_close(self.from, self.target) + && now.saturating_duration_since(self.started).as_secs_f32() + * 1000.0 + < TILE_RECT_GLIDE_MS + } +} #[derive(Clone, Copy, Debug)] struct TileFade { @@ -1101,6 +1155,8 @@ pub struct Disktree { pub updating_paths: FxHashSet, pub refreshed_paths: FxHashSet, pub active_scan_path: Option, + pending_arena_flush: bool, + last_arena_flush: Option, pub scan_epoch: u64, pub progress: ScanSnapshot, pub scan_error: Option, @@ -1123,6 +1179,9 @@ pub struct Disktree { pub transition: Option, /// Per-tile smooth colour fade when freshness changes (200 ms ease-out). tile_fades: FxHashMap, + /// Per-tile smooth rectangle glide when live updates shift sizes (200 ms). + tile_rects: FxHashMap, + last_treemap_size: Size, pub layout_options: LayoutOptions, cache: Option, marked: Option, @@ -1305,6 +1364,8 @@ impl Disktree { updating_paths: FxHashSet::default(), refreshed_paths: FxHashSet::default(), active_scan_path: None, + pending_arena_flush: false, + last_arena_flush: None, scan_epoch: 0, progress: ScanSnapshot::default(), scan_error: None, @@ -1318,6 +1379,8 @@ impl Disktree { view: View::default(), transition: None, tile_fades: FxHashMap::default(), + tile_rects: FxHashMap::default(), + last_treemap_size: Size::default(), layout_options: LayoutOptions { max_depth: depth.clamp(1, 6), ..LayoutOptions::default() @@ -2255,7 +2318,10 @@ impl Disktree { self.updating_paths.clear(); self.refreshed_paths.clear(); self.active_scan_path = None; + self.pending_arena_flush = false; + self.last_arena_flush = None; self.tile_fades.clear(); + self.tile_rects.clear(); self.crumbs.clear(); self.selected = None; self.hovered = None; @@ -2439,7 +2505,15 @@ impl Disktree { }); self.install_tree(stale.tree.clone(), None, cx); } - self.scan_preview.clone_from(&self.remote_progress.preview); + if self.remote_progress.preview.is_some() + && (self.scan_preview.is_none() + || self + .preview_updated + .is_none_or(|at| at.elapsed().as_secs() >= 1)) + { + self.scan_preview.clone_from(&self.remote_progress.preview); + self.preview_updated = Some(Instant::now()); + } self.progress.files = self.remote_progress.files; self.progress.dirs = self.remote_progress.dirs; self.progress.bytes = self.remote_progress.bytes; @@ -2541,120 +2615,158 @@ impl Disktree { self.preview_updated = Some(Instant::now()); } } - let Some(update) = handle.poll_update() else { + let mut drained = Vec::new(); + while drained.len() < 64 + && let Some(update) = handle.poll_update() + { + let stop = matches!( + update, + ScanUpdate::Live { .. } + | ScanUpdate::Error(_) + | ScanUpdate::Finished + ); + drained.push(update); + if stop { + break; + } + } + let mut keep_polling = true; + let mut spliced_arenas: Vec<(PathBuf, Arc)> = + Vec::new(); + for update in drained { + match update { + ScanUpdate::Cached { + arena, + node, + freshness, + } => { + let is_fresh = + matches!(freshness, Freshness::Fresh { .. }); + self.arena = Some(arena); + self.freshness = Some(freshness); + self.install_tree(node, None, cx); + if is_fresh { + keep_polling = false; + break; + } + // Stale SWR hit: paint immediately and transition + // the active scan's intent to Refresh so the live + // landing preserves navigation by path. + if let Some(active) = &mut self.active_scan { + active.set_intent(ScanIntent::Refresh { + metric: self.options.metric, + forced: false, + }); + } + } + ScanUpdate::SubtreeUpdating { path } => { + self.updating_paths.insert(path); + } + ScanUpdate::SubtreeRefreshed { path, arena: sub } => { + self.updating_paths.remove(&path); + self.refreshed_paths.insert(path.clone()); + spliced_arenas.push((path, sub)); + } + ScanUpdate::Live { arena, node } => { + spliced_arenas.clear(); + self.pending_arena_flush = false; + self.arena = Some(arena); + self.freshness = Some(Freshness::Live { + scanned_at: disktree_scanner::unix_now(), + }); + match &intent { + ScanIntent::Refresh { metric, .. } => { + let directory = self.current_path(); + let selected = self + .selected + .as_deref() + .and_then(|c| self.path_at(c)); + self.install_refresh( + node, *metric, &directory, selected, cx, + ); + self.scan_elapsed = self + .scan_started + .map(|started| started.elapsed()); + } + ScanIntent::Widening { target } => { + self.install_tree( + node, + Some(target.clone()), + cx, + ); + } + ScanIntent::Initial => { + self.install_tree(node, None, cx); + } + } + keep_polling = false; + break; + } + ScanUpdate::Error(error) => { + self.scan_error = Some(error.to_string()); + keep_polling = false; + break; + } + ScanUpdate::Finished => { + keep_polling = false; + break; + } + } + } + + // Coalesce all SubtreeRefreshed checkpoints received on this + // tick into one arena splice, and buffer full tree re-layout to + // at most once per LIVE_REPROJECT_BUFFER so the treemap stays + // calm instead of jumping around on every folder. + if !spliced_arenas.is_empty() + && let Some(current_arena) = self.arena.as_ref() + { + let root = current_arena.root_path().to_path_buf(); + let mut next = (**current_arena).clone(); + let mut changed = false; + for (path, sub) in spliced_arenas { + if path == root { + next = (*sub).clone(); + changed = true; + } else if let Ok(rel) = path.strip_prefix(&root) { + let parts: Vec = rel + .components() + .map(|c| { + c.as_os_str().to_string_lossy().into_owned() + }) + .collect(); + if let Some(target_id) = next + .find_relative(parts.iter().map(String::as_str)) + { + next.replace_node_contents(target_id, &sub); + changed = true; + } + } + } + if changed { + next.aggregate( + self.options.dedup_hardlinks, + self.options.include_hidden, + ); + self.arena = Some(Arc::new(next)); + self.pending_arena_flush = true; + } + } + + if self.pending_arena_flush + && self + .last_arena_flush + .is_none_or(|t| t.elapsed() >= LIVE_REPROJECT_BUFFER) + && let Some(arena) = self.arena.clone() + { + self.pending_arena_flush = false; + self.last_arena_flush = Some(Instant::now()); + self.reproject_arena(&arena, cx); + } + + if keep_polling { cx.notify(); return true; - }; - match update { - ScanUpdate::Cached { - arena, - node, - freshness, - } => { - let is_fresh = - matches!(freshness, Freshness::Fresh { .. }); - self.arena = Some(arena); - self.freshness = Some(freshness); - self.install_tree(node, None, cx); - if is_fresh { - self.active_scan = None; - self.updating_paths.clear(); - self.refreshed_paths.clear(); - self.active_scan_path = None; - self.scan_preview = None; - self.progress.finished = true; - cx.notify(); - return false; - } - // Stale SWR hit: paint immediately and transition the - // active scan's intent to Refresh so the live landing - // preserves navigation by path. - if let Some(active) = &mut self.active_scan { - active.set_intent(ScanIntent::Refresh { - metric: self.options.metric, - forced: false, - }); - } - cx.notify(); - return true; - } - ScanUpdate::SubtreeUpdating { path } => { - self.updating_paths.insert(path); - cx.notify(); - return true; - } - ScanUpdate::SubtreeRefreshed { path, arena: sub } => { - self.updating_paths.remove(&path); - self.refreshed_paths.insert(path.clone()); - if let Some(current_arena) = self.arena.as_mut() { - let root = current_arena.root_path().to_path_buf(); - let updated = if path == root { - Some((*sub).clone()) - } else if let Ok(rel) = path.strip_prefix(&root) { - let parts: Vec = rel - .components() - .map(|c| { - c.as_os_str() - .to_string_lossy() - .into_owned() - }) - .collect(); - let mut next = (**current_arena).clone(); - if let Some(target_id) = next.find_relative( - parts.iter().map(String::as_str), - ) { - next.replace_node_contents(target_id, &sub); - next.aggregate( - self.options.dedup_hardlinks, - self.options.include_hidden, - ); - Some(next) - } else { - None - } - } else { - None - }; - if let Some(next) = updated { - let next = Arc::new(next); - self.arena = Some(Arc::clone(&next)); - self.reproject_arena(&next, cx); - } - } - cx.notify(); - return true; - } - ScanUpdate::Live { arena, node } => { - self.arena = Some(arena); - self.freshness = Some(Freshness::Live { - scanned_at: disktree_scanner::unix_now(), - }); - match intent { - ScanIntent::Refresh { metric, .. } => { - let directory = self.current_path(); - let selected = self - .selected - .as_deref() - .and_then(|c| self.path_at(c)); - self.install_refresh( - node, metric, &directory, selected, cx, - ); - self.scan_elapsed = self - .scan_started - .map(|started| started.elapsed()); - } - ScanIntent::Widening { target } => { - self.install_tree(node, Some(target), cx); - } - ScanIntent::Initial => { - self.install_tree(node, None, cx); - } - } - } - ScanUpdate::Error(error) => { - self.scan_error = Some(error.to_string()); - } - ScanUpdate::Finished => {} } } } @@ -3803,7 +3915,14 @@ impl Disktree { let mut decorations = Vec::with_capacity(tiles.len()); let mut slots: Vec> = Vec::new(); let now_instant = Instant::now(); + let current_area = self.treemap_size.get(); + let viewport_resized = current_area != self.last_treemap_size; + self.last_treemap_size = current_area; + if viewport_resized || self.transition.is_some() { + self.tile_rects.clear(); + } let mut tile_fades = std::mem::take(&mut self.tile_fades); + let mut tile_rects = std::mem::take(&mut self.tile_rects); let mut visible_fade_keys = FxHashSet::default(); for tile in tiles { let crumbs = tile.crumbs(); @@ -3826,21 +3945,20 @@ impl Disktree { let freshness = self.tile_freshness_at(crumbs, now_unix, refresh_mode); let target_fade = freshness.fade_amount(); - let freshness_fade = match &tile.kind { - TileKind::Node { crumbs } => { - if let Some(path) = self.path_at(crumbs) { - visible_fade_keys.insert(path.clone()); - sample_tile_fade( - &mut tile_fades, - path, - target_fade, - now_instant, - ) - } else { - target_fade - } - } - TileKind::Others { .. } => target_fade, + let node_path = match &tile.kind { + TileKind::Node { crumbs } => self.path_at(crumbs), + TileKind::Others { .. } => None, + }; + let freshness_fade = if let Some(path) = &node_path { + visible_fade_keys.insert(path.clone()); + sample_tile_fade( + &mut tile_fades, + path.clone(), + target_fade, + now_instant, + ) + } else { + target_fade }; let is_marked = marked.contains(crumbs); // Everything inside a marked directory goes with it, so it is @@ -3848,7 +3966,13 @@ impl Disktree { let is_covered = !marked.is_empty() && (1..crumbs.len()) .any(|length| marked.contains(&crumbs[..length])); - let rect = self.animated_rect(tile.rect); + let rect = if self.transition.is_some() { + self.animated_rect(tile.rect) + } else if let Some(path) = node_path { + sample_tile_rect(&mut tile_rects, path, tile.rect, now_instant) + } else { + tile.rect + }; decorations.push(TileDeco { rect, depth: tile.depth, @@ -3867,7 +3991,18 @@ impl Disktree { // Labels are chosen in screen space: zooming in makes room for more // of them, which is the point of zooming in. - let header = tile.header.map(|header| self.animated_rect(header)); + let header = tile.header.map(|header| { + if self.transition.is_some() { + self.animated_rect(header) + } else { + Rect::new( + rect.x + (header.x - tile.rect.x), + rect.y + (header.y - tile.rect.y), + rect.w.min(header.w), + rect.h.min(header.h), + ) + } + }); let screen = view.project(header.unwrap_or(rect)); if screen.w < LABEL_MIN_W_REMS * self.rem || screen.h < LABEL_MIN_H_REMS * self.rem @@ -3900,6 +4035,9 @@ impl Disktree { tile_fades.retain(|path, fade| { visible_fade_keys.contains(path) || fade.is_running(now_instant) }); + tile_rects.retain(|path, anim| { + visible_fade_keys.contains(path) || anim.is_running(now_instant) + }); drop(visible_fade_keys); slots.sort_by(|left, right| { @@ -3930,6 +4068,7 @@ impl Disktree { .collect(); self.cache = Some(cache); self.tile_fades = tile_fades; + self.tile_rects = tile_rects; Mosaic { tiles: decorations, @@ -5114,16 +5253,85 @@ impl Disktree { self.tick_freshness_fades(window); } - /// Keep animation frames flowing while any tile is mid-fade after a - /// freshness change (200 ms ease-out), then stop cleanly at 0% idle CPU. + /// Plain-language explanation of active background work for the sidebar + /// Activity card (`(heading, why)`), when a tree is already on screen. + #[must_use] + pub fn scan_activity_summary(&self) -> Option<(&'static str, String)> { + self.tree.as_ref()?; + let active = self.active_scan.as_ref()?; + match active { + ActiveScan::Remote { intent, .. } => { + let host = self.remote.as_deref().unwrap_or("remote"); + Some(match intent { + ScanIntent::Refresh { forced: true, .. } => ( + "Rescanning remote", + format!("Rescanning {host} on request"), + ), + ScanIntent::Refresh { forced: false, .. } => ( + "Refreshing cache", + format!("Updating stale {host} cache in background"), + ), + ScanIntent::Widening { .. } => ( + "Expanding scan", + format!("Reading parent folder on {host}"), + ), + ScanIntent::Initial => { + ("Scanning remote", format!("Indexing {host} over SSH")) + } + }) + } + ActiveScan::Local { intent, .. } => Some(match intent { + ScanIntent::Refresh { forced: true, .. } => { + ("Rescanning", "Rescanning this folder on request".into()) + } + ScanIntent::Refresh { forced: false, .. } => ( + "Refreshing cache", + "Updating folders older than 15 min — keep browsing".into(), + ), + ScanIntent::Widening { .. } => ( + "Expanding scan", + "Reading parent folder around current view".into(), + ), + ScanIntent::Initial => { + ("Scanning", "Indexing this folder".into()) + } + }), + } + } + + /// Keep animation frames flowing while any tile is mid-fade or mid-glide + /// after a freshness/layout change (200 ms ease-out), then stop cleanly at + /// 0% idle CPU. pub fn tick_freshness_fades(&self, window: &Window) { let now = Instant::now(); - if self.tile_fades.values().any(|fade| fade.is_running(now)) { + if self.tile_fades.values().any(|fade| fade.is_running(now)) + || self.tile_rects.values().any(|anim| anim.is_running(now)) + { window.request_animation_frame(); } } } +fn sample_tile_rect( + tile_rects: &mut FxHashMap, + path: PathBuf, + target: Rect, + now: Instant, +) -> Rect { + if let Some(anim) = tile_rects.get_mut(&path) { + if !TileRectAnim::rects_close(anim.target, target) { + let current = anim.value(now); + anim.from = current; + anim.target = target; + anim.started = now; + } + anim.value(now) + } else { + tile_rects.insert(path, TileRectAnim::settled(target, now)); + target + } +} + fn sample_tile_fade( tile_fades: &mut FxHashMap, path: PathBuf, @@ -5696,6 +5904,24 @@ mod tests { assert!(!fade.is_running(start + Duration::from_millis(200))); } + #[test] + fn tile_rect_glides_smoothly_over_200ms() { + let start = Instant::now(); + let anim = TileRectAnim { + from: Rect::new(0.0, 0.0, 100.0, 100.0), + target: Rect::new(50.0, 20.0, 200.0, 140.0), + started: start, + }; + assert!(anim.is_running(start)); + let mid = anim.value(start + Duration::from_millis(100)); + assert!(mid.x > 0.0 && mid.x < 50.0); + assert!(mid.w > 100.0 && mid.w < 200.0); + let done = anim.value(start + Duration::from_millis(200)); + assert!((done.x - 50.0).abs() < 1e-3); + assert!((done.w - 200.0).abs() < 1e-3); + assert!(!anim.is_running(start + Duration::from_millis(200))); + } + #[test] fn ssh_hosts_record_deduplicates_mru_and_persists() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index 4b3ad2f..734ce26 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -1891,12 +1891,122 @@ fn side_panel( .child(rule()) .child(marked_section(app, theme, cx)), ) + .children(activity_section(app, theme, cx)) .children(notice_line(app, theme, cx)) .children(privacy_line(app, theme, cx)) .children(administrator_line(app, theme, cx)) .child(disk_section(app, theme, cx)) } +/// Calm, fixed-height sidebar banner explaining WHEN background scanning is +/// running and WHY (stale cache refresh, explicit rescan, widening, or remote), +/// with live monospace counters and current folder lane plus a Stop control. +fn activity_section( + app: &Disktree, + theme: &Theme, + cx: &Context<'_, Disktree>, +) -> Option
{ + let (heading, why) = app.scan_activity_summary()?; + let counts = if app.progress.files > 0 || app.progress.dirs > 0 { + format!( + "{} · {} files · {} dirs", + human_bytes(app.progress.bytes), + disktree_core::size::human_count(app.progress.files), + disktree_core::size::human_count(app.progress.dirs), + ) + } else if app.remote.is_some() { + app.remote_progress.stage.label().to_owned() + } else { + "Checking cached folders…".to_owned() + }; + let current_path = app + .remote + .as_ref() + .and(app.remote_progress.directory.as_deref()) + .or(app.active_scan_path.as_deref()) + .map(|p| app.display_path(p)) + .unwrap_or_default(); + + Some( + div() + .debug_selector(|| "sidebar-activity".into()) + .flex() + .flex_col() + .gap(space::XXS) + .px(space::LG) + .py(space::SM) + .bg(theme.inset) + .border_t_1() + .border_color(theme.divider()) + .child( + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap(space::SM) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .child( + gpui_omarchy::icon( + gpui_omarchy::IconName::RotateCw, + ) + .size(icon::SM) + .text_color(theme.accent), + ) + .child(widgets::eyebrow(heading, cx)), + ) + .child( + button( + "activity-stop", + "Stop", + ButtonVariant::Outline, + cx, + ) + .tab_stop(false) + .px(space::XS) + .py(space::XXS) + .on_click(cx.listener( + |this, _, window, cx| { + this.cancel_scan(cx); + window.focus(&this.focus, cx); + }, + )), + ), + ) + .child( + div() + .h(size::PROGRESS_ROW) + .truncate() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(why), + ) + .child( + div() + .h(size::PROGRESS_ROW) + .truncate() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(counts), + ) + .child( + div() + .h(size::PROGRESS_ROW) + .truncate() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(current_path), + ), + ) +} + /// What the keys act on: compact, static-height summary with Open, Mark and /// Refresh icon controls in the top right so the lists below never jump. fn selection_section( diff --git a/crates/disktree-cli/src/cli.rs b/crates/disktree-cli/src/cli.rs index a0e3b66..e5c3358 100644 --- a/crates/disktree-cli/src/cli.rs +++ b/crates/disktree-cli/src/cli.rs @@ -90,6 +90,18 @@ pub struct Cli { /// Fixed worker threads for scanning (defaults to CPU count). #[arg(long)] pub scan_threads: Option, + + /// Directory enumeration / metadata strategy (auto, statx, uring, portable). + #[arg(long, value_enum, default_value_t = BackendArg::Auto)] + pub backend: BackendArg, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] +pub enum BackendArg { + Auto, + Statx, + Uring, + Portable, } #[derive(Clone, Debug, Subcommand)] @@ -177,6 +189,18 @@ impl Cli { max_depth: None, dedup_hardlinks: true, threads: self.scan_threads, + backend: match self.backend { + BackendArg::Auto => disktree_scanner::ScanBackend::Auto, + BackendArg::Portable => disktree_scanner::ScanBackend::Portable, + BackendArg::Statx => { + disktree_scanner::ScanBackend::parse("statx") + .unwrap_or(disktree_scanner::ScanBackend::Auto) + } + BackendArg::Uring => { + disktree_scanner::ScanBackend::parse("uring") + .unwrap_or(disktree_scanner::ScanBackend::Auto) + } + }, } } diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rs index e355ee8..b37b37a 100644 --- a/crates/disktree-core/src/scan.rs +++ b/crates/disktree-core/src/scan.rs @@ -75,6 +75,7 @@ impl ScanOptions { max_depth: self.max_depth, dedup_hardlinks: self.dedup_hardlinks, threads: self.threads, + backend: disktree_scanner::ScanBackend::Auto, } } } diff --git a/crates/disktree-scanner/Cargo.toml b/crates/disktree-scanner/Cargo.toml index 5d7fafe..09b0969 100644 --- a/crates/disktree-scanner/Cargo.toml +++ b/crates/disktree-scanner/Cargo.toml @@ -10,8 +10,9 @@ description = "High-efficiency disk space scanner with Protobuf cache DB, prefix workspace = true [features] -default = ["cache-db"] +default = ["cache-db", "io-uring"] cache-db = ["dep:redb"] +io-uring = ["dep:io-uring"] [dependencies] lz4_flex = { version = "0.11", default-features = false, features = ["safe-encode", "safe-decode"] } @@ -24,6 +25,9 @@ serde = { version = "1", features = ["derive"] } [target.'cfg(not(windows))'.dependencies] rustix = { version = "1.1", features = ["fs"] } +[target.'cfg(target_os = "linux")'.dependencies] +io-uring = { version = "0.7", optional = true } + [target.'cfg(windows)'.dependencies] winapi-util = "0.1.11" windows-sys = { version = "0.61", features = [ diff --git a/crates/disktree-scanner/src/backend.rs b/crates/disktree-scanner/src/backend.rs new file mode 100644 index 0000000..782e0d8 --- /dev/null +++ b/crates/disktree-scanner/src/backend.rs @@ -0,0 +1,304 @@ +//! Strategy-invariant directory enumeration and metadata backend interface. +//! +//! Everything above this module (`walk`, `TreeArena`, checkpointing, SWR cache, +//! CLI, and GUI) operates solely on [`DirEntryMeta`] streams and never branches +//! on whether `io_uring`, synchronous `statx`, or portable `std::fs` produced +//! them. Adding a new OS or filesystem strategy only requires implementing one +//! backend behind [`visit_dir_entries`]. + +use std::io; +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::types::NodeKind; + +/// Uniform metadata for a single directory entry, independent of the OS +/// strategy that read it. +#[derive(Clone, Copy, Debug)] +pub struct DirEntryMeta { + pub kind: NodeKind, + pub device: u64, + pub allocated_bytes: u64, + pub apparent_bytes: u64, + pub modified: i64, + pub hardlink: Option<(u64, u64)>, + pub inode: Option<(u64, u64)>, + pub hidden_attr: bool, + pub evicted: bool, +} + +/// Directory-enumeration / metadata strategy selector. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, +)] +#[serde(rename_all = "kebab-case")] +pub enum ScanBackend { + /// Pick the fastest available strategy for the host (checks + /// `DISKTREE_SCAN_BACKEND` if set; otherwise prefers `LinuxIoUring` when + /// enabled and permitted on Linux, falling back to `LinuxStatx`). + #[default] + Auto, + /// Linux `openat` + 64 KiB `getdents64` + relative `statx`. + #[cfg(target_os = "linux")] + LinuxStatx, + /// Linux `openat` + 64 KiB `getdents64` + batched `io_uring` + /// `IORING_OP_STATX` (automatically falls back to `LinuxStatx` if blocked). + #[cfg(all(target_os = "linux", feature = "io-uring"))] + LinuxIoUring, + /// Portable `std::fs::read_dir` + `symlink_metadata` strategy. + Portable, +} + +impl ScanBackend { + /// Resolve `Auto` via `DISKTREE_SCAN_BACKEND` (or the platform default). + #[must_use] + pub fn resolve(self) -> Self { + if self != Self::Auto { + return self; + } + if let Ok(raw) = std::env::var("DISKTREE_SCAN_BACKEND") + && let Some(parsed) = Self::parse(&raw) + && parsed != Self::Auto + { + return parsed; + } + Self::platform_default() + } + + #[must_use] + pub fn parse(raw: &str) -> Option { + match raw.trim().to_ascii_lowercase().as_str() { + "auto" => Some(Self::Auto), + "portable" | "std" => Some(Self::Portable), + #[cfg(target_os = "linux")] + "statx" | "linux-statx" => Some(Self::LinuxStatx), + #[cfg(all(target_os = "linux", feature = "io-uring"))] + "uring" | "io-uring" | "io_uring" | "linux-io-uring" => { + Some(Self::LinuxIoUring) + } + _ => None, + } + } + + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Auto => "auto", + #[cfg(target_os = "linux")] + Self::LinuxStatx => "linux-statx", + #[cfg(all(target_os = "linux", feature = "io-uring"))] + Self::LinuxIoUring => "linux-io-uring", + Self::Portable => "portable", + } + } + + #[must_use] + const fn platform_default() -> Self { + #[cfg(all(target_os = "linux", feature = "io-uring"))] + { + Self::LinuxIoUring + } + #[cfg(all(target_os = "linux", not(feature = "io-uring")))] + { + Self::LinuxStatx + } + #[cfg(not(target_os = "linux"))] + { + Self::Portable + } + } +} + +/// Enumerate and measure every non-`.` / non-`..` entry in `dir_path` using +/// `backend`. +/// +/// - `should_skip(raw_name_bytes, is_dir_hint)` runs **before** issuing any +/// `stat` / `statx` syscall so cached fresh subtrees and mount exclusions +/// never touch the inode. +/// - `visit(raw_name_bytes, meta_result)` receives each unskipped entry; +/// returning `false` stops scanning the directory early (e.g. on cancel). +#[cfg(target_os = "linux")] +pub fn visit_dir_entries( + dir_path: &Path, + follow_links: bool, + backend: ScanBackend, + should_skip: S, + visit: V, +) -> io::Result<()> +where + S: FnMut(&[u8], bool) -> bool, + V: FnMut(&[u8], io::Result) -> bool, +{ + match backend.resolve() { + #[cfg(feature = "io-uring")] + ScanBackend::LinuxIoUring | ScanBackend::Auto => { + crate::linux::visit_dir_uring( + dir_path, + follow_links, + should_skip, + visit, + ) + } + #[cfg(not(feature = "io-uring"))] + ScanBackend::Auto => crate::linux::visit_dir_statx( + dir_path, + follow_links, + should_skip, + visit, + ), + ScanBackend::LinuxStatx => crate::linux::visit_dir_statx( + dir_path, + follow_links, + should_skip, + visit, + ), + ScanBackend::Portable => { + visit_dir_portable(dir_path, follow_links, should_skip, visit) + } + } +} + +#[cfg(target_os = "linux")] +fn visit_dir_portable( + dir_path: &Path, + follow_links: bool, + mut should_skip: S, + mut visit: V, +) -> io::Result<()> +where + S: FnMut(&[u8], bool) -> bool, + V: FnMut(&[u8], io::Result) -> bool, +{ + use std::fs; + use std::os::unix::ffi::OsStrExt as _; + + use crate::stream::{ + device_of, inode_of, measure_both, modified_seconds, nlink_of, + }; + + for entry_res in fs::read_dir(dir_path)? { + let entry = match entry_res { + Ok(e) => e, + Err(err) => { + if !visit(b"", Err(err)) { + break; + } + continue; + } + }; + let raw_name = entry.file_name(); + let raw_bytes = raw_name.as_bytes(); + let is_dir_hint = entry.file_type().is_ok_and(|ft| ft.is_dir()); + if should_skip(raw_bytes, is_dir_hint) { + continue; + } + let path = entry.path(); + let meta_res = if follow_links { + fs::metadata(&path) + } else { + fs::symlink_metadata(&path) + }; + let mapped = meta_res.map(|meta| { + let ft = meta.file_type(); + let kind = if ft.is_symlink() { + NodeKind::Symlink + } else if ft.is_dir() { + NodeKind::Directory + } else if ft.is_file() { + NodeKind::File + } else { + NodeKind::Other + }; + let (allocated_bytes, apparent_bytes) = measure_both(&meta); + let inode = inode_of(&meta); + let hardlink = (kind == NodeKind::File + && (follow_links || nlink_of(&meta) > 1)) + .then_some(inode) + .flatten(); + DirEntryMeta { + kind, + device: device_of(&meta), + allocated_bytes, + apparent_bytes, + modified: modified_seconds(&meta), + hardlink, + inode, + hidden_attr: false, + evicted: false, + } + }); + if !visit(raw_bytes, mapped) { + break; + } + } + Ok(()) +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use std::fs; + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + + use super::*; + use crate::types::ScanOptions; + use crate::walk::{WalkConfig, WalkProgress, walk_parallel}; + + #[test] + fn all_linux_strategies_produce_identical_trees() { + let temp = tempfile::tempdir().expect("tempdir"); + let root = temp.path(); + fs::create_dir_all(root.join("a/b/c/d/e")).expect("mkdir"); + fs::create_dir_all(root.join(".hidden")).expect("mkdir hidden"); + for i in 0..40 { + fs::write( + root.join(format!("a/file-{i:02}.bin")), + vec![1u8; 64 + i], + ) + .expect("write"); + } + fs::write(root.join("a/b/c/d/e/deep.txt"), b"hello deep") + .expect("write deep"); + fs::write(root.join(".hidden/secret.txt"), b"hidden") + .expect("write hidden"); + fs::hard_link( + root.join("a/file-00.bin"), + root.join("a/file-00-link.bin"), + ) + .expect("hardlink"); + + let run = |backend: ScanBackend| { + let options = ScanOptions { + backend, + ..ScanOptions::default() + }; + let outcome = walk_parallel( + root, + WalkConfig { + options: &options, + cancel: Arc::new(AtomicBool::new(false)), + progress: Arc::new(WalkProgress::default()), + pause_gate: None, + skip_oracle: None, + on_dir_start: None, + on_dir_tally: None, + on_dir_complete: None, + }, + ) + .expect("walk"); + let r = outcome.arena.node(outcome.arena.root()); + (r.files, r.dirs, r.allocated_bytes, r.apparent_bytes) + }; + + let portable = run(ScanBackend::Portable); + let statx = run(ScanBackend::LinuxStatx); + assert_eq!(statx, portable, "statx must match portable"); + + #[cfg(feature = "io-uring")] + { + let uring = run(ScanBackend::LinuxIoUring); + assert_eq!(uring, portable, "io_uring must match portable"); + } + } +} diff --git a/crates/disktree-scanner/src/lib.rs b/crates/disktree-scanner/src/lib.rs index 953617b..222b658 100644 --- a/crates/disktree-scanner/src/lib.rs +++ b/crates/disktree-scanner/src/lib.rs @@ -3,6 +3,7 @@ //! DB, priority-interruptible stale-while-revalidate (SWR), and automatic //! fallback to in-memory or streaming modes. +pub mod backend; pub mod db; #[cfg(target_os = "linux")] mod linux; @@ -21,6 +22,7 @@ pub mod walk; #[cfg(windows)] pub mod windows; +pub use backend::{DirEntryMeta, ScanBackend}; pub use db::{CacheDb, CachedSubtree, InvalidateReport, SubtreeCatalog}; pub use mounts::{default_cache_db_path, space_info}; pub use session::{ScanEvent, ScanSession, ScanSnapshot, Scanner}; diff --git a/crates/disktree-scanner/src/linux.rs b/crates/disktree-scanner/src/linux.rs index 5d5436f..8e7a894 100644 --- a/crates/disktree-scanner/src/linux.rs +++ b/crates/disktree-scanner/src/linux.rs @@ -1,9 +1,13 @@ -//! Zero-allocation Linux directory walker built on `openat` + 64 KiB -//! `getdents64` + relative `statx(dirfd, d_name, AT_SYMLINK_NOFOLLOW | -//! AT_STATX_DONT_SYNC)`. +//! Linux directory enumeration & metadata backends behind the strategy-invariant +//! [`crate::backend::visit_dir_entries`] interface: //! -//! Avoids constructing a `PathBuf`, `OsString`, or `CString` for leaf entries -//! and avoids full-path kernel VFS dentry traversal from `/` on every file. +//! 1. `visit_dir_statx`: `openat` + thread-local 64 KiB `getdents64` + +//! synchronous relative `statx(dirfd, d_name, AT_SYMLINK_NOFOLLOW | +//! AT_STATX_DONT_SYNC)` (with `statat` fallback on `ENOSYS`). +//! 2. `visit_dir_uring` (optional `io-uring` feature): same 64 KiB `getdents64` +//! buffer, submitting up to 64 `IORING_OP_STATX` operations per single +//! `io_uring_enter` syscall (automatically falling back to `visit_dir_statx` +//! on tiny directories or if the kernel/seccomp disallows `io_uring`). use std::cell::RefCell; use std::ffi::CStr; @@ -12,12 +16,13 @@ use std::mem::MaybeUninit; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; -use rustix::fd::AsFd; +use rustix::fd::{AsFd, BorrowedFd}; use rustix::fs::{ AtFlags, CWD, FileType, Mode, OFlags, RawDir, StatxFlags, makedev, openat, statat, statx, }; +use crate::backend::DirEntryMeta; use crate::types::NodeKind; /// 64 KiB `getdents64` read buffer reused per worker thread (zero per-dir @@ -41,23 +46,16 @@ thread_local! { ); } -#[derive(Clone, Copy, Debug)] -pub struct EntryStat { - pub kind: NodeKind, - pub device: u64, - pub allocated_bytes: u64, - pub apparent_bytes: u64, - pub modified: i64, - pub hardlink: Option<(u64, u64)>, - pub inode: Option<(u64, u64)>, -} - -/// Read every entry of `dir_path` using a single `openat` + 64 KiB `getdents64` -/// chunks, passing each non-`.`/non-`..` entry's raw NUL-terminated `d_name`, -/// `d_type`, and open `dirfd` to `visit` with zero heap allocations. -pub fn scan_dir_entries(dir_path: &Path, mut visit: F) -> io::Result<()> +/// Strategy 1: `openat` + 64 KiB `getdents64` + synchronous relative `statx`. +pub fn visit_dir_statx( + dir_path: &Path, + follow_links: bool, + mut should_skip: S, + mut visit: V, +) -> io::Result<()> where - F: FnMut(rustix::fd::BorrowedFd<'_>, &CStr, FileType) -> io::Result, + S: FnMut(&[u8], bool) -> bool, + V: FnMut(&[u8], io::Result) -> bool, { let dirfd = openat( CWD, @@ -72,13 +70,18 @@ where let mut raw_dir = RawDir::new(&dirfd, &mut buf[..]); while let Some(entry_res) = raw_dir.next() { let entry = entry_res.map_err(io::Error::from)?; - let name = entry.file_name(); - let bytes = name.to_bytes(); - if bytes == b"." || bytes == b".." { + let c_name = entry.file_name(); + let raw_bytes = c_name.to_bytes(); + if raw_bytes == b"." || raw_bytes == b".." { continue; } - let keep_going = visit(dirfd.as_fd(), name, entry.file_type())?; - if !keep_going { + let file_type = entry.file_type(); + if should_skip(raw_bytes, file_type == FileType::Directory) { + continue; + } + let follow = follow_links && file_type == FileType::Symlink; + let meta = stat_at(dirfd.as_fd(), c_name, follow); + if !visit(raw_bytes, meta) { break; } } @@ -89,10 +92,10 @@ where /// Stat `name` relative to `dirfd` with `statx(..., AT_STATX_DONT_SYNC)` (or /// `statat` fallback on `ENOSYS`), performing zero path allocations. pub fn stat_at( - dirfd: rustix::fd::BorrowedFd<'_>, + dirfd: BorrowedFd<'_>, name: &CStr, follow_links: bool, -) -> io::Result { +) -> io::Result { if STATX_SUPPORTED.load(Ordering::Relaxed) { let flags = if follow_links { AtFlags::STATX_DONT_SYNC @@ -101,22 +104,7 @@ pub fn stat_at( }; match statx(dirfd, name, flags, STATX_MASK) { Ok(st) => { - let kind = kind_from_mode(u32::from(st.stx_mode)); - let device = makedev(st.stx_dev_major, st.stx_dev_minor); - let allocated_bytes = st.stx_blocks.saturating_mul(512); - let apparent_bytes = st.stx_size; - let modified = st.stx_mtime.tv_sec; - let inode = (st.stx_ino != 0).then_some((device, st.stx_ino)); - let hardlink = (st.stx_nlink > 1).then_some(inode).flatten(); - return Ok(EntryStat { - kind, - device, - allocated_bytes, - apparent_bytes, - modified, - hardlink, - inode, - }); + return Ok(meta_from_statx(&st, follow_links)); } Err(rustix::io::Errno::NOSYS | rustix::io::Errno::PERM) => { STATX_SUPPORTED.store(false, Ordering::Relaxed); @@ -138,8 +126,11 @@ pub fn stat_at( let apparent_bytes = u64::try_from(st.st_size).unwrap_or(0); let modified = st.st_mtime; let inode = (st.st_ino != 0).then_some((device, st.st_ino)); - let hardlink = (st.st_nlink > 1).then_some(inode).flatten(); - Ok(EntryStat { + let hardlink = (kind == NodeKind::File + && (follow_links || st.st_nlink > 1)) + .then_some(inode) + .flatten(); + Ok(DirEntryMeta { kind, device, allocated_bytes, @@ -147,9 +138,35 @@ pub fn stat_at( modified, hardlink, inode, + hidden_attr: false, + evicted: false, }) } +fn meta_from_statx(st: &rustix::fs::Statx, follow_links: bool) -> DirEntryMeta { + let kind = kind_from_mode(u32::from(st.stx_mode)); + let device = makedev(st.stx_dev_major, st.stx_dev_minor); + let allocated_bytes = st.stx_blocks.saturating_mul(512); + let apparent_bytes = st.stx_size; + let modified = st.stx_mtime.tv_sec; + let inode = (st.stx_ino != 0).then_some((device, st.stx_ino)); + let hardlink = (kind == NodeKind::File + && (follow_links || st.stx_nlink > 1)) + .then_some(inode) + .flatten(); + DirEntryMeta { + kind, + device, + allocated_bytes, + apparent_bytes, + modified, + hardlink, + inode, + hidden_attr: false, + evicted: false, + } +} + const fn kind_from_mode(mode: u32) -> NodeKind { // POSIX S_IFMT = 0o170000 match mode & 0o170_000 { @@ -159,3 +176,279 @@ const fn kind_from_mode(mode: u32) -> NodeKind { _ => NodeKind::Other, } } + +#[cfg(feature = "io-uring")] +#[allow( + unsafe_code, + reason = "io_uring SQE submission passes pinned ring-owned buffers to the kernel" +)] +mod uring { + use std::cell::RefCell; + use std::ffi::CStr; + use std::io; + use std::mem::MaybeUninit; + use std::path::Path; + use std::sync::atomic::{AtomicBool, Ordering}; + + use io_uring::{IoUring, opcode, types}; + use rustix::fd::{AsFd, AsRawFd}; + use rustix::fs::{ + AtFlags, CWD, FileType, Mode, OFlags, RawDir, Statx, openat, + }; + + use super::{ + GETDENTS_BUF, STATX_MASK, meta_from_statx, stat_at, visit_dir_statx, + }; + use crate::backend::DirEntryMeta; + + /// Number of `IORING_OP_STATX` operations submitted per `io_uring_enter`. + const URING_BATCH: usize = 64; + /// Below this threshold, synchronous `statx` avoids ring setup/enter cost. + const MIN_URING_BATCH: usize = 8; + + static URING_AVAILABLE: AtomicBool = AtomicBool::new(true); + + struct Pending { + /// Byte range of NUL-terminated `d_name` inside `name_slab` (including + /// the trailing NUL byte so `as_ptr()` is a valid C string). + start: usize, + end: usize, + follow: bool, + } + + struct UringThreadState { + ring: IoUring, + /// Heap-pinned array of kernel `Statx` output buffers (1 per slot). + statx_bufs: Box<[Statx; URING_BATCH]>, + /// Contiguous NUL-terminated name copy for the active batch (reused + /// across batches with zero per-batch allocation). + name_slab: Vec, + pending: Vec, + results: Vec, + } + + impl UringThreadState { + fn try_new() -> io::Result { + let ring = IoUring::new((URING_BATCH * 2) as u32)?; + // SAFETY: `Statx` is a plain C POD struct of integers. + let zeroed: Statx = unsafe { MaybeUninit::zeroed().assume_init() }; + Ok(Self { + ring, + statx_bufs: Box::new([zeroed; URING_BATCH]), + name_slab: Vec::with_capacity(4096), + pending: Vec::with_capacity(URING_BATCH), + results: vec![0; URING_BATCH], + }) + } + + fn flush_batch( + &mut self, + dirfd: rustix::fd::BorrowedFd<'_>, + visit: &mut V, + ) -> io::Result + where + V: FnMut(&[u8], io::Result) -> bool, + { + let count = self.pending.len(); + if count == 0 { + return Ok(true); + } + + // Tiny batch fast path: avoid `io_uring_enter` overhead when a + // directory only has a handful of entries. + if count < MIN_URING_BATCH { + for slot in &self.pending { + let bytes_with_nul = &self.name_slab[slot.start..slot.end]; + let c_name = CStr::from_bytes_with_nul(bytes_with_nul) + .expect("nul-terminated d_name"); + let raw = &bytes_with_nul[..bytes_with_nul.len() - 1]; + let meta = stat_at(dirfd, c_name, slot.follow); + if !visit(raw, meta) { + self.pending.clear(); + self.name_slab.clear(); + return Ok(false); + } + } + self.pending.clear(); + self.name_slab.clear(); + return Ok(true); + } + + let raw_fd = types::Fd(dirfd.as_raw_fd()); + let mask = STATX_MASK.bits(); + let base_flags_nofollow = (AtFlags::SYMLINK_NOFOLLOW + | AtFlags::STATX_DONT_SYNC) + .bits() + .cast_signed(); + let base_flags_follow = + AtFlags::STATX_DONT_SYNC.bits().cast_signed(); + + { + let mut sq = self.ring.submission(); + for (i, slot) in self.pending.iter().enumerate() { + let path_ptr = self.name_slab[slot.start..slot.end] + .as_ptr() + .cast::(); + let statx_ptr = + (&raw mut self.statx_bufs[i]).cast::(); + let flags = if slot.follow { + base_flags_follow + } else { + base_flags_nofollow + }; + let sqe = opcode::Statx::new(raw_fd, path_ptr, statx_ptr) + .flags(flags) + .mask(mask) + .build() + .user_data(i as u64); + // SAFETY: `self.name_slab` is not mutated/reallocated and + // `self.statx_bufs` is heap-pinned until after + // `submit_and_wait(count)` finishes draining all `count` + // CQEs below. + unsafe { + sq.push(&sqe).map_err(|_| { + io::Error::other("io_uring submission queue full") + })?; + } + } + } + + self.ring.submit_and_wait(count)?; + + let mut completed = 0usize; + while completed < count { + { + let mut cq = self.ring.completion(); + for cqe in &mut cq { + let idx = cqe.user_data() as usize; + if idx < count { + self.results[idx] = cqe.result(); + } + completed += 1; + } + } + if completed < count { + self.ring.submit_and_wait(count - completed)?; + } + } + + let mut keep_going = true; + for (i, slot) in self.pending.iter().enumerate() { + let raw = &self.name_slab[slot.start..slot.end - 1]; + let res = self.results[i]; + let meta = if res == 0 { + Ok(meta_from_statx(&self.statx_bufs[i], slot.follow)) + } else { + Err(io::Error::from_raw_os_error(-res)) + }; + if !visit(raw, meta) { + keep_going = false; + break; + } + } + + self.pending.clear(); + self.name_slab.clear(); + Ok(keep_going) + } + } + + thread_local! { + static URING_STATE: RefCell> = + const { RefCell::new(None) }; + } + + /// Strategy 2: `openat` + 64 KiB `getdents64` + batched `io_uring` + /// `IORING_OP_STATX` (transparent fallback to `visit_dir_statx` if blocked). + pub fn visit_dir_uring( + dir_path: &Path, + follow_links: bool, + mut should_skip: S, + mut visit: V, + ) -> io::Result<()> + where + S: FnMut(&[u8], bool) -> bool, + V: FnMut(&[u8], io::Result) -> bool, + { + if !URING_AVAILABLE.load(Ordering::Relaxed) { + return visit_dir_statx(dir_path, follow_links, should_skip, visit); + } + + let initialized = URING_STATE.with(|cell| { + let mut opt = cell.borrow_mut(); + if opt.is_none() { + if let Ok(state) = UringThreadState::try_new() { + *opt = Some(state); + } else { + URING_AVAILABLE.store(false, Ordering::Relaxed); + return false; + } + } + true + }); + + if !initialized { + return visit_dir_statx(dir_path, follow_links, should_skip, visit); + } + + let dirfd = openat( + CWD, + dir_path, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) + .map_err(io::Error::from)?; + + GETDENTS_BUF.with(|buf_cell| { + URING_STATE.with(|ring_cell| { + let mut buf = buf_cell.borrow_mut(); + let mut ring_opt = ring_cell.borrow_mut(); + let state = ring_opt + .as_mut() + .expect("io_uring thread state initialized above"); + state.pending.clear(); + state.name_slab.clear(); + + let mut raw_dir = RawDir::new(&dirfd, &mut buf[..]); + let mut keep_going = true; + while let Some(entry_res) = raw_dir.next() { + let entry = entry_res.map_err(io::Error::from)?; + let c_name = entry.file_name(); + let raw_bytes = c_name.to_bytes(); + if raw_bytes == b"." || raw_bytes == b".." { + continue; + } + let file_type = entry.file_type(); + if should_skip(raw_bytes, file_type == FileType::Directory) + { + continue; + } + let start = state.name_slab.len(); + state + .name_slab + .extend_from_slice(c_name.to_bytes_with_nul()); + let end = state.name_slab.len(); + state.pending.push(Pending { + start, + end, + follow: follow_links && file_type == FileType::Symlink, + }); + if state.pending.len() >= URING_BATCH { + keep_going = + state.flush_batch(dirfd.as_fd(), &mut visit)?; + if !keep_going { + break; + } + } + } + if keep_going { + let _ = state.flush_batch(dirfd.as_fd(), &mut visit)?; + } + Ok(()) + }) + }) + } +} + +#[cfg(feature = "io-uring")] +pub use uring::visit_dir_uring; diff --git a/crates/disktree-scanner/src/types.rs b/crates/disktree-scanner/src/types.rs index 240a8a3..2e8b820 100644 --- a/crates/disktree-scanner/src/types.rs +++ b/crates/disktree-scanner/src/types.rs @@ -262,6 +262,9 @@ pub struct ScanOptions { pub dedup_hardlinks: bool, /// Optional explicit worker count; `None` uses available parallelism. pub threads: Option, + /// Directory-enumeration / metadata strategy (`Auto` by default). + #[serde(default)] + pub backend: crate::backend::ScanBackend, } impl Default for ScanOptions { @@ -274,6 +277,7 @@ impl Default for ScanOptions { max_depth: None, dedup_hardlinks: true, threads: None, + backend: crate::backend::ScanBackend::Auto, } } } diff --git a/crates/disktree-scanner/src/walk.rs b/crates/disktree-scanner/src/walk.rs index 13210b0..d0f2ffc 100644 --- a/crates/disktree-scanner/src/walk.rs +++ b/crates/disktree-scanner/src/walk.rs @@ -385,6 +385,8 @@ pub fn walk_parallel( let ctx = Arc::new(WalkContext { options: *config.options, + #[cfg(target_os = "linux")] + backend: config.options.backend.resolve(), root_dev, foreign_mounts, never_scanned: never, @@ -636,6 +638,8 @@ fn run_deferred_stale(ctx: &Arc, sub: &Arc) { struct WalkContext { options: ScanOptions, + #[cfg(target_os = "linux")] + backend: crate::backend::ScanBackend, root_dev: u64, foreign_mounts: Option>, never_scanned: FxHashSet, @@ -1046,14 +1050,12 @@ fn scan_dir(scope: &Scope<'_>, ctx: &Arc, dir: &Arc) { #[cfg(target_os = "linux")] #[allow( clippy::too_many_lines, - reason = "zero-alloc iterative Linux subtree walker kept inline" + reason = "strategy-invariant zero-alloc iterative subtree walker" )] fn scan_dir_linux_direct(ctx: &Arc, dir: &Arc) { use std::ffi::OsStr; use std::os::unix::ffi::{OsStrExt as _, OsStringExt as _}; - use rustix::fs::FileType; - // Single reusable PathBuf + flat LIFO byte buffer for child dir names: // zero PathBuf / String / Arc / Mutex / PendingDir allocations for the // entire subtree beneath `dir`. @@ -1180,21 +1182,60 @@ fn scan_dir_linux_direct(ctx: &Arc, dir: &Arc) { let dir_path_ref = Path::new(&cur_path); let check_mounts = !ctx.mount_parents.is_empty() && ctx.mount_parents.contains(dir_path_ref); + let check_oracle = + ctx.skip_oracle.as_ref().is_some_and(|o| o.has_fresh()); let parent_path_len = cur_path.len(); let mut dir_files = 0u64; let mut dir_alloc = 0u64; let mut dir_apparent = 0u64; + let mut deferred_grafts: Vec<(Vec, TreeArena)> = Vec::new(); - let read_res = crate::linux::scan_dir_entries( + let read_res = crate::backend::visit_dir_entries( dir_path_ref, - |dirfd, c_name, file_type| { + ctx.options.follow_links, + ctx.backend, + |raw_bytes, is_dir_hint| { + if check_mounts { + let path = dir_path_ref.join(OsStr::from_bytes(raw_bytes)); + if ctx.never_scanned.contains(&path) + || (ctx.options.one_filesystem + && ctx + .foreign_mounts + .as_ref() + .is_some_and(|m| m.contains(&path))) + { + return true; + } + } + if is_dir_hint + && check_oracle + && let Some(oracle) = &ctx.skip_oracle + { + let path = dir_path_ref.join(OsStr::from_bytes(raw_bytes)); + if let Some(reused) = oracle.try_reuse(&path) { + deferred_grafts.push((raw_bytes.to_vec(), reused)); + return true; + } + } + false + }, + |raw_bytes, meta_res| { if ctx.cancel.load(Ordering::Relaxed) { incomplete = true; - return Ok(false); + return false; } - - let raw_bytes = c_name.to_bytes(); - let hidden = raw_bytes.first() == Some(&b'.'); + let st = match meta_res { + Ok(st) => st, + Err(err) => { + if !(ctx.options.follow_links + && err.kind() == io::ErrorKind::NotFound) + { + batch_errors += 1; + } + return true; + } + }; + let hidden = st.hidden_attr || raw_bytes.first() == Some(&b'.'); let utf8 = std::str::from_utf8(raw_bytes); let lossy_name = utf8.is_err(); let lossy_owned; @@ -1205,323 +1246,129 @@ fn scan_dir_linux_direct(ctx: &Arc, dir: &Arc) { lossy_owned.as_ref() }; - if matches!( - file_type, - FileType::RegularFile - | FileType::Fifo - | FileType::Socket - | FileType::CharacterDevice - | FileType::BlockDevice - ) { - if check_mounts { - let path = - dir_path_ref.join(OsStr::from_bytes(raw_bytes)); - if ctx.never_scanned.contains(&path) - || (ctx.options.one_filesystem - && ctx - .foreign_mounts - .as_ref() - .is_some_and(|m| m.contains(&path))) - { - return Ok(true); - } + if st.kind == NodeKind::Directory { + if st.evicted { + return true; } - let Ok(st) = crate::linux::stat_at(dirfd, c_name, false) - else { - batch_errors += 1; - return Ok(true); - }; - let (alloc, apparent) = if st.kind == NodeKind::Other { - (0, 0) - } else { - (st.allocated_bytes, st.apparent_bytes) - }; - if st.kind == NodeKind::File { - dir_files += 1; + if ctx.options.one_filesystem + && ctx.foreign_mounts.is_none() + && st.device != ctx.root_dev + { + return true; } - dir_alloc = dir_alloc.saturating_add(alloc); - dir_apparent = dir_apparent.saturating_add(apparent); - let mut flags = NodeFlags::new(st.kind); + if ctx.options.follow_links + && let Some(id) = st.inode + && !ctx + .visited_dirs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(id) + { + return true; + } + if ctx + .options + .max_depth + .is_some_and(|limit| frame.depth + 1 > limit) + { + return true; + } + let mut flags = NodeFlags::new(NodeKind::Directory); flags.set(NodeFlags::HIDDEN, hidden); flags.set(NodeFlags::LOSSY_NAME, lossy_name); - let id = arena.add_child_raw( + let cid = arena.add_child_raw( frame.node_id, name_str, - st.kind, - alloc, - apparent, + NodeKind::Directory, + 0, + 0, st.modified, flags, ); - if st.kind == NodeKind::File - && let Some((dev, ino)) = st.hardlink - { - arena.record_hardlink(id, dev, ino); - } - return Ok(true); + arena + .node_mut(cid) + .set_status(SubtreeStatus::Fresh { scanned_at }); + let name_start = name_buf.len(); + name_buf.extend_from_slice(raw_bytes); + let name_end = name_buf.len(); + stack.push(Frame { + node_id: cid, + depth: frame.depth + 1, + path_len: parent_path_len, + name_start, + name_end, + }); + return true; } - if file_type == FileType::Symlink { - if !ctx.options.follow_links { - let Ok(st) = - crate::linux::stat_at(dirfd, c_name, false) - else { - batch_errors += 1; - return Ok(true); - }; - dir_alloc = - dir_alloc.saturating_add(st.allocated_bytes); - dir_apparent = - dir_apparent.saturating_add(st.apparent_bytes); - let mut flags = NodeFlags::new(NodeKind::Symlink); - flags.set(NodeFlags::HIDDEN, hidden); - flags.set(NodeFlags::LOSSY_NAME, lossy_name); - arena.add_child_raw( - frame.node_id, - name_str, - NodeKind::Symlink, - st.allocated_bytes, - st.apparent_bytes, - st.modified, - flags, - ); - return Ok(true); - } - - let Ok(st) = crate::linux::stat_at(dirfd, c_name, true) - else { - return Ok(true); - }; - if st.kind == NodeKind::Directory { - let path = - dir_path_ref.join(OsStr::from_bytes(raw_bytes)); - if ctx.never_scanned.contains(&path) - || (ctx.options.one_filesystem - && ctx - .foreign_mounts - .as_ref() - .is_some_and(|m| m.contains(&path))) - || (ctx.options.one_filesystem - && ctx.foreign_mounts.is_none() - && st.device != ctx.root_dev) - { - return Ok(true); - } - if let Some(id) = st.inode - && !ctx - .visited_dirs - .lock() - .unwrap_or_else( - std::sync::PoisonError::into_inner, - ) - .insert(id) - { - return Ok(true); - } - if ctx - .options - .max_depth - .is_some_and(|limit| frame.depth + 1 > limit) - { - return Ok(true); - } - let mut flags = NodeFlags::new(NodeKind::Directory); - flags.set(NodeFlags::HIDDEN, hidden); - flags.set(NodeFlags::LOSSY_NAME, lossy_name); - let cid = arena.add_child_raw( - frame.node_id, - name_str, - NodeKind::Directory, - 0, - 0, - st.modified, - flags, - ); - arena - .node_mut(cid) - .set_status(SubtreeStatus::Fresh { scanned_at }); - let name_start = name_buf.len(); - name_buf.extend_from_slice(raw_bytes); - let name_end = name_buf.len(); - stack.push(Frame { - node_id: cid, - depth: frame.depth + 1, - path_len: parent_path_len, - name_start, - name_end, - }); - return Ok(true); - } - - if st.kind == NodeKind::File { - dir_files += 1; - } - dir_alloc = dir_alloc.saturating_add(st.allocated_bytes); - dir_apparent = - dir_apparent.saturating_add(st.apparent_bytes); - let mut flags = NodeFlags::new(st.kind); - flags.set(NodeFlags::HIDDEN, hidden); - flags.set(NodeFlags::LOSSY_NAME, lossy_name); - let id = arena.add_child_raw( - frame.node_id, - name_str, - st.kind, - st.allocated_bytes, - st.apparent_bytes, - st.modified, - flags, - ); - if let Some((dev, ino)) = st.hardlink { - arena.record_hardlink(id, dev, ino); - } - return Ok(true); - } - - // Directory or DT_UNKNOWN. - if file_type != FileType::Directory { - let Ok(st) = crate::linux::stat_at(dirfd, c_name, false) - else { - batch_errors += 1; - return Ok(true); - }; - if st.kind != NodeKind::Directory { - let (alloc, apparent) = if st.kind == NodeKind::Other { - (0, 0) - } else { - (st.allocated_bytes, st.apparent_bytes) - }; - if st.kind == NodeKind::File { - dir_files += 1; - } - dir_alloc = dir_alloc.saturating_add(alloc); - dir_apparent = dir_apparent.saturating_add(apparent); - let mut flags = NodeFlags::new(st.kind); - flags.set(NodeFlags::HIDDEN, hidden); - flags.set(NodeFlags::LOSSY_NAME, lossy_name); - let id = arena.add_child_raw( - frame.node_id, - name_str, - st.kind, - alloc, - apparent, - st.modified, - flags, - ); - if st.kind == NodeKind::File - && let Some((dev, ino)) = st.hardlink - { - arena.record_hardlink(id, dev, ino); - } - return Ok(true); - } - } - - if check_mounts { - let path = dir_path_ref.join(OsStr::from_bytes(raw_bytes)); - if ctx.never_scanned.contains(&path) - || (ctx.options.one_filesystem - && ctx - .foreign_mounts - .as_ref() - .is_some_and(|m| m.contains(&path))) - { - return Ok(true); - } - } - - if let Some(oracle) = &ctx.skip_oracle - && oracle.has_fresh() - { - let path = dir_path_ref.join(OsStr::from_bytes(raw_bytes)); - if let Some(reused) = oracle.try_reuse(&path) { - let reused_root = reused.node(reused.root()); - ctx.progress.skipped_fresh_dirs.fetch_add( - u64::from(reused_root.dirs), - Ordering::Relaxed, - ); - batch_dirs += u64::from(reused_root.dirs); - batch_files += reused_root.files; - batch_alloc = batch_alloc - .saturating_add(reused_root.allocated_bytes); - batch_apparent = batch_apparent - .saturating_add(reused_root.apparent_bytes); - if let Some(hook) = &ctx.on_dir_tally { - hook( - &path, - reused_root.allocated_bytes, - reused_root.apparent_bytes, - reused_root.files, - ); - } - let gid = arena.graft_subtree( - frame.node_id, - &reused, - Some(name_str), - ); - let gn = arena.node_mut(gid); - gn.flags.set(NodeFlags::HIDDEN, hidden); - gn.flags.set(NodeFlags::LOSSY_NAME, lossy_name); - return Ok(true); - } - } - - let Ok(st) = crate::linux::stat_at(dirfd, c_name, false) else { - batch_errors += 1; - return Ok(true); + let (alloc, apparent) = if st.kind == NodeKind::Other { + (0, 0) + } else { + (st.allocated_bytes, st.apparent_bytes) }; - if ctx.options.one_filesystem - && ctx.foreign_mounts.is_none() - && st.device != ctx.root_dev - { - return Ok(true); + if st.kind == NodeKind::File { + dir_files += 1; } - if ctx.options.follow_links - && let Some(id) = st.inode - && !ctx - .visited_dirs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(id) - { - return Ok(true); - } - if ctx - .options - .max_depth - .is_some_and(|limit| frame.depth + 1 > limit) - { - return Ok(true); - } - - let mut flags = NodeFlags::new(NodeKind::Directory); + dir_alloc = dir_alloc.saturating_add(alloc); + dir_apparent = dir_apparent.saturating_add(apparent); + let mut flags = NodeFlags::new(st.kind); flags.set(NodeFlags::HIDDEN, hidden); flags.set(NodeFlags::LOSSY_NAME, lossy_name); - let cid = arena.add_child_raw( + let id = arena.add_child_raw( frame.node_id, name_str, - NodeKind::Directory, - 0, - 0, + st.kind, + alloc, + apparent, st.modified, flags, ); - arena - .node_mut(cid) - .set_status(SubtreeStatus::Fresh { scanned_at }); - let name_start = name_buf.len(); - name_buf.extend_from_slice(raw_bytes); - let name_end = name_buf.len(); - stack.push(Frame { - node_id: cid, - depth: frame.depth + 1, - path_len: parent_path_len, - name_start, - name_end, - }); - Ok(true) + if st.kind == NodeKind::File + && let Some((dev, ino)) = st.hardlink + { + arena.record_hardlink(id, dev, ino); + } + true }, ); + for (raw_bytes, reused) in deferred_grafts { + let hidden = raw_bytes.first() == Some(&b'.'); + let utf8 = std::str::from_utf8(&raw_bytes); + let lossy_name = utf8.is_err(); + let lossy_owned; + let name_str: &str = if let Ok(s) = utf8 { + s + } else { + lossy_owned = String::from_utf8_lossy(&raw_bytes); + lossy_owned.as_ref() + }; + let reused_root = reused.node(reused.root()); + ctx.progress + .skipped_fresh_dirs + .fetch_add(u64::from(reused_root.dirs), Ordering::Relaxed); + batch_dirs += u64::from(reused_root.dirs); + batch_files += reused_root.files; + batch_alloc = + batch_alloc.saturating_add(reused_root.allocated_bytes); + batch_apparent = + batch_apparent.saturating_add(reused_root.apparent_bytes); + if let Some(hook) = &ctx.on_dir_tally { + let path = dir_path_ref.join(OsStr::from_bytes(&raw_bytes)); + hook( + &path, + reused_root.allocated_bytes, + reused_root.apparent_bytes, + reused_root.files, + ); + } + let gid = + arena.graft_subtree(frame.node_id, &reused, Some(name_str)); + let gn = arena.node_mut(gid); + gn.flags.set(NodeFlags::HIDDEN, hidden); + gn.flags.set(NodeFlags::LOSSY_NAME, lossy_name); + } + if let Err(error) = read_res { arena .node_mut(frame.node_id) @@ -1575,7 +1422,7 @@ fn scan_dir_linux_direct(ctx: &Arc, dir: &Arc) { #[cfg(target_os = "linux")] #[allow( clippy::too_many_lines, - reason = "hot Linux openat+getdents64+statx loop kept inline" + reason = "strategy-invariant shallow fan-out directory scan" )] fn scan_dir_linux( scope: &Scope<'_>, @@ -1585,8 +1432,6 @@ fn scan_dir_linux( use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt as _; - use rustix::fs::FileType; - if let Some(gate) = &ctx.pause_gate { gate.wait_if_paused(&ctx.cancel); } @@ -1607,6 +1452,7 @@ fn scan_dir_linux( } let check_mounts = ctx.mount_parents.contains(&dir.path); + let check_oracle = ctx.skip_oracle.as_ref().is_some_and(|o| o.has_fresh()); let mut local_leaves = LeafSlab::new(); let mut local_children: Vec = Vec::new(); let mut subdirs: Vec> = Vec::new(); @@ -1614,16 +1460,95 @@ fn scan_dir_linux( let mut local_alloc = 0u64; let mut local_apparent = 0u64; - let read_res = crate::linux::scan_dir_entries( + let read_res = crate::backend::visit_dir_entries( &dir.path, - |dirfd, c_name, file_type| { + ctx.options.follow_links, + ctx.backend, + |raw_bytes, is_dir_hint| { + if check_mounts { + let path = dir.path.join(OsStr::from_bytes(raw_bytes)); + if ctx.never_scanned.contains(&path) + || (ctx.options.one_filesystem + && ctx + .foreign_mounts + .as_ref() + .is_some_and(|m| m.contains(&path))) + { + return true; + } + } + if is_dir_hint + && check_oracle + && let Some(oracle) = &ctx.skip_oracle + { + let path = dir.path.join(OsStr::from_bytes(raw_bytes)); + if let Some(reused) = oracle.try_reuse(&path) { + let hidden = raw_bytes.first() == Some(&b'.'); + let utf8 = std::str::from_utf8(raw_bytes); + let lossy_name = utf8.is_err(); + let name = utf8.map_or_else( + |_| String::from_utf8_lossy(raw_bytes).into_owned(), + str::to_owned, + ); + let reused_root = reused.node(reused.root()); + ctx.progress.skipped_fresh_dirs.fetch_add( + u64::from(reused_root.dirs), + Ordering::Relaxed, + ); + ctx.progress.dirs.fetch_add( + u64::from(reused_root.dirs), + Ordering::Relaxed, + ); + ctx.progress + .files + .fetch_add(reused_root.files, Ordering::Relaxed); + ctx.progress.allocated_bytes.fetch_add( + reused_root.allocated_bytes, + Ordering::Relaxed, + ); + ctx.progress.apparent_bytes.fetch_add( + reused_root.apparent_bytes, + Ordering::Relaxed, + ); + if let Some(hook) = &ctx.on_dir_tally { + hook( + &path, + reused_root.allocated_bytes, + reused_root.apparent_bytes, + reused_root.files, + ); + } + local_children.push(BuiltChild::Grafted(Box::new( + GraftedChild { + name, + arena: Arc::new(reused), + hidden, + lossy_name, + }, + ))); + return true; + } + } + false + }, + |raw_bytes, meta_res| { if ctx.cancel.load(Ordering::Relaxed) { dir.incomplete.store(true, Ordering::Relaxed); - return Ok(false); + return false; } + let st = match meta_res { + Ok(st) => st, + Err(err) => { + if !(ctx.options.follow_links + && err.kind() == io::ErrorKind::NotFound) + { + ctx.progress.errors.fetch_add(1, Ordering::Relaxed); + } + return true; + } + }; - let raw_bytes = c_name.to_bytes(); - let hidden = raw_bytes.first() == Some(&b'.'); + let hidden = st.hidden_attr || raw_bytes.first() == Some(&b'.'); let utf8 = std::str::from_utf8(raw_bytes); let lossy_name = utf8.is_err(); let lossy_owned; @@ -1634,275 +1559,67 @@ fn scan_dir_linux( lossy_owned.as_ref() }; - // Fast path: regular files, FIFOs, sockets, devices never need a - // `PathBuf` unless this directory actually holds a mount point. - if matches!( - file_type, - FileType::RegularFile - | FileType::Fifo - | FileType::Socket - | FileType::CharacterDevice - | FileType::BlockDevice - ) { - if check_mounts { - let path = dir.path.join(OsStr::from_bytes(raw_bytes)); - if ctx.never_scanned.contains(&path) - || (ctx.options.one_filesystem - && ctx - .foreign_mounts - .as_ref() - .is_some_and(|m| m.contains(&path))) - { - return Ok(true); - } - } - let Ok(st) = crate::linux::stat_at(dirfd, c_name, false) else { - ctx.progress.errors.fetch_add(1, Ordering::Relaxed); - return Ok(true); - }; - let (alloc, apparent) = if st.kind == NodeKind::Other { - (0, 0) - } else { - (st.allocated_bytes, st.apparent_bytes) - }; - if st.kind == NodeKind::File { - local_files += 1; - } - local_alloc = local_alloc.saturating_add(alloc); - local_apparent = local_apparent.saturating_add(apparent); - local_leaves.push( - name_str, - st.kind, - alloc, - apparent, - st.modified, - hidden, - lossy_name, - (st.kind == NodeKind::File) - .then_some(st.hardlink) - .flatten(), - ); - return Ok(true); - } - - // Symlinks (no PathBuf allocated unless follow_links && target dir). - if file_type == FileType::Symlink { - if !ctx.options.follow_links { - let Ok(st) = crate::linux::stat_at(dirfd, c_name, false) - else { - ctx.progress.errors.fetch_add(1, Ordering::Relaxed); - return Ok(true); - }; - local_alloc = - local_alloc.saturating_add(st.allocated_bytes); - local_apparent = - local_apparent.saturating_add(st.apparent_bytes); - local_leaves.push( - name_str, - NodeKind::Symlink, - st.allocated_bytes, - st.apparent_bytes, - st.modified, - hidden, - lossy_name, - None, - ); - return Ok(true); - } - - let Ok(st) = crate::linux::stat_at(dirfd, c_name, true) else { - return Ok(true); - }; - if st.kind == NodeKind::Directory { - let path = dir.path.join(OsStr::from_bytes(raw_bytes)); - if ctx.never_scanned.contains(&path) { - return Ok(true); - } - if ctx.options.one_filesystem - && ctx - .foreign_mounts - .as_ref() - .is_some_and(|m| m.contains(&path)) - { - return Ok(true); - } - if ctx.options.one_filesystem - && ctx.foreign_mounts.is_none() - && st.device != ctx.root_dev - { - return Ok(true); - } - if let Some(id) = st.inode - && !ctx - .visited_dirs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(id) - { - return Ok(true); - } - if ctx - .options - .max_depth - .is_some_and(|limit| dir.depth + 1 > limit) - { - return Ok(true); - } - subdirs.push(Arc::new(PendingDir::new( - name_str.to_owned(), - path, - Some(Arc::clone(dir)), - dir.depth + 1, - st.modified, - hidden, - lossy_name, - ))); - return Ok(true); - } - - if st.kind == NodeKind::File { - local_files += 1; - } - local_alloc = local_alloc.saturating_add(st.allocated_bytes); - local_apparent = - local_apparent.saturating_add(st.apparent_bytes); - local_leaves.push( - name_str, - st.kind, - st.allocated_bytes, - st.apparent_bytes, - st.modified, - hidden, - lossy_name, - st.hardlink, - ); - return Ok(true); - } - - // Directory or DT_UNKNOWN: resolve kind via relative statx first. - if file_type != FileType::Directory { - let Ok(st) = crate::linux::stat_at(dirfd, c_name, false) else { - ctx.progress.errors.fetch_add(1, Ordering::Relaxed); - return Ok(true); - }; - if st.kind != NodeKind::Directory { - let (alloc, apparent) = if st.kind == NodeKind::Other { - (0, 0) - } else { - (st.allocated_bytes, st.apparent_bytes) - }; - if st.kind == NodeKind::File { - local_files += 1; - } - local_alloc = local_alloc.saturating_add(alloc); - local_apparent = local_apparent.saturating_add(apparent); - local_leaves.push( - name_str, - st.kind, - alloc, - apparent, - st.modified, - hidden, - lossy_name, - (st.kind == NodeKind::File) - .then_some(st.hardlink) - .flatten(), - ); - return Ok(true); - } - } - - let path = dir.path.join(OsStr::from_bytes(raw_bytes)); - if check_mounts { - if ctx.never_scanned.contains(&path) { - return Ok(true); + if st.kind == NodeKind::Directory { + if st.evicted { + return true; } if ctx.options.one_filesystem - && ctx - .foreign_mounts - .as_ref() - .is_some_and(|m| m.contains(&path)) + && ctx.foreign_mounts.is_none() + && st.device != ctx.root_dev { - return Ok(true); + return true; } - } - - // Fresh-subtree cache skip BEFORE statting or descending. - if let Some(oracle) = &ctx.skip_oracle - && let Some(reused) = oracle.try_reuse(&path) - { - let reused_root = reused.node(reused.root()); - ctx.progress - .skipped_fresh_dirs - .fetch_add(u64::from(reused_root.dirs), Ordering::Relaxed); - ctx.progress - .dirs - .fetch_add(u64::from(reused_root.dirs), Ordering::Relaxed); - ctx.progress - .files - .fetch_add(reused_root.files, Ordering::Relaxed); - ctx.progress - .allocated_bytes - .fetch_add(reused_root.allocated_bytes, Ordering::Relaxed); - ctx.progress - .apparent_bytes - .fetch_add(reused_root.apparent_bytes, Ordering::Relaxed); - if let Some(hook) = &ctx.on_dir_tally { - hook( - &path, - reused_root.allocated_bytes, - reused_root.apparent_bytes, - reused_root.files, - ); + if ctx.options.follow_links + && let Some(id) = st.inode + && !ctx + .visited_dirs + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .insert(id) + { + return true; } - local_children.push(BuiltChild::Grafted(Box::new( - GraftedChild { - name: name_str.to_owned(), - arena: Arc::new(reused), - hidden, - lossy_name, - }, + if ctx + .options + .max_depth + .is_some_and(|limit| dir.depth + 1 > limit) + { + return true; + } + let path = dir.path.join(OsStr::from_bytes(raw_bytes)); + subdirs.push(Arc::new(PendingDir::new( + name_str.to_owned(), + path, + Some(Arc::clone(dir)), + dir.depth + 1, + st.modified, + hidden, + lossy_name, ))); - return Ok(true); + return true; } - let Ok(st) = crate::linux::stat_at(dirfd, c_name, false) else { - ctx.progress.errors.fetch_add(1, Ordering::Relaxed); - return Ok(true); + let (alloc, apparent) = if st.kind == NodeKind::Other { + (0, 0) + } else { + (st.allocated_bytes, st.apparent_bytes) }; - if ctx.options.one_filesystem - && ctx.foreign_mounts.is_none() - && st.device != ctx.root_dev - { - return Ok(true); + if st.kind == NodeKind::File { + local_files += 1; } - if ctx.options.follow_links - && let Some(id) = st.inode - && !ctx - .visited_dirs - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(id) - { - return Ok(true); - } - if ctx - .options - .max_depth - .is_some_and(|limit| dir.depth + 1 > limit) - { - return Ok(true); - } - subdirs.push(Arc::new(PendingDir::new( - name_str.to_owned(), - path, - Some(Arc::clone(dir)), - dir.depth + 1, + local_alloc = local_alloc.saturating_add(alloc); + local_apparent = local_apparent.saturating_add(apparent); + local_leaves.push( + name_str, + st.kind, + alloc, + apparent, st.modified, hidden, lossy_name, - ))); - Ok(true) + (st.kind == NodeKind::File).then_some(st.hardlink).flatten(), + ); + true }, );