btrfs-uapi 0.8.0

Wrappers around the btrfs userspace interface (ioctls and sysfs)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! # Quota and qgroup management: enabling quotas and tracking disk usage
//!
//! Quota accounting tracks disk usage per subvolume via qgroups (quota groups).
//! It must be explicitly enabled before any qgroup limits or usage data are
//! available.  Once enabled, usage numbers are maintained incrementally by the
//! kernel; a rescan rebuilds them from scratch if they become inconsistent.
//!
//! Every subvolume automatically gets a level-0 qgroup whose ID matches the
//! subvolume ID.  Higher-level qgroups can be created and linked into a
//! parent-child hierarchy so that space usage rolls up through the tree.
//!
//! Quota status (whether quotas are on, which mode, inconsistency flag) is
//! read from sysfs via [`crate::sysfs::SysfsBtrfs::quota_status`].
//!
//! Most operations require `CAP_SYS_ADMIN`.

use crate::{
    raw::{
        BTRFS_FIRST_FREE_OBJECTID, BTRFS_LAST_FREE_OBJECTID,
        BTRFS_QGROUP_INFO_KEY, BTRFS_QGROUP_LIMIT_EXCL_CMPR,
        BTRFS_QGROUP_LIMIT_KEY, BTRFS_QGROUP_LIMIT_MAX_EXCL,
        BTRFS_QGROUP_LIMIT_MAX_RFER, BTRFS_QGROUP_LIMIT_RFER_CMPR,
        BTRFS_QGROUP_RELATION_KEY, BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT,
        BTRFS_QGROUP_STATUS_FLAG_ON, BTRFS_QGROUP_STATUS_FLAG_RESCAN,
        BTRFS_QGROUP_STATUS_FLAG_SIMPLE_MODE, BTRFS_QGROUP_STATUS_KEY,
        BTRFS_QUOTA_CTL_DISABLE, BTRFS_QUOTA_CTL_ENABLE,
        BTRFS_QUOTA_CTL_ENABLE_SIMPLE_QUOTA, BTRFS_QUOTA_TREE_OBJECTID,
        BTRFS_ROOT_ITEM_KEY, BTRFS_ROOT_TREE_OBJECTID, btrfs_ioc_qgroup_assign,
        btrfs_ioc_qgroup_create, btrfs_ioc_qgroup_limit, btrfs_ioc_quota_ctl,
        btrfs_ioc_quota_rescan, btrfs_ioc_quota_rescan_status,
        btrfs_ioc_quota_rescan_wait, btrfs_ioctl_qgroup_assign_args,
        btrfs_ioctl_qgroup_create_args, btrfs_ioctl_qgroup_limit_args,
        btrfs_ioctl_quota_ctl_args, btrfs_ioctl_quota_rescan_args,
        btrfs_qgroup_limit,
    },
    tree_search::{SearchKey, tree_search},
};
use bitflags::bitflags;
use nix::errno::Errno;
use std::{
    collections::{HashMap, HashSet},
    mem,
    os::{fd::AsRawFd, unix::io::BorrowedFd},
};

/// Enable quota accounting on the filesystem referred to by `fd`.
///
/// When `simple` is `true`, uses `BTRFS_QUOTA_CTL_ENABLE_SIMPLE_QUOTA`, which
/// accounts for extent ownership by lifetime rather than backref walks. This is
/// faster but less precise than full qgroup accounting.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn quota_enable(fd: BorrowedFd, simple: bool) -> nix::Result<()> {
    let cmd = if simple {
        u64::from(BTRFS_QUOTA_CTL_ENABLE_SIMPLE_QUOTA)
    } else {
        u64::from(BTRFS_QUOTA_CTL_ENABLE)
    };
    let mut args: btrfs_ioctl_quota_ctl_args = unsafe { mem::zeroed() };
    args.cmd = cmd;
    unsafe { btrfs_ioc_quota_ctl(fd.as_raw_fd(), &raw mut args) }?;
    Ok(())
}

