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 [`filesystem_info`][`crate::filesystem::filesystem_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::filesystem_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 = filesystem_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 =
117                parts.next().unwrap_or("").trim().parse().map_err(|e| {
118                    io::Error::new(io::ErrorKind::InvalidData, e)
119                })?;
120            match key {
121                "commits" => commits = Some(val),
122                "cur_commit_ms" => cur_commit_ms = Some(val),
123                "last_commit_ms" => last_commit_ms = Some(val),
124                "max_commit_ms" => max_commit_ms = Some(val),
125                "total_commit_ms" => total_commit_ms = Some(val),
126                _ => {}
127            }
128        }
129
130        let missing = |name| {
131            io::Error::new(
132                io::ErrorKind::InvalidData,
133                format!("commit_stats: missing field '{name}'"),
134            )
135        };
136
137        Ok(CommitStats {
138            commits: commits.ok_or_else(|| missing("commits"))?,
139            cur_commit_ms: cur_commit_ms
140                .ok_or_else(|| missing("cur_commit_ms"))?,
141            last_commit_ms: last_commit_ms
142                .ok_or_else(|| missing("last_commit_ms"))?,
143            max_commit_ms: max_commit_ms
144                .ok_or_else(|| missing("max_commit_ms"))?,
145            total_commit_ms: total_commit_ms
146                .ok_or_else(|| missing("total_commit_ms"))?,
147        })
148    }
149
150    /// Reset the `max_commit_ms` counter by writing `0` to the commit_stats
151    /// file. Requires root.
152    /// `/sys/fs/btrfs/<uuid>/commit_stats`
153    pub fn reset_commit_stats(&self) -> io::Result<()> {
154        fs::write(self.base.join("commit_stats"), b"0")
155    }
156
157    /// Name of the exclusive operation currently running, e.g. `"none"`,
158    /// `"balance"`, `"device add"`.
159    /// `/sys/fs/btrfs/<uuid>/exclusive_operation`
160    pub fn exclusive_operation(&self) -> io::Result<String> {
161        self.read_file("exclusive_operation")
162    }
163
164    /// Wait until no exclusive operation is running on the filesystem.
165    ///
166    /// Polls the `exclusive_operation` sysfs file at one-second intervals.
167    /// Returns immediately if no exclusive operation is in progress, or after
168    /// the running operation completes. Returns the name of the operation
169    /// that was waited on, or `"none"` if nothing was running.
170    pub fn wait_for_exclusive_operation(&self) -> io::Result<String> {
171        let mut op = self.exclusive_operation()?;
172        if op == "none" {
173            return Ok(op);
174        }
175        let waited_for = op.clone();
176        while op != "none" {
177            std::thread::sleep(std::time::Duration::from_secs(1));
178            op = self.exclusive_operation()?;
179        }
180        Ok(waited_for)
181    }
182
183    /// Names of the filesystem features that are enabled. Each feature
184    /// corresponds to a file in the `features/` subdirectory.
185    /// `/sys/fs/btrfs/<uuid>/features/`
186    pub fn features(&self) -> io::Result<Vec<String>> {
187        let mut features = Vec::new();
188        for entry in fs::read_dir(self.base.join("features"))? {
189            let entry = entry?;
190            if let Some(name) = entry.file_name().to_str() {
191                features.push(name.to_owned());
192            }
193        }
194        features.sort();
195        Ok(features)
196    }
197
198    /// Current filesystem generation number.
199    /// `/sys/fs/btrfs/<uuid>/generation`
200    pub fn generation(&self) -> io::Result<u64> {
201        self.read_u64("generation")
202    }
203
204    /// Filesystem label. Empty string if no label is set.
205    /// `/sys/fs/btrfs/<uuid>/label`
206    pub fn label(&self) -> io::Result<String> {
207        self.read_file("label")
208    }
209
210    /// Metadata UUID. May differ from the filesystem UUID if the metadata UUID
211    /// feature is in use.
212    /// `/sys/fs/btrfs/<uuid>/metadata_uuid`
213    pub fn metadata_uuid(&self) -> io::Result<Uuid> {
214        let s = self.read_file("metadata_uuid")?;
215        Uuid::parse_str(&s)
216            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
217    }
218
219    /// B-tree node size in bytes.
220    /// `/sys/fs/btrfs/<uuid>/nodesize`
221    pub fn nodesize(&self) -> io::Result<u64> {
222        self.read_u64("nodesize")
223    }
224
225    /// Whether the quota override is active.
226    /// `/sys/fs/btrfs/<uuid>/quota_override`
227    pub fn quota_override(&self) -> io::Result<bool> {
228        self.read_bool("quota_override")
229    }
230
231    /// Read policy for RAID profiles, e.g. `"[pid]"` or `"[roundrobin]"`.
232    /// `/sys/fs/btrfs/<uuid>/read_policy`
233    pub fn read_policy(&self) -> io::Result<String> {
234        self.read_file("read_policy")
235    }
236
237    /// Sector size in bytes.
238    /// `/sys/fs/btrfs/<uuid>/sectorsize`
239    pub fn sectorsize(&self) -> io::Result<u64> {
240        self.read_u64("sectorsize")
241    }
242
243    /// Whether a temporary fsid is in use (seeding device feature).
244    /// `/sys/fs/btrfs/<uuid>/temp_fsid`
245    pub fn temp_fsid(&self) -> io::Result<bool> {
246        self.read_bool("temp_fsid")
247    }
248
249    /// Read the per-device scrub throughput limit for the given device, in
250    /// bytes per second. A value of `0` means no limit is set (unlimited).
251    /// `/sys/fs/btrfs/<uuid>/devinfo/<devid>/scrub_speed_max`
252    pub fn scrub_speed_max_get(&self, devid: u64) -> io::Result<u64> {
253        let path = format!("devinfo/{devid}/scrub_speed_max");
254        match self.read_u64(&path) {
255            Ok(v) => Ok(v),
256            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(0),
257            Err(e) => Err(e),
258        }
259    }
260
261    /// Set the per-device scrub throughput limit for the given device, in
262    /// bytes per second. Pass `0` to remove the limit (unlimited).
263    /// Requires root.
264    /// `/sys/fs/btrfs/<uuid>/devinfo/<devid>/scrub_speed_max`
265    pub fn scrub_speed_max_set(
266        &self,
267        devid: u64,
268        limit: u64,
269    ) -> io::Result<()> {
270        let path = self.base.join(format!("devinfo/{devid}/scrub_speed_max"));
271        fs::write(path, format!("{limit}\n"))
272    }
273
274    /// Maximum send stream protocol version supported by the kernel.
275    ///
276    /// Returns `1` if the sysfs file does not exist (older kernels without
277    /// versioned send stream support).
278    /// `/sys/fs/btrfs/features/send_stream_version`
279    pub fn send_stream_version(&self) -> u32 {
280        // This is a global feature file, not per-filesystem.
281        let path =
282            std::path::Path::new("/sys/fs/btrfs/features/send_stream_version");
283        match fs::read_to_string(path) {
284            Ok(s) => s.trim().parse::<u32>().unwrap_or(1),
285            Err(_) => 1,
286        }
287    }
288
289    /// Quota status for this filesystem, read from
290    /// `/sys/fs/btrfs/<uuid>/qgroups/`.
291    ///
292    /// Returns `Ok(QuotaStatus { enabled: false, .. })` when quota is not
293    /// enabled (the `qgroups/` directory does not exist). Returns an
294    /// [`io::Error`] with kind `NotFound` if the sysfs entry for this UUID
295    /// does not exist (i.e. the filesystem is not currently mounted).
296    pub fn quota_status(&self) -> io::Result<QuotaStatus> {
297        let qgroups = self.base.join("qgroups");
298
299        if !qgroups.exists() {
300            return Ok(QuotaStatus {
301                enabled: false,
302                mode: None,
303                inconsistent: None,
304                override_limits: None,
305                drop_subtree_threshold: None,
306                total_count: None,
307                level0_count: None,
308            });
309        }
310
311        let mode = {
312            let s = fs::read_to_string(qgroups.join("mode"))?;
313            s.trim_end().to_owned()
314        };
315        let inconsistent = fs::read_to_string(qgroups.join("inconsistent"))?
316            .trim()
317            .parse::<u64>()
318            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
319            != 0;
320        let override_limits = self.read_bool("quota_override")?;
321        let drop_subtree_threshold =
322            fs::read_to_string(qgroups.join("drop_subtree_threshold"))?
323                .trim()
324                .parse::<u64>()
325                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
326
327        let mut total_count: u64 = 0;
328        let mut level0_count: u64 = 0;
329        for entry in fs::read_dir(&qgroups)? {
330            let entry = entry?;
331            let raw_name = entry.file_name();
332            let name = raw_name.to_string_lossy();
333            if let Some((level, _id)) =
334                parse_qgroup_entry_name(OsStr::new(name.as_ref()))
335            {
336                total_count += 1;
337                if level == 0 {
338                    level0_count += 1;
339                }
340            }
341        }
342
343        Ok(QuotaStatus {
344            enabled: true,
345            mode: Some(mode),
346            inconsistent: Some(inconsistent),
347            override_limits: Some(override_limits),
348            drop_subtree_threshold: Some(drop_subtree_threshold),
349            total_count: Some(total_count),
350            level0_count: Some(level0_count),
351        })
352    }
353}
354
355/// Parse a qgroups sysfs directory entry name of the form `<level>_<id>`.
356///
357/// Returns `Some((level, id))` for valid entries, `None` for anything else
358/// (e.g. `mode`, `inconsistent`, and other non-qgroup files in the directory).
359fn parse_qgroup_entry_name(name: &OsStr) -> Option<(u64, u64)> {
360    let s = name.to_str()?;
361    let (level_str, id_str) = s.split_once('_')?;
362    let level: u64 = level_str.parse().ok()?;
363    let id: u64 = id_str.parse().ok()?;
364    Some((level, id))
365}
366
367/// Quota status for a mounted btrfs filesystem, read from sysfs under
368/// `/sys/fs/btrfs/<uuid>/qgroups/`.
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub struct QuotaStatus {
371    /// Whether quota accounting is currently enabled.
372    pub enabled: bool,
373    /// Accounting mode: `"qgroup"` (full backref accounting) or `"squota"`
374    /// (simplified lifetime accounting). `None` when quotas are disabled.
375    pub mode: Option<String>,
376    /// Whether the quota tree is inconsistent; a rescan is needed to restore
377    /// accurate numbers. `None` when quotas are disabled.
378    pub inconsistent: Option<bool>,
379    /// Whether the quota override flag is active (limits are bypassed for
380    /// the current mount). `None` when quotas are disabled.
381    pub override_limits: Option<bool>,
382    /// Drop-subtree threshold: qgroup hierarchy levels below this value skip
383    /// detailed tracking during heavy write workloads. `None` when disabled.
384    pub drop_subtree_threshold: Option<u64>,
385    /// Total number of qgroups tracked by the kernel. `None` when disabled.
386    pub total_count: Option<u64>,
387    /// Number of level-0 qgroups (one per subvolume). `None` when disabled.
388    pub level0_count: Option<u64>,
389}