btrfs-fuse 0.13.0

Userspace FUSE driver for btrfs, built on btrfs-disk.
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
//! `BtrfsFuse`: a thin `fuser::Filesystem` adapter on top of [`btrfs_fs`].
//!
//! All filesystem semantics live in the [`btrfs_fs`] crate. This module
//! is responsible for the FUSE protocol mapping only:
//!
//! - inode-number translation (FUSE root = 1 ⇄ btrfs root dir = 256),
//! - converting [`btrfs_fs::Stat`] → [`fuser::FileAttr`] and
//!   [`btrfs_fs::FileKind`] → [`fuser::FileType`],
//! - spawning a tokio task per FUSE callback that owns the `Reply*`,
//!   awaits the async filesystem op, and replies from the task. The
//!   FUSE worker thread returns immediately, so concurrent FUSE
//!   callbacks don't serialise on a single in-flight I/O.

use crate::{
    inode,
    ioctl::{self, IoctlOutcome},
};
use anyhow::{Context, Result};
use btrfs_fs::{
    CacheConfig, FileKind, Filesystem, Inode, SeekHoleData, Stat, SubvolId,
};
use fuser::{
    Errno, FileAttr, FileHandle, FileType, Filesystem as FuserFilesystem,
    Generation, INodeNo, InitFlags, IoctlFlags, KernelConfig, LockOwner,
    OpenFlags, ReplyAttr, ReplyData, ReplyDirectory, ReplyDirectoryPlus,
    ReplyEntry, ReplyIoctl, ReplyLseek, ReplyStatfs, ReplyXattr, Request,
};
use std::{ffi::OsStr, fs::File, io, os::unix::ffi::OsStrExt, time::Duration};
use tokio::runtime::Runtime;

const TTL: Duration = Duration::from_secs(1);

pub struct BtrfsFuse {
    fs: Filesystem<File>,
    blksize: u32,
    /// Subvolume that the FUSE root inode (`1`) maps onto. This is
    /// whatever `Filesystem` was opened with — the default `FS_TREE`
    /// for `BtrfsFuse::open`, or a user-selected subvolume for
    /// `BtrfsFuse::open_subvol`.
    mount_subvol: SubvolId,
    /// Tokio runtime used to drive async [`Filesystem`] ops. Each FUSE
    /// callback `spawn`s a task here; the FUSE worker thread itself
    /// returns immediately.
    runtime: Runtime,
}

impl BtrfsFuse {
    /// Bootstrap the filesystem from an open image file or block device,
    /// using the default subvolume (`FS_TREE`, id 5) as the mount root.
    pub fn open(file: File) -> Result<Self> {
        Self::from_filesystem(Filesystem::open(file)?)
    }

    /// Bootstrap the filesystem with a non-default subvolume as the
    /// mount root. The id must come from a previous call to
    /// [`btrfs_fs::Filesystem::list_subvolumes`].
    pub fn open_subvol(file: File, subvol: btrfs_fs::SubvolId) -> Result<Self> {
        Self::from_filesystem(Filesystem::open_subvol(file, subvol)?)
    }

    /// Like [`BtrfsFuse::open`] but with caller-chosen cache sizes.
    pub fn open_with_caches(file: File, caches: CacheConfig) -> Result<Self> {
        Self::from_filesystem(Filesystem::open_with_caches(file, caches)?)
    }

    /// Like [`BtrfsFuse::open_subvol`] but with caller-chosen cache
    /// sizes.
    pub fn open_subvol_with_caches(
        file: File,
        subvol: SubvolId,
        caches: CacheConfig,
    ) -> Result<Self> {
        Self::from_filesystem(Filesystem::open_subvol_with_caches(
            file, subvol, caches,
        )?)
    }

    fn from_filesystem(fs: Filesystem<File>) -> Result<Self> {
        let blksize = fs.blksize();
        let mount_subvol = fs.default_subvol();
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .thread_name("btrfs-fuse-worker")
            .build()
            .context("failed to build tokio runtime")?;
        Ok(Self {
            fs,
            blksize,
            mount_subvol,
            runtime,
        })
    }

    /// Translate a FUSE inode (always `1` for the mount root) into a
    /// btrfs [`Inode`] in the active mount subvolume.
    fn fuse_inode(&self, ino: u64) -> Inode {
        Inode {
            subvol: self.mount_subvol,
            ino: inode::fuse_to_btrfs(ino),
        }
    }
}

