btrfs-uapi 0.10.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
//! # Inode and path resolution: mapping between inodes, logical addresses, and paths
//!
//! Covers looking up the subvolume root ID that contains a given file, resolving
//! an inode number to its filesystem paths, mapping a logical byte address back
//! to the inodes that reference it, and resolving a subvolume ID to its path
//! within the filesystem.

use crate::{
    raw::{
        BTRFS_FIRST_FREE_OBJECTID, btrfs_ioc_ino_lookup,
        btrfs_ioc_ino_lookup_user, btrfs_ioc_ino_paths,
        btrfs_ioc_logical_ino_v2, btrfs_ioctl_ino_lookup_user_args,
        btrfs_root_ref,
    },
    tree_search::{SearchFilter, tree_search},
};
use std::os::fd::{AsRawFd, BorrowedFd};

/// Look up the tree ID (root ID) of the subvolume containing the given file or directory.
///
/// For a file or directory, returns the containing tree root ID.
/// For a subvolume, returns its own tree ID.
///
/// # Arguments
///
/// * `fd` - File descriptor to a file or directory on the btrfs filesystem
///
/// # Returns
///
/// The tree ID (root ID) of the containing subvolume
///
/// # Errors
///
/// Returns an error if the ioctl fails (e.g., file descriptor is not on a btrfs filesystem)
pub fn lookup_path_rootid(fd: BorrowedFd<'_>) -> nix::Result<u64> {
    let mut args = crate::raw::btrfs_ioctl_ino_lookup_args {
        treeid: 0,
        objectid: u64::from(BTRFS_FIRST_FREE_OBJECTID),
        ..unsafe { std::mem::zeroed() }
    };

    unsafe {
        btrfs_ioc_ino_lookup(fd.as_raw_fd(), &raw mut args)?;
    }

    Ok(args.treeid)
}

/// Get file system paths for the given inode.
///
/// Returns a vector of path strings relative to the filesystem root that correspond
/// to the given inode number.
///
/// # Arguments
///
/// * `fd` - File descriptor to a file or directory on the btrfs filesystem
/// * `inum` - Inode number to look up
///
/// # Returns
///
/// A vector of path strings for the given inode
///
/// # Errors
///
/// Returns an error if the ioctl fails
pub fn ino_paths(fd: BorrowedFd<'_>, inum: u64) -> nix::Result<Vec<String>> {
    const PATH_MAX: usize = 4096;

    // First, allocate a buffer for the response
    // The buffer needs to be large enough to hold btrfs_data_container plus the path data
    let mut buf = vec![0u8; PATH_MAX];

    // Set up the ioctl arguments
    let mut args = crate::raw::btrfs_ioctl_ino_path_args {
        inum,
        size: PATH_MAX as u64,
        reserved: [0; 4],
        fspath: buf.as_mut_ptr() as u64,
    };

    unsafe {
        btrfs_ioc_ino_paths(fd.as_raw_fd(), &raw mut args)?;
    }

    // Parse the results from the data container
    // The buffer is laid out as: btrfs_data_container header, followed by val[] array
    // SAFETY: buf is u64-aligned from the Vec<u8> allocation, and the ioctl
    // populated it as a btrfs_data_container. The cast is safe because the
    // buffer was allocated with at least PATH_MAX bytes.
    #[allow(clippy::cast_ptr_alignment)]
    let container =
        unsafe { &*buf.as_ptr().cast::<crate::raw::btrfs_data_container>() };

    let mut paths = Vec::new();

    // Each element in val[] is an offset into the data buffer where a path string starts
    for i in 0..container.elem_cnt as usize {
        // Get the offset from val[i]
        #[allow(clippy::cast_possible_truncation)] // offsets fit in usize
        let val_offset = unsafe {
            let val_ptr = container.val.as_ptr();
            *val_ptr.add(i) as usize
        };

        // The path string starts at the base of val array plus the offset
        let val_base = container.val.as_ptr() as usize;
        let path_ptr = (val_base + val_offset) as *const i8;

        // Convert C string to Rust String
        let c_str = unsafe { std::ffi::CStr::from_ptr(path_ptr) };
        if let Ok(path_str) = c_str.to_str() {
            paths.push(path_str.to_string());
        }
    }

    Ok(paths)
}

/// Result from logical-ino resolution: (inode, offset, root)
#[derive(Debug, Clone)]
pub struct LogicalInoResult {
    /// Inode number that contains data at the queried logical address.
    pub inode: u64,
    /// Byte offset within the file where the logical address maps.
    pub offset: u64,
    /// Subvolume tree ID (root) that owns this inode.
    pub root: u64,
}

