btrfs_cli/inspect/
dump_super.rs1use crate::{Format, Runnable};
2use anyhow::{Context, Result, bail};
3use btrfs_disk::superblock::{self, SUPER_MIRROR_MAX};
4use clap::Parser;
5use std::{fs::File, path::PathBuf};
6
7#[derive(Parser, Debug)]
14pub struct DumpSuperCommand {
15 path: PathBuf,
17
18 #[clap(short = 'f', long)]
20 full: bool,
21
22 #[clap(short = 'a', long)]
24 all: bool,
25
26 #[clap(short = 's', long = "super", value_parser = clap::value_parser!(u32).range(..SUPER_MIRROR_MAX as i64))]
28 mirror: Option<u32>,
29
30 #[clap(short = 'F', long)]
32 force: bool,
33}
34
35impl Runnable for DumpSuperCommand {
36 fn run(&self, _format: Format, _dry_run: bool) -> Result<()> {
37 let mut file = File::open(&self.path)
38 .with_context(|| format!("failed to open '{}'", self.path.display()))?;
39
40 let mirrors: Vec<u32> = if self.all {
41 (0..SUPER_MIRROR_MAX).collect()
42 } else if let Some(m) = self.mirror {
43 vec![m]
44 } else {
45 vec![0]
46 };
47
48 for (i, &mirror) in mirrors.iter().enumerate() {
49 if i > 0 {
50 println!();
51 }
52
53 let offset = superblock::super_mirror_offset(mirror);
54 println!(
55 "superblock: bytenr={offset}, device={}",
56 self.path.display()
57 );
58
59 let sb = match superblock::read_superblock(&mut file, mirror) {
60 Ok(sb) => sb,
61 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
62 println!("superblock mirror {mirror} beyond end of device, skipping");
63 continue;
64 }
65 Err(e) => {
66 return Err(e).with_context(|| {
67 format!(
68 "failed to read superblock mirror {mirror} from '{}'",
69 self.path.display()
70 )
71 });
72 }
73 };
74
75 if !sb.magic_is_valid() && !self.force {
76 if self.all {
77 println!(
78 "superblock mirror {mirror} has bad magic, skipping (use -F to force)"
79 );
80 continue;
81 }
82 bail!(
83 "bad magic on superblock mirror {mirror} of '{}' (use -F to force)",
84 self.path.display()
85 );
86 }
87
88 println!("---------------------------------------------------------");
89 superblock::print_superblock(&sb, self.full);
90 }
91
92 Ok(())
93 }
94}