/// Disable quota accounting on the filesystem referred to by `fd`.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn quota_disable(fd: BorrowedFd) -> nix::Result<()> {
    let mut args: btrfs_ioctl_quota_ctl_args = unsafe { mem::zeroed() };
    args.cmd = u64::from(BTRFS_QUOTA_CTL_DISABLE);
    unsafe { btrfs_ioc_quota_ctl(fd.as_raw_fd(), &raw mut args) }?;
    Ok(())
}

/// Start a quota rescan on the filesystem referred to by `fd`.
///
/// Returns immediately after kicking off the background scan. Use
/// [`quota_rescan_wait`] to block until it finishes. If a rescan is already
/// in progress the kernel returns `EINPROGRESS`; callers that are about to
/// wait anyway can treat that as a non-error.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails. `EINPROGRESS` if a rescan is
/// already running.
pub fn quota_rescan(fd: BorrowedFd) -> nix::Result<()> {
    let args: btrfs_ioctl_quota_rescan_args = unsafe { mem::zeroed() };
    unsafe { btrfs_ioc_quota_rescan(fd.as_raw_fd(), &raw const args) }?;
    Ok(())
}

/// Block until the quota rescan currently running on the filesystem referred
/// to by `fd` completes. Returns immediately if no rescan is in progress.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn quota_rescan_wait(fd: BorrowedFd) -> nix::Result<()> {
    unsafe { btrfs_ioc_quota_rescan_wait(fd.as_raw_fd()) }?;
    Ok(())
}

/// Status of an in-progress (or absent) quota rescan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QuotaRescanStatus {
    /// Whether a rescan is currently running.
    pub running: bool,
    /// Object ID of the most recently scanned tree item. Only meaningful
    /// when `running` is `true`.
    pub progress: u64,
}

/// Query the status of the quota rescan on the filesystem referred to by `fd`.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn quota_rescan_status(fd: BorrowedFd) -> nix::Result<QuotaRescanStatus> {
    let mut args: btrfs_ioctl_quota_rescan_args = unsafe { mem::zeroed() };
    unsafe { btrfs_ioc_quota_rescan_status(fd.as_raw_fd(), &raw mut args) }?;
    Ok(QuotaRescanStatus {
        running: args.flags != 0,
        progress: args.progress,
    })
}

/// Extract the hierarchy level from a packed qgroup ID.
///
/// `qgroupid = (level << 48) | subvolid`.  Level 0 qgroups correspond
/// directly to subvolumes.
#[inline]
#[must_use]
pub fn qgroupid_level(qgroupid: u64) -> u16 {
    (qgroupid >> 48) as u16
}

/// Extract the subvolume ID component from a packed qgroup ID.
///
/// Only meaningful for level-0 qgroups.
#[inline]
#[must_use]
pub fn qgroupid_subvolid(qgroupid: u64) -> u64 {
    qgroupid & 0x0000_FFFF_FFFF_FFFF
}

bitflags! {
    /// Status flags for the quota tree as a whole (`BTRFS_QGROUP_STATUS_KEY`).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct QgroupStatusFlags: u64 {
        /// Quota accounting is enabled.
        const ON           = BTRFS_QGROUP_STATUS_FLAG_ON as u64;
        /// A rescan is currently in progress.
        const RESCAN       = BTRFS_QGROUP_STATUS_FLAG_RESCAN as u64;
        /// Accounting is inconsistent and a rescan is needed.
        const INCONSISTENT = BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT as u64;
        /// Simple quota mode (squota) is active.
        const SIMPLE_MODE  = BTRFS_QGROUP_STATUS_FLAG_SIMPLE_MODE as u64;
    }
}

