2 pub static stdout: *mut libc::FILE;
5 use getset::{CopyGetters, Getters};
6 use std::path::PathBuf;
7 #[derive(Getters, CopyGetters)]
8 pub struct FileSystem {
9 /// External UUID of the bcachefs
10 #[getset(get = "pub")]
12 /// Whether filesystem is encrypted
13 #[getset(get_copy = "pub")]
16 #[getset(get = "pub")]
17 sb: bcachefs::bch_sb_handle,
18 /// Member devices for this filesystem
19 #[getset(get = "pub")]
20 devices: Vec<PathBuf>,
22 impl std::fmt::Debug for FileSystem {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 f.debug_struct("FileSystem")
25 .field("uuid", &self.uuid)
26 .field("encrypted", &self.encrypted)
27 .field("devices", &self.device_string())
32 impl std::fmt::Display for FileSystem {
33 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34 let devs = self.device_string();
37 "{:?}: locked?={lock} ({}) ",
46 pub(crate) fn new(sb: bcachefs::bch_sb_handle) -> Self {
49 encrypted: sb.sb().crypt().is_some(),
55 pub fn device_string(&self) -> String {
56 use itertools::Itertools;
57 self.devices.iter().map(|d| d.display()).join(":")
62 target: impl AsRef<std::path::Path>,
63 options: impl AsRef<str>,
64 ) -> anyhow::Result<()> {
65 tracing::info_span!("mount").in_scope(|| {
66 let src = self.device_string();
67 let (data, mountflags) = parse_mount_options(options);
68 // let fstype = c_str!("bcachefs");
70 tracing::info!(msg="mounting bcachefs filesystem", target=%target.as_ref().display());
71 mount_inner(src, target, "bcachefs", mountflags, data)
78 target: impl AsRef<std::path::Path>,
82 ) -> anyhow::Result<()> {
84 ffi::{c_void, CString},
85 os::{raw::c_char, unix::ffi::OsStrExt},
88 // bind the CStrings to keep them alive
89 let src = CString::new(src)?;
90 let target = CString::new(target.as_ref().as_os_str().as_bytes())?;
91 let data = data.map(CString::new).transpose()?;
92 let fstype = CString::new(fstype)?;
94 // convert to pointers for ffi
95 let src = src.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
96 let target = target.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
97 let data = data.as_ref().map_or(std::ptr::null(), |data| {
98 data.as_c_str().to_bytes_with_nul().as_ptr() as *const c_void
100 let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
102 let ret = {let _entered = tracing::info_span!("libc::mount").entered();
103 tracing::info!("mounting filesystem");
104 // REQUIRES: CAP_SYS_ADMIN
105 unsafe { libc::mount(src, target, fstype, mountflags, data) }
109 _ => Err(crate::ErrnoError(errno::errno()).into()),
113 /// Parse a comma-separated mount options and split out mountflags and filesystem
114 /// specific options.
115 #[tracing_attributes::instrument(skip(options))]
116 fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, u64) {
117 use either::Either::*;
118 tracing::debug!(msg="parsing mount options", 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 "ro" => Left(libc::MS_RDONLY),
133 "relatime" => Left(libc::MS_RELATIME),
134 "strictatime" => Left(libc::MS_STRICTATIME),
135 "sync" => Left(libc::MS_SYNCHRONOUS),
139 .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
140 Left(f) => (opts, flags | f),
147 use itertools::Itertools;
152 Some(opts.iter().join(","))
158 use bch_bindgen::bcachefs;
159 use std::collections::HashMap;
162 #[tracing_attributes::instrument]
163 pub fn probe_filesystems() -> anyhow::Result<HashMap<Uuid, FileSystem>> {
164 tracing::trace!("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();
173 .filter_map(|dev| dev.devnode().map(ToOwned::to_owned));
175 for pathbuf in devresults {
176 match get_super_block_uuid(&pathbuf)? {
178 Ok((uuid_key, superblock)) => {
179 let fs = fs_map.entry(uuid_key).or_insert_with(|| {
180 tracing::info!(msg="found bcachefs pool", uuid=?uuid_key);
181 FileSystem::new(superblock)
184 fs.devices.push(pathbuf);
187 Err(e) => { tracing::debug!(inner2_error=?e);}
192 tracing::info!(msg = "found filesystems", count = fs_map.len());
196 // #[tracing_attributes::instrument(skip(dev, fs_map))]
197 fn get_super_block_uuid(path: &std::path::Path) -> std::io::Result<std::io::Result<(Uuid, bcachefs::bch_sb_handle)>> {
198 let sb = bch_bindgen::rs::read_super(&path)?;
199 let super_block = match sb {
200 Err(e) => { return Ok(Err(e)); }
204 let uuid = (&super_block).sb().uuid();
205 tracing::debug!(found="bcachefs superblock", devnode=?path, ?uuid);
207 Ok(Ok((uuid, super_block)))