]> git.sesse.net Git - bcachefs-tools-debian/blob - rust-src/mount/src/filesystem.rs
New upstream release
[bcachefs-tools-debian] / rust-src / mount / src / filesystem.rs
1 extern "C" {
2         pub static stdout: *mut libc::FILE;
3 }
4
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")]
11         uuid: uuid::Uuid,
12         /// Whether filesystem is encrypted
13         #[getset(get_copy = "pub")]
14         encrypted: bool,
15         /// Super block
16         #[getset(get = "pub")]
17         sb: bcachefs::bch_sb_handle,
18         /// Member devices for this filesystem
19         #[getset(get = "pub")]
20         devices: Vec<PathBuf>,
21 }
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())
28                         .finish()
29         }
30 }
31 use std::fmt;
32 impl std::fmt::Display for FileSystem {
33         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34                 let devs = self.device_string();
35                 write!(
36                         f,
37                         "{:?}: locked?={lock} ({}) ",
38                         self.uuid,
39                         devs,
40                         lock = self.encrypted
41                 )
42         }
43 }
44
45 impl FileSystem {
46         pub(crate) fn new(sb: bcachefs::bch_sb_handle) -> Self {
47                 Self {
48                         uuid: sb.sb().uuid(),
49                         encrypted: sb.sb().crypt().is_some(),
50                         sb: sb,
51                         devices: Vec::new(),
52                 }
53         }
54
55         pub fn device_string(&self) -> String {
56                 use itertools::Itertools;
57                 self.devices.iter().map(|d| d.display()).join(":")
58         }
59
60         pub fn mount(
61                 &self,
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");
69
70                         tracing::info!(msg="mounting bcachefs filesystem", target=%target.as_ref().display());
71                         mount_inner(src, target, "bcachefs", mountflags, data)
72                 })
73         }
74 }
75
76 fn mount_inner(
77         src: String,
78         target: impl AsRef<std::path::Path>,
79         fstype: &str,
80         mountflags: u64,
81         data: Option<String>,
82 ) -> anyhow::Result<()> {
83         use std::{
84                 ffi::{c_void, CString},
85                 os::{raw::c_char, unix::ffi::OsStrExt},
86         };
87
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)?;
93
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
99         });
100         let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
101         
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) }
106         };
107         match ret {
108                 0 => Ok(()),
109                 _ => Err(crate::ErrnoError(errno::errno()).into()),
110         }
111 }
112
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
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                         "ro" => Left(libc::MS_RDONLY),
132                         "rw" => Left(0),
133                         "relatime" => Left(libc::MS_RELATIME),
134                         "strictatime" => Left(libc::MS_STRICTATIME),
135                         "sync" => Left(libc::MS_SYNCHRONOUS),
136                         "" => Left(0),
137                         o @ _ => Right(o),
138                 })
139                 .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
140                         Left(f) => (opts, flags | f),
141                         Right(o) => {
142                                 opts.push(o);
143                                 (opts, flags)
144                         }
145                 });
146
147         use itertools::Itertools;
148         (
149                 if opts.len() == 0 {
150                         None
151                 } else {
152                         Some(opts.iter().join(","))
153                 },
154                 flags,
155         )
156 }
157
158 use bch_bindgen::bcachefs;
159 use std::collections::HashMap;
160 use uuid::Uuid;
161
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()?;
166
167         udev.match_subsystem("block")?; // find kernel block devices
168
169         let mut fs_map = HashMap::new();
170         let devresults = 
171                         udev.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
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)
182                                         });
183
184                                         fs.devices.push(pathbuf);
185                                 },
186
187                                 Err(e) => { tracing::debug!(inner2_error=?e);}
188                 }
189         }
190
191         
192         tracing::info!(msg = "found filesystems", count = fs_map.len());
193         Ok(fs_map)
194 }
195
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)); }
201                 Ok(sb) => sb,
202         };
203
204         let uuid = (&super_block).sb().uuid();
205         tracing::debug!(found="bcachefs superblock", devnode=?path, ?uuid);
206
207         Ok(Ok((uuid, super_block)))
208 }