bitflags! {
    /// Which limit fields are actively enforced on a qgroup.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct QgroupLimitFlags: u64 {
        /// `max_rfer` (maximum referenced bytes) is enforced.
        const MAX_RFER  = BTRFS_QGROUP_LIMIT_MAX_RFER as u64;
        /// `max_excl` (maximum exclusive bytes) is enforced.
        const MAX_EXCL  = BTRFS_QGROUP_LIMIT_MAX_EXCL as u64;
        /// Referenced bytes are compressed before comparison.
        const RFER_CMPR = BTRFS_QGROUP_LIMIT_RFER_CMPR as u64;
        /// Exclusive bytes are compressed before comparison.
        const EXCL_CMPR = BTRFS_QGROUP_LIMIT_EXCL_CMPR as u64;
    }
}

/// Usage and limit information for a single qgroup.
#[derive(Debug, Clone)]
pub struct QgroupInfo {
    /// Packed qgroup ID: `(level << 48) | subvolid`.
    pub qgroupid: u64,
    /// Total referenced bytes (includes shared data).
    pub rfer: u64,
    /// Referenced bytes after compression.
    pub rfer_cmpr: u64,
    /// Exclusively-owned bytes (not shared with any other subvolume).
    pub excl: u64,
    /// Exclusively-owned bytes after compression.
    pub excl_cmpr: u64,
    /// Limit flags — which of the limit fields below are enforced.
    pub limit_flags: QgroupLimitFlags,
    /// Maximum referenced bytes.  `u64::MAX` when no limit is set.
    pub max_rfer: u64,
    /// Maximum exclusive bytes.  `u64::MAX` when no limit is set.
    pub max_excl: u64,
    /// IDs of qgroups that are parents of this one in the hierarchy.
    pub parents: Vec<u64>,
    /// IDs of qgroups that are children of this one in the hierarchy.
    pub children: Vec<u64>,
    /// Level-0 only: `true` when the corresponding subvolume no longer
    /// exists (this is a "stale" qgroup left behind after deletion).
    pub stale: bool,
}

/// Result of [`qgroup_list`]: overall quota status and per-qgroup details.
#[derive(Debug, Clone)]
pub struct QgroupList {
    /// Flags from the `BTRFS_QGROUP_STATUS_KEY` item.
    pub status_flags: QgroupStatusFlags,
    /// All qgroups found in the quota tree, sorted by `qgroupid`.
    pub qgroups: Vec<QgroupInfo>,
}

#[derive(Default)]
struct QgroupEntryBuilder {
    // From INFO item
    has_info: bool,
    rfer: u64,
    rfer_cmpr: u64,
    excl: u64,
    excl_cmpr: u64,
    // From LIMIT item
    has_limit: bool,
    limit_flags: u64,
    max_rfer: u64,
    max_excl: u64,
    // From RELATION items
    parents: Vec<u64>,
    children: Vec<u64>,
}

impl QgroupEntryBuilder {
    fn build(self, qgroupid: u64, stale: bool) -> QgroupInfo {
        QgroupInfo {
            qgroupid,
            rfer: self.rfer,
            rfer_cmpr: self.rfer_cmpr,
            excl: self.excl,
            excl_cmpr: self.excl_cmpr,
            limit_flags: QgroupLimitFlags::from_bits_truncate(self.limit_flags),
            max_rfer: if self.limit_flags
                & u64::from(BTRFS_QGROUP_LIMIT_MAX_RFER)
                != 0
            {
                self.max_rfer
            } else {
                u64::MAX
            },
            max_excl: if self.limit_flags
                & u64::from(BTRFS_QGROUP_LIMIT_MAX_EXCL)
                != 0
            {
                self.max_excl
            } else {
                u64::MAX
            },
            parents: self.parents,
            children: self.children,
            stale,
        }
    }
}

fn parse_status_flags(data: &[u8]) -> Option<u64> {
    btrfs_disk::items::QgroupStatus::parse(data).map(|qs| qs.flags)
}