fn to_file_type(kind: FileKind) -> FileType {
    match kind {
        FileKind::RegularFile => FileType::RegularFile,
        FileKind::Directory => FileType::Directory,
        FileKind::Symlink => FileType::Symlink,
        FileKind::BlockDevice => FileType::BlockDevice,
        FileKind::CharDevice => FileType::CharDevice,
        FileKind::NamedPipe => FileType::NamedPipe,
        FileKind::Socket => FileType::Socket,
    }
}

fn to_file_attr(fuse_ino: u64, stat: &Stat) -> FileAttr {
    FileAttr {
        ino: INodeNo(fuse_ino),
        size: stat.size,
        blocks: stat.blocks,
        atime: stat.atime,
        mtime: stat.mtime,
        ctime: stat.ctime,
        crtime: stat.btime,
        kind: to_file_type(stat.kind),
        perm: stat.perm,
        nlink: stat.nlink,
        uid: stat.uid,
        gid: stat.gid,
        rdev: stat.rdev,
        blksize: stat.blksize,
        flags: 0,
    }
}

impl FuserFilesystem for BtrfsFuse {
    /// Negotiate kernel capabilities at mount time. We opt into the
    /// extras that benefit a read-only filesystem; attribute caching
    /// is left at the default since the underlying image is
    /// immutable and the kernel can hold attributes indefinitely.
    ///
    /// - `FUSE_DO_READDIRPLUS` advertises that we serve `readdirplus`
    ///   so the kernel coalesces `readdir + lookup-per-entry` into a
    ///   single round trip — major speedup for `ls -l`.
    /// - `FUSE_AUTO_INVAL_DATA` lets the kernel auto-invalidate page
    ///   cache when our `getattr` reports a changed `mtime`/`size`,
    ///   so callers see fresh data without explicit `O_DIRECT`.
    /// - `FUSE_SPLICE_READ` / `FUSE_SPLICE_WRITE` enable zero-copy
    ///   data transfer between FUSE and the kernel page cache.
    ///
    /// Capabilities the kernel doesn't advertise are silently
    /// skipped; we don't fail the mount over a missing extra.
    fn init(
        &mut self,
        _req: &Request,
        config: &mut KernelConfig,
    ) -> io::Result<()> {
        for cap in [
            InitFlags::FUSE_DO_READDIRPLUS,
            InitFlags::FUSE_AUTO_INVAL_DATA,
            InitFlags::FUSE_SPLICE_READ,
            InitFlags::FUSE_SPLICE_WRITE,
        ] {
            // `add_capabilities` returns `Err` only when the kernel
            // doesn't advertise the cap; gracefully drop it instead
            // of failing the mount.
            let _ = config.add_capabilities(cap);
        }
        Ok(())
    }

    /// Drop a single inode from our caches once the kernel says it
    /// no longer references it. Without this we'd hold cached
    /// `InodeItem`s and `ExtentMap`s until LRU eviction; with it,
    /// they're freed eagerly so memory tracks the kernel's
    /// working set. The default `batch_forget` impl in fuser
    /// loops over each `ForgetOne` and calls this method, so we
    /// don't override `batch_forget` separately.
    fn forget(&self, _req: &Request, ino: INodeNo, _nlookup: u64) {
        self.fs.forget(self.fuse_inode(ino.0));
    }

    fn lookup(
        &self,
        _req: &Request,
        parent: INodeNo,
        name: &OsStr,
        reply: ReplyEntry,
    ) {
        let parent_ino = self.fuse_inode(parent.0);
        let name = name.as_bytes().to_vec();
        let fs = self.fs.clone();
        let blksize = self.blksize;
        self.runtime.spawn(async move {
            match fs.lookup(parent_ino, &name).await {
                Ok(Some((ino, item))) => {
                    let fuse_ino = inode::btrfs_to_fuse(ino.ino);
                    let stat = Stat::from_inode(ino, &item, blksize);
                    reply.entry(
                        &TTL,
                        &to_file_attr(fuse_ino, &stat),
                        Generation(0),
                    );
                }
                Ok(None) => reply.error(Errno::ENOENT),
                Err(e) => {
                    log::warn!(
                        "lookup parent={} name={}: {e}",
                        parent_ino.ino,
                        String::from_utf8_lossy(&name),
                    );
                    reply.error(Errno::EIO);
                }
            }
        });
    }

