Skip to main content

btrfs_uapi/
sysfs.rs

1//! # Sysfs interface: reading filesystem and device state from `/sys/fs/btrfs/`
2//!
3//! The kernel exposes per-filesystem information under
4//! `/sys/fs/btrfs/<uuid>/`, where `<uuid>` is the filesystem UUID as returned
5//! by [`fs_info`][`crate::filesystem::fs_info`]. This includes commit statistics,
6//! feature flags, quota state, and per-device scrub limits.
7//!
8//! The primary entry point is [`SysfsBtrfs`], which is constructed from a
9//! filesystem UUID and provides typed accessors for each sysfs file:
10//!
11//! ```no_run
12//! # use btrfs_uapi::{filesystem::fs_info, sysfs::SysfsBtrfs};
13//! # use std::{fs::File, os::unix::io::AsFd};
14//! # let file = File::open("/mnt/btrfs").unwrap();
15//! # let fd = file.as_fd();
16//! let info = fs_info(fd).unwrap();
17//! let sysfs = SysfsBtrfs::new(&info.uuid);
18//! println!("label: {}", sysfs.label().unwrap());
19//! println!("quota status: {:?}", sysfs.quota_status().unwrap());
20//! ```
21//!
22//! All accessors return [`std::io::Result`] and will return an error with kind
23//! [`std::io::ErrorKind::NotFound`] if the filesystem is not currently mounted.
24
25use std::{ffi::OsStr, fs, io, path::PathBuf};
26use uuid::Uuid;
27
28/// Returns the sysfs directory path for the btrfs filesystem with the given
29/// UUID: `/sys/fs/btrfs/<uuid>`.
30pub fn sysfs_btrfs_path(uuid: &Uuid) -> PathBuf {
31    PathBuf::from(format!("/sys/fs/btrfs/{}", uuid.as_hyphenated()))
32}
33
34/// Returns the path to a named file within the sysfs directory for the
35/// filesystem with the given UUID: `/sys/fs/btrfs/<uuid>/<name>`.
36pub fn sysfs_btrfs_path_file(uuid: &Uuid, name: &str) -> PathBuf {
37    sysfs_btrfs_path(uuid).join(name)
38}
39
40/// Commit statistics for a mounted btrfs filesystem, read from
41/// `/sys/fs/btrfs/<uuid>/commit_stats`.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct CommitStats {
44    /// Total number of commits since mount.
45    pub commits: u64,
46    /// Duration of the current (in-progress) commit in milliseconds.
47    pub cur_commit_ms: u64,
48    /// Duration of the last completed commit in milliseconds.
49    pub last_commit_ms: u64,
50    /// Maximum commit duration since mount (or last reset) in milliseconds.
51    pub max_commit_ms: u64,
52    /// Total time spent in commits since mount in milliseconds.
53    pub total_commit_ms: u64,
54}
55
56/// Provides typed access to the sysfs files exposed for a single mounted btrfs
57/// filesystem under `/sys/fs/btrfs/<uuid>/`.
58pub struct SysfsBtrfs {
59    base: PathBuf,
60}
61
62impl SysfsBtrfs {
63    /// Create a new `SysfsBtrfs` for the filesystem with the given UUID.
64    pub fn new(uuid: &Uuid) -> Self {
65        Self {
66            base: sysfs_btrfs_path(uuid),
67        }
68    }
69
70    fn read_file(&self, name: &str) -> io::Result<String> {
71        let s = fs::read_to_string(self.base.join(name))?;
72        Ok(s.trim_end().to_owned())
73    }
74
75    fn read_u64(&self, name: &str) -> io::Result<u64> {
76        let s = self.read_file(name)?;
77        s.parse()
78            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
79    }
80
81    fn read_bool(&self, name: &str) -> io::Result<bool> {
82        Ok(self.read_u64(name)? != 0)
83    }
84
85    /// Background reclaim threshold as a percentage (0–100).
86    /// `/sys/fs/btrfs/<uuid>/bg_reclaim_threshold`
87    pub fn bg_reclaim_threshold(&self) -> io::Result<u64> {
88        self.read_u64("bg_reclaim_threshold")
89    }
90
91    /// Checksum algorithm in use, e.g. `"crc32c (crc32c-lib)"`.
92    /// `/sys/fs/btrfs/<uuid>/checksum`
93    pub fn checksum(&self) -> io::Result<String> {
94        self.read_file("checksum")
95    }
96
97    /// Minimum clone/reflink alignment in bytes.
98    /// `/sys/fs/btrfs/<uuid>/clone_alignment`
99    pub fn clone_alignment(&self) -> io::Result<u64> {
100        self.read_u64("clone_alignment")
101    }
102
103    /// Commit statistics since mount (or last reset).
104    /// `/sys/fs/btrfs/<uuid>/commit_stats`
105    pub fn commit_stats(&self) -> io::Result<CommitStats> {
106        let contents = self.read_file("commit_stats")?;
107        let mut commits = None;
108        let mut cur_commit_ms = None;
109        let mut last_commit_ms = None;
110        let mut max_commit_ms = None;
111        let mut total_commit_ms = None;
112
113        for line in contents.lines() {
114            let mut parts = line.splitn(2, ' ');
115            let key = parts.next().unwrap_or("").trim();
116            let val: u64 = parts
117                .next()
118                .unwrap_or("")
119                .trim()
120                .parse()
121                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
122            match key {
123                "commits" => commits = Some(val),
124                "cur_commit_ms" => cur_commit_ms = Some(val),
125                "last_commit_ms" => last_commit_ms = Some(val),
126                "max_commit_ms" => max_commit_ms = Some(val),
127                "total_commit_ms" => total_commit_ms = Some(val),
128                _ => {}
129            }
130        }
131
132        let missing = |name| {
133            io::Error::new(
134                io::ErrorKind::InvalidData,
135                format!("commit_stats: missing field '{name}'"),
136            )
137        };
138
139        Ok(CommitStats {
140            commits: commits.ok_or_else(|| missing("commits"))?,
141            cur_commit_ms: cur_commit_ms.ok_or_else(|| missing("cur_commit_ms"))?,
142            last_commit_ms: last_commit_ms.ok_or_else(|| missing("last_commit_ms"))?,
143            max_commit_ms: max_commit_ms.ok_or_else(|| missing("max_commit_ms"))?,
144            total_commit_ms: total_commit_ms.ok_or_else(|| missing("total_commit_ms"))?,
145        })
146    }
147
148    /// Reset the `max_commit_ms` counter by writing `0` to the commit_stats
149    /// file. Requires root.
150    /// `/sys/fs/btrfs/<uuid>/commit_stats`
151    pub fn reset_commit_stats(&self) -> io::Result<()> {
152        fs::write(self.base.join("commit_stats"), b"0")
153    }
154
155    /// Name of the exclusive operation currently running, e.g. `"none"`,
156    /// `"balance"`, `"device add"`.
157    /// `/sys/fs/btrfs/<uuid>/exclusive_operation`
158    pub fn exclusive_operation(&self) -> io::Result<String> {
159        self.read_file("exclusive_operation")
160    }
161
162    /// Wait until no exclusive operation is running on the filesystem.
163    ///
164    /// Polls the `exclusive_operation` sysfs file at one-second intervals.
165    /// Returns immediately if no exclusive operation is in progress, or after
166    /// the running operation completes. Returns the name of the operation
167    /// that was waited on, or `"none"` if nothing was running.
168    pub fn wait_for_exclusive_operation(&self) -> io::Result<String> {
169        let mut op = self.exclusive_operation()?;
170        if op == "none" {
171            return Ok(op);
172        }
173        let waited_for = op.clone();
174        while op != "none" {
175            std::thread::sleep(std::time::Duration::from_secs(1));
176            op = self.exclusive_operation()?;
177        }
178        Ok(waited_for)
179    }
180
181    /// Names of the filesystem features that are enabled. Each feature
182    /// corresponds to a file in the `features/` subdirectory.
183    /// `/sys/fs/btrfs/<uuid>/features/`
184    pub fn features(&self) -> io::Result<Vec<String>> {
185        let mut features = Vec::new();
186        for entry in fs::read_dir(self.base.join("features"))? {
187            let entry = entry?;
188            if let Some(name) = entry.file_name().to_str() {
189                features.push(name.to_owned());
190            }
191        }
192        features.sort();
193        Ok(features)
194    }
195
196    /// Current filesystem generation number.
197    /// `/sys/fs/btrfs/<uuid>/generation`
198    pub fn generation(&self) -> io::Result<u64> {
199        self.read_u64("generation")
200    }
201
202    /// Filesystem label. Empty string if no label is set.
203    /// `/sys/fs/btrfs/<uuid>/label`
204    pub fn label(&self) -> io::Result<String> {
205        self.read_file("label")
206    }
207
208    /// Metadata UUID. May differ from the filesystem UUID if the metadata UUID
209    /// feature is in use.
210    /// `/sys/fs/btrfs/<uuid>/metadata_uuid`
211    pub fn metadata_uuid(&self) -> io::Result<Uuid> {
212        let s = self.read_file("metadata_uuid")?;
213        Uuid::parse_str(&s).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
214    }
215
216    /// B-tree node size in bytes.
217    /// `/sys/fs/btrfs/<uuid>/nodesize`
218    pub fn nodesize(&self) -> io::Result<u64> {
219        self.read_u64("nodesize")
220    }
221
222    /// Whether the quota override is active.
223    /// `/sys/fs/btrfs/<uuid>/quota_override`
224    pub fn quota_override(&self) -> io::Result<bool> {
225        self.read_bool("quota_override")
226    }
227
228    /// Read policy for RAID profiles, e.g. `"[pid]"` or `"[roundrobin]"`.
229    /// `/sys/fs/btrfs/<uuid>/read_policy`
230    pub fn read_policy(&self) -> io::Result<String> {
231        self.read_file("read_policy")
232    }
233
234    /// Sector size in bytes.
235    /// `/sys/fs/btrfs/<uuid>/sectorsize`
236    pub fn sectorsize(&self) -> io::Result<u64> {
237        self.read_u64("sectorsize")
238    }
239
240    /// Whether a temporary fsid is in use (seeding device feature).
241    /// `/sys/fs/btrfs/<uuid>/temp_fsid`
242    pub fn temp_fsid(&self) -> io::Result<bool> {
243        self.read_bool("temp_fsid")
244    }
245
246    /// Read the per-device scrub throughput limit for the given device, in
247    /// bytes per second. A value of `0` means no limit is set (unlimited).
248    /// `/sys/fs/btrfs/<uuid>/devinfo/<devid>/scrub_speed_max`
249    pub fn scrub_speed_max_get(&self, devid: u64) -> io::Result<u64> {
250        let path = format!("devinfo/{devid}/scrub_speed_max");
251        match self.read_u64(&path) {
252            Ok(v) => Ok(v),
253            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(0),
254            Err(e) => Err(e),
255        }
256    }
257
258    /// Set the per-device scrub throughput limit for the given device, in
259    /// bytes per second. Pass `0` to remove the limit (unlimited).
260    /// Requires root.
261    /// `/sys/fs/btrfs/<uuid>/devinfo/<devid>/scrub_speed_max`
262    pub fn scrub_speed_max_set(&self, devid: u64, limit: u64) -> io::Result<()> {
263        let path = self.base.join(format!("devinfo/{devid}/scrub_speed_max"));
264        fs::write(path, format!("{limit}\n"))
265    }
266
267    /// Maximum send stream protocol version supported by the kernel.
268    ///
269    /// Returns `1` if the sysfs file does not exist (older kernels without
270    /// versioned send stream support).
271    /// `/sys/fs/btrfs/features/send_stream_version`
272    pub fn send_stream_version(&self) -> u32 {
273        // This is a global feature file, not per-filesystem.
274        let path = std::path::Path::new("/sys/fs/btrfs/features/send_stream_version");
275        match fs::read_to_string(path) {
276            Ok(s) => s.trim().parse::<u32>().unwrap_or(1),
277            Err(_) => 1,
278        }
279    }
280
281    /// Quota status for this filesystem, read from
282    /// `/sys/fs/btrfs/<uuid>/qgroups/`.
283    ///
284    /// Returns `Ok(QuotaStatus { enabled: false, .. })` when quota is not
285    /// enabled (the `qgroups/` directory does not exist). Returns an
286    /// [`io::Error`] with kind `NotFound` if the sysfs entry for this UUID
287    /// does not exist (i.e. the filesystem is not currently mounted).
288    pub fn quota_status(&self) -> io::Result<QuotaStatus> {
289        let qgroups = self.base.join("qgroups");
290
291        if !qgroups.exists() {
292            return Ok(QuotaStatus {
293                enabled: false,
294                mode: None,
295                inconsistent: None,
296                override_limits: None,
297                drop_subtree_threshold: None,
298                total_count: None,
299                level0_count: None,
300            });
301        }
302
303        let mode = {
304            let s = fs::read_to_string(qgroups.join("mode"))?;
305            s.trim_end().to_owned()
306        };
307        let inconsistent = fs::read_to_string(qgroups.join("inconsistent"))?
308            .trim()
309            .parse::<u64>()
310            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
311            != 0;
312        let override_limits = self.read_bool("quota_override")?;
313        let drop_subtree_threshold = fs::read_to_string(qgroups.join("drop_subtree_threshold"))?
314            .trim()
315            .parse::<u64>()
316            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
317
318        let mut total_count: u64 = 0;
319        let mut level0_count: u64 = 0;
320        for entry in fs::read_dir(&qgroups)? {
321            let entry = entry?;
322            let raw_name = entry.file_name();
323            let name = raw_name.to_string_lossy();
324            if let Some((level, _id)) = parse_qgroup_entry_name(OsStr::new(name.as_ref())) {
325                total_count += 1;
326                if level == 0 {
327                    level0_count += 1;
328                }
329            }
330        }
331
332        Ok(QuotaStatus {
333            enabled: true,
334            mode: Some(mode),
335            inconsistent: Some(inconsistent),
336            override_limits: Some(override_limits),
337            drop_subtree_threshold: Some(drop_subtree_threshold),
338            total_count: Some(total_count),
339            level0_count: Some(level0_count),
340        })
341    }
342}
343
344/// Parse a qgroups sysfs directory entry name of the form `<level>_<id>`.
345///
346/// Returns `Some((level, id))` for valid entries, `None` for anything else
347/// (e.g. `mode`, `inconsistent`, and other non-qgroup files in the directory).
348fn parse_qgroup_entry_name(name: &OsStr) -> Option<(u64, u64)> {
349    let s = name.to_str()?;
350    let (level_str, id_str) = s.split_once('_')?;
351    let level: u64 = level_str.parse().ok()?;
352    let id: u64 = id_str.parse().ok()?;
353    Some((level, id))
354}
355
356/// Quota status for a mounted btrfs filesystem, read from sysfs under
357/// `/sys/fs/btrfs/<uuid>/qgroups/`.
358#[derive(Debug, Clone, PartialEq, Eq)]
359pub struct QuotaStatus {
360    /// Whether quota accounting is currently enabled.
361    pub enabled: bool,
362    /// Accounting mode: `"qgroup"` (full backref accounting) or `"squota"`
363    /// (simplified lifetime accounting). `None` when quotas are disabled.
364    pub mode: Option<String>,
365    /// Whether the quota tree is inconsistent; a rescan is needed to restore
366    /// accurate numbers. `None` when quotas are disabled.
367    pub inconsistent: Option<bool>,
368    /// Whether the quota override flag is active (limits are bypassed for
369    /// the current mount). `None` when quotas are disabled.
370    pub override_limits: Option<bool>,
371    /// Drop-subtree threshold: qgroup hierarchy levels below this value skip
372    /// detailed tracking during heavy write workloads. `None` when disabled.
373    pub drop_subtree_threshold: Option<u64>,
374    /// Total number of qgroups tracked by the kernel. `None` when disabled.
375    pub total_count: Option<u64>,
376    /// Number of level-0 qgroups (one per subvolume). `None` when disabled.
377    pub level0_count: Option<u64>,
378}