fn parse_info(builder: &mut QgroupEntryBuilder, data: &[u8]) {
    let Some(qi) = btrfs_disk::items::QgroupInfo::parse(data) else {
        return;
    };
    builder.has_info = true;
    builder.rfer = qi.referenced;
    builder.rfer_cmpr = qi.referenced_compressed;
    builder.excl = qi.exclusive;
    builder.excl_cmpr = qi.exclusive_compressed;
}

fn parse_limit(builder: &mut QgroupEntryBuilder, data: &[u8]) {
    let Some(ql) = btrfs_disk::items::QgroupLimit::parse(data) else {
        return;
    };
    builder.has_limit = true;
    builder.limit_flags = ql.flags;
    builder.max_rfer = ql.max_referenced;
    builder.max_excl = ql.max_exclusive;
}

/// Create a new qgroup with the given `qgroupid` on the filesystem referred
/// to by `fd`.
///
/// `qgroupid` is the packed form: `(level << 48) | subvolid`.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn qgroup_create(fd: BorrowedFd, qgroupid: u64) -> nix::Result<()> {
    let mut args: btrfs_ioctl_qgroup_create_args = unsafe { mem::zeroed() };
    args.create = 1;
    args.qgroupid = qgroupid;
    // SAFETY: args is fully initialised above and lives for the duration of
    // the ioctl call.
    unsafe { btrfs_ioc_qgroup_create(fd.as_raw_fd(), &raw const args) }?;
    Ok(())
}

/// Destroy the qgroup with the given `qgroupid` on the filesystem referred
/// to by `fd`.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn qgroup_destroy(fd: BorrowedFd, qgroupid: u64) -> nix::Result<()> {
    let mut args: btrfs_ioctl_qgroup_create_args = unsafe { mem::zeroed() };
    args.create = 0;
    args.qgroupid = qgroupid;
    // SAFETY: args is fully initialised above and lives for the duration of
    // the ioctl call.
    unsafe { btrfs_ioc_qgroup_create(fd.as_raw_fd(), &raw const args) }?;
    Ok(())
}

/// Assign qgroup `src` as a member of qgroup `dst` (i.e. `src` becomes a
/// child of `dst`).
///
/// Returns `true` if the kernel indicates that a quota rescan is now needed
/// (the ioctl returned a positive value).
///
/// Errors: ENOENT if either qgroup does not exist.  EEXIST if the
/// relationship already exists.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn qgroup_assign(fd: BorrowedFd, src: u64, dst: u64) -> nix::Result<bool> {
    let mut args: btrfs_ioctl_qgroup_assign_args = unsafe { mem::zeroed() };
    args.assign = 1;
    args.src = src;
    args.dst = dst;
    // SAFETY: args is fully initialised above and lives for the duration of
    // the ioctl call.
    let ret =
        unsafe { btrfs_ioc_qgroup_assign(fd.as_raw_fd(), &raw const args) }?;
    Ok(ret > 0)
}

/// Remove the child-parent relationship between qgroups `src` and `dst`.
///
/// Returns `true` if the kernel indicates that a quota rescan is now needed.
///
/// Errors: ENOENT if either qgroup does not exist or the relationship
/// is not present.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn qgroup_remove(fd: BorrowedFd, src: u64, dst: u64) -> nix::Result<bool> {
    let mut args: btrfs_ioctl_qgroup_assign_args = unsafe { mem::zeroed() };
    args.assign = 0;
    args.src = src;
    args.dst = dst;
    // SAFETY: args is fully initialised above and lives for the duration of
    // the ioctl call.
    let ret =
        unsafe { btrfs_ioc_qgroup_assign(fd.as_raw_fd(), &raw const args) }?;
    Ok(ret > 0)
}