    fn getattr(
        &self,
        _req: &Request,
        ino: INodeNo,
        _fh: Option<FileHandle>,
        reply: ReplyAttr,
    ) {
        let target = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            match fs.getattr(target).await {
                Ok(Some(stat)) => {
                    reply.attr(&TTL, &to_file_attr(fuse_ino, &stat));
                }
                Ok(None) => reply.error(Errno::ENOENT),
                Err(e) => {
                    log::warn!("getattr ino={fuse_ino}: {e}");
                    reply.error(Errno::EIO);
                }
            }
        });
    }

    fn readdir(
        &self,
        _req: &Request,
        ino: INodeNo,
        _fh: FileHandle,
        offset: u64,
        mut reply: ReplyDirectory,
    ) {
        let dir_ino = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            let entries = match fs.readdir(dir_ino, offset).await {
                Ok(v) => v,
                Err(e) => {
                    log::warn!("readdir ino={fuse_ino} offset={offset}: {e}");
                    reply.error(Errno::EIO);
                    return;
                }
            };
            for entry in entries {
                let child_ino = INodeNo(inode::btrfs_to_fuse(entry.ino.ino));
                if reply.add(
                    child_ino,
                    entry.offset,
                    to_file_type(entry.kind),
                    OsStr::from_bytes(&entry.name),
                ) {
                    break;
                }
            }
            reply.ok();
        });
    }

    fn readdirplus(
        &self,
        _req: &Request,
        ino: INodeNo,
        _fh: FileHandle,
        offset: u64,
        mut reply: ReplyDirectoryPlus,
    ) {
        let dir_ino = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            let entries = match fs.readdirplus(dir_ino, offset).await {
                Ok(v) => v,
                Err(e) => {
                    log::warn!(
                        "readdirplus ino={fuse_ino} offset={offset}: {e}",
                    );
                    reply.error(Errno::EIO);
                    return;
                }
            };
            for (entry, stat) in entries {
                let child_ino = inode::btrfs_to_fuse(entry.ino.ino);
                if reply.add(
                    INodeNo(child_ino),
                    entry.offset,
                    OsStr::from_bytes(&entry.name),
                    &TTL,
                    &to_file_attr(child_ino, &stat),
                    Generation(0),
                ) {
                    break;
                }
            }
            reply.ok();
        });
    }

    fn readlink(&self, _req: &Request, ino: INodeNo, reply: ReplyData) {
        let target = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            match fs.readlink(target).await {
                Ok(Some(t)) => reply.data(&t),
                Ok(None) => {
                    log::warn!(
                        "readlink ino={fuse_ino}: no inline extent found"
                    );
                    reply.error(Errno::EIO);
                }
                Err(e) => {
                    log::warn!("readlink ino={fuse_ino}: {e}");
                    reply.error(Errno::EIO);
                }
            }
        });
    }

    fn read(
        &self,
        _req: &Request,
        ino: INodeNo,
        _fh: FileHandle,
        offset: u64,
        size: u32,
        _flags: OpenFlags,
        _lock: Option<LockOwner>,
        reply: ReplyData,
    ) {
        let target = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            match fs.read(target, offset, size).await {
                Ok(data) => reply.data(&data),
                Err(e) if e.kind() == io::ErrorKind::NotFound => {
                    reply.error(Errno::ENOENT);
                }
                Err(e) => {
                    log::warn!(
                        "read ino={fuse_ino} offset={offset} size={size}: {e}"
                    );
                    reply.error(Errno::EIO);
                }
            }
        });
    }

    fn listxattr(
        &self,
        _req: &Request,
        ino: INodeNo,
        size: u32,
        reply: ReplyXattr,
    ) {
        let target = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            let names = match fs.xattr_list(target).await {
                Ok(v) => v,
                Err(e) => {
                    log::warn!("listxattr ino={fuse_ino}: {e}");
                    reply.error(Errno::EIO);
                    return;
                }
            };

            let mut buf: Vec<u8> = Vec::new();
            for name in &names {
                buf.extend_from_slice(name);
                buf.push(0);
            }

            #[allow(clippy::cast_possible_truncation)]
            if size == 0 {
                reply.size(buf.len() as u32);
            } else if buf.len() <= size as usize {
                reply.data(&buf);
            } else {
                reply.error(Errno::ERANGE);
            }
        });
    }

    fn getxattr(
        &self,
        _req: &Request,
        ino: INodeNo,
        name: &OsStr,
        size: u32,
        reply: ReplyXattr,
    ) {
        let target = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let name_bytes = name.as_bytes().to_vec();
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            match fs.xattr_get(target, &name_bytes).await {
                Ok(Some(value)) =>
                {
                    #[allow(clippy::cast_possible_truncation)]
                    if size == 0 {
                        reply.size(value.len() as u32);
                    } else if value.len() <= size as usize {
                        reply.data(&value);
                    } else {
                        reply.error(Errno::ERANGE);
                    }
                }
                Ok(None) => {
                    #[cfg(target_os = "linux")]
                    reply.error(Errno::ENODATA);
                    #[cfg(not(target_os = "linux"))]
                    reply.error(Errno::ENOENT);
                }
                Err(e) => {
                    log::warn!(
                        "getxattr ino={fuse_ino} name={}: {e}",
                        String::from_utf8_lossy(&name_bytes),
                    );
                    reply.error(Errno::EIO);
                }
            }
        });
    }

    fn statfs(&self, _req: &Request, _ino: INodeNo, reply: ReplyStatfs) {
        let s = self.fs.statfs();
        reply.statfs(
            s.blocks, s.bfree, s.bavail, 0, 0, s.bsize, s.namelen, s.frsize,
        );
    }

    /// `SEEK_HOLE` / `SEEK_DATA` support. The kernel only forwards
    /// these whence values via `FUSE_LSEEK` — `SEEK_SET`,
    /// `SEEK_CUR`, `SEEK_END` are handled in-kernel against the
    /// file's current position and size, so we never see them here.
    /// Other whence values get `EINVAL`.
    fn lseek(
        &self,
        _req: &Request,
        ino: INodeNo,
        _fh: FileHandle,
        offset: i64,
        whence: i32,
        reply: ReplyLseek,
    ) {
        let target = self.fuse_inode(ino.0);
        let fuse_ino = ino.0;
        let whence = match whence {
            // libc::SEEK_DATA = 3, libc::SEEK_HOLE = 4 on Linux. We
            // hardcode the values rather than depending on libc here
            // since the integers are stable kernel ABI.
            3 => SeekHoleData::Data,
            4 => SeekHoleData::Hole,
            _ => {
                reply.error(Errno::EINVAL);
                return;
            }
        };
        let Ok(offset) = u64::try_from(offset) else {
            reply.error(Errno::EINVAL);
            return;
        };
        let fs = self.fs.clone();
        self.runtime.spawn(async move {
            match fs.seek_hole_data(target, offset, whence).await {
                Ok(pos) => {
                    // Cap the response to i64::MAX since lseek
                    // returns off_t (signed). File sizes that
                    // exceed this are pathological and should fail.
                    if let Ok(signed) = i64::try_from(pos) {
                        reply.offset(signed);
                    } else {
                        reply.error(Errno::EOVERFLOW);
                    }
                }
                Err(e) => {
                    // ENXIO is the expected outcome for offset >=
                    // file_size and for SEEK_DATA with no data
                    // beyond the offset; don't spam logs for it.
                    let raw = e.raw_os_error().unwrap_or(0);
                    if raw != libc::ENXIO {
                        log::warn!(
                            "lseek ino={fuse_ino} offset={offset}: {e}",
                        );
                    }
                    reply.error(Errno::from(e));
                }
            }
        });
    }

    fn ioctl(
        &self,
        _req: &Request,
        ino: INodeNo,
        _fh: FileHandle,
        _flags: IoctlFlags,
        cmd: u32,
        in_data: &[u8],
        _out_size: u32,
        reply: ReplyIoctl,
    ) {
        let target = self.fuse_inode(ino.0);
        let fs = self.fs.clone();
        let in_data = in_data.to_vec();
        self.runtime.spawn(async move {
            match ioctl::dispatch(&fs, target, cmd, &in_data).await {
                IoctlOutcome::Ok(data) => reply.ioctl(0, &data),
                IoctlOutcome::Err(errno) => reply.error(errno),
            }
        });
    }
}