]> git.sesse.net Git - bcachefs-tools-debian/blob - rust-src/mount/src/filesystem.rs
Update bcachefs sources to 8e1519ccb6 bcachefs: Add tracepoint & counter for btree...
[bcachefs-tools-debian] / rust-src / mount / src / filesystem.rs
1 extern "C" {
2     pub static stdout: *mut libc::FILE;
3 }
4 use bch_bindgen::{debug, info};
5 use colored::Colorize;
6 use getset::{CopyGetters, Getters};
7 use std::path::PathBuf;
8 #[derive(Getters, CopyGetters)]
9 pub struct FileSystem {
10     /// External UUID of the bcachefs
11     #[getset(get = "pub")]
12     uuid: uuid::Uuid,
13     /// Whether filesystem is encrypted
14     #[getset(get_copy = "pub")]
15     encrypted: bool,
16     /// Super block
17     #[getset(get = "pub")]
18     sb: bcachefs::bch_sb_handle,
19     /// Member devices for this filesystem
20     #[getset(get = "pub")]
21     devices: Vec<PathBuf>,
22 }
23 impl std::fmt::Debug for FileSystem {
24     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25         f.debug_struct("FileSystem")
26             .field("uuid", &self.uuid)
27             .field("encrypted", &self.encrypted)
28             .field("devices", &self.device_string())
29             .finish()
30     }
31 }
32 use std::fmt;
33 impl std::fmt::Display for FileSystem {
34     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35         let devs = self.device_string();
36         write!(
37             f,
38             "{:?}: locked?={lock} ({}) ",
39             self.uuid,
40             devs,
41             lock = self.encrypted
42         )
43     }
44 }
45
46 impl FileSystem {
47     pub(crate) fn new(sb: bcachefs::bch_sb_handle) -> Self {
48         Self {
49             uuid: sb.sb().uuid(),
50             encrypted: sb.sb().crypt().is_some(),
51             sb: sb,
52             devices: Vec::new(),
53         }
54     }
55
56     pub fn device_string(&self) -> String {
57         use itertools::Itertools;
58         self.devices.iter().map(|d| d.display()).join(":")
59     }
60
61     pub fn mount(
62         &self,
63         target: impl AsRef<std::path::Path>,
64         options: impl AsRef<str>,
65     ) -> anyhow::Result<()> {
66         let src = self.device_string();
67         let (data, mountflags) = parse_mount_options(options);
68
69         info!(
70             "mounting bcachefs filesystem, {}",
71             target.as_ref().display()
72         );
73         mount_inner(src, target, "bcachefs", mountflags, data)
74     }
75 }
76
77 fn mount_inner(
78     src: String,
79     target: impl AsRef<std::path::Path>,
80     fstype: &str,
81     mountflags: u64,
82     data: Option<String>,
83 ) -> anyhow::Result<()> {
84     use std::{
85         ffi::{c_void, CString},
86         os::{raw::c_char, unix::ffi::OsStrExt},
87     };
88
89     // bind the CStrings to keep them alive
90     let src = CString::new(src)?;
91     let target = CString::new(target.as_ref().as_os_str().as_bytes())?;
92     let data = data.map(CString::new).transpose()?;
93     let fstype = CString::new(fstype)?;
94
95     // convert to pointers for ffi
96     let src = src.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
97     let target = target.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
98     let data = data.as_ref().map_or(std::ptr::null(), |data| {
99         data.as_c_str().to_bytes_with_nul().as_ptr() as *const c_void
100     });
101     let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
102
103     let ret = {
104         info!("mounting filesystem");
105         // REQUIRES: CAP_SYS_ADMIN
106         unsafe { libc::mount(src, target, fstype, mountflags, data) }
107     };
108     match ret {
109         0 => Ok(()),
110         _ => Err(crate::ErrnoError(errno::errno()).into()),
111     }
112 }
113
114 /// Parse a comma-separated mount options and split out mountflags and filesystem
115 /// specific options.
116 fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, u64) {
117     use either::Either::*;
118     debug!("parsing mount options: {}", options.as_ref());
119     let (opts, flags) = options
120         .as_ref()
121         .split(",")
122         .map(|o| match o {
123             "dirsync" => Left(libc::MS_DIRSYNC),
124             "lazytime" => Left(1 << 25), // MS_LAZYTIME
125             "mand" => Left(libc::MS_MANDLOCK),
126             "noatime" => Left(libc::MS_NOATIME),
127             "nodev" => Left(libc::MS_NODEV),
128             "nodiratime" => Left(libc::MS_NODIRATIME),
129             "noexec" => Left(libc::MS_NOEXEC),
130             "nosuid" => Left(libc::MS_NOSUID),
131             "relatime" => Left(libc::MS_RELATIME),
132             "remount" => Left(libc::MS_REMOUNT),
133             "ro" => Left(libc::MS_RDONLY),
134             "rw" => Left(0),
135             "strictatime" => Left(libc::MS_STRICTATIME),
136             "sync" => Left(libc::MS_SYNCHRONOUS),
137             "" => Left(0),
138             o @ _ => Right(o),
139         })
140         .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
141             Left(f) => (opts, flags | f),
142             Right(o) => {
143                 opts.push(o);
144                 (opts, flags)
145             }
146         });
147
148     use itertools::Itertools;
149     (
150         if opts.len() == 0 {
151             None
152         } else {
153             Some(opts.iter().join(","))
154         },
155         flags,
156     )
157 }
158
159 use bch_bindgen::bcachefs;
160 use std::collections::HashMap;
161 use uuid::Uuid;
162
163 pub fn probe_filesystems() -> anyhow::Result<HashMap<Uuid, FileSystem>> {
164     debug!("enumerating udev devices");
165     let mut udev = udev::Enumerator::new()?;
166
167     udev.match_subsystem("block")?; // find kernel block devices
168
169     let mut fs_map = HashMap::new();
170     let devresults = udev
171         .scan_devices()?
172         .into_iter()
173         .filter_map(|dev| dev.devnode().map(ToOwned::to_owned));
174
175     for pathbuf in devresults {
176         match get_super_block_uuid(&pathbuf)? {
177             Ok((uuid_key, superblock)) => {
178                 let fs = fs_map.entry(uuid_key).or_insert_with(|| {
179                     info!("found bcachefs pool: {}", uuid_key);
180                     FileSystem::new(superblock)
181                 });
182
183                 fs.devices.push(pathbuf);
184             }
185
186             Err(e) => {
187                 debug!("{}", e);
188             }
189         }
190     }
191
192     info!("found {} filesystems", fs_map.len());
193     Ok(fs_map)
194 }
195
196 // #[tracing_attributes::instrument(skip(dev, fs_map))]
197 fn get_super_block_uuid(
198     path: &std::path::Path,
199 ) -> std::io::Result<std::io::Result<(Uuid, bcachefs::bch_sb_handle)>> {
200     use gag::BufferRedirect;
201     // Stop libbcachefs from spamming the output
202     let gag = BufferRedirect::stdout().unwrap();
203
204     let sb = bch_bindgen::rs::read_super(&path)?;
205     let super_block = match sb {
206         Err(e) => {
207             return Ok(Err(e));
208         }
209         Ok(sb) => sb,
210     };
211     drop(gag);
212
213     let uuid = (&super_block).sb().uuid();
214     debug!("bcachefs superblock path={} uuid={}", path.display(), uuid);
215
216     Ok(Ok((uuid, super_block)))
217 }