/// Set usage limits on a qgroup.
///
/// Pass `QgroupLimitFlags::MAX_RFER` in `flags` to enforce `max_rfer`, and/or
/// `QgroupLimitFlags::MAX_EXCL` to enforce `max_excl`.  Clear a limit by
/// omitting the corresponding flag.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn qgroup_limit(
    fd: BorrowedFd,
    qgroupid: u64,
    flags: QgroupLimitFlags,
    max_rfer: u64,
    max_excl: u64,
) -> nix::Result<()> {
    let lim = btrfs_qgroup_limit {
        flags: flags.bits(),
        max_referenced: max_rfer,
        max_exclusive: max_excl,
        rsv_referenced: 0,
        rsv_exclusive: 0,
    };
    let mut args: btrfs_ioctl_qgroup_limit_args = unsafe { mem::zeroed() };
    args.qgroupid = qgroupid;
    args.lim = lim;
    // SAFETY: args is fully initialised above and lives for the duration of
    // the ioctl call.  The ioctl number is #43 (_IOR direction in the kernel
    // header), which reads args from userspace.
    unsafe { btrfs_ioc_qgroup_limit(fd.as_raw_fd(), &raw mut args) }?;
    Ok(())
}

/// List all qgroups and overall quota status for the filesystem referred to
/// by `fd`.
///
/// Returns `Ok(QgroupList { status_flags: empty, qgroups: [] })` when quota
/// accounting is not enabled (`ENOENT` from the kernel).
///
/// # Errors
///
/// Returns `Err` if the tree search fails (other than `ENOENT`).
pub fn qgroup_list(fd: BorrowedFd) -> nix::Result<QgroupList> {
    // Build a map of qgroupid → builder as we walk the quota tree.
    let mut builders: HashMap<u64, QgroupEntryBuilder> = HashMap::new();
    let mut status_flags = QgroupStatusFlags::empty();

    // Scan the quota tree for STATUS / INFO / LIMIT / RELATION items in one pass.
    let quota_key = SearchKey {
        tree_id: u64::from(BTRFS_QUOTA_TREE_OBJECTID),
        min_objectid: 0,
        max_objectid: u64::MAX,
        min_type: BTRFS_QGROUP_STATUS_KEY,
        max_type: BTRFS_QGROUP_RELATION_KEY,
        min_offset: 0,
        max_offset: u64::MAX,
        min_transid: 0,
        max_transid: u64::MAX,
    };

    let scan_result = tree_search(fd, quota_key, |hdr, data| {
        match hdr.item_type {
            t if t == BTRFS_QGROUP_STATUS_KEY => {
                if let Some(raw) = parse_status_flags(data) {
                    status_flags = QgroupStatusFlags::from_bits_truncate(raw);
                }
            }
            t if t == BTRFS_QGROUP_INFO_KEY => {
                // offset = qgroupid
                let entry = builders.entry(hdr.offset).or_default();
                parse_info(entry, data);
            }
            t if t == BTRFS_QGROUP_LIMIT_KEY => {
                // offset = qgroupid
                let entry = builders.entry(hdr.offset).or_default();
                parse_limit(entry, data);
            }
            t if t == BTRFS_QGROUP_RELATION_KEY => {
                // The kernel stores two entries per relation:
                //   (child, RELATION_KEY, parent)
                //   (parent, RELATION_KEY, child)
                // Only process the canonical form where objectid > offset,
                // i.e. parent > child.
                if hdr.objectid > hdr.offset {
                    let parent = hdr.objectid;
                    let child = hdr.offset;
                    builders.entry(child).or_default().parents.push(parent);
                    builders.entry(parent).or_default().children.push(child);
                }
            }
            _ => {}
        }
        Ok(())
    });

    match scan_result {
        Err(Errno::ENOENT) => {
            // Quota tree does not exist — quotas are disabled.
            return Ok(QgroupList {
                status_flags: QgroupStatusFlags::empty(),
                qgroups: Vec::new(),
            });
        }
        Err(e) => return Err(e),
        Ok(()) => {}
    }

    // Collect existing subvolume IDs so we can mark stale level-0 qgroups.
    let existing_subvol_ids = collect_subvol_ids(fd)?;

    // Convert builders to QgroupInfo, computing stale flag for level-0 groups.
    let mut qgroups: Vec<QgroupInfo> = builders
        .into_iter()
        .map(|(qgroupid, builder)| {
            let stale = if qgroupid_level(qgroupid) == 0 {
                !existing_subvol_ids.contains(&qgroupid_subvolid(qgroupid))
            } else {
                false
            };
            builder.build(qgroupid, stale)
        })
        .collect();

    qgroups.sort_by_key(|q| q.qgroupid);

    Ok(QgroupList {
        status_flags,
        qgroups,
    })
}

