Skip to main content

btrfs_cli/filesystem/
usage.rs

1use super::UnitMode;
2use crate::{
3    Format, RunContext, Runnable,
4    util::{SizeFormat, fmt_size},
5};
6use anyhow::{Context, Result};
7use btrfs_uapi::{
8    chunk::device_chunk_allocations,
9    device::device_info_all,
10    filesystem::filesystem_info,
11    space::{BlockGroupFlags, SpaceInfo, space_info},
12};
13use clap::Parser;
14use cols::Cols;
15use std::{
16    collections::{HashMap, HashSet},
17    fs::File,
18    os::unix::io::AsFd,
19    path::PathBuf,
20};
21
22/// Show detailed information about internal filesystem usage
23#[derive(Parser, Debug)]
24pub struct FilesystemUsageCommand {
25    #[clap(flatten)]
26    pub units: UnitMode,
27
28    /// Use base 1000 for human-readable sizes
29    #[clap(short = 'H', long)]
30    pub human_si: bool,
31
32    /// Show data in tabular format
33    #[clap(short = 'T', long)]
34    pub tabular: bool,
35
36    /// One or more mount points to show usage for
37    #[clap(required = true)]
38    pub paths: Vec<PathBuf>,
39}
40
41/// Number of raw-device copies per chunk for a given profile.
42/// Returns 0 for RAID5/6 which require chunk tree data to compute accurately.
43fn profile_ncopies(flags: BlockGroupFlags) -> u64 {
44    if flags.contains(BlockGroupFlags::RAID1C4) {
45        4
46    } else if flags.contains(BlockGroupFlags::RAID1C3) {
47        3
48    } else if flags.contains(BlockGroupFlags::RAID1)
49        || flags.contains(BlockGroupFlags::DUP)
50        || flags.contains(BlockGroupFlags::RAID10)
51    {
52        2
53    } else {
54        u64::from(
55            !(flags.contains(BlockGroupFlags::RAID5)
56                || flags.contains(BlockGroupFlags::RAID6)),
57        )
58    }
59}
60
61fn has_multiple_profiles(spaces: &[SpaceInfo]) -> bool {
62    let profile_mask = BlockGroupFlags::RAID0
63        | BlockGroupFlags::RAID1
64        | BlockGroupFlags::DUP
65        | BlockGroupFlags::RAID10
66        | BlockGroupFlags::RAID5
67        | BlockGroupFlags::RAID6
68        | BlockGroupFlags::RAID1C3
69        | BlockGroupFlags::RAID1C4
70        | BlockGroupFlags::SINGLE;
71
72    let profiles_for = |type_flag: BlockGroupFlags| {
73        spaces
74            .iter()
75            .filter(|s| {
76                s.flags.contains(type_flag)
77                    && !s.flags.contains(BlockGroupFlags::GLOBAL_RSV)
78            })
79            .map(|s| s.flags & profile_mask)
80            .collect::<HashSet<_>>()
81    };
82
83    profiles_for(BlockGroupFlags::DATA).len() > 1
84        || profiles_for(BlockGroupFlags::METADATA).len() > 1
85        || profiles_for(BlockGroupFlags::SYSTEM).len() > 1
86}
87
88impl Runnable for FilesystemUsageCommand {
89    fn run(&self, ctx: &RunContext) -> Result<()> {
90        let mut mode = self.units.resolve();
91        if self.human_si {
92            mode = SizeFormat::HumanSi;
93        }
94        for (i, path) in self.paths.iter().enumerate() {
95            if i > 0 {
96                println!();
97            }
98            match ctx.format {
99                Format::Modern => print_usage_modern(path, &mode)?,
100                Format::Text | Format::Json => {
101                    print_usage(path, self.tabular, &mode)?;
102                }
103            }
104        }
105        Ok(())
106    }
107}
108
109const MIN_UNALLOCATED_THRESH: u64 = 16 * 1024 * 1024;
110
111/// Computed overall stats for a filesystem.
112struct OverallStats {
113    r_total_size: u64,
114    r_total_chunks: u64,
115    r_total_unused: u64,
116    r_total_missing: u64,
117    r_total_used: u64,
118    data_ratio: f64,
119    meta_ratio: f64,
120    free_estimated: u64,
121    free_min: u64,
122    free_statfs: u64,
123    l_global_reserve: u64,
124    l_global_reserve_used: u64,
125    multiple: bool,
126}
127
128#[allow(
129    clippy::cast_precision_loss,
130    clippy::cast_possible_truncation,
131    clippy::cast_sign_loss
132)]
133fn compute_overall(
134    path: &std::path::Path,
135    devices: &[btrfs_uapi::device::DeviceInfo],
136    spaces: &[SpaceInfo],
137) -> OverallStats {
138    let mut r_data_chunks: u64 = 0;
139    let mut r_data_used: u64 = 0;
140    let mut l_data_chunks: u64 = 0;
141    let mut r_meta_chunks: u64 = 0;
142    let mut r_meta_used: u64 = 0;
143    let mut l_meta_chunks: u64 = 0;
144    let mut r_sys_chunks: u64 = 0;
145    let mut r_sys_used: u64 = 0;
146    let mut l_global_reserve: u64 = 0;
147    let mut l_global_reserve_used: u64 = 0;
148    let mut max_ncopies: u64 = 1;
149
150    for s in spaces {
151        if s.flags.contains(BlockGroupFlags::GLOBAL_RSV) {
152            l_global_reserve = s.total_bytes;
153            l_global_reserve_used = s.used_bytes;
154            continue;
155        }
156        let ncopies = profile_ncopies(s.flags);
157        if ncopies > max_ncopies {
158            max_ncopies = ncopies;
159        }
160        if s.flags.contains(BlockGroupFlags::DATA) {
161            r_data_chunks += s.total_bytes * ncopies;
162            r_data_used += s.used_bytes * ncopies;
163            l_data_chunks += s.total_bytes;
164        }
165        if s.flags.contains(BlockGroupFlags::METADATA) {
166            r_meta_chunks += s.total_bytes * ncopies;
167            r_meta_used += s.used_bytes * ncopies;
168            l_meta_chunks += s.total_bytes;
169        }
170        if s.flags.contains(BlockGroupFlags::SYSTEM) {
171            r_sys_chunks += s.total_bytes * ncopies;
172            r_sys_used += s.used_bytes * ncopies;
173        }
174    }
175
176    let r_total_size: u64 = devices.iter().map(|d| d.total_bytes).sum();
177    let r_total_chunks = r_data_chunks + r_meta_chunks + r_sys_chunks;
178    let r_total_used = r_data_used + r_meta_used + r_sys_used;
179    let r_total_unused = r_total_size.saturating_sub(r_total_chunks);
180
181    let r_total_missing: u64 = devices
182        .iter()
183        .filter(|d| std::fs::metadata(&d.path).is_err())
184        .map(|d| d.total_bytes)
185        .sum();
186
187    let data_ratio = if l_data_chunks > 0 {
188        r_data_chunks as f64 / l_data_chunks as f64
189    } else {
190        1.0
191    };
192    let meta_ratio = if l_meta_chunks > 0 {
193        r_meta_chunks as f64 / l_meta_chunks as f64
194    } else {
195        1.0
196    };
197    let max_data_ratio = max_ncopies as f64;
198
199    let free_base = if data_ratio > 0.0 {
200        ((r_data_chunks.saturating_sub(r_data_used)) as f64 / data_ratio) as u64
201    } else {
202        0
203    };
204    let (free_estimated, free_min) = if r_total_unused >= MIN_UNALLOCATED_THRESH
205    {
206        (
207            free_base + (r_total_unused as f64 / data_ratio) as u64,
208            free_base + (r_total_unused as f64 / max_data_ratio) as u64,
209        )
210    } else {
211        (free_base, free_base)
212    };
213
214    let free_statfs = nix::sys::statfs::statfs(path)
215        .map_or(0, |st| st.blocks_available() * st.block_size() as u64);
216
217    let multiple = has_multiple_profiles(spaces);
218
219    OverallStats {
220        r_total_size,
221        r_total_chunks,
222        r_total_unused,
223        r_total_missing,
224        r_total_used,
225        data_ratio,
226        meta_ratio,
227        free_estimated,
228        free_min,
229        free_statfs,
230        l_global_reserve,
231        l_global_reserve_used,
232        multiple,
233    }
234}
235
236#[allow(
237    clippy::too_many_lines,
238    clippy::cast_precision_loss,
239    clippy::cast_possible_truncation,
240    clippy::cast_sign_loss
241)]
242fn print_usage(
243    path: &std::path::Path,
244    _tabular: bool,
245    mode: &SizeFormat,
246) -> Result<()> {
247    let file = File::open(path)
248        .with_context(|| format!("failed to open '{}'", path.display()))?;
249    let fd = file.as_fd();
250
251    let fs = filesystem_info(fd).with_context(|| {
252        format!("failed to get filesystem info for '{}'", path.display())
253    })?;
254    let devices = device_info_all(fd, &fs).with_context(|| {
255        format!("failed to get device info for '{}'", path.display())
256    })?;
257    let spaces = space_info(fd).with_context(|| {
258        format!("failed to get space info for '{}'", path.display())
259    })?;
260
261    // Per-device chunk allocations from the chunk tree.  This requires
262    // CAP_SYS_ADMIN; if it fails we degrade gracefully and note it below.
263    let chunk_allocs = device_chunk_allocations(fd).ok();
264
265    // Map devid -> path for display.
266    let devid_to_path: HashMap<u64, &str> =
267        devices.iter().map(|d| (d.devid, d.path.as_str())).collect();
268
269    let stats = compute_overall(path, &devices, &spaces);
270
271    println!("Overall:");
272    println!(
273        "    Device size:\t\t{:>10}",
274        fmt_size(stats.r_total_size, mode)
275    );
276    println!(
277        "    Device allocated:\t\t{:>10}",
278        fmt_size(stats.r_total_chunks, mode)
279    );
280    println!(
281        "    Device unallocated:\t\t{:>10}",
282        fmt_size(stats.r_total_unused, mode)
283    );
284    println!(
285        "    Device missing:\t\t{:>10}",
286        fmt_size(stats.r_total_missing, mode)
287    );
288    println!("    Device slack:\t\t{:>10}", fmt_size(0, mode));
289    println!("    Used:\t\t\t{:>10}", fmt_size(stats.r_total_used, mode));
290    println!(
291        "    Free (estimated):\t\t{:>10}\t(min: {})",
292        fmt_size(stats.free_estimated, mode),
293        fmt_size(stats.free_min, mode)
294    );
295    println!(
296        "    Free (statfs, df):\t\t{:>10}",
297        fmt_size(stats.free_statfs, mode)
298    );
299    println!("    Data ratio:\t\t\t{:>10.2}", stats.data_ratio);
300    println!("    Metadata ratio:\t\t{:>10.2}", stats.meta_ratio);
301    println!(
302        "    Global reserve:\t\t{:>10}\t(used: {})",
303        fmt_size(stats.l_global_reserve, mode),
304        fmt_size(stats.l_global_reserve_used, mode)
305    );
306    println!(
307        "    Multiple profiles:\t\t{:>10}",
308        if stats.multiple { "yes" } else { "no" }
309    );
310
311    if chunk_allocs.is_none() {
312        eprintln!(
313            "NOTE: per-device usage breakdown unavailable \
314             (chunk tree requires CAP_SYS_ADMIN)"
315        );
316    }
317
318    for s in &spaces {
319        if s.flags.contains(BlockGroupFlags::GLOBAL_RSV) {
320            continue;
321        }
322        #[allow(clippy::cast_precision_loss)]
323        let pct = if s.total_bytes > 0 {
324            100.0 * s.used_bytes as f64 / s.total_bytes as f64
325        } else {
326            0.0
327        };
328        println!(
329            "\n{},{}: Size:{}, Used:{} ({:.2}%)",
330            s.flags.type_name(),
331            s.flags.profile_name(),
332            fmt_size(s.total_bytes, mode),
333            fmt_size(s.used_bytes, mode),
334            pct
335        );
336
337        // Per-device lines: one row per device that holds stripes for this
338        // exact profile.  Sorted by devid for stable output.
339        if let Some(allocs) = &chunk_allocs {
340            let mut profile_allocs: Vec<_> =
341                allocs.iter().filter(|a| a.flags == s.flags).collect();
342            profile_allocs.sort_by_key(|a| a.devid);
343
344            for alloc in profile_allocs {
345                let path = devid_to_path
346                    .get(&alloc.devid)
347                    .copied()
348                    .unwrap_or("<unknown>");
349                println!("   {}\t\t{:>10}", path, fmt_size(alloc.bytes, mode));
350            }
351        }
352    }
353
354    println!("\nUnallocated:");
355    for dev in &devices {
356        let unallocated = dev.total_bytes.saturating_sub(dev.bytes_used);
357        println!("   {}\t{:>10}", dev.path, fmt_size(unallocated, mode));
358    }
359
360    Ok(())
361}
362
363// -- Modern output -----------------------------------------------------------
364
365#[derive(Cols)]
366struct OverallRow {
367    #[column(header = "PROPERTY")]
368    label: String,
369    #[column(header = "VALUE", right)]
370    value: String,
371}
372
373#[derive(Cols)]
374struct ProfileRow {
375    #[column(header = "TYPE")]
376    bg_type: String,
377    #[column(header = "PROFILE")]
378    profile: String,
379    #[column(header = "TOTAL", right)]
380    total: String,
381    #[column(header = "USED", right)]
382    used: String,
383    #[column(header = "USED%", right)]
384    pct: String,
385}
386
387#[allow(
388    clippy::too_many_lines,
389    clippy::cast_precision_loss,
390    clippy::cast_possible_truncation,
391    clippy::cast_sign_loss
392)]
393fn print_usage_modern(path: &std::path::Path, mode: &SizeFormat) -> Result<()> {
394    let file = File::open(path)
395        .with_context(|| format!("failed to open '{}'", path.display()))?;
396    let fd = file.as_fd();
397
398    let fs = filesystem_info(fd).with_context(|| {
399        format!("failed to get filesystem info for '{}'", path.display())
400    })?;
401    let devices = device_info_all(fd, &fs).with_context(|| {
402        format!("failed to get device info for '{}'", path.display())
403    })?;
404    let spaces = space_info(fd).with_context(|| {
405        format!("failed to get space info for '{}'", path.display())
406    })?;
407    let chunk_allocs = device_chunk_allocations(fd).ok();
408
409    let stats = compute_overall(path, &devices, &spaces);
410
411    // Section 1: Overall key-value table
412    println!("Overall:");
413    let mut overall_rows = vec![
414        OverallRow {
415            label: "Device size".to_string(),
416            value: fmt_size(stats.r_total_size, mode),
417        },
418        OverallRow {
419            label: "Device allocated".to_string(),
420            value: fmt_size(stats.r_total_chunks, mode),
421        },
422        OverallRow {
423            label: "Device unallocated".to_string(),
424            value: fmt_size(stats.r_total_unused, mode),
425        },
426        OverallRow {
427            label: "Device missing".to_string(),
428            value: fmt_size(stats.r_total_missing, mode),
429        },
430        OverallRow {
431            label: "Device slack".to_string(),
432            value: fmt_size(0, mode),
433        },
434        OverallRow {
435            label: "Used".to_string(),
436            value: fmt_size(stats.r_total_used, mode),
437        },
438        OverallRow {
439            label: "Free (estimated)".to_string(),
440            value: format!(
441                "{}  (min: {})",
442                fmt_size(stats.free_estimated, mode),
443                fmt_size(stats.free_min, mode)
444            ),
445        },
446        OverallRow {
447            label: "Free (statfs, df)".to_string(),
448            value: fmt_size(stats.free_statfs, mode),
449        },
450        OverallRow {
451            label: "Data ratio".to_string(),
452            value: format!("{:.2}", stats.data_ratio),
453        },
454        OverallRow {
455            label: "Metadata ratio".to_string(),
456            value: format!("{:.2}", stats.meta_ratio),
457        },
458    ];
459
460    overall_rows.push(OverallRow {
461        label: "Global reserve".to_string(),
462        value: format!(
463            "{}  (used: {})",
464            fmt_size(stats.l_global_reserve, mode),
465            fmt_size(stats.l_global_reserve_used, mode)
466        ),
467    });
468    overall_rows.push(OverallRow {
469        label: "Multiple profiles".to_string(),
470        value: if stats.multiple { "yes" } else { "no" }.to_string(),
471    });
472
473    let mut out = std::io::stdout().lock();
474    let _ = OverallRow::print_table(&overall_rows, &mut out);
475
476    if chunk_allocs.is_none() {
477        eprintln!(
478            "NOTE: per-device usage breakdown unavailable \
479             (chunk tree requires CAP_SYS_ADMIN)"
480        );
481    }
482
483    // Section 2: Profile summary table
484    let profile_rows: Vec<ProfileRow> = spaces
485        .iter()
486        .filter(|s| !s.flags.contains(BlockGroupFlags::GLOBAL_RSV))
487        .map(|s| {
488            let pct = if s.total_bytes > 0 {
489                100.0 * s.used_bytes as f64 / s.total_bytes as f64
490            } else {
491                0.0
492            };
493            ProfileRow {
494                bg_type: s.flags.type_name().to_string(),
495                profile: s.flags.profile_name().to_string(),
496                total: fmt_size(s.total_bytes, mode),
497                used: fmt_size(s.used_bytes, mode),
498                pct: format!("{pct:.2}%"),
499            }
500        })
501        .collect();
502
503    if !profile_rows.is_empty() {
504        println!();
505        let _ = ProfileRow::print_table(&profile_rows, &mut out);
506    }
507
508    // Section 3: Per-device allocation table (dynamic columns)
509    if let Some(allocs) = &chunk_allocs {
510        // Collect unique profiles in display order.
511        let mut profile_flags: Vec<BlockGroupFlags> = Vec::new();
512        for s in &spaces {
513            if s.flags.contains(BlockGroupFlags::GLOBAL_RSV) {
514                continue;
515            }
516            if !profile_flags.contains(&s.flags) {
517                profile_flags.push(s.flags);
518            }
519        }
520
521        let mut table = cols::Table::new();
522        table.add_column(cols::Column::new("PATH"));
523        for flags in &profile_flags {
524            table.add_column(
525                cols::Column::new(&format!(
526                    "{},{}",
527                    flags.type_name(),
528                    flags.profile_name()
529                ))
530                .right(true),
531            );
532        }
533        table.add_column(cols::Column::new("UNALLOC").right(true));
534
535        for dev in &devices {
536            let line = table.new_line(None);
537            let row = table.line_mut(line);
538            row.data_set(0, &dev.path);
539
540            let mut allocated: u64 = 0;
541            for (ci, flags) in profile_flags.iter().enumerate() {
542                let bytes: u64 = allocs
543                    .iter()
544                    .filter(|a| a.devid == dev.devid && a.flags == *flags)
545                    .map(|a| a.bytes)
546                    .sum();
547                allocated += bytes;
548                if bytes > 0 {
549                    row.data_set(ci + 1, &fmt_size(bytes, mode));
550                } else {
551                    row.data_set(ci + 1, "-");
552                }
553            }
554
555            let unallocated = dev.total_bytes.saturating_sub(allocated);
556            row.data_set(profile_flags.len() + 1, &fmt_size(unallocated, mode));
557        }
558
559        println!();
560        let _ = cols::print_table(&table, &mut out);
561    }
562
563    Ok(())
564}