2 pub static stdout: *mut libc::FILE;
4 use bch_bindgen::{debug, info};
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")]
13 /// Whether filesystem is encrypted
14 #[getset(get_copy = "pub")]
17 #[getset(get = "pub")]
18 sb: bcachefs::bch_sb_handle,
19 /// Member devices for this filesystem
20 #[getset(get = "pub")]
21 devices: Vec<PathBuf>,
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())
33 impl std::fmt::Display for FileSystem {
34 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
35 let devs = self.device_string();
38 "{:?}: locked?={lock} ({}) ",
47 pub(crate) fn new(sb: bcachefs::bch_sb_handle) -> Self {
50 encrypted: sb.sb().crypt().is_some(),
56 pub fn device_string(&self) -> String {
57 use itertools::Itertools;
58 self.devices.iter().map(|d| d.display()).join(":")
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);
70 "mounting bcachefs filesystem, {}",
71 target.as_ref().display()
73 mount_inner(src, target, "bcachefs", mountflags, data)
79 target: impl AsRef<std::path::Path>,
83 ) -> anyhow::Result<()> {
85 ffi::{c_void, CString},
86 os::{raw::c_char, unix::ffi::OsStrExt},
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)?;
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
101 let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
104 info!("mounting filesystem");
105 // REQUIRES: CAP_SYS_ADMIN
106 unsafe { libc::mount(src, target, fstype, mountflags, data) }
110 _ => Err(crate::ErrnoError(errno::errno()).into()),
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
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),
135 "strictatime" => Left(libc::MS_STRICTATIME),
136 "sync" => Left(libc::MS_SYNCHRONOUS),
140 .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
141 Left(f) => (opts, flags | f),
148 use itertools::Itertools;
153 Some(opts.iter().join(","))
159 use bch_bindgen::bcachefs;
160 use std::collections::HashMap;
163 pub fn probe_filesystems() -> anyhow::Result<HashMap<Uuid, FileSystem>> {
164 debug!("enumerating udev devices");
165 let mut udev = udev::Enumerator::new()?;
167 udev.match_subsystem("block")?; // find kernel block devices
169 let mut fs_map = HashMap::new();
170 let devresults = udev
173 .filter_map(|dev| dev.devnode().map(ToOwned::to_owned));
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)
183 fs.devices.push(pathbuf);
192 info!("found {} filesystems", fs_map.len());
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();
204 let sb = bch_bindgen::rs::read_super(&path)?;
205 let super_block = match sb {
213 let uuid = (&super_block).sb().uuid();
214 debug!("bcachefs superblock path={} uuid={}", path.display(), uuid);
216 Ok(Ok((uuid, super_block)))