/// Collect the set of all existing subvolume IDs by scanning
/// `ROOT_ITEM_KEY` entries in the root tree.
fn collect_subvol_ids(fd: BorrowedFd) -> nix::Result<HashSet<u64>> {
    let mut ids: HashSet<u64> = HashSet::new();

    // BTRFS_LAST_FREE_OBJECTID binds as i32 = -256; cast to u64 gives
    // 0xFFFFFFFF_FFFFFF00 as expected.
    #[allow(clippy::cast_sign_loss)]
    let key = SearchKey::for_objectid_range(
        u64::from(BTRFS_ROOT_TREE_OBJECTID),
        BTRFS_ROOT_ITEM_KEY,
        u64::from(BTRFS_FIRST_FREE_OBJECTID),
        BTRFS_LAST_FREE_OBJECTID as u64,
    );

    tree_search(fd, key, |hdr, _data| {
        ids.insert(hdr.objectid);
        Ok(())
    })?;

    Ok(ids)
}

/// Destroy all "stale" level-0 qgroups — those whose corresponding subvolume
/// no longer exists.
///
/// In simple-quota mode (`SIMPLE_MODE` flag set), stale qgroups with non-zero
/// `rfer` or `excl` are retained because they hold accounting information for
/// dropped subvolumes.
///
/// Returns the number of qgroups successfully destroyed.
///
/// # Errors
///
/// Returns `Err` if listing qgroups fails.
pub fn qgroup_clear_stale(fd: BorrowedFd) -> nix::Result<usize> {
    let list = qgroup_list(fd)?;
    let simple_mode =
        list.status_flags.contains(QgroupStatusFlags::SIMPLE_MODE);

    let mut count = 0usize;

    for qg in &list.qgroups {
        // Only process level-0 stale qgroups.
        if qgroupid_level(qg.qgroupid) != 0 || !qg.stale {
            continue;
        }

        // In simple-quota mode, keep stale qgroups that still have usage data.
        if simple_mode && (qg.rfer != 0 || qg.excl != 0) {
            continue;
        }

        if qgroup_destroy(fd, qg.qgroupid).is_ok() {
            count += 1;
        }
    }

    Ok(count)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn qgroupid_level_zero() {
        assert_eq!(qgroupid_level(5), 0);
        assert_eq!(qgroupid_level(256), 0);
    }

    #[test]
    fn qgroupid_level_nonzero() {
        let id = (1u64 << 48) | 100;
        assert_eq!(qgroupid_level(id), 1);

        let id = (3u64 << 48) | 42;
        assert_eq!(qgroupid_level(id), 3);
    }

    #[test]
    fn qgroupid_subvolid_extracts_lower_48_bits() {
        assert_eq!(qgroupid_subvolid(256), 256);
        assert_eq!(qgroupid_subvolid((1u64 << 48) | 100), 100);
        assert_eq!(qgroupid_subvolid((2u64 << 48) | 0), 0);
    }

    #[test]
    fn qgroupid_roundtrip() {
        let level: u64 = 2;
        let subvolid: u64 = 999;
        let packed = (level << 48) | subvolid;
        assert_eq!(qgroupid_level(packed), level as u16);
        assert_eq!(qgroupid_subvolid(packed), subvolid);
    }
}