/// Get inode, offset, and root information for a logical address.
///
/// Resolves a logical address on the filesystem to one or more (inode, offset, root) tuples.
/// The offset is the position within the file, and the root is the subvolume ID.
///
/// # Arguments
///
/// * `fd` - File descriptor to a file or directory on the btrfs filesystem
/// * `logical` - Logical address to resolve
/// * `ignore_offset` - If true, ignores offsets when matching references
/// * `bufsize` - Size of buffer to allocate (default 64KB, max 16MB)
///
/// # Returns
///
/// A vector of (inode, offset, root) tuples
///
/// # Errors
///
/// Returns an error if the ioctl fails
pub fn logical_ino(
    fd: BorrowedFd<'_>,
    logical: u64,
    ignore_offset: bool,
    bufsize: Option<u64>,
) -> nix::Result<Vec<LogicalInoResult>> {
    const MAX_BUFSIZE: u64 = 16 * 1024 * 1024; // 16MB
    const DEFAULT_BUFSIZE: u64 = 64 * 1024; // 64KB

    let size = std::cmp::min(bufsize.unwrap_or(DEFAULT_BUFSIZE), MAX_BUFSIZE);
    #[allow(clippy::cast_possible_truncation)] // buffer size fits in usize
    let mut buf = vec![0u8; size as usize];

    // Set up flags for v2 ioctl
    let mut flags = 0u64;
    if ignore_offset {
        flags |= u64::from(crate::raw::BTRFS_LOGICAL_INO_ARGS_IGNORE_OFFSET);
    }

    // Set up the ioctl arguments
    let mut args = crate::raw::btrfs_ioctl_logical_ino_args {
        logical,
        size,
        reserved: [0; 3],
        flags,
        inodes: buf.as_mut_ptr() as u64,
    };

    unsafe {
        btrfs_ioc_logical_ino_v2(fd.as_raw_fd(), &raw mut args)?;
    }

    // Parse the results from the data container.
    // SAFETY: buf is correctly sized and was populated by the ioctl.
    #[allow(clippy::cast_ptr_alignment)]
    let container =
        unsafe { &*buf.as_ptr().cast::<crate::raw::btrfs_data_container>() };

    let mut results = Vec::new();

    // Each result is 3 consecutive u64 values: inum, offset, root
    for i in (0..container.elem_cnt as usize).step_by(3) {
        if i + 2 < container.elem_cnt as usize {
            let val_offset_inum = unsafe {
                let val_ptr = container.val.as_ptr();
                *val_ptr.add(i)
            };

            let val_offset_offset = unsafe {
                let val_ptr = container.val.as_ptr();
                *val_ptr.add(i + 1)
            };

            let val_offset_root = unsafe {
                let val_ptr = container.val.as_ptr();
                *val_ptr.add(i + 2)
            };

            results.push(LogicalInoResult {
                inode: val_offset_inum,
                offset: val_offset_offset,
                root: val_offset_root,
            });
        }
    }

    Ok(results)
}

/// Resolve a subvolume ID to its full path on the filesystem.
///
/// Recursively resolves the path to a subvolume by walking the root tree and using
/// `INO_LOOKUP` to get directory names. The path is built from the subvolume's name
/// and the names of all parent directories up to the mount point.
///
/// # Arguments
///
/// * `fd` - File descriptor to a file or directory on the btrfs filesystem
/// * `subvol_id` - The subvolume ID to resolve
///
/// # Returns
///
/// The full path to the subvolume relative to the filesystem root, or an empty string
/// for the filesystem root itself (`FS_TREE_OBJECTID`).
///
/// # Errors
///
/// Returns an error if:
/// * The ioctl fails (fd is not on a btrfs filesystem)
/// * The subvolume ID does not exist
/// * The path buffer overflows
///
/// # Example
///
/// ```ignore
/// let path = subvolid_resolve(fd, 5)?;
/// println!("Subvolume 5 is at: {}", path);
/// ```
pub fn subvolid_resolve(
    fd: BorrowedFd<'_>,
    subvol_id: u64,
) -> nix::Result<String> {
    let mut path = String::new();
    subvolid_resolve_sub(fd, &mut path, subvol_id)?;
    Ok(path)
}

