Skip to main content

btrfs_uapi/
defrag.rs

1//! # File defragmentation: rewriting fragmented extents into contiguous runs
2//!
3//! Defragmenting a file rewrites its extents contiguously on disk, which can
4//! improve sequential read performance.  Optionally applies or removes
5//! transparent compression at the same time.
6
7use crate::raw::{
8    BTRFS_DEFRAG_RANGE_COMPRESS, BTRFS_DEFRAG_RANGE_COMPRESS_LEVEL,
9    BTRFS_DEFRAG_RANGE_NOCOMPRESS, BTRFS_DEFRAG_RANGE_START_IO,
10    btrfs_ioc_defrag_range, btrfs_ioctl_defrag_range_args,
11};
12use std::{
13    mem,
14    os::{fd::AsRawFd, unix::io::BorrowedFd},
15};
16
17/// Compression algorithm to use when defragmenting.
18///
19/// Corresponds to the `BTRFS_COMPRESS_*` values from `compression.h`.
20/// The numeric values are part of the on-disk/ioctl ABI.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum CompressType {
23    Zlib = 1,
24    Lzo = 2,
25    Zstd = 3,
26}
27
28impl std::fmt::Display for CompressType {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match self {
31            Self::Zlib => f.write_str("zlib"),
32            Self::Lzo => f.write_str("lzo"),
33            Self::Zstd => f.write_str("zstd"),
34        }
35    }
36}
37
38impl std::str::FromStr for CompressType {
39    type Err = String;
40
41    fn from_str(s: &str) -> Result<Self, Self::Err> {
42        match s.to_ascii_lowercase().as_str() {
43            "zlib" => Ok(Self::Zlib),
44            "lzo" => Ok(Self::Lzo),
45            "zstd" => Ok(Self::Zstd),
46            _ => Err(format!(
47                "unknown compress type '{s}'; expected zlib, lzo, or zstd"
48            )),
49        }
50    }
51}
52
53/// Arguments for a defragmentation operation.
54///
55/// Construct with [`DefragRangeArgs::new`] and use the builder methods to set
56/// options. All options are optional; the defaults match the kernel's defaults.
57#[derive(Debug, Clone)]
58pub struct DefragRangeArgs {
59    /// Start offset in bytes. Defaults to `0`.
60    pub start: u64,
61    /// Number of bytes to defragment. Defaults to `u64::MAX` (the entire file).
62    pub len: u64,
63    /// Flush dirty pages to disk immediately after defragmenting.
64    pub flush: bool,
65    /// Extents larger than this threshold are considered already defragmented
66    /// and will not be rewritten. `0` uses the kernel default (32 MiB as of
67    /// recent kernels). `1` forces every extent to be rewritten.
68    pub extent_thresh: u32,
69    /// Compress the file while defragmenting. `None` leaves the file's
70    /// existing compression attribute unchanged.
71    pub compress: Option<CompressSpec>,
72    /// Explicitly disable compression during defragmentation (uncompress if
73    /// necessary). Mutually exclusive with `compress`.
74    pub nocomp: bool,
75}
76
77/// Compression specification for [`DefragRangeArgs`].
78#[derive(Debug, Clone, Copy)]
79pub struct CompressSpec {
80    /// Compression algorithm to use.
81    pub compress_type: CompressType,
82    /// Optional compression level. When `None`, the kernel default for the
83    /// chosen algorithm is used. When `Some`, the
84    /// `BTRFS_DEFRAG_RANGE_COMPRESS_LEVEL` flag is set and the level is
85    /// passed via the `compress.level` union member.
86    pub level: Option<i8>,
87}
88
89impl DefragRangeArgs {
90    /// Create a new `DefragRangeArgs` with all defaults: defragment the
91    /// entire file, no compression change, no flush.
92    pub fn new() -> Self {
93        Self {
94            start: 0,
95            len: u64::MAX,
96            flush: false,
97            extent_thresh: 0,
98            compress: None,
99            nocomp: false,
100        }
101    }
102
103    /// Set the start offset in bytes.
104    pub fn start(mut self, start: u64) -> Self {
105        self.start = start;
106        self
107    }
108
109    /// Set the number of bytes to defragment.
110    pub fn len(mut self, len: u64) -> Self {
111        self.len = len;
112        self
113    }
114
115    /// Flush dirty data to disk after defragmenting.
116    pub fn flush(mut self) -> Self {
117        self.flush = true;
118        self
119    }
120
121    /// Set the extent size threshold. Extents larger than this will not be
122    /// rewritten.
123    pub fn extent_thresh(mut self, thresh: u32) -> Self {
124        self.extent_thresh = thresh;
125        self
126    }
127
128    /// Compress the file using the given algorithm while defragmenting.
129    pub fn compress(mut self, spec: CompressSpec) -> Self {
130        self.compress = Some(spec);
131        self.nocomp = false;
132        self
133    }
134
135    /// Disable compression while defragmenting (decompresses existing data).
136    pub fn nocomp(mut self) -> Self {
137        self.nocomp = true;
138        self.compress = None;
139        self
140    }
141}
142
143impl Default for DefragRangeArgs {
144    fn default() -> Self {
145        Self::new()
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    // --- CompressType Display ---
154
155    #[test]
156    fn compress_type_display() {
157        assert_eq!(format!("{}", CompressType::Zlib), "zlib");
158        assert_eq!(format!("{}", CompressType::Lzo), "lzo");
159        assert_eq!(format!("{}", CompressType::Zstd), "zstd");
160    }
161
162    // --- CompressType FromStr ---
163
164    #[test]
165    fn compress_type_from_str() {
166        assert_eq!("zlib".parse::<CompressType>().unwrap(), CompressType::Zlib);
167        assert_eq!("lzo".parse::<CompressType>().unwrap(), CompressType::Lzo);
168        assert_eq!("zstd".parse::<CompressType>().unwrap(), CompressType::Zstd);
169    }
170
171    #[test]
172    fn compress_type_from_str_case_insensitive() {
173        assert_eq!("ZLIB".parse::<CompressType>().unwrap(), CompressType::Zlib);
174        assert_eq!("Zstd".parse::<CompressType>().unwrap(), CompressType::Zstd);
175    }
176
177    #[test]
178    fn compress_type_from_str_invalid() {
179        assert!("lz4".parse::<CompressType>().is_err());
180        assert!("".parse::<CompressType>().is_err());
181    }
182
183    // --- DefragRangeArgs builder ---
184
185    #[test]
186    fn defrag_args_defaults() {
187        let args = DefragRangeArgs::new();
188        assert_eq!(args.start, 0);
189        assert_eq!(args.len, u64::MAX);
190        assert!(!args.flush);
191        assert_eq!(args.extent_thresh, 0);
192        assert!(args.compress.is_none());
193        assert!(!args.nocomp);
194    }
195
196    #[test]
197    fn defrag_args_builder_chain() {
198        let args = DefragRangeArgs::new()
199            .start(4096)
200            .len(1024 * 1024)
201            .flush()
202            .extent_thresh(256 * 1024);
203        assert_eq!(args.start, 4096);
204        assert_eq!(args.len, 1024 * 1024);
205        assert!(args.flush);
206        assert_eq!(args.extent_thresh, 256 * 1024);
207    }
208
209    #[test]
210    fn defrag_args_compress_clears_nocomp() {
211        let args = DefragRangeArgs::new().nocomp().compress(CompressSpec {
212            compress_type: CompressType::Zstd,
213            level: None,
214        });
215        assert!(args.compress.is_some());
216        assert!(!args.nocomp);
217    }
218
219    #[test]
220    fn defrag_args_nocomp_clears_compress() {
221        let args = DefragRangeArgs::new()
222            .compress(CompressSpec {
223                compress_type: CompressType::Zlib,
224                level: Some(3),
225            })
226            .nocomp();
227        assert!(args.compress.is_none());
228        assert!(args.nocomp);
229    }
230
231    #[test]
232    fn defrag_args_default_trait() {
233        let a = DefragRangeArgs::default();
234        let b = DefragRangeArgs::new();
235        assert_eq!(a.start, b.start);
236        assert_eq!(a.len, b.len);
237    }
238}
239
240/// Defragment a byte range of the file referred to by `fd`.
241///
242/// `fd` must be an open file descriptor to a regular file on a btrfs
243/// filesystem. Pass `&DefragRangeArgs::new()` to defragment the entire file
244/// with default settings.
245pub fn defrag_range(fd: BorrowedFd, args: &DefragRangeArgs) -> nix::Result<()> {
246    let mut raw: btrfs_ioctl_defrag_range_args = unsafe { mem::zeroed() };
247
248    raw.start = args.start;
249    raw.len = args.len;
250    raw.extent_thresh = args.extent_thresh;
251
252    if args.flush {
253        raw.flags |= BTRFS_DEFRAG_RANGE_START_IO as u64;
254    }
255
256    if args.nocomp {
257        raw.flags |= BTRFS_DEFRAG_RANGE_NOCOMPRESS as u64;
258    } else if let Some(spec) = args.compress {
259        raw.flags |= BTRFS_DEFRAG_RANGE_COMPRESS as u64;
260        match spec.level {
261            None => {
262                raw.__bindgen_anon_1.compress_type = spec.compress_type as u32;
263            }
264            Some(level) => {
265                raw.flags |= BTRFS_DEFRAG_RANGE_COMPRESS_LEVEL as u64;
266                raw.__bindgen_anon_1.compress.type_ = spec.compress_type as u8;
267                raw.__bindgen_anon_1.compress.level = level;
268            }
269        }
270    }
271
272    unsafe { btrfs_ioc_defrag_range(fd.as_raw_fd(), &mut raw) }?;
273    Ok(())
274}