fn subvolid_resolve_sub(
    fd: BorrowedFd<'_>,
    path: &mut String,
    subvol_id: u64,
) -> nix::Result<()> {
    use crate::raw::BTRFS_FS_TREE_OBJECTID;

    // If this is the filesystem root, we're done (empty path means root)
    if subvol_id == u64::from(BTRFS_FS_TREE_OBJECTID) {
        return Ok(());
    }

    // Search the root tree for ROOT_BACKREF_KEY entries for this subvolume.
    // ROOT_BACKREF_KEY (item type 156) has:
    // - objectid: the subvolume ID
    // - offset: the parent subvolume ID
    // - data: btrfs_root_ref struct containing the subvolume name
    let mut found = false;

    tree_search(
        fd,
        SearchFilter::for_objectid_range(
            u64::from(crate::raw::BTRFS_ROOT_TREE_OBJECTID),
            crate::raw::BTRFS_ROOT_BACKREF_KEY,
            subvol_id,
            subvol_id,
        ),
        |hdr, data| {
            use std::mem::{offset_of, size_of};

            found = true;

            // The parent subvolume ID is stored in the offset field
            let parent_subvol_id = hdr.offset;

            // Recursively resolve the parent path first
            subvolid_resolve_sub(fd, path, parent_subvol_id)?;

            // data is a packed btrfs_root_ref followed by name bytes.

            let header_size = size_of::<btrfs_root_ref>();
            if data.len() < header_size {
                return Err(nix::errno::Errno::EOVERFLOW);
            }

            let dirid = u64::from_le_bytes(
                data[offset_of!(btrfs_root_ref, dirid)..][..8]
                    .try_into()
                    .unwrap(),
            );

            let name_off = offset_of!(btrfs_root_ref, name_len);
            let name_len =
                u16::from_le_bytes([data[name_off], data[name_off + 1]])
                    as usize;

            if data.len() < header_size + name_len {
                return Err(nix::errno::Errno::EOVERFLOW);
            }

            let name_bytes = &data[header_size..header_size + name_len];

            // If dirid is not the first free objectid, we need to resolve the directory path too
            if dirid != u64::from(BTRFS_FIRST_FREE_OBJECTID) {
                // Look up the directory in the parent subvolume
                let mut ino_lookup_args =
                    crate::raw::btrfs_ioctl_ino_lookup_args {
                        treeid: parent_subvol_id,
                        objectid: dirid,
                        ..unsafe { std::mem::zeroed() }
                    };

                unsafe {
                    btrfs_ioc_ino_lookup(
                        fd.as_raw_fd(),
                        &raw mut ino_lookup_args,
                    )?;
                }

                // Get the directory name (it's a null-terminated C string)
                let dir_name = unsafe {
                    std::ffi::CStr::from_ptr(ino_lookup_args.name.as_ptr())
                }
                .to_str()
                .map_err(|_| nix::errno::Errno::EINVAL)?;

                if !dir_name.is_empty() {
                    if !path.is_empty() {
                        path.push('/');
                    }
                    path.push_str(dir_name);
                }
            }

            // Append the subvolume name
            if !path.is_empty() {
                path.push('/');
            }

            // Convert name bytes to string
            let name_str = std::str::from_utf8(name_bytes)
                .map_err(|_| nix::errno::Errno::EINVAL)?;
            path.push_str(name_str);

            Ok(())
        },
    )?;

    if !found {
        return Err(nix::errno::Errno::ENOENT);
    }

    Ok(())
}

/// Result of an unprivileged inode lookup (`BTRFS_IOC_INO_LOOKUP_USER`).
///
/// Contains the subvolume name and the path from the fd's subvolume root
/// to the directory containing the subvolume.
#[derive(Debug, Clone)]
pub struct InoLookupUserResult {
    /// Name of the subvolume.
    pub name: String,
    /// Path from the fd's subvolume root to the directory containing the
    /// subvolume entry (`dirid`). Empty if the subvolume sits directly
    /// under the subvolume root.
    pub path: String,
}

/// Unprivileged inode lookup: resolve a subvolume's name and parent path.
///
/// Given a subvolume ID (`treeid`) and the inode of the directory that
/// contains it (`dirid`), returns the subvolume name and the path from
/// the fd's subvolume root to that directory.
///
/// Unlike [`subvolid_resolve`], this does not require `CAP_SYS_ADMIN`.
/// However, it only resolves one level — for nested subvolumes the caller
/// must walk up the tree.
///
/// # Errors
///
/// Returns `Err` if the ioctl fails.
pub fn ino_lookup_user(
    fd: BorrowedFd<'_>,
    treeid: u64,
    dirid: u64,
) -> nix::Result<InoLookupUserResult> {
    let mut args = btrfs_ioctl_ino_lookup_user_args {
        dirid,
        treeid,
        ..unsafe { std::mem::zeroed() }
    };

    unsafe {
        btrfs_ioc_ino_lookup_user(fd.as_raw_fd(), &raw mut args)?;
    }

    let name = unsafe { std::ffi::CStr::from_ptr(args.name.as_ptr()) }
        .to_str()
        .map_err(|_| nix::errno::Errno::EINVAL)?
        .to_owned();

    let path = unsafe { std::ffi::CStr::from_ptr(args.path.as_ptr()) }
        .to_str()
        .map_err(|_| nix::errno::Errno::EINVAL)?
        .to_owned();

    Ok(InoLookupUserResult { name, path })
}