Skip to contentSkip to conversation

Rust abstractions for VFS

RFC PATCH In review Wedson Almeida Filho 3 participants 35 messages May 14, 2024 – May 31, 2024

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v2 cover Rust abstractions for VFS

This series introduces Rust abstractions that allow read-only file systems to be written in Rust.

There are three file systems implementations using these abstractions
abstractions: ext2, tarfs, and puzzlefs. The first two are part of this series.

Rust file system modules can be declared with the module_fs macro and are required to implement the following functions (which are part of the FileSystem trait):

    fn fill_super(
        sb: &mut SuperBlock<Self, sb::New>,
        mapper: Option<inode::Mapper>,
    ) -> Result<Self::Data>;

    fn init_root(sb: &SuperBlock<Self>) -> Result<dentry::Root<Self>>;

They can optionally implement the following:

    fn read_xattr(
        _dentry: &DEntry<Self>,
        _inode: &INode<Self>,
        _name: &CStr,
        _outbuf: &mut [u8],
    ) -> Result<usize>;

    fn statfs(_dentry: &DEntry<Self>) -> Result<Stat>;

They may also choose the type of the data they can attach to superblocks and/or inodes.

Lastly, file systems can implement inode, file, and address space operations and attach them to inodes when they're created, similar to how C does it. They can get a ro address space operations table from an implementation of iomap operations, to be used with generic ro file operations.

A git tree is available here:
git://github.com/wedsonaf/linux.git vfs-v2

Web:
https://github.com/wedsonaf/linux/commits/vfs-v2

---

Changes in v2:

- Rebased to latest rust-next tree
- Removed buffer heads
- Added iomap support
- Removed _pin field from Registration as it's not needed anymore
- Renamed sample filesystem to match the module's name
- Using typestate instead of a separate type for superblock/new-superblock
- Created separate submodules for superblocks, inodes, dentries, and files
- Split out operations from FileSystem to inode/file/address_space ops, similar to how C does it
- Removed usages of folio_set_error
- Removed UniqueFolio, for now reading blocks from devices via the pagecache
- Changed map() to return the entire folio if not in highmem
- Added support for unlocking the folio asynchronously
- Added from_raw to all new ref-counted types
- Added explicit types in calls to cast()
- Added typestate to folio
- Added support for implementing get_link
- Fixed data race when reading inode->i_state
- Added nofs scope support during allocation
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/

---

Wedson Almeida Filho (30):
rust: fs: add registration/unregistration of file systems
rust: fs: introduce the module_fs macro
samples: rust: add initial ro file system sample
rust: fs: introduce FileSystem::fill_super
rust: fs: introduce INode<T>
rust: fs: introduce DEntry<T>
rust: fs: introduce FileSystem::init_root
rust: file: move kernel::file to kernel::fs::file
rust: fs: generalise File for different file systems
rust: fs: add empty file operations
rust: fs: introduce file::Operations::read_dir
rust: fs: introduce file::Operations::seek
rust: fs: introduce file::Operations::read
rust: fs: add empty inode operations
rust: fs: introduce inode::Operations::lookup
rust: folio: introduce basic support for folios
rust: fs: add empty address space operations
rust: fs: introduce address_space::Operations::read_folio
rust: fs: introduce FileSystem::read_xattr
rust: fs: introduce FileSystem::statfs
rust: fs: introduce more inode types
rust: fs: add per-superblock data
rust: fs: allow file systems backed by a block device
rust: fs: allow per-inode data
rust: fs: export file type from mode constants
rust: fs: allow populating i_lnk
rust: fs: add iomap module
rust: fs: add memalloc_nofs support
tarfs: introduce tar fs
WIP: fs: ext2: add rust ro ext2 implementation

 fs/Kconfig                        |   2 +
 fs/Makefile                       |   2 +
 fs/rust-ext2/Kconfig              |  13 +
 fs/rust-ext2/Makefile             |   8 +
 fs/rust-ext2/defs.rs              | 173 +++++++
 fs/rust-ext2/ext2.rs              | 551 +++++++++++++++++++++
 fs/tarfs/Kconfig                  |  15 +
 fs/tarfs/Makefile                 |   8 +
 fs/tarfs/defs.rs                  |  80 +++
 fs/tarfs/tar.rs                   | 394 +++++++++++++++
 rust/bindings/bindings_helper.h   |  11 +
 rust/helpers.c                    | 182 +++++++
 rust/kernel/block.rs              |  10 +-
 rust/kernel/error.rs              |   8 +-
 rust/kernel/file.rs               | 251 ----------
 rust/kernel/folio.rs              | 305 ++++++++++++
 rust/kernel/fs.rs                 | 492 +++++++++++++++++++
 rust/kernel/fs/address_space.rs   |  90 ++++
 rust/kernel/fs/dentry.rs          | 136 ++++++
 rust/kernel/fs/file.rs            | 607 +++++++++++++++++++++++
 rust/kernel/fs/inode.rs           | 780 ++++++++++++++++++++++++++++++
 rust/kernel/fs/iomap.rs           | 281 +++++++++++
 rust/kernel/fs/sb.rs              | 194 ++++++++
 rust/kernel/lib.rs                |   6 +-
 rust/kernel/mem_cache.rs          |   2 -
 rust/kernel/user.rs               |   1 -
 samples/rust/Kconfig              |  10 +
 samples/rust/Makefile             |   1 +
 samples/rust/rust_rofs.rs         | 202 ++++++++
 scripts/generate_rust_analyzer.py |   2 +-
 30 files changed, 4555 insertions(+), 262 deletions(-)
 create mode 100644 fs/rust-ext2/Kconfig
 create mode 100644 fs/rust-ext2/Makefile
 create mode 100644 fs/rust-ext2/defs.rs
 create mode 100644 fs/rust-ext2/ext2.rs
 create mode 100644 fs/tarfs/Kconfig
 create mode 100644 fs/tarfs/Makefile
 create mode 100644 fs/tarfs/defs.rs
 create mode 100644 fs/tarfs/tar.rs
 delete mode 100644 rust/kernel/file.rs
 create mode 100644 rust/kernel/folio.rs
 create mode 100644 rust/kernel/fs.rs
 create mode 100644 rust/kernel/fs/address_space.rs
 create mode 100644 rust/kernel/fs/dentry.rs
 create mode 100644 rust/kernel/fs/file.rs
 create mode 100644 rust/kernel/fs/inode.rs
 create mode 100644 rust/kernel/fs/iomap.rs
 create mode 100644 rust/kernel/fs/sb.rs
 create mode 100644 samples/rust/rust_rofs.rs

base-commit: 183ea65d1fcd71039cf4d111a22d69c337bfd344

Signature · 1 line
2.34.1
#1 lore raw

RFC PATCH v2 1/30 rust: fs: add registration/unregistration of file systems

From: Wedson Almeida Filho <[email protected]>

Allow basic registration and unregistration of Rust file system types. Unregistration happens automatically when a registration variable is dropped (e.g., when it goes out of scope).

File systems registered this way are visible in /proc/filesystems but cannot be mounted yet because init_fs_context fails.

---
 rust/kernel/error.rs |  2 --
 rust/kernel/fs.rs    | 75 ++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs   |  1 +
 3 files changed, 76 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/fs.rs
rust/kernel/error.rs +0 -2
index b248a4c22fb4..f4fa2847e210 100644
@@ -308,8 +308,6 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
 ///     })
 /// }
 /// ```
-// TODO: Remove `dead_code` marker once an in-kernel client is available.
-#[allow(dead_code)]
 pub(crate) fn from_result<T, F>(f: F) -> T
 where
     T: From<i16>,
rust/kernel/fs.rs new file +75 -0

75 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index 4b629aa94735..e664f80b8141 100644
@@ -31,6 +31,7 @@
 mod build_assert;
 pub mod error;
 pub mod file;
+pub mod fs;
 pub mod init;
 pub mod ioctl;
 #[cfg(CONFIG_KUNIT)]
Signature · 1 line
2.34.1
#2 lore raw

RFC PATCH v2 2/30 rust: fs: introduce the `module_fs` macro

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Simplify the declaration of modules that only expose a file system type. They can now do it using the module_fs macro.

---
 rust/kernel/fs.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 55 insertions(+), 1 deletion(-)
rust/kernel/fs.rs +55 -1
index cc1ed7ed2f54..fb7a9b200b85 100644
@@ -9,7 +9,7 @@
 use crate::error::{code::*, from_result, to_result, Error};
 use crate::types::Opaque;
 use crate::{bindings, init::PinInit, str::CStr, try_pin_init, ThisModule};
-use core::{ffi, pin::Pin};
+use core::{ffi, marker::PhantomData, pin::Pin};
 use macros::{pin_data, pinned_drop};
 
 /// A file system type.
@@ -73,3 +73,57 @@ fn drop(self: Pin<&mut Self>) {
         unsafe { bindings::unregister_filesystem(self.fs.get()) };
     }
 }
+
+/// Kernel module that exposes a single file system implemented by `T`.
+#[pin_data]
+pub struct Module<T: FileSystem + ?Sized> {
+    #[pin]
+    fs_reg: Registration,
+    _p: PhantomData<T>,
+}
+
+impl<T: FileSystem + ?Sized + Sync + Send> crate::InPlaceModule for Module<T> {
+    fn init(module: &'static ThisModule) -> impl PinInit<Self, Error> {
+        try_pin_init!(Self {
+            fs_reg <- Registration::new::<T>(module),
+            _p: PhantomData,
+        })
+    }
+}
+
+/// Declares a kernel module that exposes a single file system.
+///
+/// The `type` argument must be a type which implements the [`FileSystem`] trait. Also accepts
+/// various forms of kernel metadata.
+///
+/// # Examples
+///
+/// ```
+/// # mod module_fs_sample {
+/// use kernel::fs;
+/// use kernel::prelude::*;
+///
+/// kernel::module_fs! {
+///     type: MyFs,
+///     name: "myfs",
+///     author: "Rust for Linux Contributors",
+///     description: "My Rust fs",
+///     license: "GPL",
+/// }
+///
+/// struct MyFs;
+/// impl fs::FileSystem for MyFs {
+///     const NAME: &'static CStr = kernel::c_str!("myfs");
+/// }
+/// # }
+/// ```
+#[macro_export]
+macro_rules! module_fs {
+    (type: $type:ty, $($f:tt)*) => {
+        type ModuleType = $crate::fs::Module<$type>;
+        $crate::macros::module! {
+            type: ModuleType,
+            $($f)*
+        }
+    }
+}
Signature · 1 line
2.34.1
#3 lore raw

RFC PATCH v2 3/30 samples: rust: add initial ro file system sample

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Introduce a basic sample that for now only registers the file system and doesn't really provide any functionality beyond having it listed in /proc/filesystems. New functionality will be added to the sample in subsequent patches as their abstractions are introduced.

---
 samples/rust/Kconfig      | 10 ++++++++++
 samples/rust/Makefile     |  1 +
 samples/rust/rust_rofs.rs | 19 +++++++++++++++++++
 3 files changed, 30 insertions(+)
 create mode 100644 samples/rust/rust_rofs.rs
samples/rust/Kconfig +10 -0
index 59f44a8b6958..2f26c5c52813 100644
@@ -41,6 +41,16 @@ config SAMPLE_RUST_PRINT
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_ROFS
+	tristate "Read-only file system"
+	help
+	  This option builds the Rust read-only file system sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_rofs.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_HOSTPROGS
 	bool "Host programs"
 	help
samples/rust/Makefile +1 -0
index 791fc18180e9..df1e4341ae95 100644
@@ -3,5 +3,6 @@
 obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
 obj-$(CONFIG_SAMPLE_RUST_INPLACE)		+= rust_inplace.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
+obj-$(CONFIG_SAMPLE_RUST_ROFS)			+= rust_rofs.o
 
 subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS)		+= hostprogs
samples/rust/rust_rofs.rs new file +19 -0
new file mode 100644
index 000000000000..d465b107a07d
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust read-only file system sample.
+
+use kernel::prelude::*;
+use kernel::{c_str, fs};
+
+kernel::module_fs! {
+    type: RoFs,
+    name: "rust_rofs",
+    author: "Rust for Linux Contributors",
+    description: "Rust read-only file system sample",
+    license: "GPL",
+}
+
+struct RoFs;
+impl fs::FileSystem for RoFs {
+    const NAME: &'static CStr = c_str!("rust_rofs");
+}
Signature · 1 line
2.34.1
#4 lore raw

RFC PATCH v2 4/30 rust: fs: introduce `FileSystem::fill_super`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to initialise superblocks, which allows them to be mounted (though they are still empty).

Some scaffolding code is added to create an empty directory as the root. It is replaced by proper inode creation in a subsequent patch in this series.

---
 rust/bindings/bindings_helper.h |   5 ++
 rust/kernel/fs.rs               | 147 ++++++++++++++++++++++++++++++--
 rust/kernel/fs/sb.rs            |  50 +++++++++++
 samples/rust/rust_rofs.rs       |   6 ++
 4 files changed, 202 insertions(+), 6 deletions(-)
 create mode 100644 rust/kernel/fs/sb.rs
rust/bindings/bindings_helper.h +5 -0
index 1bef4dff3019..dabb5a787e0d 100644
@@ -12,6 +12,7 @@
 #include <linux/ethtool.h>
 #include <linux/file.h>
 #include <linux/fs.h>
+#include <linux/fs_context.h>
 #include <linux/jiffies.h>
 #include <linux/mdio.h>
 #include <linux/phy.h>
@@ -32,3 +33,7 @@ const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO;
 
 const slab_flags_t RUST_CONST_HELPER_SLAB_RECLAIM_ACCOUNT = SLAB_RECLAIM_ACCOUNT;
 const slab_flags_t RUST_CONST_HELPER_SLAB_ACCOUNT = SLAB_ACCOUNT;
+
+const unsigned long RUST_CONST_HELPER_SB_RDONLY = SB_RDONLY;
+
+const loff_t RUST_CONST_HELPER_MAX_LFS_FILESIZE = MAX_LFS_FILESIZE;
rust/kernel/fs.rs +141 -6

194 lines not on this page · raw message

rust/kernel/fs/sb.rs new file +50 -0

50 lines not on this page · raw message

samples/rust/rust_rofs.rs +6 -0
index d465b107a07d..022addf68891 100644
@@ -2,6 +2,7 @@
 
 //! Rust read-only file system sample.
 
+use kernel::fs::sb;
 use kernel::prelude::*;
 use kernel::{c_str, fs};
 
@@ -16,4 +17,9 @@
 struct RoFs;
 impl fs::FileSystem for RoFs {
     const NAME: &'static CStr = c_str!("rust_rofs");
+
+    fn fill_super(sb: &mut sb::SuperBlock<Self>) -> Result {
+        sb.set_magic(0x52555354);
+        Ok(())
+    }
 }
Signature · 1 line
2.34.1
#5 lore raw

Re: [RFC PATCH v2 04/30] rust: fs: introduce `FileSystem::fill_super`

Quoted 47 lines · Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to initialise superblocks, which allows them to be mounted (though they are still empty).

Some scaffolding code is added to create an empty directory as the root. It is replaced by proper inode creation in a subsequent patch in this series.

---
 rust/bindings/bindings_helper.h |   5 ++
 rust/kernel/fs.rs               | 147 ++++++++++++++++++++++++++++++--
 rust/kernel/fs/sb.rs            |  50 +++++++++++
 samples/rust/rust_rofs.rs       |   6 ++
 4 files changed, 202 insertions(+), 6 deletions(-)
 create mode 100644 rust/kernel/fs/sb.rs
rust/bindings/bindings_helper.h +5 -0
index 1bef4dff3019..dabb5a787e0d 100644
@@ -12,6 +12,7 @@
 #include <linux/ethtool.h>
 #include <linux/file.h>
 #include <linux/fs.h>
+#include <linux/fs_context.h>
 #include <linux/jiffies.h>
 #include <linux/mdio.h>
 #include <linux/phy.h>
@@ -32,3 +33,7 @@ const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO;
 
 const slab_flags_t RUST_CONST_HELPER_SLAB_RECLAIM_ACCOUNT = SLAB_RECLAIM_ACCOUNT;
 const slab_flags_t RUST_CONST_HELPER_SLAB_ACCOUNT = SLAB_ACCOUNT;
+
+const unsigned long RUST_CONST_HELPER_SB_RDONLY = SB_RDONLY;
+
+const loff_t RUST_CONST_HELPER_MAX_LFS_FILESIZE = MAX_LFS_FILESIZE;
rust/kernel/fs.rs +0 -1
index fb7a9b200b85..263b4b6186ae 100644
@@ -6,16 +6,30 @@
 //!
 //! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
 
-use crate::error::{code::*, from_result, to_result, Error};

rust/kernel/fs.rs line 18

Quoted 10 lines
rust/kernel/fs.rs +6 -0
+use crate::error::{code::*, from_result, to_result, Error, Result};
 use crate::types::Opaque;
 use crate::{bindings, init::PinInit, str::CStr, try_pin_init, ThisModule};
 use core::{ffi, marker::PhantomData, pin::Pin};
 use macros::{pin_data, pinned_drop};
+use sb::SuperBlock;
+
+pub mod sb;
+
+/// The offset of a file in a file system.

This is really the position of some data within a file, in bytes.

rust/kernel/fs.rs line 21

Quoted 3 lines
rust/kernel/fs.rs +3 -0
+///
+/// This is C's `loff_t`.
+pub type Offset = i64;

Ergh, I really wish this was loff (or LOff if we're really doing camelcase for rust code) for somewhat better greppability.

Quoted 97 lines
rust/kernel/fs.rs +65 -4
+
+/// Maximum size of an inode.
+pub const MAX_LFS_FILESIZE: Offset = bindings::MAX_LFS_FILESIZE;
 
 /// A file system type.
 pub trait FileSystem {
     /// The name of the file system type.
     const NAME: &'static CStr;
+
+    /// Initialises the new superblock.
+    fn fill_super(sb: &mut SuperBlock<Self>) -> Result;
 }
 
 /// A registration of a file system.
@@ -46,7 +60,7 @@ pub fn new<T: FileSystem + ?Sized>(module: &'static ThisModule) -> impl PinInit<
                 let fs = unsafe { &mut *fs_ptr };
                 fs.owner = module.0;
                 fs.name = T::NAME.as_char_ptr();
-                fs.init_fs_context = Some(Self::init_fs_context_callback);
+                fs.init_fs_context = Some(Self::init_fs_context_callback::<T>);
                 fs.kill_sb = Some(Self::kill_sb_callback);
                 fs.fs_flags = 0;
 
@@ -57,11 +71,22 @@ pub fn new<T: FileSystem + ?Sized>(module: &'static ThisModule) -> impl PinInit<
         })
     }
 
-    unsafe extern "C" fn init_fs_context_callback(_fc: *mut bindings::fs_context) -> ffi::c_int {
-        from_result(|| Err(ENOTSUPP))
+    unsafe extern "C" fn init_fs_context_callback<T: FileSystem + ?Sized>(
+        fc_ptr: *mut bindings::fs_context,
+    ) -> ffi::c_int {
+        from_result(|| {
+            // SAFETY: The C callback API guarantees that `fc_ptr` is valid.
+            let fc = unsafe { &mut *fc_ptr };
+            fc.ops = &Tables::<T>::CONTEXT;
+            Ok(0)
+        })
     }
 
-    unsafe extern "C" fn kill_sb_callback(_sb_ptr: *mut bindings::super_block) {}
+    unsafe extern "C" fn kill_sb_callback(sb_ptr: *mut bindings::super_block) {
+        // SAFETY: In `get_tree_callback` we always call `get_tree_nodev`, so `kill_anon_super` is
+        // the appropriate function to call for cleanup.
+        unsafe { bindings::kill_anon_super(sb_ptr) };
+    }
 }
 
 #[pinned_drop]
@@ -74,6 +99,113 @@ fn drop(self: Pin<&mut Self>) {
     }
 }
 
+struct Tables<T: FileSystem + ?Sized>(T);
+impl<T: FileSystem + ?Sized> Tables<T> {
+    const CONTEXT: bindings::fs_context_operations = bindings::fs_context_operations {
+        free: None,
+        parse_param: None,
+        get_tree: Some(Self::get_tree_callback),
+        reconfigure: None,
+        parse_monolithic: None,
+        dup: None,
+    };
+
+    unsafe extern "C" fn get_tree_callback(fc: *mut bindings::fs_context) -> ffi::c_int {
+        // SAFETY: `fc` is valid per the callback contract. `fill_super_callback` also has
+        // the right type and is a valid callback.
+        unsafe { bindings::get_tree_nodev(fc, Some(Self::fill_super_callback)) }
+    }
+
+    unsafe extern "C" fn fill_super_callback(
+        sb_ptr: *mut bindings::super_block,
+        _fc: *mut bindings::fs_context,
+    ) -> ffi::c_int {
+        from_result(|| {
+            // SAFETY: The callback contract guarantees that `sb_ptr` is a unique pointer to a
+            // newly-created superblock.
+            let new_sb = unsafe { SuperBlock::from_raw_mut(sb_ptr) };
+
+            // SAFETY: The callback contract guarantees that `sb_ptr`, from which `new_sb` is
+            // derived, is valid for write.
+            let sb = unsafe { &mut *new_sb.0.get() };
+            sb.s_op = &Tables::<T>::SUPER_BLOCK;
+            sb.s_flags |= bindings::SB_RDONLY;
+
+            T::fill_super(new_sb)?;
+
+            // The following is scaffolding code that will be removed in a subsequent patch. It is
+            // needed to build a root dentry, otherwise core code will BUG().
+            // SAFETY: `sb` is the superblock being initialised, it is valid for read and write.
+            let inode = unsafe { bindings::new_inode(sb) };
+            if inode.is_null() {
+                return Err(ENOMEM);
+            }
+
+            // SAFETY: `inode` is valid for write.
+            unsafe { bindings::set_nlink(inode, 2) };

rust/kernel/fs.rs fn drop(self: Pin<&mut Self>) { · line 155

Quoted 10 lines
rust/kernel/fs.rs +10 -0
+
+            {
+                // SAFETY: This is a newly-created inode. No other references to it exist, so it is
+                // safe to mutably dereference it.
+                let inode = unsafe { &mut *inode };
+                inode.i_ino = 1;
+                inode.i_mode = (bindings::S_IFDIR | 0o755) as _;
+
+                // SAFETY: `simple_dir_operations` never changes, it's safe to reference it.
+                inode.__bindgen_anon_3.i_fop = unsafe { &bindings::simple_dir_operations };
                         ^^^^^^^^^^^^^^^^

This is a gross way to handle anonymous struct fields. What happens when struct inode changes and we have to do a giant treewide sed?

(and yes, I understand that's likely going to be a rustc change...)

--D

Quoted 157 lines
rust/kernel/fs.rs +57 -1
+
+                // SAFETY: `simple_dir_inode_operations` never changes, it's safe to reference it.
+                inode.i_op = unsafe { &bindings::simple_dir_inode_operations };
+            }
+
+            // SAFETY: `d_make_root` requires that `inode` be valid and referenced, which is the
+            // case for this call.
+            //
+            // It takes over the inode, even on failure, so we don't need to clean it up.
+            let dentry = unsafe { bindings::d_make_root(inode) };
+            if dentry.is_null() {
+                return Err(ENOMEM);
+            }
+
+            sb.s_root = dentry;
+
+            Ok(0)
+        })
+    }
+
+    const SUPER_BLOCK: bindings::super_operations = bindings::super_operations {
+        alloc_inode: None,
+        destroy_inode: None,
+        free_inode: None,
+        dirty_inode: None,
+        write_inode: None,
+        drop_inode: None,
+        evict_inode: None,
+        put_super: None,
+        sync_fs: None,
+        freeze_super: None,
+        freeze_fs: None,
+        thaw_super: None,
+        unfreeze_fs: None,
+        statfs: None,
+        remount_fs: None,
+        umount_begin: None,
+        show_options: None,
+        show_devname: None,
+        show_path: None,
+        show_stats: None,
+        #[cfg(CONFIG_QUOTA)]
+        quota_read: None,
+        #[cfg(CONFIG_QUOTA)]
+        quota_write: None,
+        #[cfg(CONFIG_QUOTA)]
+        get_dquots: None,
+        nr_cached_objects: None,
+        free_cached_objects: None,
+        shutdown: None,
+    };
+}
+
 /// Kernel module that exposes a single file system implemented by `T`.
 #[pin_data]
 pub struct Module<T: FileSystem + ?Sized> {
@@ -100,7 +232,7 @@ fn init(module: &'static ThisModule) -> impl PinInit<Self, Error> {
 ///
 /// ```
 /// # mod module_fs_sample {
-/// use kernel::fs;
+/// use kernel::fs::{sb::SuperBlock, self};
 /// use kernel::prelude::*;
 ///
 /// kernel::module_fs! {
@@ -114,6 +246,9 @@ fn init(module: &'static ThisModule) -> impl PinInit<Self, Error> {
 /// struct MyFs;
 /// impl fs::FileSystem for MyFs {
 ///     const NAME: &'static CStr = kernel::c_str!("myfs");
+///     fn fill_super(_: &mut SuperBlock<Self>) -> Result {
+///         todo!()
+///     }
 /// }
 /// # }
 /// ```
rust/kernel/fs/sb.rs new file +50 -0
new file mode 100644
index 000000000000..113d3c0d8148
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! File system super blocks.
+//!
+//! This module allows Rust code to use superblocks.
+//!
+//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
+
+use super::FileSystem;
+use crate::{bindings, types::Opaque};
+use core::marker::PhantomData;
+
+/// A file system super block.
+///
+/// Wraps the kernel's `struct super_block`.
+#[repr(transparent)]
+pub struct SuperBlock<T: FileSystem + ?Sized>(
+    pub(crate) Opaque<bindings::super_block>,
+    PhantomData<T>,
+);
+
+impl<T: FileSystem + ?Sized> SuperBlock<T> {
+    /// Creates a new superblock mutable reference from the given raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that:
+    ///
+    /// * `ptr` is valid and remains so for the lifetime of the returned object.
+    /// * `ptr` has the correct file system type.
+    /// * `ptr` is the only active pointer to the superblock.
+    pub(crate) unsafe fn from_raw_mut<'a>(ptr: *mut bindings::super_block) -> &'a mut Self {
+        // SAFETY: The safety requirements guarantee that the cast below is ok.
+        unsafe { &mut *ptr.cast::<Self>() }
+    }
+
+    /// Returns whether the superblock is mounted in read-only mode.
+    pub fn rdonly(&self) -> bool {
+        // SAFETY: `s_flags` only changes during init, so it is safe to read it.
+        unsafe { (*self.0.get()).s_flags & bindings::SB_RDONLY != 0 }
+    }
+
+    /// Sets the magic number of the superblock.
+    pub fn set_magic(&mut self, magic: usize) -> &mut Self {
+        // SAFETY: This is a new superblock that is being initialised, so it's ok to write to its
+        // fields.
+        unsafe { (*self.0.get()).s_magic = magic as core::ffi::c_ulong };
+        self
+    }
+}
samples/rust/rust_rofs.rs +6 -0
index d465b107a07d..022addf68891 100644
@@ -2,6 +2,7 @@
 
 //! Rust read-only file system sample.
 
+use kernel::fs::sb;
 use kernel::prelude::*;
 use kernel::{c_str, fs};
 
@@ -16,4 +17,9 @@
 struct RoFs;
 impl fs::FileSystem for RoFs {
     const NAME: &'static CStr = c_str!("rust_rofs");
+
+    fn fill_super(sb: &mut sb::SuperBlock<Self>) -> Result {
+        sb.set_magic(0x52555354);
+        Ok(())
+    }
 }
Signature · 1 line
2.34.1
#6 lore raw

RFC PATCH v2 5/30 rust: fs: introduce `INode<T>`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to handle typed and ref-counted inodes.

This is in preparation for creating new inodes (for example, to create the root inode of a new superblock), which comes in the next patch in the series.

---
 rust/helpers.c          |  7 ++++
 rust/kernel/block.rs    |  9 +++++
 rust/kernel/fs.rs       | 20 +++++++++++
 rust/kernel/fs/inode.rs | 78 +++++++++++++++++++++++++++++++++++++++++
 rust/kernel/fs/sb.rs    | 15 +++++++-
 5 files changed, 128 insertions(+), 1 deletion(-)
 create mode 100644 rust/kernel/fs/inode.rs
rust/helpers.c +7 -0
index 318e3e85dddd..c697c1c4c9d7 100644
@@ -164,6 +164,13 @@ struct file *rust_helper_get_file(struct file *f)
 }
 EXPORT_SYMBOL_GPL(rust_helper_get_file);
 
+
+loff_t rust_helper_i_size_read(const struct inode *inode)
+{
+	return i_size_read(inode);
+}
+EXPORT_SYMBOL_GPL(rust_helper_i_size_read);
+
 unsigned long rust_helper_copy_to_user(void __user *to, const void *from,
 				       unsigned long n)
 {
rust/kernel/block.rs +9 -0
index 38d2a3089ae7..868623d7c873 100644
@@ -5,6 +5,7 @@
 //! C headers: [`include/linux/blk_types.h`](../../include/linux/blk_types.h)
 
 use crate::bindings;
+use crate::fs::inode::INode;
 use crate::types::Opaque;
 
 /// The type used for indexing onto a disc or disc partition.
@@ -35,4 +36,12 @@ pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::block_device) -> &'a Self
         // SAFETY: The safety requirements guarantee that the cast below is ok.
         unsafe { &*ptr.cast::<Self>() }
     }
+
+    /// Returns the inode associated with this block device.
+    pub fn inode(&self) -> &INode {
+        // SAFETY: `bd_inode` is never reassigned.
+        let ptr = unsafe { (*self.0.get()).bd_inode };
+        // SAFET: `ptr` is valid as long as the block device remains valid as well.
+        unsafe { INode::from_raw(ptr) }
+    }
 }
rust/kernel/fs.rs +20 -0
index 263b4b6186ae..89dcd5537830 100644
@@ -13,6 +13,7 @@
 use macros::{pin_data, pinned_drop};
 use sb::SuperBlock;
 
+pub mod inode;
 pub mod sb;
 
 /// The offset of a file in a file system.
@@ -28,10 +29,29 @@ pub trait FileSystem {
     /// The name of the file system type.
     const NAME: &'static CStr;
 
+    /// Determines if an implementation doesn't specify the required types.
+    ///
+    /// This is meant for internal use only.
+    #[doc(hidden)]
+    const IS_UNSPECIFIED: bool = false;
+
     /// Initialises the new superblock.
     fn fill_super(sb: &mut SuperBlock<Self>) -> Result;
 }
 
+/// A file system that is unspecified.
+///
+/// Attempting to get super-block or inode data from it will result in a build error.
+pub struct UnspecifiedFS;
+
+impl FileSystem for UnspecifiedFS {
+    const NAME: &'static CStr = crate::c_str!("unspecified");
+    const IS_UNSPECIFIED: bool = true;
+    fn fill_super(_: &mut SuperBlock<Self>) -> Result {
+        Err(ENOTSUPP)
+    }
+}
+
 /// A registration of a file system.
 #[pin_data(PinnedDrop)]
 pub struct Registration {
rust/kernel/fs/inode.rs new file +78 -0

78 lines not on this page · raw message

rust/kernel/fs/sb.rs +14 -1
index 113d3c0d8148..f48e0e2695fa 100644
@@ -20,6 +20,19 @@ pub struct SuperBlock<T: FileSystem + ?Sized>(
 );
 
 impl<T: FileSystem + ?Sized> SuperBlock<T> {
+    /// Creates a new superblock reference from the given raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that:
+    ///
+    /// * `ptr` is valid and remains so for the lifetime of the returned object.
+    /// * `ptr` has the correct file system type, or `T` is [`super::UnspecifiedFS`].
+    pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::super_block) -> &'a Self {
+        // SAFETY: The safety requirements guarantee that the cast below is ok.
+        unsafe { &*ptr.cast::<Self>() }
+    }
+
     /// Creates a new superblock mutable reference from the given raw pointer.
     ///
     /// # Safety
@@ -27,7 +40,7 @@ impl<T: FileSystem + ?Sized> SuperBlock<T> {
     /// Callers must ensure that:
     ///
     /// * `ptr` is valid and remains so for the lifetime of the returned object.
-    /// * `ptr` has the correct file system type.
+    /// * `ptr` has the correct file system type, or `T` is [`super::UnspecifiedFS`].
     /// * `ptr` is the only active pointer to the superblock.
     pub(crate) unsafe fn from_raw_mut<'a>(ptr: *mut bindings::super_block) -> &'a mut Self {
         // SAFETY: The safety requirements guarantee that the cast below is ok.
Signature · 1 line
2.34.1
#7 lore raw

RFC PATCH v2 6/30 rust: fs: introduce `DEntry<T>`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

---
 rust/helpers.c           |   6 ++
 rust/kernel/error.rs     |   2 -
 rust/kernel/fs.rs        |   1 +
 rust/kernel/fs/dentry.rs | 137 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 144 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/fs/dentry.rs
rust/helpers.c +6 -0
index c697c1c4c9d7..c7fe6917251e 100644
@@ -165,6 +165,12 @@ struct file *rust_helper_get_file(struct file *f)
 EXPORT_SYMBOL_GPL(rust_helper_get_file);
 
 
+struct dentry *rust_helper_dget(struct dentry *dentry)
+{
+	return dget(dentry);
+}
+EXPORT_SYMBOL_GPL(rust_helper_dget);
+
 loff_t rust_helper_i_size_read(const struct inode *inode)
 {
 	return i_size_read(inode);
rust/kernel/error.rs +0 -2
index f4fa2847e210..bb13bd4a7fa6 100644
@@ -261,8 +261,6 @@ pub fn to_result(err: core::ffi::c_int) -> Result {
 ///     from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
 /// }
 /// ```
-// TODO: Remove `dead_code` marker once an in-kernel client is available.
-#[allow(dead_code)]
 pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
     // CAST: Casting a pointer to `*const core::ffi::c_void` is always valid.
     let const_ptr: *const core::ffi::c_void = ptr.cast();
rust/kernel/fs.rs +1 -0
index 89dcd5537830..4f07da71e1ec 100644
@@ -13,6 +13,7 @@
 use macros::{pin_data, pinned_drop};
 use sb::SuperBlock;
 
+pub mod dentry;
 pub mod inode;
 pub mod sb;
 
rust/kernel/fs/dentry.rs new file +137 -0

137 lines not on this page · raw message

Signature · 1 line
2.34.1
#8 lore raw

RFC PATCH v2 7/30 rust: fs: introduce `FileSystem::init_root`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to specify their root directory. Also allow them to create (and do cache lookups of) directory inodes. (More types of inodes are added in subsequent patches in the series.)

The inode::New type ensures that a new inode is properly initialised before it is marked so. It also facilitates error paths by automatically marking inodes as failed if they're not properly initialised.

---
 rust/helpers.c            |  11 ++++
 rust/kernel/fs.rs         |  56 ++++++++-----------
 rust/kernel/fs/inode.rs   | 111 +++++++++++++++++++++++++++++++++++++-
 rust/kernel/fs/sb.rs      |  48 ++++++++++++++++-
 samples/rust/rust_rofs.rs |  25 +++++++--
 5 files changed, 211 insertions(+), 40 deletions(-)
rust/helpers.c +11 -0
index c7fe6917251e..87301e1ace65 100644
@@ -164,6 +164,17 @@ struct file *rust_helper_get_file(struct file *f)
 }
 EXPORT_SYMBOL_GPL(rust_helper_get_file);
 
+void rust_helper_i_uid_write(struct inode *inode, uid_t uid)
+{
+	i_uid_write(inode, uid);
+}
+EXPORT_SYMBOL_GPL(rust_helper_i_uid_write);
+
+void rust_helper_i_gid_write(struct inode *inode, gid_t gid)
+{
+	i_gid_write(inode, gid);
+}
+EXPORT_SYMBOL_GPL(rust_helper_i_gid_write);
 
 struct dentry *rust_helper_dget(struct dentry *dentry)
 {
rust/kernel/fs.rs +23 -33

96 lines not on this page · raw message

rust/kernel/fs/inode.rs +109 -2

120 lines not on this page · raw message

rust/kernel/fs/sb.rs +46 -2

59 lines not on this page · raw message

samples/rust/rust_rofs.rs +22 -3
index 022addf68891..d32c4645ebe8 100644
@@ -2,9 +2,9 @@
 
 //! Rust read-only file system sample.
 
-use kernel::fs::sb;
+use kernel::fs::{dentry, inode, sb::SuperBlock};
 use kernel::prelude::*;
-use kernel::{c_str, fs};
+use kernel::{c_str, fs, time::UNIX_EPOCH, types::Either};
 
 kernel::module_fs! {
     type: RoFs,
@@ -18,8 +18,27 @@
 impl fs::FileSystem for RoFs {
     const NAME: &'static CStr = c_str!("rust_rofs");
 
-    fn fill_super(sb: &mut sb::SuperBlock<Self>) -> Result {
+    fn fill_super(sb: &mut SuperBlock<Self>) -> Result {
         sb.set_magic(0x52555354);
         Ok(())
     }
+
+    fn init_root(sb: &SuperBlock<Self>) -> Result<dentry::Root<Self>> {
+        let inode = match sb.get_or_create_inode(1)? {
+            Either::Left(existing) => existing,
+            Either::Right(new) => new.init(inode::Params {
+                typ: inode::Type::Dir,
+                mode: 0o555,
+                size: 1,
+                blocks: 1,
+                nlink: 2,
+                uid: 0,
+                gid: 0,
+                atime: UNIX_EPOCH,
+                ctime: UNIX_EPOCH,
+                mtime: UNIX_EPOCH,
+            })?,
+        };
+        dentry::Root::try_new(inode)
+    }
 }
Signature · 1 line
2.34.1
#9 lore raw

RFC PATCH v2 8/30 rust: file: move `kernel::file` to `kernel::fs::file`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

This is in preparation for making File parametrised on the file system type, so we can get a typed inode in file system implementations that have data attached to inodes.

---
 rust/kernel/fs.rs            | 1 +
 rust/kernel/{ => fs}/file.rs | 2 +-
 rust/kernel/lib.rs           | 1 -
 3 files changed, 2 insertions(+), 2 deletions(-)
 rename rust/kernel/{ => fs}/file.rs (99%)
rust/kernel/fs.rs +1 -0
index f32c2f89f781..20fb6107eb4b 100644
@@ -14,6 +14,7 @@
 use sb::SuperBlock;
 
 pub mod dentry;
+pub mod file;
 pub mod inode;
 pub mod sb;
 
rust/kernel/fs/file.rs renamed from rust/kernel/file.rs +1 -1
similarity index 99%
rename from rust/kernel/file.rs
rename to rust/kernel/fs/file.rs
index b7ded0cdd063..908e2672676f 100644
@@ -76,7 +76,7 @@ pub mod flags {
     /// # Examples
     ///
     /// ```
-    /// use kernel::file;
+    /// use kernel::fs::file;
     /// # fn do_something() {}
     /// # let flags = 0;
     /// if (flags & file::flags::O_ACCMODE) == file::flags::O_RDONLY {
rust/kernel/lib.rs +0 -1
index e664f80b8141..81065d1bd679 100644
@@ -30,7 +30,6 @@
 pub mod block;
 mod build_assert;
 pub mod error;
-pub mod file;
 pub mod fs;
 pub mod init;
 pub mod ioctl;
Signature · 1 line
2.34.1
#10 lore raw

RFC PATCH v2 9/30 rust: fs: generalise `File` for different file systems

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

This is in preparation for allowing file operation implementations for different file systems.

Also add an unspecified file system so that users of the File type that don't care about the file system may continue to do so.

---
 rust/kernel/fs/file.rs  | 53 ++++++++++++++++++++++++++++-------------
 rust/kernel/fs/inode.rs |  1 -
 2 files changed, 36 insertions(+), 18 deletions(-)
rust/kernel/fs/file.rs +36 -17
index 908e2672676f..b8386a396251 100644
@@ -2,15 +2,18 @@
 
 //! Files and file descriptors.
 //!
-//! C headers: [`include/linux/fs.h`](../../../../include/linux/fs.h) and
-//! [`include/linux/file.h`](../../../../include/linux/file.h)
+//! This module allows Rust code to interact with and implement files.
+//!
+//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h) and
+//! [`include/linux/file.h`](srctree/include/linux/file.h)
 
+use super::{dentry::DEntry, inode::INode, FileSystem, UnspecifiedFS};
 use crate::{
     bindings,
     error::{code::*, Error, Result},
     types::{ARef, AlwaysRefCounted, Opaque},
 };
-use core::ptr;
+use core::{marker::PhantomData, ptr};
 
 /// Flags associated with a [`File`].
 pub mod flags {
@@ -95,6 +98,8 @@ pub mod flags {
     pub const O_RDWR: u32 = bindings::O_RDWR;
 }
 
+/// A file.
+///
 /// Wraps the kernel's `struct file`.
 ///
 /// # Refcounting
@@ -139,7 +144,7 @@ pub mod flags {
 /// * The Rust borrow-checker normally ensures this by enforcing that the `ARef<File>` from which
 ///   a `&File` is created outlives the `&File`.
 ///
-/// * Using the unsafe [`File::from_ptr`] means that it is up to the caller to ensure that the
+/// * Using the unsafe [`File::from_raw`] means that it is up to the caller to ensure that the
 ///   `&File` only exists while the reference count is positive.
 ///
 /// * You can think of `fdget` as using an fd to look up an `ARef<File>` in the `struct
@@ -154,20 +159,20 @@ pub mod flags {
 ///   closed.
 /// * A light refcount must be dropped before returning to userspace.
 #[repr(transparent)]
-pub struct File(Opaque<bindings::file>);
+pub struct File<T: FileSystem + ?Sized = UnspecifiedFS>(Opaque<bindings::file>, PhantomData<T>);
 
 // SAFETY: By design, the only way to access a `File` is via an immutable reference or an `ARef`.
 // This means that the only situation in which a `File` can be accessed mutably is when the
 // refcount drops to zero and the destructor runs. It is safe for that to happen on any thread, so
 // it is ok for this type to be `Send`.
-unsafe impl Send for File {}
+unsafe impl<T: FileSystem + ?Sized> Send for File<T> {}
 
 // SAFETY: All methods defined on `File` that take `&self` are safe to call even if other threads
 // are concurrently accessing the same `struct file`, because those methods either access immutable
 // properties or have proper synchronization to ensure that such accesses are safe.
-unsafe impl Sync for File {}
+unsafe impl<T: FileSystem + ?Sized> Sync for File<T> {}
 
-impl File {
+impl<T: FileSystem + ?Sized> File<T> {
     /// Constructs a new `struct file` wrapper from a file descriptor.
     ///
     /// The file descriptor belongs to the current process.
@@ -187,15 +192,17 @@ pub fn fget(fd: u32) -> Result<ARef<Self>, BadFdError> {
     ///
     /// # Safety
     ///
-    /// The caller must ensure that `ptr` points at a valid file and that the file's refcount is
-    /// positive for the duration of 'a.
-    pub unsafe fn from_ptr<'a>(ptr: *const bindings::file) -> &'a File {
+    /// Callers must ensure that:
+    ///
+    /// * `ptr` is valid and remains so for the duration of 'a.
+    /// * `ptr` has the correct file system type, or `T` is [`UnspecifiedFS`].
+    pub unsafe fn from_raw<'a>(ptr: *const bindings::file) -> &'a Self {
         // SAFETY: The caller guarantees that the pointer is not dangling and stays valid for the
         // duration of 'a. The cast is okay because `File` is `repr(transparent)`.
         //
         // INVARIANT: The safety requirements guarantee that the refcount does not hit zero during
         // 'a.
-        unsafe { &*ptr.cast() }
+        unsafe { &*ptr.cast::<Self>() }
     }
 
     /// Returns a raw pointer to the inner C struct.
@@ -215,20 +222,32 @@ pub fn flags(&self) -> u32 {
         // TODO: Replace with `read_once` when available on the Rust side.
         unsafe { core::ptr::addr_of!((*self.as_ptr()).f_flags).read_volatile() }
     }
+
+    /// Returns the inode associated with the file.
+    pub fn inode(&self) -> &INode<T> {
+        // SAFETY: `f_inode` is an immutable field, so it's safe to read it.
+        unsafe { INode::from_raw((*self.0.get()).f_inode) }
+    }
+
+    /// Returns the dentry associated with the file.
+    pub fn dentry(&self) -> &DEntry<T> {
+        // SAFETY: `f_path` is an immutable field, so it's safe to read it. And will remain safe to
+        // read while the `&self` is valid.
+        unsafe { DEntry::from_raw((*self.0.get()).f_path.dentry) }
+    }
 }
 
 // SAFETY: The type invariants guarantee that `File` is always ref-counted. This implementation
 // makes `ARef<File>` own a normal refcount.
-unsafe impl AlwaysRefCounted for File {
+unsafe impl<T: FileSystem + ?Sized> AlwaysRefCounted for File<T> {
     fn inc_ref(&self) {
         // SAFETY: The existence of a shared reference means that the refcount is nonzero.
         unsafe { bindings::get_file(self.as_ptr()) };
     }
 
-    unsafe fn dec_ref(obj: ptr::NonNull<File>) {
-        // SAFETY: To call this method, the caller passes us ownership of a normal refcount, so we
-        // may drop it. The cast is okay since `File` has the same representation as `struct file`.
-        unsafe { bindings::fput(obj.cast().as_ptr()) }
+    unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that the refcount is nonzero.
+        unsafe { bindings::fput(obj.as_ref().0.get()) }
     }
 }
 
rust/kernel/fs/inode.rs +0 -1
index 4ccbb4145918..11df493314ea 100644
@@ -39,7 +39,6 @@ impl<T: FileSystem + ?Sized> INode<T> {
     ///
     /// * `ptr` is valid and remains so for the lifetime of the returned object.
     /// * `ptr` has the correct file system type, or `T` is [`super::UnspecifiedFS`].
-    #[allow(dead_code)]
     pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::inode) -> &'a Self {
         // SAFETY: The safety requirements guarantee that the cast below is ok.
         unsafe { &*ptr.cast::<Self>() }
Signature · 1 line
2.34.1
#11 lore raw

RFC PATCH v2 10/30 rust: fs: add empty file operations

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

This is in preparation for allowing modules to implement different file callbacks, which will be introduced in subsequent patches.

---
 rust/kernel/fs/file.rs | 57 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
rust/kernel/fs/file.rs +57 -0
index b8386a396251..67dd3ecf7d98 100644
@@ -14,6 +14,7 @@
     types::{ARef, AlwaysRefCounted, Opaque},
 };
 use core::{marker::PhantomData, ptr};
+use macros::vtable;
 
 /// Flags associated with a [`File`].
 pub mod flags {
@@ -268,3 +269,59 @@ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
         f.pad("EBADF")
     }
 }
+
+/// Operations implemented by files.
+#[vtable]
+pub trait Operations {
+    /// File system that these operations are compatible with.
+    type FileSystem: FileSystem + ?Sized;
+}
+
+/// Represents file operations.
+#[allow(dead_code)]
+pub struct Ops<T: FileSystem + ?Sized>(pub(crate) *const bindings::file_operations, PhantomData<T>);
+
+impl<T: FileSystem + ?Sized> Ops<T> {
+    /// Creates file operations from a type that implements the [`Operations`] trait.
+    pub const fn new<U: Operations<FileSystem = T> + ?Sized>() -> Self {
+        struct Table<T: Operations + ?Sized>(PhantomData<T>);
+        impl<T: Operations + ?Sized> Table<T> {
+            const TABLE: bindings::file_operations = bindings::file_operations {
+                owner: ptr::null_mut(),
+                llseek: None,
+                read: None,
+                write: None,
+                read_iter: None,
+                write_iter: None,
+                iopoll: None,
+                iterate_shared: None,
+                poll: None,
+                unlocked_ioctl: None,
+                compat_ioctl: None,
+                mmap: None,
+                mmap_supported_flags: 0,
+                open: None,
+                flush: None,
+                release: None,
+                fsync: None,
+                fasync: None,
+                lock: None,
+                get_unmapped_area: None,
+                check_flags: None,
+                flock: None,
+                splice_write: None,
+                splice_read: None,
+                splice_eof: None,
+                setlease: None,
+                fallocate: None,
+                show_fdinfo: None,
+                copy_file_range: None,
+                remap_file_range: None,
+                fadvise: None,
+                uring_cmd: None,
+                uring_cmd_iopoll: None,
+            };
+        }
+        Self(&Table::<U>::TABLE, PhantomData)
+    }
+}
Signature · 1 line
2.34.1
#12 lore raw

RFC PATCH v2 11/30 rust: fs: introduce `file::Operations::read_dir`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allows Rust file systems to report the contents of their directory inodes. The reported entries cannot be opened yet.

---
 rust/helpers.c            |  12 +++
 rust/kernel/fs/file.rs    | 176 ++++++++++++++++++++++++++++++++++++--
 rust/kernel/fs/inode.rs   |  31 +++++--
 samples/rust/rust_rofs.rs |  85 +++++++++++++++---
 4 files changed, 279 insertions(+), 25 deletions(-)
rust/helpers.c +12 -0
index 87301e1ace65..deb2d21f3096 100644
@@ -195,6 +195,18 @@ unsigned long rust_helper_copy_to_user(void __user *to, const void *from,
 }
 EXPORT_SYMBOL_GPL(rust_helper_copy_to_user);
 
+void rust_helper_inode_lock_shared(struct inode *inode)
+{
+	inode_lock_shared(inode);
+}
+EXPORT_SYMBOL_GPL(rust_helper_inode_lock_shared);
+
+void rust_helper_inode_unlock_shared(struct inode *inode)
+{
+	inode_unlock_shared(inode);
+}
+EXPORT_SYMBOL_GPL(rust_helper_inode_unlock_shared);
+
 /*
  * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can
  * use it in contexts where Rust expects a `usize` like slice (array) indices.
rust/kernel/fs/file.rs +170 -6

207 lines not on this page · raw message

rust/kernel/fs/inode.rs +26 -5
index 11df493314ea..d84d8d2f7076 100644
@@ -6,9 +6,9 @@
 //!
 //! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
 
-use super::{sb::SuperBlock, FileSystem, Offset, UnspecifiedFS};
+use super::{file, sb::SuperBlock, FileSystem, Offset, UnspecifiedFS};
 use crate::error::Result;
-use crate::types::{ARef, AlwaysRefCounted, Opaque};
+use crate::types::{ARef, AlwaysRefCounted, Lockable, Opaque};
 use crate::{bindings, block, time::Timespec};
 use core::mem::ManuallyDrop;
 use core::{marker::PhantomData, ptr};
@@ -78,6 +78,22 @@ unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
     }
 }
 
+/// Indicates that the an inode's rw semapahore is locked in read (shared) mode.
+pub struct ReadSem;
+
+unsafe impl<T: FileSystem + ?Sized> Lockable<ReadSem> for INode<T> {
+    fn raw_lock(&self) {
+        // SAFETY: Since there's a reference to the inode, it must be valid.
+        unsafe { bindings::inode_lock_shared(self.0.get()) };
+    }
+
+    unsafe fn unlock(&self) {
+        // SAFETY: Since there's a reference to the inode, it must be valid. Additionally, the
+        // safety requirements of this functino require that the inode be locked in read mode.
+        unsafe { bindings::inode_unlock_shared(self.0.get()) };
+    }
+}
+
 /// An inode that is locked and hasn't been initialised yet.
 ///
 /// # Invariants
@@ -95,9 +111,6 @@ pub fn init(mut self, params: Params) -> Result<ARef<INode<T>>> {
         let inode = unsafe { self.0.as_mut() };
         let mode = match params.typ {
             Type::Dir => {
-                // SAFETY: `simple_dir_operations` never changes, it's safe to reference it.
-                inode.__bindgen_anon_3.i_fop = unsafe { &bindings::simple_dir_operations };
-
                 // SAFETY: `simple_dir_inode_operations` never changes, it's safe to reference it.
                 inode.i_op = unsafe { &bindings::simple_dir_inode_operations };
 
@@ -126,6 +139,14 @@ pub fn init(mut self, params: Params) -> Result<ARef<INode<T>>> {
         // being called with the `ManuallyDrop` instance created above.
         Ok(unsafe { ARef::from_raw(manual.0.cast::<INode<T>>()) })
     }
+
+    /// Sets the file operations on this new inode.
+    pub fn set_fops(&mut self, fops: file::Ops<T>) -> &mut Self {
+        // SAFETY: By the type invariants, it's ok to modify the inode.
+        let inode = unsafe { self.0.as_mut() };
+        inode.__bindgen_anon_3.i_fop = fops.0;
+        self
+    }
 }
 
 impl<T: FileSystem + ?Sized> Drop for New<T> {
samples/rust/rust_rofs.rs +71 -14

105 lines not on this page · raw message

Signature · 1 line
2.34.1
#13 lore raw

RFC PATCH v2 12/30 rust: fs: introduce `file::Operations::seek`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

This allows file systems to customise their behaviour when callers want to seek to a different file location, which may also be used when reading directory entries.

---
 rust/kernel/fs/file.rs    | 73 ++++++++++++++++++++++++++++++++++++++-
 samples/rust/rust_rofs.rs |  6 +++-
 2 files changed, 77 insertions(+), 2 deletions(-)
rust/kernel/fs/file.rs +72 -1
index 6d61723f440d..77eb6d230568 100644
@@ -270,12 +270,65 @@ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
     }
 }
 
+/// Indicates how to interpret the `offset` argument in [`Operations::seek`].
+#[repr(u32)]
+pub enum Whence {
+    /// `offset` bytes from the start of the file.
+    Set = bindings::SEEK_SET,
+
+    /// `offset` bytes from the end of the file.
+    End = bindings::SEEK_END,
+
+    /// `offset` bytes from the current location.
+    Cur = bindings::SEEK_CUR,
+
+    /// The next location greater than or equal to `offset` that contains data.
+    Data = bindings::SEEK_DATA,
+
+    /// The next location greater than or equal to `offset` that contains a hole.
+    Hole = bindings::SEEK_HOLE,
+}
+
+impl TryFrom<i32> for Whence {
+    type Error = crate::error::Error;
+
+    fn try_from(v: i32) -> Result<Self> {
+        match v {
+            v if v == Self::Set as i32 => Ok(Self::Set),
+            v if v == Self::End as i32 => Ok(Self::End),
+            v if v == Self::Cur as i32 => Ok(Self::Cur),
+            v if v == Self::Data as i32 => Ok(Self::Data),
+            v if v == Self::Hole as i32 => Ok(Self::Hole),
+            _ => Err(EDOM),
+        }
+    }
+}
+
+/// Generic implementation of [`Operations::seek`].
+pub fn generic_seek(
+    file: &File<impl FileSystem + ?Sized>,
+    offset: Offset,
+    whence: Whence,
+) -> Result<Offset> {
+    let n = unsafe { bindings::generic_file_llseek(file.0.get(), offset, whence as i32) };
+    if n < 0 {
+        Err(Error::from_errno(n.try_into()?))
+    } else {
+        Ok(n)
+    }
+}
+
 /// Operations implemented by files.
 #[vtable]
 pub trait Operations {
     /// File system that these operations are compatible with.
     type FileSystem: FileSystem + ?Sized;
 
+    /// Seeks the file to the given offset.
+    fn seek(_file: &File<Self::FileSystem>, _offset: Offset, _whence: Whence) -> Result<Offset> {
+        Err(EINVAL)
+    }
+
     /// Reads directory entries from directory files.
     ///
     /// [`DirEmitter::pos`] holds the current position of the directory reader.
@@ -298,7 +351,11 @@ pub const fn new<U: Operations<FileSystem = T> + ?Sized>() -> Self {
         impl<T: Operations + ?Sized> Table<T> {
             const TABLE: bindings::file_operations = bindings::file_operations {
                 owner: ptr::null_mut(),
-                llseek: None,
+                llseek: if T::HAS_SEEK {
+                    Some(Self::seek_callback)
+                } else {
+                    None
+                },
                 read: None,
                 write: None,
                 read_iter: None,
@@ -336,6 +393,20 @@ impl<T: Operations + ?Sized> Table<T> {
                 uring_cmd_iopoll: None,
             };
 
+            unsafe extern "C" fn seek_callback(
+                file_ptr: *mut bindings::file,
+                offset: bindings::loff_t,
+                whence: i32,
+            ) -> bindings::loff_t {
+                from_result(|| {
+                    // SAFETY: The C API guarantees that `file` is valid for the duration of the
+                    // callback. Since this callback is specifically for filesystem T, we know `T`
+                    // is the right filesystem.
+                    let file = unsafe { File::from_raw(file_ptr) };
+                    T::seek(file, offset, whence.try_into()?)
+                })
+            }
+
             unsafe extern "C" fn read_dir_callback(
                 file_ptr: *mut bindings::file,
                 ctx_ptr: *mut bindings::dir_context,
samples/rust/rust_rofs.rs +5 -1
index 9da01346d8f8..abec084360da 100644
@@ -2,7 +2,7 @@
 
 //! Rust read-only file system sample.
 
-use kernel::fs::{dentry, file, file::File, inode, inode::INode, sb::SuperBlock};
+use kernel::fs::{dentry, file, file::File, inode, inode::INode, sb::SuperBlock, Offset};
 use kernel::prelude::*;
 use kernel::{c_str, fs, time::UNIX_EPOCH, types::Either, types::Locked};
 
@@ -76,6 +76,10 @@ fn init_root(sb: &SuperBlock<Self>) -> Result<dentry::Root<Self>> {
 impl file::Operations for RoFs {
     type FileSystem = Self;
 
+    fn seek(file: &File<Self>, offset: Offset, whence: file::Whence) -> Result<Offset> {
+        file::generic_seek(file, offset, whence)
+    }
+
     fn read_dir(
         _file: &File<Self>,
         inode: &Locked<&INode<Self>, inode::ReadSem>,
Signature · 1 line
2.34.1
#14 lore raw

RFC PATCH v2 13/30 rust: fs: introduce `file::Operations::read`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

This allows file systems to customise their behaviour when callers want to read from a file.

---
 rust/kernel/fs/file.rs    | 35 ++++++++++++++++++++++++++++++++++-
 rust/kernel/user.rs       |  1 -
 samples/rust/rust_rofs.rs |  6 +++++-
 3 files changed, 39 insertions(+), 3 deletions(-)
rust/kernel/fs/file.rs +34 -1
index 77eb6d230568..2ba456a1eee1 100644
@@ -12,6 +12,7 @@
     bindings,
     error::{code::*, from_result, Error, Result},
     types::{ARef, AlwaysRefCounted, Locked, Opaque},
+    user,
 };
 use core::{marker::PhantomData, mem::ManuallyDrop, ptr};
 use macros::vtable;
@@ -324,6 +325,15 @@ pub trait Operations {
     /// File system that these operations are compatible with.
     type FileSystem: FileSystem + ?Sized;
 
+    /// Reads data from this file into the caller's buffer.
+    fn read(
+        _file: &File<Self::FileSystem>,
+        _buffer: &mut user::Writer,
+        _offset: &mut Offset,
+    ) -> Result<usize> {
+        Err(EINVAL)
+    }
+
     /// Seeks the file to the given offset.
     fn seek(_file: &File<Self::FileSystem>, _offset: Offset, _whence: Whence) -> Result<Offset> {
         Err(EINVAL)
@@ -356,7 +366,11 @@ impl<T: Operations + ?Sized> Table<T> {
                 } else {
                     None
                 },
-                read: None,
+                read: if T::HAS_READ {
+                    Some(Self::read_callback)
+                } else {
+                    None
+                },
                 write: None,
                 read_iter: None,
                 write_iter: None,
@@ -407,6 +421,25 @@ impl<T: Operations + ?Sized> Table<T> {
                 })
             }
 
+            unsafe extern "C" fn read_callback(
+                file_ptr: *mut bindings::file,
+                ptr: *mut core::ffi::c_char,
+                len: usize,
+                offset: *mut bindings::loff_t,
+            ) -> isize {
+                from_result(|| {
+                    // SAFETY: The C API guarantees that `file` is valid for the duration of the
+                    // callback. Since this callback is specifically for filesystem T, we know `T`
+                    // is the right filesystem.
+                    let file = unsafe { File::from_raw(file_ptr) };
+                    let mut writer = user::Writer::new(ptr, len);
+
+                    // SAFETY: The C API guarantees that `offset` is valid for read and write.
+                    let read = T::read(file, &mut writer, unsafe { &mut *offset })?;
+                    Ok(isize::try_from(read)?)
+                })
+            }
+
             unsafe extern "C" fn read_dir_callback(
                 file_ptr: *mut bindings::file,
                 ctx_ptr: *mut bindings::dir_context,
rust/kernel/user.rs +0 -1
index 35a673ebcd58..20fb887f4640 100644
@@ -11,7 +11,6 @@ pub struct Writer {
 }
 
 impl Writer {
-    #[allow(dead_code)]
     pub(crate) fn new(ptr: *mut i8, len: usize) -> Self {
         Self {
             ptr: ptr.cast::<u8>(),
samples/rust/rust_rofs.rs +5 -1
index abec084360da..f4be5908369c 100644
@@ -4,7 +4,7 @@
 
 use kernel::fs::{dentry, file, file::File, inode, inode::INode, sb::SuperBlock, Offset};
 use kernel::prelude::*;
-use kernel::{c_str, fs, time::UNIX_EPOCH, types::Either, types::Locked};
+use kernel::{c_str, fs, time::UNIX_EPOCH, types::Either, types::Locked, user};
 
 kernel::module_fs! {
     type: RoFs,
@@ -80,6 +80,10 @@ fn seek(file: &File<Self>, offset: Offset, whence: file::Whence) -> Result<Offse
         file::generic_seek(file, offset, whence)
     }
 
+    fn read(_: &File<Self>, _: &mut user::Writer, _: &mut Offset) -> Result<usize> {
+        Err(EISDIR)
+    }
+
     fn read_dir(
         _file: &File<Self>,
         inode: &Locked<&INode<Self>, inode::ReadSem>,
Signature · 1 line
2.34.1
#15 lore raw

RFC PATCH v2 14/30 rust: fs: add empty inode operations

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

This is in preparation for allowing modules to implement different inode callbacks, which will be introduced in subsequent patches.

---
 rust/kernel/fs/inode.rs | 48 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 48 insertions(+)
rust/kernel/fs/inode.rs +48 -0
index d84d8d2f7076..3d65b917af0e 100644
@@ -12,10 +12,18 @@
 use crate::{bindings, block, time::Timespec};
 use core::mem::ManuallyDrop;
 use core::{marker::PhantomData, ptr};
+use macros::vtable;
 
 /// The number of an inode.
 pub type Ino = u64;
 
+/// Operations implemented by inodes.
+#[vtable]
+pub trait Operations {
+    /// File system that these operations are compatible with.
+    type FileSystem: FileSystem + ?Sized;
+}
+
 /// A node (inode) in the file index.
 ///
 /// Wraps the kernel's `struct inode`.
@@ -203,3 +211,43 @@ pub struct Params {
     /// Last access time.
     pub atime: Timespec,
 }
+
+/// Represents inode operations.
+pub struct Ops<T: FileSystem + ?Sized>(*const bindings::inode_operations, PhantomData<T>);
+
+impl<T: FileSystem + ?Sized> Ops<T> {
+    /// Creates the inode operations from a type that implements the [`Operations`] trait.
+    pub const fn new<U: Operations<FileSystem = T> + ?Sized>() -> Self {
+        struct Table<T: Operations + ?Sized>(PhantomData<T>);
+        impl<T: Operations + ?Sized> Table<T> {
+            const TABLE: bindings::inode_operations = bindings::inode_operations {
+                lookup: None,
+                get_link: None,
+                permission: None,
+                get_inode_acl: None,
+                readlink: None,
+                create: None,
+                link: None,
+                unlink: None,
+                symlink: None,
+                mkdir: None,
+                rmdir: None,
+                mknod: None,
+                rename: None,
+                setattr: None,
+                getattr: None,
+                listxattr: None,
+                fiemap: None,
+                update_time: None,
+                atomic_open: None,
+                tmpfile: None,
+                get_acl: None,
+                set_acl: None,
+                fileattr_set: None,
+                fileattr_get: None,
+                get_offset_ctx: None,
+            };
+        }
+        Self(&Table::<U>::TABLE, PhantomData)
+    }
+}
Signature · 1 line
2.34.1
#16 lore raw

RFC PATCH v2 15/30 rust: fs: introduce `inode::Operations::lookup`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to create inodes that are children of a directory inode when they're looked up by name.

---
 rust/kernel/error.rs      |  1 -
 rust/kernel/fs/dentry.rs  |  1 -
 rust/kernel/fs/inode.rs   | 58 ++++++++++++++++++++++++-----
 samples/rust/rust_rofs.rs | 77 +++++++++++++++++++++++++++++----------
 4 files changed, 105 insertions(+), 32 deletions(-)
rust/kernel/error.rs +0 -1
index bb13bd4a7fa6..15628d2fa3b2 100644
@@ -129,7 +129,6 @@ pub fn to_errno(self) -> core::ffi::c_int {
     }
 
     /// Returns the error encoded as a pointer.
-    #[allow(dead_code)]
     pub(crate) fn to_ptr<T>(self) -> *mut T {
         // SAFETY: `self.0` is a valid error due to its invariant.
         unsafe { bindings::ERR_PTR(self.0.into()) as *mut _ }
rust/kernel/fs/dentry.rs +0 -1
index 6a36a48cd28b..c93debb70ea3 100644
@@ -43,7 +43,6 @@ impl<T: FileSystem + ?Sized> DEntry<T> {
     ///
     /// * `ptr` must be valid for at least the lifetime of the returned reference.
     /// * `ptr` has the correct file system type, or `T` is [`super::UnspecifiedFS`].
-    #[allow(dead_code)]
     pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::dentry) -> &'a Self {
         // SAFETY: The safety requirements guarantee that the reference is and remains valid.
         unsafe { &*ptr.cast::<Self>() }
rust/kernel/fs/inode.rs +48 -10

94 lines not on this page · raw message

samples/rust/rust_rofs.rs +57 -20

102 lines not on this page · raw message

Signature · 1 line
2.34.1
#17 lore raw

RFC PATCH v2 16/30 rust: folio: introduce basic support for folios

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to handle ref-counted folios.

Provide the minimum needed to implement read_folio (part of struct address_space_operations) in read-only file systems and to read uncached blocks.

---
 rust/bindings/bindings_helper.h |   3 +
 rust/helpers.c                  |  94 ++++++++++
 rust/kernel/folio.rs            | 306 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   1 +
 4 files changed, 404 insertions(+)
 create mode 100644 rust/kernel/folio.rs
rust/bindings/bindings_helper.h +3 -0
index dabb5a787e0d..fd22b1eafb1d 100644
@@ -15,6 +15,7 @@
 #include <linux/fs_context.h>
 #include <linux/jiffies.h>
 #include <linux/mdio.h>
+#include <linux/pagemap.h>
 #include <linux/phy.h>
 #include <linux/refcount.h>
 #include <linux/sched.h>
@@ -37,3 +38,5 @@ const slab_flags_t RUST_CONST_HELPER_SLAB_ACCOUNT = SLAB_ACCOUNT;
 const unsigned long RUST_CONST_HELPER_SB_RDONLY = SB_RDONLY;
 
 const loff_t RUST_CONST_HELPER_MAX_LFS_FILESIZE = MAX_LFS_FILESIZE;
+
+const size_t RUST_CONST_HELPER_PAGE_SIZE = PAGE_SIZE;
rust/helpers.c +94 -0

110 lines not on this page · raw message

rust/kernel/folio.rs new file +306 -0

306 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index 81065d1bd679..445599d4bff6 100644
@@ -30,6 +30,7 @@
 pub mod block;
 mod build_assert;
 pub mod error;
+pub mod folio;
 pub mod fs;
 pub mod init;
 pub mod ioctl;
Signature · 1 line
2.34.1
#18 lore raw

RFC PATCH v2 17/30 rust: fs: add empty address space operations

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

This is in preparation for allowing modules to implement different address space callbacks, which will be introduced in subsequent patches.

---
 rust/kernel/fs.rs               |  1 +
 rust/kernel/fs/address_space.rs | 58 +++++++++++++++++++++++++++++++++
 2 files changed, 59 insertions(+)
 create mode 100644 rust/kernel/fs/address_space.rs
rust/kernel/fs.rs +1 -0
index 20fb6107eb4b..f1c1972fabcf 100644
@@ -13,6 +13,7 @@
 use macros::{pin_data, pinned_drop};
 use sb::SuperBlock;
 
+pub mod address_space;
 pub mod dentry;
 pub mod file;
 pub mod inode;
rust/kernel/fs/address_space.rs new file +58 -0

58 lines not on this page · raw message

Signature · 1 line
2.34.1
#19 lore raw

RFC PATCH v2 18/30 rust: fs: introduce `address_space::Operations::read_folio`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to create regular file inodes backed by the page cache. The contents of such files are read into folios via read_folio.

---
 rust/helpers.c                  |  6 +++
 rust/kernel/folio.rs            |  1 -
 rust/kernel/fs/address_space.rs | 40 ++++++++++++++++++--
 rust/kernel/fs/file.rs          |  7 ++++
 rust/kernel/fs/inode.rs         | 20 +++++++++-
 samples/rust/rust_rofs.rs       | 67 ++++++++++++++++++++++++++-------
 6 files changed, 122 insertions(+), 19 deletions(-)
rust/helpers.c +6 -0
index acff58e6caff..2db5df578df2 100644
@@ -282,6 +282,12 @@ loff_t rust_helper_i_size_read(const struct inode *inode)
 }
 EXPORT_SYMBOL_GPL(rust_helper_i_size_read);
 
+void rust_helper_mapping_set_large_folios(struct address_space *mapping)
+{
+	mapping_set_large_folios(mapping);
+}
+EXPORT_SYMBOL_GPL(rust_helper_mapping_set_large_folios);
+
 unsigned long rust_helper_copy_to_user(void __user *to, const void *from,
 				       unsigned long n)
 {
rust/kernel/folio.rs +0 -1
index 20f51db920e4..077328b733e4 100644
@@ -49,7 +49,6 @@ impl<S> Folio<S> {
     /// Callers must ensure that:
     /// * `ptr` is valid and remains so for the lifetime of the returned reference.
     /// * The folio has the right state.
-    #[allow(dead_code)]
     pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::folio) -> &'a Self {
         // SAFETY: The safety requirements guarantee that the cast below is ok.
         unsafe { &*ptr.cast::<Self>() }
rust/kernel/fs/address_space.rs +36 -4
index 5b4fcb568f46..e539d690235b 100644
@@ -6,8 +6,9 @@
 //!
 //! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
 
-use super::FileSystem;
-use crate::bindings;
+use super::{file::File, FileSystem};
+use crate::error::{from_result, Result};
+use crate::{bindings, folio::Folio, folio::PageCache, types::Locked};
 use core::marker::PhantomData;
 use macros::vtable;
 
@@ -16,10 +17,15 @@
 pub trait Operations {
     /// File system that these operations are compatible with.
     type FileSystem: FileSystem + ?Sized;
+
+    /// Reads the contents of the inode into the given folio.
+    fn read_folio(
+        file: Option<&File<Self::FileSystem>>,
+        folio: Locked<&Folio<PageCache<Self::FileSystem>>>,
+    ) -> Result;
 }
 
 /// Represents address space operations.
-#[allow(dead_code)]
 pub struct Ops<T: FileSystem + ?Sized>(
     pub(crate) *const bindings::address_space_operations,
     pub(crate) PhantomData<T>,
@@ -32,7 +38,11 @@ pub const fn new<U: Operations<FileSystem = T> + ?Sized>() -> Self {
         impl<T: Operations + ?Sized> Table<T> {
             const TABLE: bindings::address_space_operations = bindings::address_space_operations {
                 writepage: None,
-                read_folio: None,
+                read_folio: if T::HAS_READ_FOLIO {
+                    Some(Self::read_folio_callback)
+                } else {
+                    None
+                },
                 writepages: None,
                 dirty_folio: None,
                 readahead: None,
@@ -52,6 +62,28 @@ impl<T: Operations + ?Sized> Table<T> {
                 swap_deactivate: None,
                 swap_rw: None,
             };
+
+            extern "C" fn read_folio_callback(
+                file_ptr: *mut bindings::file,
+                folio_ptr: *mut bindings::folio,
+            ) -> i32 {
+                from_result(|| {
+                    let file = if file_ptr.is_null() {
+                        None
+                    } else {
+                        // SAFETY: The C API guarantees that `file_ptr` is a valid file if non-null.
+                        Some(unsafe { File::from_raw(file_ptr) })
+                    };
+
+                    // SAFETY: The C API guarantees that `folio_ptr` is a valid folio.
+                    let folio = unsafe { Folio::from_raw(folio_ptr) };
+
+                    // SAFETY: The C contract guarantees that the folio is valid and locked, with
+                    // ownership of the lock transferred to the callee (this function).
+                    T::read_folio(file, unsafe { Locked::new(folio) })?;
+                    Ok(0)
+                })
+            }
         }
         Self(&Table::<U>::TABLE, PhantomData)
     }
rust/kernel/fs/file.rs +7 -0
index 2ba456a1eee1..0828676eae1c 100644
@@ -355,6 +355,12 @@ fn read_dir(
 pub struct Ops<T: FileSystem + ?Sized>(pub(crate) *const bindings::file_operations, PhantomData<T>);
 
 impl<T: FileSystem + ?Sized> Ops<T> {
+    /// Returns file operations for page-cache-based ro files.
+    pub fn generic_ro_file() -> Self {
+        // SAFETY: This is a constant in C, it never changes.
+        Self(unsafe { &bindings::generic_ro_fops }, PhantomData)
+    }
+
     /// Creates file operations from a type that implements the [`Operations`] trait.
     pub const fn new<U: Operations<FileSystem = T> + ?Sized>() -> Self {
         struct Table<T: Operations + ?Sized>(PhantomData<T>);
@@ -516,6 +522,7 @@ impl From<inode::Type> for DirEntryType {
     fn from(value: inode::Type) -> Self {
         match value {
             inode::Type::Dir => DirEntryType::Dir,
+            inode::Type::Reg => DirEntryType::Reg,
         }
     }
 }
rust/kernel/fs/inode.rs +19 -1
index c314d036c87e..1a41c824d30d 100644
@@ -6,7 +6,9 @@
 //!
 //! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
 
-use super::{dentry, dentry::DEntry, file, sb::SuperBlock, FileSystem, Offset, UnspecifiedFS};
+use super::{
+    address_space, dentry, dentry::DEntry, file, sb::SuperBlock, FileSystem, Offset, UnspecifiedFS,
+};
 use crate::error::{code::*, Result};
 use crate::types::{ARef, AlwaysRefCounted, Lockable, Locked, Opaque};
 use crate::{bindings, block, time::Timespec};
@@ -127,6 +129,11 @@ pub fn init(mut self, params: Params) -> Result<ARef<INode<T>>> {
         let inode = unsafe { self.0.as_mut() };
         let mode = match params.typ {
             Type::Dir => bindings::S_IFDIR,
+            Type::Reg => {
+                // SAFETY: The `i_mapping` pointer doesn't change and is valid.
+                unsafe { bindings::mapping_set_large_folios(inode.i_mapping) };
+                bindings::S_IFREG
+            }
         };
 
         inode.i_mode = (params.mode & 0o777) | u16::try_from(mode)?;
@@ -166,6 +173,14 @@ pub fn set_fops(&mut self, fops: file::Ops<T>) -> &mut Self {
         inode.__bindgen_anon_3.i_fop = fops.0;
         self
     }
+
+    /// Sets the address space operations on this new inode.
+    pub fn set_aops(&mut self, aops: address_space::Ops<T>) -> &mut Self {
+        // SAFETY: By the type invariants, it's ok to modify the inode.
+        let inode = unsafe { self.0.as_mut() };
+        inode.i_data.a_ops = aops.0;
+        self
+    }
 }
 
 impl<T: FileSystem + ?Sized> Drop for New<T> {
@@ -181,6 +196,9 @@ fn drop(&mut self) {
 pub enum Type {
     /// Directory type.
     Dir,
+
+    /// Regular file type.
+    Reg,
 }
 
 /// Required inode parameters.
samples/rust/rust_rofs.rs +54 -13

129 lines not on this page · raw message

Signature · 1 line
2.34.1
#20 lore raw

RFC PATCH v2 19/30 rust: fs: introduce `FileSystem::read_xattr`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to expose xattrs associated with inodes. overlayfs uses an xattr to indicate that a directory is opaque (i.e., that lower layers should not be looked up). The planned file systems need to support opaque directories, so they must be able to implement this.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/error.rs            |  2 ++
 rust/kernel/fs.rs               | 59 +++++++++++++++++++++++++++++++++
 3 files changed, 62 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index fd22b1eafb1d..2133f95e8be5 100644
@@ -22,6 +22,7 @@
 #include <linux/slab.h>
 #include <linux/wait.h>
 #include <linux/workqueue.h>
+#include <linux/xattr.h>
 
 /* `bindgen` gets confused at certain things. */
 const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN = ARCH_SLAB_MINALIGN;
rust/kernel/error.rs +2 -0
index 15628d2fa3b2..f40a2bdf28d4 100644
@@ -77,6 +77,8 @@ macro_rules! declare_err {
     declare_err!(EIOCBQUEUED, "iocb queued, will get completion event.");
     declare_err!(ERECALLCONFLICT, "Conflict with recalled state.");
     declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
+    declare_err!(ENODATA, "No data available.");
+    declare_err!(EOPNOTSUPP, "Operation not supported on transport endpoint.");
     declare_err!(ESTALE, "Stale file handle.");
     declare_err!(EUCLEAN, "Structure needs cleaning.");
 }
rust/kernel/fs.rs +59 -0

83 lines not on this page · raw message

Signature · 1 line
2.34.1
#21 lore raw

RFC PATCH v2 20/30 rust: fs: introduce `FileSystem::statfs`

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to expose their stats. overlayfs requires that this be implemented by all file systems that are part of an overlay. The planned file systems need to be overlayed with overlayfs, so they must be able to implement this.

---
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/error.rs            |  1 +
 rust/kernel/fs.rs               | 47 ++++++++++++++++++++++++++++++++-
 3 files changed, 48 insertions(+), 1 deletion(-)
rust/bindings/bindings_helper.h +1 -0
index 2133f95e8be5..f4c7c3951dbe 100644
@@ -20,6 +20,7 @@
 #include <linux/refcount.h>
 #include <linux/sched.h>
 #include <linux/slab.h>
+#include <linux/statfs.h>
 #include <linux/wait.h>
 #include <linux/workqueue.h>
 #include <linux/xattr.h>
rust/kernel/error.rs +1 -0
index f40a2bdf28d4..edada157879a 100644
@@ -79,6 +79,7 @@ macro_rules! declare_err {
     declare_err!(ENOGRACE, "NFS file lock reclaim refused.");
     declare_err!(ENODATA, "No data available.");
     declare_err!(EOPNOTSUPP, "Operation not supported on transport endpoint.");
+    declare_err!(ENOSYS, "Invalid system call number.");
     declare_err!(ESTALE, "Stale file handle.");
     declare_err!(EUCLEAN, "Structure needs cleaning.");
 }
rust/kernel/fs.rs +46 -1

65 lines not on this page · raw message

Signature · 1 line
2.34.1
#22 lore raw

RFC PATCH v2 21/30 rust: fs: introduce more inode types

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file system modules to create inodes that are symlinks, pipes, sockets, char devices and block devices (in addition to the already-supported directories and regular files).

---
 rust/helpers.c            |  13 ++++
 rust/kernel/fs/file.rs    |   5 ++
 rust/kernel/fs/inode.rs   | 131 +++++++++++++++++++++++++++++++++++++-
 samples/rust/rust_rofs.rs |  43 ++++++++++++-
 4 files changed, 187 insertions(+), 5 deletions(-)
rust/helpers.c +13 -0
index 2db5df578df2..360a1d38ac19 100644
@@ -288,6 +288,12 @@ void rust_helper_mapping_set_large_folios(struct address_space *mapping)
 }
 EXPORT_SYMBOL_GPL(rust_helper_mapping_set_large_folios);
 
+unsigned int rust_helper_MKDEV(unsigned int major, unsigned int minor)
+{
+	return MKDEV(major, minor);
+}
+EXPORT_SYMBOL_GPL(rust_helper_MKDEV);
+
 unsigned long rust_helper_copy_to_user(void __user *to, const void *from,
 				       unsigned long n)
 {
@@ -307,6 +313,13 @@ void rust_helper_inode_unlock_shared(struct inode *inode)
 }
 EXPORT_SYMBOL_GPL(rust_helper_inode_unlock_shared);
 
+void rust_helper_set_delayed_call(struct delayed_call *call,
+				  void (*fn)(void *), void *arg)
+{
+	set_delayed_call(call, fn, arg);
+}
+EXPORT_SYMBOL_GPL(rust_helper_set_delayed_call);
+
 /*
  * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can
  * use it in contexts where Rust expects a `usize` like slice (array) indices.
rust/kernel/fs/file.rs +5 -0
index 0828676eae1c..a819724b75f8 100644
@@ -521,8 +521,13 @@ pub enum DirEntryType {
 impl From<inode::Type> for DirEntryType {
     fn from(value: inode::Type) -> Self {
         match value {
+            inode::Type::Fifo => DirEntryType::Fifo,
+            inode::Type::Chr(_, _) => DirEntryType::Chr,
             inode::Type::Dir => DirEntryType::Dir,
+            inode::Type::Blk(_, _) => DirEntryType::Blk,
             inode::Type::Reg => DirEntryType::Reg,
+            inode::Type::Lnk => DirEntryType::Lnk,
+            inode::Type::Sock => DirEntryType::Sock,
         }
     }
 }
rust/kernel/fs/inode.rs +128 -3

178 lines not on this page · raw message

samples/rust/rust_rofs.rs +41 -2

78 lines not on this page · raw message

Signature · 1 line
2.34.1
#23 lore raw

RFC PATCH v2 22/30 rust: fs: add per-superblock data

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to associate [typed] data to super blocks when they're created. Since we only have a pointer-sized field in which to store the state, it must implement the ForeignOwnable trait.

---
 rust/kernel/fs.rs         | 46 ++++++++++++++++++++++++++++---------
 rust/kernel/fs/sb.rs      | 48 +++++++++++++++++++++++++++++++++++----
 samples/rust/rust_rofs.rs |  3 ++-
 3 files changed, 81 insertions(+), 16 deletions(-)
rust/kernel/fs.rs +35 -11
index 51de73008857..387e87e3edaf 100644
@@ -7,7 +7,7 @@
 //! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
 
 use crate::error::{code::*, from_result, to_result, Error, Result};
-use crate::types::Opaque;
+use crate::types::{ForeignOwnable, Opaque};
 use crate::{bindings, init::PinInit, str::CStr, try_pin_init, ThisModule};
 use core::{ffi, marker::PhantomData, mem::ManuallyDrop, pin::Pin, ptr};
 use dentry::DEntry;
@@ -31,6 +31,9 @@
 
 /// A file system type.
 pub trait FileSystem {
+    /// Data associated with each file system instance (super-block).
+    type Data: ForeignOwnable + Send + Sync;
+
     /// The name of the file system type.
     const NAME: &'static CStr;
 
@@ -40,8 +43,8 @@ pub trait FileSystem {
     #[doc(hidden)]
     const IS_UNSPECIFIED: bool = false;
 
-    /// Initialises the new superblock.
-    fn fill_super(sb: &mut SuperBlock<Self>) -> Result;
+    /// Initialises the new superblock and returns the data to attach to it.
+    fn fill_super(sb: &mut SuperBlock<Self, sb::New>) -> Result<Self::Data>;
 
     /// Initialises and returns the root inode of the given superblock.
     ///
@@ -94,9 +97,10 @@ pub struct Stat {
 pub struct UnspecifiedFS;
 
 impl FileSystem for UnspecifiedFS {
+    type Data = ();
     const NAME: &'static CStr = crate::c_str!("unspecified");
     const IS_UNSPECIFIED: bool = true;
-    fn fill_super(_: &mut SuperBlock<Self>) -> Result {
+    fn fill_super(_: &mut SuperBlock<Self, sb::New>) -> Result {
         Err(ENOTSUPP)
     }
 
@@ -134,7 +138,7 @@ pub fn new<T: FileSystem + ?Sized>(module: &'static ThisModule) -> impl PinInit<
                 fs.owner = module.0;
                 fs.name = T::NAME.as_char_ptr();
                 fs.init_fs_context = Some(Self::init_fs_context_callback::<T>);
-                fs.kill_sb = Some(Self::kill_sb_callback);
+                fs.kill_sb = Some(Self::kill_sb_callback::<T>);
                 fs.fs_flags = 0;
 
                 // SAFETY: Pointers stored in `fs` are static so will live for as long as the
@@ -155,10 +159,22 @@ pub fn new<T: FileSystem + ?Sized>(module: &'static ThisModule) -> impl PinInit<
         })
     }
 
-    unsafe extern "C" fn kill_sb_callback(sb_ptr: *mut bindings::super_block) {
+    unsafe extern "C" fn kill_sb_callback<T: FileSystem + ?Sized>(
+        sb_ptr: *mut bindings::super_block,
+    ) {
         // SAFETY: In `get_tree_callback` we always call `get_tree_nodev`, so `kill_anon_super` is
         // the appropriate function to call for cleanup.
         unsafe { bindings::kill_anon_super(sb_ptr) };
+
+        // SAFETY: The C API contract guarantees that `sb_ptr` is valid for read.
+        let ptr = unsafe { (*sb_ptr).s_fs_info };
+        if !ptr.is_null() {
+            // SAFETY: The only place where `s_fs_info` is assigned is `NewSuperBlock::init`, where
+            // it's initialised with the result of an `into_foreign` call. We checked above that
+            // `ptr` is non-null because it would be null if we never reached the point where we
+            // init the field.
+            unsafe { T::Data::from_foreign(ptr) };
+        }
     }
 }
 
@@ -205,12 +221,19 @@ impl<T: FileSystem + ?Sized> Tables<T> {
             sb.s_xattr = &Tables::<T>::XATTR_HANDLERS[0];
             sb.s_flags |= bindings::SB_RDONLY;
 
-            T::fill_super(new_sb)?;
+            let data = T::fill_super(new_sb)?;
+
+            // N.B.: Even on failure, `kill_sb` is called and frees the data.
+            sb.s_fs_info = data.into_foreign().cast_mut();
 
-            let root = T::init_root(new_sb)?;
+            // SAFETY: The callback contract guarantees that `sb_ptr` is a unique pointer to a
+            // newly-created (and initialised above) superblock. And we have just initialised
+            // `s_fs_info`.
+            let sb = unsafe { SuperBlock::from_raw(sb_ptr) };
+            let root = T::init_root(sb)?;
 
             // Reject root inode if it belongs to a different superblock.
-            if !ptr::eq(root.super_block(), new_sb) {
+            if !ptr::eq(root.super_block(), sb) {
                 return Err(EINVAL);
             }
 
@@ -346,7 +369,7 @@ fn init(module: &'static ThisModule) -> impl PinInit<Self, Error> {
 ///
 /// ```
 /// # mod module_fs_sample {
-/// use kernel::fs::{dentry, inode::INode, sb::SuperBlock, self};
+/// use kernel::fs::{dentry, inode::INode, sb, sb::SuperBlock, self};
 /// use kernel::prelude::*;
 ///
 /// kernel::module_fs! {
@@ -359,8 +382,9 @@ fn init(module: &'static ThisModule) -> impl PinInit<Self, Error> {
 ///
 /// struct MyFs;
 /// impl fs::FileSystem for MyFs {
+///     type Data = ();
 ///     const NAME: &'static CStr = kernel::c_str!("myfs");
-///     fn fill_super(_: &mut SuperBlock<Self>) -> Result {
+///     fn fill_super(_: &mut SuperBlock<Self, sb::New>) -> Result {
 ///         todo!()
 ///     }
 ///     fn init_root(_sb: &SuperBlock<Self>) -> Result<dentry::Root<Self>> {
rust/kernel/fs/sb.rs +44 -4

90 lines not on this page · raw message

samples/rust/rust_rofs.rs +2 -1
index 7a09e2db878d..7027ca067f8f 100644
@@ -98,9 +98,10 @@ fn iget(sb: &sb::SuperBlock<Self>, e: &'static Entry) -> Result<ARef<INode<Self>
 }
 
 impl fs::FileSystem for RoFs {
+    type Data = ();
     const NAME: &'static CStr = c_str!("rust_rofs");
 
-    fn fill_super(sb: &mut sb::SuperBlock<Self>) -> Result {
+    fn fill_super(sb: &mut sb::SuperBlock<Self, sb::New>) -> Result {
         sb.set_magic(0x52555354);
         Ok(())
     }
Signature · 1 line
2.34.1
#24 lore raw

RFC PATCH v2 23/30 rust: fs: allow file systems backed by a block device

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems that are backed by block devices (in addition to in-memory ones).

---
 rust/helpers.c            |  14 +++
 rust/kernel/block.rs      |   1 -
 rust/kernel/fs.rs         |  60 ++++++++---
 rust/kernel/fs/inode.rs   | 221 +++++++++++++++++++++++++++++++++++++-
 rust/kernel/fs/sb.rs      |  49 ++++++++-
 samples/rust/rust_rofs.rs |   2 +-
 6 files changed, 328 insertions(+), 19 deletions(-)
rust/helpers.c +14 -0
index 360a1d38ac19..6c6d18df055f 100644
@@ -21,6 +21,7 @@
  */
 
 #include <kunit/test-bug.h>
+#include <linux/blkdev.h>
 #include <linux/bug.h>
 #include <linux/build_bug.h>
 #include <linux/cacheflush.h>
@@ -258,6 +259,13 @@ void rust_helper_kunmap_local(const void *vaddr)
 }
 EXPORT_SYMBOL_GPL(rust_helper_kunmap_local);
 
+struct folio *rust_helper_read_mapping_folio(struct address_space *mapping,
+					     pgoff_t index, struct file *file)
+{
+	return read_mapping_folio(mapping, index, file);
+}
+EXPORT_SYMBOL_GPL(rust_helper_read_mapping_folio);
+
 void rust_helper_i_uid_write(struct inode *inode, uid_t uid)
 {
 	i_uid_write(inode, uid);
@@ -294,6 +302,12 @@ unsigned int rust_helper_MKDEV(unsigned int major, unsigned int minor)
 }
 EXPORT_SYMBOL_GPL(rust_helper_MKDEV);
 
+sector_t rust_helper_bdev_nr_sectors(struct block_device *bdev)
+{
+	return bdev_nr_sectors(bdev);
+}
+EXPORT_SYMBOL_GPL(rust_helper_bdev_nr_sectors);
+
 unsigned long rust_helper_copy_to_user(void __user *to, const void *from,
 				       unsigned long n)
 {
rust/kernel/block.rs +0 -1
index 868623d7c873..4d669bd5dce9 100644
@@ -31,7 +31,6 @@ impl Device {
     ///
     /// Callers must ensure that `ptr` is valid and remains so for the lifetime of the returned
     /// object.
-    #[allow(dead_code)]
     pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::block_device) -> &'a Self {
         // SAFETY: The safety requirements guarantee that the cast below is ok.
         unsafe { &*ptr.cast::<Self>() }
rust/kernel/fs.rs +48 -12

120 lines not on this page · raw message

rust/kernel/fs/inode.rs +217 -4

245 lines not on this page · raw message

rust/kernel/fs/sb.rs +48 -1

71 lines not on this page · raw message

samples/rust/rust_rofs.rs +1 -1
index 7027ca067f8f..fea3360b6e7a 100644
@@ -101,7 +101,7 @@ impl fs::FileSystem for RoFs {
     type Data = ();
     const NAME: &'static CStr = c_str!("rust_rofs");
 
-    fn fill_super(sb: &mut sb::SuperBlock<Self, sb::New>) -> Result {
+    fn fill_super(sb: &mut sb::SuperBlock<Self, sb::New>, _: Option<inode::Mapper>) -> Result {
         sb.set_magic(0x52555354);
         Ok(())
     }
Signature · 1 line
2.34.1
#25 lore raw

RFC PATCH v2 24/30 rust: fs: allow per-inode data

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to attach extra [typed] data to each inode. If no data is needed, use the regular inode kmem_cache, otherwise we create a new one.

---
 rust/helpers.c            |   7 +++
 rust/kernel/fs.rs         |  19 ++++--
 rust/kernel/fs/inode.rs   | 123 ++++++++++++++++++++++++++++++++++++--
 rust/kernel/mem_cache.rs  |   2 -
 samples/rust/rust_rofs.rs |  13 ++--
 5 files changed, 143 insertions(+), 21 deletions(-)
rust/helpers.c +7 -0
index 6c6d18df055f..edf12868962c 100644
@@ -266,6 +266,13 @@ struct folio *rust_helper_read_mapping_folio(struct address_space *mapping,
 }
 EXPORT_SYMBOL_GPL(rust_helper_read_mapping_folio);
 
+void *rust_helper_alloc_inode_sb(struct super_block *sb,
+				 struct kmem_cache *cache, gfp_t gfp)
+{
+	return alloc_inode_sb(sb, cache, gfp);
+}
+EXPORT_SYMBOL_GPL(rust_helper_alloc_inode_sb);
+
 void rust_helper_i_uid_write(struct inode *inode, uid_t uid)
 {
 	i_uid_write(inode, uid);
rust/kernel/fs.rs +15 -4
index 864aca24d12c..d64fe1a5812f 100644
@@ -8,8 +8,8 @@
 
 use crate::error::{code::*, from_result, to_result, Error, Result};
 use crate::types::{ForeignOwnable, Opaque};
-use crate::{bindings, init::PinInit, str::CStr, try_pin_init, ThisModule};
-use core::{ffi, marker::PhantomData, mem::ManuallyDrop, pin::Pin, ptr};
+use crate::{bindings, init::PinInit, mem_cache::MemCache, str::CStr, try_pin_init, ThisModule};
+use core::{ffi, marker::PhantomData, mem::size_of, mem::ManuallyDrop, pin::Pin, ptr};
 use dentry::DEntry;
 use inode::INode;
 use macros::{pin_data, pinned_drop};
@@ -39,6 +39,9 @@ pub trait FileSystem {
     /// Data associated with each file system instance (super-block).
     type Data: ForeignOwnable + Send + Sync;
 
+    /// Type of data associated with each inode.
+    type INodeData: Send + Sync;
+
     /// The name of the file system type.
     const NAME: &'static CStr;
 
@@ -109,6 +112,7 @@ pub struct Stat {
 
 impl FileSystem for UnspecifiedFS {
     type Data = ();
+    type INodeData = ();
     const NAME: &'static CStr = crate::c_str!("unspecified");
     const IS_UNSPECIFIED: bool = true;
     fn fill_super(_: &mut SuperBlock<Self, sb::New>, _: Option<inode::Mapper>) -> Result {
@@ -125,6 +129,7 @@ fn init_root(_: &SuperBlock<Self>) -> Result<dentry::Root<Self>> {
 pub struct Registration {
     #[pin]
     fs: Opaque<bindings::file_system_type>,
+    inode_cache: Option<MemCache>,
 }
 
 // SAFETY: `Registration` doesn't provide any `&self` methods, so it is safe to pass references
@@ -139,6 +144,7 @@ impl Registration {
     /// Creates the initialiser of a new file system registration.
     pub fn new<T: FileSystem + ?Sized>(module: &'static ThisModule) -> impl PinInit<Self, Error> {
         try_pin_init!(Self {
+            inode_cache: INode::<T>::new_cache()?,
             fs <- Opaque::try_ffi_init(|fs_ptr: *mut bindings::file_system_type| {
                 // SAFETY: `try_ffi_init` guarantees that `fs_ptr` is valid for write.
                 unsafe { fs_ptr.write(bindings::file_system_type::default()) };
@@ -284,8 +290,12 @@ impl<T: FileSystem + ?Sized> Tables<T> {
     }
 
     const SUPER_BLOCK: bindings::super_operations = bindings::super_operations {
-        alloc_inode: None,
-        destroy_inode: None,
+        alloc_inode: if size_of::<T::INodeData>() != 0 {
+            Some(INode::<T>::alloc_inode_callback)
+        } else {
+            None
+        },
+        destroy_inode: Some(INode::<T>::destroy_inode_callback),
         free_inode: None,
         dirty_inode: None,
         write_inode: None,
@@ -419,6 +429,7 @@ fn init(module: &'static ThisModule) -> impl PinInit<Self, Error> {
 /// struct MyFs;
 /// impl fs::FileSystem for MyFs {
 ///     type Data = ();
+///     type INodeData = ();
 ///     const NAME: &'static CStr = kernel::c_str!("myfs");
 ///     fn fill_super(_: &mut SuperBlock<Self, sb::New>, _: Option<Mapper>) -> Result {
 ///         todo!()
rust/kernel/fs/inode.rs +117 -6

166 lines not on this page · raw message

rust/kernel/mem_cache.rs +0 -2
index e7e2720ff6cd..cbf1b7e75334 100644
@@ -20,7 +20,6 @@ impl MemCache {
     /// Allocates a new `kmem_cache` for type `T`.
     ///
     /// `init` is called by the C code when entries are allocated.
-    #[allow(dead_code)]
     pub(crate) fn try_new<T>(
         name: &'static CStr,
         init: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
@@ -43,7 +42,6 @@ pub(crate) fn try_new<T>(
     /// Returns the pointer to the `kmem_cache` instance, or null if it's `None`.
     ///
     /// This is a helper for functions like `alloc_inode_sb` where the cache is optional.
-    #[allow(dead_code)]
     pub(crate) fn ptr(c: &Option<Self>) -> *mut bindings::kmem_cache {
         match c {
             Some(m) => m.ptr.as_ptr(),
samples/rust/rust_rofs.rs +4 -9
index fea3360b6e7a..5b6c3f50adf4 100644
@@ -93,12 +93,14 @@ fn iget(sb: &sb::SuperBlock<Self>, e: &'static Entry) -> Result<ARef<INode<Self>
             atime: UNIX_EPOCH,
             ctime: UNIX_EPOCH,
             mtime: UNIX_EPOCH,
+            value: e,
         })
     }
 }
 
 impl fs::FileSystem for RoFs {
     type Data = ();
+    type INodeData = &'static Entry;
     const NAME: &'static CStr = c_str!("rust_rofs");
 
     fn fill_super(sb: &mut sb::SuperBlock<Self, sb::New>, _: Option<inode::Mapper>) -> Result {
@@ -149,10 +151,7 @@ fn get_link<'a>(
             return Err(ECHILD);
         }
 
-        let name_buf = match inode.ino() {
-            3 => ENTRIES[3].contents,
-            _ => return Err(EINVAL),
-        };
+        let name_buf = inode.data().contents;
         let mut name = Box::new_slice(
             name_buf.len().checked_add(1).ok_or(ENOMEM)?,
             b'\0',
@@ -168,11 +167,7 @@ impl address_space::Operations for RoFs {
     type FileSystem = Self;
 
     fn read_folio(_: Option<&File<Self>>, mut folio: Locked<&Folio<PageCache<Self>>>) -> Result {
-        let data = match folio.inode().ino() {
-            2 => ENTRIES[2].contents,
-            _ => return Err(EINVAL),
-        };
-
+        let data = folio.inode().data().contents;
         let pos = usize::try_from(folio.pos()).unwrap_or(usize::MAX);
         let copied = if pos >= data.len() {
             0
Signature · 1 line
2.34.1
#26 lore raw

RFC PATCH v2 25/30 rust: fs: export file type from mode constants

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file system modules to use these constants if needed.

---
 rust/kernel/fs.rs | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
rust/kernel/fs.rs +27 -0
index d64fe1a5812f..4d90b23735bc 100644
@@ -31,6 +31,33 @@
 /// This is C's `pgoff_t`.
 pub type PageOffset = usize;
 
+/// Contains constants related to Linux file modes.
+pub mod mode {
+    /// A bitmask used to the file type from a mode value.
+    pub const S_IFMT: u16 = bindings::S_IFMT as u16;
+
+    /// File type constant for block devices.
+    pub const S_IFBLK: u16 = bindings::S_IFBLK as u16;
+
+    /// File type constant for char devices.
+    pub const S_IFCHR: u16 = bindings::S_IFCHR as u16;
+
+    /// File type constant for directories.
+    pub const S_IFDIR: u16 = bindings::S_IFDIR as u16;
+
+    /// File type constant for pipes.
+    pub const S_IFIFO: u16 = bindings::S_IFIFO as u16;
+
+    /// File type constant for symbolic links.
+    pub const S_IFLNK: u16 = bindings::S_IFLNK as u16;
+
+    /// File type constant for regular files.
+    pub const S_IFREG: u16 = bindings::S_IFREG as u16;
+
+    /// File type constant for sockets.
+    pub const S_IFSOCK: u16 = bindings::S_IFSOCK as u16;
+}
+
 /// Maximum size of an inode.
 pub const MAX_LFS_FILESIZE: Offset = bindings::MAX_LFS_FILESIZE;
 
Signature · 1 line
2.34.1
#27 lore raw

RFC PATCH v2 26/30 rust: fs: allow populating i_lnk

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow Rust file systems to store a string that represents the destination of a symbolic link inode in the inode itself.

---
 rust/kernel/fs/file.rs    |  6 ++---
 rust/kernel/fs/inode.rs   | 32 +++++++++++++++++++++----
 samples/rust/rust_rofs.rs | 50 ++++++++++++---------------------------
 3 files changed, 45 insertions(+), 43 deletions(-)
rust/kernel/fs/file.rs +3 -3
index a819724b75f8..9db70eff1169 100644
@@ -518,15 +518,15 @@ pub enum DirEntryType {
     Wht = bindings::DT_WHT,
 }
 
-impl From<inode::Type> for DirEntryType {
-    fn from(value: inode::Type) -> Self {
+impl From<&inode::Type> for DirEntryType {
+    fn from(value: &inode::Type) -> Self {
         match value {
             inode::Type::Fifo => DirEntryType::Fifo,
             inode::Type::Chr(_, _) => DirEntryType::Chr,
             inode::Type::Dir => DirEntryType::Dir,
             inode::Type::Blk(_, _) => DirEntryType::Blk,
             inode::Type::Reg => DirEntryType::Reg,
-            inode::Type::Lnk => DirEntryType::Lnk,
+            inode::Type::Lnk(_) => DirEntryType::Lnk,
             inode::Type::Sock => DirEntryType::Sock,
         }
     }
rust/kernel/fs/inode.rs +27 -5
index 5230ff2fe0dd..b2b7d000080e 100644
@@ -7,8 +7,8 @@
 //! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
 
 use super::{
-    address_space, dentry, dentry::DEntry, file, sb::SuperBlock, FileSystem, Offset, PageOffset,
-    UnspecifiedFS,
+    address_space, dentry, dentry::DEntry, file, mode, sb::SuperBlock, FileSystem, Offset,
+    PageOffset, UnspecifiedFS,
 };
 use crate::error::{code::*, from_err_ptr, Result};
 use crate::types::{ARef, AlwaysRefCounted, Either, ForeignOwnable, Lockable, Locked, Opaque};
@@ -255,6 +255,17 @@ pub(crate) fn new_cache() -> Result<Option<MemCache>> {
         let ptr = container_of!(inode, WithData<T::INodeData>, inode).cast_mut();
 
         if !is_bad {
+            // SAFETY: The API contract guarantees that `inode` is valid.
+            if unsafe { (*inode).i_mode & mode::S_IFMT == mode::S_IFLNK } {
+                // SAFETY: We just checked that the inode is a link.
+                let lnk = unsafe { (*inode).__bindgen_anon_4.i_link };
+                if !lnk.is_null() {
+                    // SAFETY: This value is on link inode are only populated from with the result
+                    // of `CString::into_foreign`.
+                    unsafe { CString::from_foreign(lnk.cast::<core::ffi::c_void>()) };
+                }
+            }
+
             // SAFETY: The code either initialises the data or marks the inode as bad. Since the
             // inode is not bad, the data is initialised, and thus safe to drop.
             unsafe { ptr::drop_in_place((*ptr).data.as_mut_ptr()) };
@@ -381,7 +392,7 @@ pub fn init(self, params: Params<T::INodeData>) -> Result<ARef<INode<T>>> {
                 unsafe { bindings::mapping_set_large_folios(inode.i_mapping) };
                 bindings::S_IFREG
             }
-            Type::Lnk => {
+            Type::Lnk(str) => {
                 // If we are using `page_get_link`, we need to prevent the use of high mem.
                 if !inode.i_op.is_null() {
                     // SAFETY: We just checked that `i_op` is non-null, and we always just set it
@@ -393,6 +404,9 @@ pub fn init(self, params: Params<T::INodeData>) -> Result<ARef<INode<T>>> {
                         unsafe { bindings::inode_nohighmem(inode) };
                     }
                 }
+                if let Some(s) = str {
+                    inode.__bindgen_anon_4.i_link = s.into_foreign().cast::<i8>().cast_mut();
+                }
                 bindings::S_IFLNK
             }
             Type::Fifo => {
@@ -485,7 +499,6 @@ fn drop(&mut self) {
 }
 
 /// The type of an inode.
-#[derive(Copy, Clone)]
 pub enum Type {
     /// Named pipe (first-in, first-out) type.
     Fifo,
@@ -503,7 +516,7 @@ pub enum Type {
     Reg,
 
     /// Symbolic link type.
-    Lnk,
+    Lnk(Option<CString>),
 
     /// Named unix-domain socket type.
     Sock,
@@ -565,6 +578,15 @@ pub fn page_symlink_inode() -> Self {
         )
     }
 
+    /// Returns inode operations for symbolic links that are stored in the `i_lnk` field.
+    pub fn simple_symlink_inode() -> Self {
+        // SAFETY: This is a constant in C, it never changes.
+        Self(
+            unsafe { &bindings::simple_symlink_inode_operations },
+            PhantomData,
+        )
+    }
+
     /// Creates the inode operations from a type that implements the [`Operations`] trait.
     pub const fn new<U: Operations<FileSystem = T> + ?Sized>() -> Self {
         struct Table<T: Operations + ?Sized>(PhantomData<T>);
samples/rust/rust_rofs.rs +15 -35

98 lines not on this page · raw message

Signature · 1 line
2.34.1
#28 lore raw

RFC PATCH v2 27/30 rust: fs: add `iomap` module

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow file systems to implement their address space operations via iomap, which delegates a lot of the complexity to common code.

---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/fs.rs               |   1 +
 rust/kernel/fs/iomap.rs         | 281 ++++++++++++++++++++++++++++++++
 3 files changed, 283 insertions(+)
 create mode 100644 rust/kernel/fs/iomap.rs
rust/bindings/bindings_helper.h +1 -0
index f4c7c3951dbe..629fce394dbe 100644
@@ -13,6 +13,7 @@
 #include <linux/file.h>
 #include <linux/fs.h>
 #include <linux/fs_context.h>
+#include <linux/iomap.h>
 #include <linux/jiffies.h>
 #include <linux/mdio.h>
 #include <linux/pagemap.h>
rust/kernel/fs.rs +1 -0
index 4d90b23735bc..7a1c4884c370 100644
@@ -19,6 +19,7 @@
 pub mod dentry;
 pub mod file;
 pub mod inode;
+pub mod iomap;
 pub mod sb;
 
 /// The offset of a file in a file system.
rust/kernel/fs/iomap.rs new file +281 -0

281 lines not on this page · raw message

Signature · 1 line
2.34.1
#29 lore raw

Re: [RFC PATCH v2 27/30] rust: fs: add `iomap` module

Quoted 43 lines · Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

Allow file systems to implement their address space operations via iomap, which delegates a lot of the complexity to common code.

---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/fs.rs               |   1 +
 rust/kernel/fs/iomap.rs         | 281 ++++++++++++++++++++++++++++++++
 3 files changed, 283 insertions(+)
 create mode 100644 rust/kernel/fs/iomap.rs
rust/bindings/bindings_helper.h +1 -0
index f4c7c3951dbe..629fce394dbe 100644
@@ -13,6 +13,7 @@
 #include <linux/file.h>
 #include <linux/fs.h>
 #include <linux/fs_context.h>
+#include <linux/iomap.h>
 #include <linux/jiffies.h>
 #include <linux/mdio.h>
 #include <linux/pagemap.h>
rust/kernel/fs.rs +1 -0
index 4d90b23735bc..7a1c4884c370 100644
@@ -19,6 +19,7 @@
 pub mod dentry;
 pub mod file;
 pub mod inode;
+pub mod iomap;
 pub mod sb;
 
 /// The offset of a file in a file system.
rust/kernel/fs/iomap.rs new file +0 -0
new file mode 100644
index 000000000000..e48e200e555e

rust/kernel/fs/iomap.rs line 3

Quoted 3 lines
rust/kernel/fs/iomap.rs new file +3 -0
@@ -0,0 +1,281 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! File system io maps.

iomap is really more of a space mapping library for filesystems at this point. Most of the code supports IO to pmem or block devices, but some of the pieces (e.g. swapfile, FIEMAP, llseek) aren't the IO path.

Quoted 41 lines
rust/kernel/fs/iomap.rs new file +41 -0
+//!
+//! This module allows Rust code to use iomaps to implement filesystems.
+//!
+//! C headers: [`include/linux/iomap.h`](srctree/include/linux/iomap.h)
+
+use super::{address_space, FileSystem, INode, Offset};
+use crate::error::{from_result, Result};
+use crate::{bindings, block};
+use core::marker::PhantomData;
+
+/// The type of mapping.
+///
+/// This is used in [`Map`].
+#[repr(u16)]
+pub enum Type {
+    /// No blocks allocated, need allocation.
+    Hole = bindings::IOMAP_HOLE as u16,
+
+    /// Delayed allocation blocks.
+    DelAlloc = bindings::IOMAP_DELALLOC as u16,
+
+    /// Blocks allocated at the given address.
+    Mapped = bindings::IOMAP_MAPPED as u16,
+
+    /// Blocks allocated at the given address in unwritten state.
+    Unwritten = bindings::IOMAP_UNWRITTEN as u16,
+
+    /// Data inline in the inode.
+    Inline = bindings::IOMAP_INLINE as u16,
+}
+
+/// Flags usable in [`Map`], in [`Map::set_flags`] in particular.
+pub mod map_flags {
+    /// Indicates that the blocks have been newly allocated and need zeroing for areas that no data
+    /// is copied to.
+    pub const NEW: u16 = bindings::IOMAP_F_NEW as u16;
+
+    /// Indicates that the inode has uncommitted metadata needed to access written data and
+    /// requires fdatasync to commit them to persistent storage. This needs to take into account
+    /// metadata changes that *may* be made at IO completion, such as file size updates from direct
+    /// IO.

rust/kernel/fs/iomap.rs line 54

Quoted 10 lines
rust/kernel/fs/iomap.rs new file +10 -0
+    pub const DIRTY: u16 = bindings::IOMAP_F_DIRTY as u16;
+
+    /// Indicates that the blocks are shared, and will need to be unshared as part a write.
+    pub const SHARED: u16 = bindings::IOMAP_F_SHARED as u16;
+
+    /// Indicates that the iomap contains the merge of multiple block mappings.
+    pub const MERGED: u16 = bindings::IOMAP_F_MERGED as u16;
+
+    /// Indicates that the file system requires the use of buffer heads for this mapping.
+    pub const BUFFER_HEAD: u16 = bindings::IOMAP_F_BUFFER_HEAD as u16;

Maybe leave this one commented out; we don't really want new filesystems to use bufferhead support in iomap.

Quoted 8 lines
rust/kernel/fs/iomap.rs new file +8 -0
+
+    /// Indicates that the iomap is for an extended attribute extent rather than a file data
+    /// extent.
+    pub const XATTR: u16 = bindings::IOMAP_F_XATTR as u16;
+
+    /// Indicates to the iomap_end method that the file size has changed as the result of this
+    /// write operation.
+    pub const SIZE_CHANGED: u16 = bindings::IOMAP_F_SIZE_CHANGED as u16;

rust/kernel/fs/iomap.rs line 72

Quoted 10 lines
rust/kernel/fs/iomap.rs new file +10 -0
+
+    /// Indicates that the iomap is not valid any longer and the file range it covers needs to be
+    /// remapped by the high level before the operation can proceed.
+    pub const STALE: u16 = bindings::IOMAP_F_STALE as u16;
+
+    /// Flags from 0x1000 up are for file system specific usage.
+    pub const PRIVATE: u16 = bindings::IOMAP_F_PRIVATE as u16;
+}
+
+/// A map from address space to block device.

It's a mapping from a range of a file to space on a storage device. Storage devices can include pmem and whatever inlinedata does. Though I guess you don't support fsdax.

Quoted 66 lines
rust/kernel/fs/iomap.rs new file +66 -0
+#[repr(transparent)]
+pub struct Map<'a>(pub bindings::iomap, PhantomData<&'a ()>);
+
+impl<'a> Map<'a> {
+    /// Sets the map type.
+    pub fn set_type(&mut self, t: Type) -> &mut Self {
+        self.0.type_ = t as u16;
+        self
+    }
+
+    /// Sets the file offset, in bytes.
+    pub fn set_offset(&mut self, v: Offset) -> &mut Self {
+        self.0.offset = v;
+        self
+    }
+
+    /// Sets the length of the mapping, in bytes.
+    pub fn set_length(&mut self, len: u64) -> &mut Self {
+        self.0.length = len;
+        self
+    }
+
+    /// Sets the mapping flags.
+    ///
+    /// Values come from the [`map_flags`] module.
+    pub fn set_flags(&mut self, flags: u16) -> &mut Self {
+        self.0.flags = flags;
+        self
+    }
+
+    /// Sets the disk offset of the mapping, in bytes.
+    pub fn set_addr(&mut self, addr: u64) -> &mut Self {
+        self.0.addr = addr;
+        self
+    }
+
+    /// Sets the block device of the mapping.
+    pub fn set_bdev(&mut self, bdev: Option<&'a block::Device>) -> &mut Self {
+        self.0.bdev = if let Some(b) = bdev {
+            b.0.get()
+        } else {
+            core::ptr::null_mut()
+        };
+        self
+    }
+}
+
+/// Flags passed to [`Operations::begin`] and [`Operations::end`].
+pub mod flags {
+    /// Writing, must allocate block.
+    pub const WRITE: u32 = bindings::IOMAP_WRITE;
+
+    /// Zeroing operation, may skip holes.
+    pub const ZERO: u32 = bindings::IOMAP_ZERO;
+
+    /// Report extent status, e.g. FIEMAP.
+    pub const REPORT: u32 = bindings::IOMAP_REPORT;
+
+    /// Mapping for page fault.
+    pub const FAULT: u32 = bindings::IOMAP_FAULT;
+
+    /// Direct I/O.
+    pub const DIRECT: u32 = bindings::IOMAP_DIRECT;
+
+    /// Do not block.
+    pub const NOWAIT: u32 = bindings::IOMAP_NOWAIT;

rust/kernel/fs/iomap.rs line 148

Quoted 10 lines
rust/kernel/fs/iomap.rs new file +10 -0
+
+    /// Only pure overwrites allowed.
+    pub const OVERWRITE_ONLY: u32 = bindings::IOMAP_OVERWRITE_ONLY;
+
+    /// `unshare_file_range`.
+    pub const UNSHARE: u32 = bindings::IOMAP_UNSHARE;
+
+    /// DAX mapping.
+    pub const DAX: u32 = bindings::IOMAP_DAX;
+}

I wonder, how hard will it be to update/regenerate these bindings when someone wants to add new features to the C iomap implementation? IIRC Ritesh's port of C ext2 to iomap adds a boundary flag somewhere.

Quoted 11 lines
rust/kernel/fs/iomap.rs new file +11 -0
+
+/// Operations implemented by iomap users.
+pub trait Operations {
+    /// File system that these operations are compatible with.
+    type FileSystem: FileSystem + ?Sized;
+
+    /// Returns the existing mapping at `pos`, or reserves space starting at `pos` for up to
+    /// `length`, as long as it can be done as a single mapping. The actual length is returned in
+    /// `iomap`.
+    ///
+    /// The values of `flags` come from the [`flags`] module.

rust/kernel/fs/iomap.rs line 169

Quoted 10 lines
rust/kernel/fs/iomap.rs new file +10 -0
+    fn begin<'a>(
+        inode: &'a INode<Self::FileSystem>,
+        pos: Offset,
+        length: Offset,
+        flags: u32,
+        map: &mut Map<'a>,
+        srcmap: &mut Map<'a>,
+    ) -> Result;
+
+    /// Commits and/or unreserves space previously allocated using [`Operations::begin`]. `writte`n

written

Quoted 14 lines
rust/kernel/fs/iomap.rs new file +14 -0
+    /// indicates the length of the successful write operation which needs to be commited, while
+    /// the rest needs to be unreserved. `written` might be zero if no data was written.
+    ///
+    /// The values of `flags` come from the [`flags`] module.
+    fn end<'a>(
+        _inode: &'a INode<Self::FileSystem>,
+        _pos: Offset,
+        _length: Offset,
+        _written: isize,
+        _flags: u32,
+        _map: &Map<'a>,
+    ) -> Result {
+        Ok(())
+    }

rust/kernel/fs/iomap.rs line 193

Quoted 10 lines
rust/kernel/fs/iomap.rs new file +10 -0
+}
+
+/// Returns address space oprerations backed by iomaps.
+pub const fn ro_aops<T: Operations + ?Sized>() -> address_space::Ops<T::FileSystem> {
+    struct Table<T: Operations + ?Sized>(PhantomData<T>);
+    impl<T: Operations + ?Sized> Table<T> {
+        const MAP_TABLE: bindings::iomap_ops = bindings::iomap_ops {
+            iomap_begin: Some(Self::iomap_begin_callback),
+            iomap_end: Some(Self::iomap_end_callback),
+        };

Hmmm. Is the model here that you can call ro_aops() with a pair of iomap function, and then it returns an address_space::Ops object (aka address_space_operations) that is ready to go with iomap functions?

  const FILE_AOPS: address_space::Ops<Ext2Fs> = iomap::ro_aops::<Ext2Fs>();

is a neat trick, but consider that XFS implements a bunch of different iomap ops structures. I suppose it could be interesting to have a bunch of different XfsInode subtypes (e.g. XfsDaxInode) and you'd always know which file is in which mode, etc.

On the other hand, coupling together two things that are /not/ coupled in the C API is awkward. XFS implements separate iomap ops for buffered reads, buffered writes, direct io, fsdax io, FIEMAP, and llseek. I've been pushing porters to make separate iomap ops so that they don't ned up with a single huge foofs_iomap_begin function that tries to dispatch based on iomap flags.

That's a bit different from the C model where the fs implementation has to assemble all the pieces on its own. But then, perhaps the strength of organizing it this way is that you don't end up with a bunch of:

STATIC int
xfs_vm_read_folio(
struct file *unused,
struct folio *folio)

{
	return iomap_read_folio(folio, &xfs_read_iomap_ops);
}

wrappers polluting the file namespace?

But then, what happens for some future rustfs that wants to implement read write support? Does that imply the creation of an iomap::rw_ops? What if they also want to support swapfiles? Is there an elegant way to tamp down the combinatoric rise? Or would we be better off leaving it decoupled the same way the C iomap API does?

Quoted 51 lines
rust/kernel/fs/iomap.rs new file +51 -0
+
+        extern "C" fn iomap_begin_callback(
+            inode_ptr: *mut bindings::inode,
+            pos: Offset,
+            length: Offset,
+            flags: u32,
+            map: *mut bindings::iomap,
+            srcmap: *mut bindings::iomap,
+        ) -> i32 {
+            from_result(|| {
+                // SAFETY: The C API guarantees that `inode_ptr` is a valid inode.
+                let inode = unsafe { INode::from_raw(inode_ptr) };
+                T::begin(
+                    inode,
+                    pos,
+                    length,
+                    flags,
+                    // SAFETY: The C API guarantees that `map` is valid for write.
+                    unsafe { &mut *map.cast::<Map<'_>>() },
+                    // SAFETY: The C API guarantees that `srcmap` is valid for write.
+                    unsafe { &mut *srcmap.cast::<Map<'_>>() },
+                )?;
+                Ok(0)
+            })
+        }
+
+        extern "C" fn iomap_end_callback(
+            inode_ptr: *mut bindings::inode,
+            pos: Offset,
+            length: Offset,
+            written: isize,
+            flags: u32,
+            map: *mut bindings::iomap,
+        ) -> i32 {
+            from_result(|| {
+                // SAFETY: The C API guarantees that `inode_ptr` is a valid inode.
+                let inode = unsafe { INode::from_raw(inode_ptr) };
+                // SAFETY: The C API guarantees that `map` is valid for read.
+                T::end(inode, pos, length, written, flags, unsafe {
+                    &*map.cast::<Map<'_>>()
+                })?;
+                Ok(0)
+            })
+        }
+
+        const TABLE: bindings::address_space_operations = bindings::address_space_operations {
+            writepage: None,
+            read_folio: Some(Self::read_folio_callback),
+            writepages: None,
+            dirty_folio: None,
+            readahead: Some(Self::readahead_callback),

rust/kernel/fs/iomap.rs line 254

Quoted 10 lines
rust/kernel/fs/iomap.rs new file +10 -0
+            write_begin: None,
+            write_end: None,
+            bmap: Some(Self::bmap_callback),
+            invalidate_folio: Some(bindings::iomap_invalidate_folio),
+            release_folio: Some(bindings::iomap_release_folio),
+            free_folio: None,
+            direct_IO: Some(bindings::noop_direct_IO),
+            migrate_folio: None,
+            launder_folio: None,
+            is_partially_uptodate: None,

Hm, isn't this needed for blocksize < pagesize?

rust/kernel/fs/iomap.rs line 259

Quoted 5 lines
rust/kernel/fs/iomap.rs new file +5 -0
+            is_dirty_writeback: None,
+            error_remove_folio: None,
+            swap_activate: None,
+            swap_deactivate: None,
+            swap_rw: None,

Would be kinda nice to sort these by name order.

--D

Quoted 26 lines
rust/kernel/fs/iomap.rs new file +22 -0
+        };
+
+        extern "C" fn read_folio_callback(
+            _file: *mut bindings::file,
+            folio: *mut bindings::folio,
+        ) -> i32 {
+            // SAFETY: `folio` is just forwarded from C and `Self::MAP_TABLE` is always valid.
+            unsafe { bindings::iomap_read_folio(folio, &Self::MAP_TABLE) }
+        }
+
+        extern "C" fn readahead_callback(rac: *mut bindings::readahead_control) {
+            // SAFETY: `rac` is just forwarded from C and `Self::MAP_TABLE` is always valid.
+            unsafe { bindings::iomap_readahead(rac, &Self::MAP_TABLE) }
+        }
+
+        extern "C" fn bmap_callback(mapping: *mut bindings::address_space, block: u64) -> u64 {
+            // SAFETY: `mapping` is just forwarded from C and `Self::MAP_TABLE` is always valid.
+            unsafe { bindings::iomap_bmap(mapping, block, &Self::MAP_TABLE) }
+        }
+    }
+    address_space::Ops(&Table::<T>::TABLE, PhantomData)
+}
Signature · 1 line
2.34.1
#30 lore raw

RFC PATCH v2 28/30 rust: fs: add memalloc_nofs support

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

When used in filesystems obviates the need for GFP_NOFS.

---
 rust/helpers.c    | 12 ++++++++++++
 rust/kernel/fs.rs | 12 ++++++++++++
 2 files changed, 24 insertions(+)
rust/helpers.c +12 -0
index edf12868962c..c26aa07cb20f 100644
@@ -273,6 +273,18 @@ void *rust_helper_alloc_inode_sb(struct super_block *sb,
 }
 EXPORT_SYMBOL_GPL(rust_helper_alloc_inode_sb);
 
+unsigned int rust_helper_memalloc_nofs_save(void)
+{
+	return memalloc_nofs_save();
+}
+EXPORT_SYMBOL_GPL(rust_helper_memalloc_nofs_save);
+
+void rust_helper_memalloc_nofs_restore(unsigned int flags)
+{
+	memalloc_nofs_restore(flags);
+}
+EXPORT_SYMBOL_GPL(rust_helper_memalloc_nofs_restore);
+
 void rust_helper_i_uid_write(struct inode *inode, uid_t uid)
 {
 	i_uid_write(inode, uid);
rust/kernel/fs.rs +12 -0
index 7a1c4884c370..b7a654546d23 100644
@@ -417,6 +417,18 @@ impl<T: FileSystem + ?Sized> Tables<T> {
     }
 }
 
+/// Calls `cb` in a nofs allocation context.
+///
+/// That is, if an allocation happens within `cb`, it will have the `__GFP_FS` bit cleared.
+pub fn memalloc_nofs<T>(cb: impl FnOnce() -> T) -> T {
+    // SAFETY: Function is safe to be called from any context.
+    let flags = unsafe { bindings::memalloc_nofs_save() };
+    let ret = cb();
+    // SAFETY: Function is safe to be called from any context.
+    unsafe { bindings::memalloc_nofs_restore(flags) };
+    ret
+}
+
 /// Kernel module that exposes a single file system implemented by `T`.
 #[pin_data]
 pub struct Module<T: FileSystem + ?Sized> {
Signature · 1 line
2.34.1
#31 lore raw

RFC PATCH v2 29/30 tarfs: introduce tar fs

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

It is a file system based on tar files and an index appended to them (to facilitate finding fs entries without having to traverse the whole tar file).

---
 fs/Kconfig                        |   1 +
 fs/Makefile                       |   1 +
 fs/tarfs/Kconfig                  |  15 ++
 fs/tarfs/Makefile                 |   8 +
 fs/tarfs/defs.rs                  |  80 ++++++
 fs/tarfs/tar.rs                   | 394 ++++++++++++++++++++++++++++++
 scripts/generate_rust_analyzer.py |   2 +-
 7 files changed, 500 insertions(+), 1 deletion(-)
 create mode 100644 fs/tarfs/Kconfig
 create mode 100644 fs/tarfs/Makefile
 create mode 100644 fs/tarfs/defs.rs
 create mode 100644 fs/tarfs/tar.rs
fs/Kconfig +1 -0
index a46b0cbc4d8f..2cbd99d6784c 100644
@@ -337,6 +337,7 @@ source "fs/sysv/Kconfig"
 source "fs/ufs/Kconfig"
 source "fs/erofs/Kconfig"
 source "fs/vboxsf/Kconfig"
+source "fs/tarfs/Kconfig"
 
 endif # MISC_FILESYSTEMS
 
fs/Makefile +1 -0
index 6ecc9b0a53f2..d8bbda73e3a9 100644
@@ -129,3 +129,4 @@ obj-$(CONFIG_EFIVAR_FS)		+= efivarfs/
 obj-$(CONFIG_EROFS_FS)		+= erofs/
 obj-$(CONFIG_VBOXSF_FS)		+= vboxsf/
 obj-$(CONFIG_ZONEFS_FS)		+= zonefs/
+obj-$(CONFIG_TARFS_FS)		+= tarfs/
fs/tarfs/Kconfig new file +15 -0
new file mode 100644
index 000000000000..fd4f1ae0f83d
@@ -0,0 +1,15 @@
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+config TARFS_FS
+	tristate "TAR file system support"
+	depends on RUST && BLOCK
+	help
+	  This is a simple read-only file system intended for mounting
+	  tar files that have had an index appened to them.
+
+	  To compile this file system support as a module, choose M here: the
+	  module will be called tarfs.
+
+	  If you don't know whether you need it, then you don't need it:
+	  answer N.
fs/tarfs/Makefile new file +8 -0
new file mode 100644
index 000000000000..011c5d64fbe3
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for the linux tarfs filesystem routines.
+#
+
+obj-$(CONFIG_TARFS_FS) += tarfs.o
+
+tarfs-y := tar.o
fs/tarfs/defs.rs new file +80 -0

80 lines not on this page · raw message

fs/tarfs/tar.rs new file +394 -0

394 lines not on this page · raw message

scripts/generate_rust_analyzer.py +1 -1
index f270c7b0cf34..6985b9e37429 100755
@@ -116,7 +116,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs):
     # Then, the rest outside of `rust/`.
     #
     # We explicitly mention the top-level folders we want to cover.
-    extra_dirs = map(lambda dir: srctree / dir, ("samples", "drivers"))
+    extra_dirs = map(lambda dir: srctree / dir, ("samples", "drivers", "fs"))
     if external_src is not None:
         extra_dirs = [external_src]
     for folder in extra_dirs:
Signature · 1 line
2.34.1
#32 lore raw

RFC PATCH v2 30/30 WIP: fs: ext2: add rust ro ext2 implementation

In reply to Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

---
 fs/Kconfig            |   1 +
 fs/Makefile           |   1 +
 fs/rust-ext2/Kconfig  |  13 +
 fs/rust-ext2/Makefile |   8 +
 fs/rust-ext2/defs.rs  | 173 +++++++++++++
 fs/rust-ext2/ext2.rs  | 551 ++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs    |   3 +
 7 files changed, 750 insertions(+)
 create mode 100644 fs/rust-ext2/Kconfig
 create mode 100644 fs/rust-ext2/Makefile
 create mode 100644 fs/rust-ext2/defs.rs
 create mode 100644 fs/rust-ext2/ext2.rs
fs/Kconfig +1 -0
index 2cbd99d6784c..cf0cac5c5b1e 100644
@@ -338,6 +338,7 @@ source "fs/ufs/Kconfig"
 source "fs/erofs/Kconfig"
 source "fs/vboxsf/Kconfig"
 source "fs/tarfs/Kconfig"
+source "fs/rust-ext2/Kconfig"
 
 endif # MISC_FILESYSTEMS
 
fs/Makefile +1 -0
index d8bbda73e3a9..c1a3007efc7d 100644
@@ -130,3 +130,4 @@ obj-$(CONFIG_EROFS_FS)		+= erofs/
 obj-$(CONFIG_VBOXSF_FS)		+= vboxsf/
 obj-$(CONFIG_ZONEFS_FS)		+= zonefs/
 obj-$(CONFIG_TARFS_FS)		+= tarfs/
+obj-$(CONFIG_RUST_EXT2_FS)	+= rust-ext2/
fs/rust-ext2/Kconfig new file +13 -0
new file mode 100644
index 000000000000..976371655ca6
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+config RUST_EXT2_FS
+	tristate "Rust second extended fs support"
+	depends on RUST && BLOCK
+	help
+	  Ext2 is a standard Linux file system for hard disks.
+
+	  To compile this file system support as a module, choose M here: the
+	  module will be called rust_ext2.
+
+	  If unsure, say Y.
fs/rust-ext2/Makefile new file +8 -0
new file mode 100644
index 000000000000..ac960b5f89d7
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for the linux tarfs filesystem routines.
+#
+
+obj-$(CONFIG_RUST_EXT2_FS) += rust_ext2.o
+
+rust_ext2-y := ext2.o
fs/rust-ext2/defs.rs new file +173 -0

173 lines not on this page · raw message

fs/rust-ext2/ext2.rs new file +551 -0

551 lines not on this page · raw message

rust/kernel/lib.rs +3 -0
index 445599d4bff6..732bc9939f7f 100644
@@ -165,3 +165,6 @@ macro_rules! container_of {
         ptr.wrapping_sub(offset) as *const $type
     }}
 }
+
+/// The size in bytes of a page of memory.
+pub const PAGE_SIZE: usize = bindings::PAGE_SIZE;
Signature · 1 line
2.34.1
#33 lore raw

Re: [RFC PATCH v2 30/30] WIP: fs: ext2: add rust ro ext2 implementation

Quoted 175 lines · Wedson Almeida Filho

From: Wedson Almeida Filho <[email protected]>

---
 fs/Kconfig            |   1 +
 fs/Makefile           |   1 +
 fs/rust-ext2/Kconfig  |  13 +
 fs/rust-ext2/Makefile |   8 +
 fs/rust-ext2/defs.rs  | 173 +++++++++++++
 fs/rust-ext2/ext2.rs  | 551 ++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs    |   3 +
 7 files changed, 750 insertions(+)
 create mode 100644 fs/rust-ext2/Kconfig
 create mode 100644 fs/rust-ext2/Makefile
 create mode 100644 fs/rust-ext2/defs.rs
 create mode 100644 fs/rust-ext2/ext2.rs
fs/Kconfig +1 -0
index 2cbd99d6784c..cf0cac5c5b1e 100644
@@ -338,6 +338,7 @@ source "fs/ufs/Kconfig"
 source "fs/erofs/Kconfig"
 source "fs/vboxsf/Kconfig"
 source "fs/tarfs/Kconfig"
+source "fs/rust-ext2/Kconfig"
 
 endif # MISC_FILESYSTEMS
 
fs/Makefile +1 -0
index d8bbda73e3a9..c1a3007efc7d 100644
@@ -130,3 +130,4 @@ obj-$(CONFIG_EROFS_FS)		+= erofs/
 obj-$(CONFIG_VBOXSF_FS)		+= vboxsf/
 obj-$(CONFIG_ZONEFS_FS)		+= zonefs/
 obj-$(CONFIG_TARFS_FS)		+= tarfs/
+obj-$(CONFIG_RUST_EXT2_FS)	+= rust-ext2/
fs/rust-ext2/Kconfig new file +13 -0
new file mode 100644
index 000000000000..976371655ca6
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-only
+#
+
+config RUST_EXT2_FS
+	tristate "Rust second extended fs support"
+	depends on RUST && BLOCK
+	help
+	  Ext2 is a standard Linux file system for hard disks.
+
+	  To compile this file system support as a module, choose M here: the
+	  module will be called rust_ext2.
+
+	  If unsure, say Y.
fs/rust-ext2/Makefile new file +8 -0
new file mode 100644
index 000000000000..ac960b5f89d7
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for the linux tarfs filesystem routines.
+#
+
+obj-$(CONFIG_RUST_EXT2_FS) += rust_ext2.o
+
+rust_ext2-y := ext2.o
fs/rust-ext2/defs.rs new file +98 -0
new file mode 100644
index 000000000000..5f84852b4961
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Definitions of tarfs structures.
+
+use kernel::types::LE;
+
+pub(crate) const EXT2_SUPER_MAGIC: u16 = 0xEF53;
+
+pub(crate) const EXT2_MAX_BLOCK_LOG_SIZE: u32 = 16;
+
+pub(crate) const EXT2_GOOD_OLD_REV: u32 = 0; /* The good old (original) format */
+pub(crate) const EXT2_DYNAMIC_REV: u32 = 1; /* V2 format w/ dynamic inode sizes */
+
+pub(crate) const EXT2_GOOD_OLD_INODE_SIZE: u16 = 128;
+
+pub(crate) const EXT2_ROOT_INO: u32 = 2; /* Root inode */
+
+/* First non-reserved inode for old ext2 filesystems. */
+pub(crate) const EXT2_GOOD_OLD_FIRST_INO: u32 = 11;
+
+pub(crate) const EXT2_FEATURE_INCOMPAT_FILETYPE: u32 = 0x0002;
+
+/*
+ * Constants relative to the data blocks
+ */
+pub(crate) const EXT2_NDIR_BLOCKS: usize = 12;
+pub(crate) const EXT2_IND_BLOCK: usize = EXT2_NDIR_BLOCKS;
+pub(crate) const EXT2_DIND_BLOCK: usize = EXT2_IND_BLOCK + 1;
+pub(crate) const EXT2_TIND_BLOCK: usize = EXT2_DIND_BLOCK + 1;
+pub(crate) const EXT2_N_BLOCKS: usize = EXT2_TIND_BLOCK + 1;
+
+kernel::derive_readable_from_bytes! {
+    #[repr(C)]
+    pub(crate) struct Super {
+        pub(crate) inodes_count: LE<u32>,
+        pub(crate) blocks_count: LE<u32>,
+        pub(crate) r_blocks_count: LE<u32>,
+        pub(crate) free_blocks_count: LE<u32>, /* Free blocks count */
+        pub(crate) free_inodes_count: LE<u32>, /* Free inodes count */
+        pub(crate) first_data_block: LE<u32>,  /* First Data Block */
+        pub(crate) log_block_size: LE<u32>,    /* Block size */
+        pub(crate) log_frag_size: LE<u32>,     /* Fragment size */
+        pub(crate) blocks_per_group: LE<u32>,  /* # Blocks per group */
+        pub(crate) frags_per_group: LE<u32>,   /* # Fragments per group */
+        pub(crate) inodes_per_group: LE<u32>,  /* # Inodes per group */
+        pub(crate) mtime: LE<u32>,             /* Mount time */
+        pub(crate) wtime: LE<u32>,             /* Write time */
+        pub(crate) mnt_count: LE<u16>,         /* Mount count */
+        pub(crate) max_mnt_count: LE<u16>,     /* Maximal mount count */
+        pub(crate) magic: LE<u16>,             /* Magic signature */
+        pub(crate) state: LE<u16>,             /* File system state */
+        pub(crate) errors: LE<u16>,            /* Behaviour when detecting errors */
+        pub(crate) minor_rev_level: LE<u16>,   /* minor revision level */
+        pub(crate) lastcheck: LE<u32>,         /* time of last check */
+        pub(crate) checkinterval: LE<u32>,     /* max. time between checks */
+        pub(crate) creator_os: LE<u32>,        /* OS */
+        pub(crate) rev_level: LE<u32>,         /* Revision level */
+        pub(crate) def_resuid: LE<u16>,        /* Default uid for reserved blocks */
+        pub(crate) def_resgid: LE<u16>,        /* Default gid for reserved blocks */
+        /*
+         * These fields are for EXT2_DYNAMIC_REV superblocks only.
+         *
+         * Note: the difference between the compatible feature set and
+         * the incompatible feature set is that if there is a bit set
+         * in the incompatible feature set that the kernel doesn't
+         * know about, it should refuse to mount the filesystem.
+         *
+         * e2fsck's requirements are more strict; if it doesn't know
+         * about a feature in either the compatible or incompatible
+         * feature set, it must abort and not try to meddle with
+         * things it doesn't understand...
+         */
+        pub(crate) first_ino: LE<u32>,              /* First non-reserved inode */
+        pub(crate) inode_size: LE<u16>,             /* size of inode structure */
+        pub(crate) block_group_nr: LE<u16>,         /* block group # of this superblock */
+        pub(crate) feature_compat: LE<u32>,         /* compatible feature set */
+        pub(crate) feature_incompat: LE<u32>,       /* incompatible feature set */
+        pub(crate) feature_ro_compat: LE<u32>,      /* readonly-compatible feature set */
+        pub(crate) uuid: [u8; 16],                  /* 128-bit uuid for volume */
+        pub(crate) volume_name: [u8; 16],           /* volume name */
+        pub(crate) last_mounted: [u8; 64],          /* directory where last mounted */
+        pub(crate) algorithm_usage_bitmap: LE<u32>, /* For compression */
+        /*
+         * Performance hints.  Directory preallocation should only
+         * happen if the EXT2_COMPAT_PREALLOC flag is on.
+         */
+        pub(crate) prealloc_blocks: u8,    /* Nr of blocks to try to preallocate*/
+        pub(crate) prealloc_dir_blocks: u8,        /* Nr to preallocate for dirs */
+        padding1: u16,
+        /*
+         * Journaling support valid if EXT3_FEATURE_COMPAT_HAS_JOURNAL set.
+         */
+        pub(crate) journal_uuid: [u8; 16],      /* uuid of journal superblock */
+        pub(crate) journal_inum: u32,           /* inode number of journal file */
+        pub(crate) journal_dev: u32,            /* device number of journal file */
+        pub(crate) last_orphan: u32,            /* start of list of inodes to delete */
+        pub(crate) hash_seed: [u32; 4],         /* HTREE hash seed */
+        pub(crate) def_hash_version: u8,        /* Default hash version to use */

fs/rust-ext2/defs.rs line 108

Quoted 10 lines
fs/rust-ext2/defs.rs new file +10 -0
+        pub(crate) reserved_char_pad: u8,
+        pub(crate) reserved_word_pad: u16,
+        pub(crate) default_mount_opts: LE<u32>,
+        pub(crate) first_meta_bg: LE<u32>,      /* First metablock block group */
+        reserved: [u32; 190],                   /* Padding to the end of the block */
+    }
+
+    #[repr(C)]
+    #[derive(Clone, Copy)]
+    pub(crate) struct Group {

Might want to call these GroupDescriptor to match(ish) the ext2 structure? I dunno, it's going to be hard to remember to change "struct ext2_group_desc" in my head to "struct ext2::GroupDescriptor" or even "struct ext2::group_desc".

Quoted 130 lines
fs/rust-ext2/defs.rs new file +65 -0
+        /// Blocks bitmap block.
+        pub block_bitmap: LE<u32>,
+
+        /// Inodes bitmap block.
+        pub inode_bitmap: LE<u32>,
+
+        /// Inodes table block.
+        pub inode_table: LE<u32>,
+
+        /// Number of free blocks.
+        pub free_blocks_count: LE<u16>,
+
+        /// Number of free inodes.
+        pub free_inodes_count: LE<u16>,
+
+        /// Number of directories.
+        pub used_dirs_count: LE<u16>,
+
+        pad: LE<u16>,
+        reserved: [u32; 3],
+    }
+
+    #[repr(C)]
+    pub(crate) struct INode {
+        pub mode: LE<u16>,                  /* File mode */
+        pub uid: LE<u16>,                   /* Low 16 bits of Owner Uid */
+        pub size: LE<u32>,                  /* Size in bytes */
+        pub atime: LE<u32>,                 /* Access time */
+        pub ctime: LE<u32>,                 /* Creation time */
+        pub mtime: LE<u32>,                 /* Modification time */
+        pub dtime: LE<u32>,                 /* Deletion Time */
+        pub gid: LE<u16>,                   /* Low 16 bits of Group Id */
+        pub links_count: LE<u16>,           /* Links count */
+        pub blocks: LE<u32>,                /* Blocks count */
+        pub flags: LE<u32>,                 /* File flags */
+        pub reserved1: LE<u32>,
+        pub block: [LE<u32>; EXT2_N_BLOCKS],/* Pointers to blocks */
+        pub generation: LE<u32>,            /* File version (for NFS) */
+        pub file_acl: LE<u32>,              /* File ACL */
+        pub dir_acl: LE<u32>,               /* Directory ACL */
+        pub faddr: LE<u32>,                 /* Fragment address */
+        pub frag: u8,	                    /* Fragment number */
+        pub fsize: u8,	                    /* Fragment size */
+        pub pad1: LE<u16>,
+        pub uid_high: LE<u16>,
+        pub gid_high: LE<u16>,
+        pub reserved2: LE<u32>,
+    }
+
+    #[repr(C)]
+    pub(crate) struct DirEntry {
+        pub(crate) inode: LE<u32>,       /* Inode number */
+        pub(crate) rec_len: LE<u16>,     /* Directory entry length */
+        pub(crate) name_len: u8,         /* Name length */
+        pub(crate) file_type: u8,        /* Only if the "filetype" feature flag is set. */
+    }
+}
+
+pub(crate) const FT_REG_FILE: u8 = 1;
+pub(crate) const FT_DIR: u8 = 2;
+pub(crate) const FT_CHRDEV: u8 = 3;
+pub(crate) const FT_BLKDEV: u8 = 4;
+pub(crate) const FT_FIFO: u8 = 5;
+pub(crate) const FT_SOCK: u8 = 6;
+pub(crate) const FT_SYMLINK: u8 = 7;
fs/rust-ext2/ext2.rs new file +59 -0
new file mode 100644
index 000000000000..2d6b1e7ca156
@@ -0,0 +1,551 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Ext2 file system.
+
+use alloc::vec::Vec;
+use core::mem::size_of;
+use defs::*;
+use kernel::fs::{
+    self, address_space, dentry, dentry::DEntry, file, file::File, inode, inode::INode, iomap, sb,
+    sb::SuperBlock, Offset,
+};
+use kernel::types::{ARef, Either, FromBytes, Locked, LE};
+use kernel::{block, c_str, prelude::*, str::CString, time::Timespec, user, PAGE_SIZE};
+
+pub mod defs;
+
+kernel::module_fs! {
+    type: Ext2Fs,
+    name: "ext2",
+    author: "Wedson Almeida Filho <[email protected]>",
+    description: "ext2 file system",
+    license: "GPL",
+}
+
+const SB_OFFSET: Offset = 1024;
+
+struct INodeData {
+    data_blocks: [u32; defs::EXT2_N_BLOCKS],
+}
+
+struct Ext2Fs {
+    mapper: inode::Mapper,
+    block_size: u32,
+    has_file_type: bool,
+    _block_size_bits: u32,
+    inodes_per_block: u32,
+    inodes_per_group: u32,
+    inode_count: u32,
+    inode_size: u16,
+    first_ino: u32,
+    group: Vec<defs::Group>,
+}
+
+impl Ext2Fs {
+    fn iget(sb: &SuperBlock<Self>, ino: u32) -> Result<ARef<INode<Self>>> {
+        let s = sb.data();
+        if (ino != EXT2_ROOT_INO && ino < s.first_ino) || ino > s.inode_count {
+            return Err(ENOENT);
+        }
+        let group = ((ino - 1) / s.inodes_per_group) as usize;
+        let offset = (ino - 1) % s.inodes_per_group;
+
+        if group >= s.group.len() {
+            return Err(ENOENT);
+        }
+
+        // Create an inode or find an existing (cached) one.
+        let mut inode = match sb.get_or_create_inode(ino.into())? {
+            Either::Left(existing) => return Ok(existing),

fs/rust-ext2/ext2.rs line 69

Quoted 10 lines
fs/rust-ext2/ext2.rs new file +10 -0
+            Either::Right(new) => new,
+        };
+
+        let inodes_block = Offset::from(s.group[group].inode_table.value());
+        let inode_block = inodes_block + Offset::from(offset / s.inodes_per_block);
+        let offset = (offset % s.inodes_per_block) as usize;
+        let b = sb
+            .data()
+            .mapper
+            .mapped_folio(inode_block * Offset::from(s.block_size))?;

It almost feels like you need a buffer cache here for fs metadata... ;)

Quoted 7 lines
fs/rust-ext2/ext2.rs new file +7 -0
+        let idata = defs::INode::from_bytes(&b, offset * s.inode_size as usize).ok_or(EIO)?;
+        let mode = idata.mode.value();
+
+        if idata.links_count.value() == 0 && (mode == 0 || idata.dtime.value() != 0) {
+            return Err(ESTALE);
+        }
+

fs/rust-ext2/ext2.rs line 86

Quoted 10 lines
fs/rust-ext2/ext2.rs new file +10 -0
+        const DIR_FOPS: file::Ops<Ext2Fs> = file::Ops::new::<Ext2Fs>();
+        const DIR_IOPS: inode::Ops<Ext2Fs> = inode::Ops::new::<Ext2Fs>();
+        const FILE_AOPS: address_space::Ops<Ext2Fs> = iomap::ro_aops::<Ext2Fs>();
+
+        let mut size = idata.size.value().into();
+        let typ = match mode & fs::mode::S_IFMT {
+            fs::mode::S_IFREG => {
+                size |= Offset::from(idata.dir_acl.value())
+                    .checked_shl(32)
+                    .ok_or(EUCLEAN)?;

I wonder, is there a clean way to log these kinds of corruption errors? ext4 (and soon xfs) have the ability to log health problems and pass those kinds of errors to a monitoring daemon via fanotify.

Quoted 100 lines
fs/rust-ext2/ext2.rs new file +100 -0
+                inode
+                    .set_aops(FILE_AOPS)
+                    .set_fops(file::Ops::generic_ro_file());
+                inode::Type::Reg
+            }
+            fs::mode::S_IFDIR => {
+                inode
+                    .set_iops(DIR_IOPS)
+                    .set_fops(DIR_FOPS)
+                    .set_aops(FILE_AOPS);
+                inode::Type::Dir
+            }
+            fs::mode::S_IFLNK => {
+                if idata.blocks.value() == 0 {
+                    const OFFSET: usize = core::mem::offset_of!(defs::INode, block);
+                    let name = &b[offset * usize::from(s.inode_size) + OFFSET..];
+                    let name_len = size as usize;
+                    if name_len > name.len() || name_len == 0 {
+                        return Err(EIO);
+                    }
+                    inode.set_iops(inode::Ops::simple_symlink_inode());
+                    inode::Type::Lnk(Some(CString::try_from(&name[..name_len])?))
+                } else {
+                    inode
+                        .set_aops(FILE_AOPS)
+                        .set_iops(inode::Ops::page_symlink_inode());
+                    inode::Type::Lnk(None)
+                }
+            }
+            fs::mode::S_IFSOCK => inode::Type::Sock,
+            fs::mode::S_IFIFO => inode::Type::Fifo,
+            fs::mode::S_IFCHR => {
+                let (major, minor) = decode_dev(&idata.block);
+                inode::Type::Chr(major, minor)
+            }
+            fs::mode::S_IFBLK => {
+                let (major, minor) = decode_dev(&idata.block);
+                inode::Type::Blk(major, minor)
+            }
+            _ => return Err(ENOENT),
+        };
+        inode.init(inode::Params {
+            typ,
+            mode: mode & 0o777,
+            size,
+            blocks: idata.blocks.value().into(),
+            nlink: idata.links_count.value().into(),
+            uid: u32::from(idata.uid.value()) | u32::from(idata.uid_high.value()) << 16,
+            gid: u32::from(idata.gid.value()) | u32::from(idata.gid_high.value()) << 16,
+            ctime: Timespec::new(idata.ctime.value().into(), 0)?,
+            mtime: Timespec::new(idata.mtime.value().into(), 0)?,
+            atime: Timespec::new(idata.atime.value().into(), 0)?,
+            value: INodeData {
+                data_blocks: core::array::from_fn(|i| idata.block[i].value()),
+            },
+        })
+    }
+
+    fn offsets<'a>(&self, mut block: u64, out: &'a mut [u32]) -> Option<&'a [u32]> {
+        let ptrs = u64::from(self.block_size / size_of::<u32>() as u32);
+        let ptr_mask = ptrs - 1;
+        let ptr_bits = ptrs.trailing_zeros();
+
+        if block < EXT2_NDIR_BLOCKS as u64 {
+            out[0] = block as u32;
+            return Some(&out[..1]);
+        }
+
+        block -= EXT2_NDIR_BLOCKS as u64;
+        if block < ptrs {
+            out[0] = EXT2_IND_BLOCK as u32;
+            out[1] = block as u32;
+            return Some(&out[..2]);
+        }
+
+        block -= ptrs;
+        if block < (1 << (2 * ptr_bits)) {
+            out[0] = EXT2_DIND_BLOCK as u32;
+            out[1] = (block >> ptr_bits) as u32;
+            out[2] = (block & ptr_mask) as u32;
+            return Some(&out[..3]);
+        }
+
+        block -= ptrs * ptrs;
+        if block < ptrs * ptrs * ptrs {
+            out[0] = EXT2_TIND_BLOCK as u32;
+            out[1] = (block >> (2 * ptr_bits)) as u32;
+            out[2] = ((block >> ptr_bits) & ptr_mask) as u32;
+            out[3] = (block & ptr_mask) as u32;
+            return Some(&out[..4]);
+        }
+
+        None
+    }
+
+    fn offset_to_block(inode: &INode<Self>, block: Offset) -> Result<u64> {
+        let s = inode.super_block().data();
+        let mut indices = [0u32; 4];
+        let boffsets = s.offsets(block as u64, &mut indices).ok_or(EIO)?;
+        let mut boffset = inode.data().data_blocks[boffsets[0] as usize];

fs/rust-ext2/ext2.rs line 196

Quoted 10 lines
fs/rust-ext2/ext2.rs new file +10 -0
+        let mapper = &s.mapper;
+        for i in &boffsets[1..] {
+            let b = mapper.mapped_folio(Offset::from(boffset) * Offset::from(s.block_size))?;
+            let table = LE::<u32>::from_bytes_to_slice(&b).ok_or(EIO)?;
+            boffset = table[*i as usize].value();
+        }
+        Ok(boffset.into())
+    }
+
+    fn check_descriptors(s: &Super, groups: &[Group]) -> Result {

It's ... very odd to mix file space mapping functions and group descriptors into the same structure. Does offset_to_block belong in a Ext2Inode structure?

I was also wondering, is there a convenient way to make it so that the compiler can enforce that a directory inode can only be passed an Operations that actually has all the directory operations initialized? Or that a regular file can't have a lookup function in its iops?

Quoted 140 lines
fs/rust-ext2/ext2.rs new file +140 -0
+        for (i, g) in groups.iter().enumerate() {
+            let first = i as u32 * s.blocks_per_group.value() + s.first_data_block.value();
+            let last = if i == groups.len() - 1 {
+                s.blocks_count.value()
+            } else {
+                first + s.blocks_per_group.value() - 1
+            };
+
+            if g.block_bitmap.value() < first || g.block_bitmap.value() > last {
+                pr_err!(
+                    "Block bitmap for group {i} no in group (block {})\n",
+                    g.block_bitmap.value()
+                );
+                return Err(EINVAL);
+            }
+
+            if g.inode_bitmap.value() < first || g.inode_bitmap.value() > last {
+                pr_err!(
+                    "Inode bitmap for group {i} no in group (block {})\n",
+                    g.inode_bitmap.value()
+                );
+                return Err(EINVAL);
+            }
+
+            if g.inode_table.value() < first || g.inode_table.value() > last {
+                pr_err!(
+                    "Inode table for group {i} no in group (block {})\n",
+                    g.inode_table.value()
+                );
+                return Err(EINVAL);
+            }
+        }
+        Ok(())
+    }
+}
+
+impl fs::FileSystem for Ext2Fs {
+    type Data = Box<Self>;
+    type INodeData = INodeData;
+    const NAME: &'static CStr = c_str!("rust-ext2");
+    const SUPER_TYPE: sb::Type = sb::Type::BlockDev;
+
+    fn fill_super(
+        sb: &mut SuperBlock<Self, sb::New>,
+        mapper: Option<inode::Mapper>,
+    ) -> Result<Self::Data> {
+        let Some(mapper) = mapper else {
+            return Err(EINVAL);
+        };
+
+        if sb.min_blocksize(PAGE_SIZE as i32) == 0 {
+            pr_err!("Unable to set block size\n");
+            return Err(EINVAL);
+        }
+
+        // Map the super block and check the magic number.
+        let mapped = mapper.mapped_folio(SB_OFFSET)?;
+        let s = Super::from_bytes(&mapped, 0).ok_or(EIO)?;
+
+        if s.magic.value() != EXT2_SUPER_MAGIC {
+            return Err(EINVAL);
+        }
+
+        // Check for unsupported flags.
+        let mut has_file_type = false;
+        if s.rev_level.value() >= EXT2_DYNAMIC_REV {
+            let features = s.feature_incompat.value();
+            if features & !EXT2_FEATURE_INCOMPAT_FILETYPE != 0 {
+                pr_err!("Unsupported incompatible feature: {:x}\n", features);
+                return Err(EINVAL);
+            }
+
+            has_file_type = features & EXT2_FEATURE_INCOMPAT_FILETYPE != 0;
+
+            let features = s.feature_ro_compat.value();
+            if !sb.rdonly() && features != 0 {
+                pr_err!("Unsupported rw incompatible feature: {:x}\n", features);
+                return Err(EINVAL);
+            }
+        }
+
+        // Set the block size.
+        let block_size_bits = s.log_block_size.value();
+        if block_size_bits > EXT2_MAX_BLOCK_LOG_SIZE - 10 {
+            pr_err!("Invalid log block size: {}\n", block_size_bits);
+            return Err(EINVAL);
+        }
+
+        let block_size = 1024u32 << block_size_bits;
+        if sb.min_blocksize(block_size as i32) != block_size as i32 {
+            pr_err!("Bad block size: {}\n", block_size);
+            return Err(ENXIO);
+        }
+
+        // Get the first inode and the inode size.
+        let (inode_size, first_ino) = if s.rev_level.value() == EXT2_GOOD_OLD_REV {
+            (EXT2_GOOD_OLD_INODE_SIZE, EXT2_GOOD_OLD_FIRST_INO)
+        } else {
+            let size = s.inode_size.value();
+            if size < EXT2_GOOD_OLD_INODE_SIZE
+                || !size.is_power_of_two()
+                || u32::from(size) > block_size
+            {
+                pr_err!("Unsupported inode size: {}\n", size);
+                return Err(EINVAL);
+            }
+            (size, s.first_ino.value())
+        };
+
+        // Get the number of inodes per group and per block.
+        let inode_count = s.inodes_count.value();
+        let inodes_per_group = s.inodes_per_group.value();
+        let inodes_per_block = block_size / u32::from(inode_size);
+        if inodes_per_group == 0 || inodes_per_block == 0 {
+            return Err(EINVAL);
+        }
+
+        if inodes_per_group > block_size * 8 || inodes_per_group < inodes_per_block {
+            pr_err!("Bad inodes per group: {}\n", inodes_per_group);
+            return Err(EINVAL);
+        }
+
+        // Check the size of the groups.
+        let itb_per_group = inodes_per_group / inodes_per_block;
+        let blocks_per_group = s.blocks_per_group.value();
+        if blocks_per_group > block_size * 8 || blocks_per_group <= itb_per_group + 3 {
+            pr_err!("Bad blocks per group: {}\n", blocks_per_group);
+            return Err(EINVAL);
+        }
+
+        let blocks_count = s.blocks_count.value();
+        if block::Sector::from(blocks_count) > sb.sector_count() >> (1 + block_size_bits) {
+            pr_err!(
+                "Block count ({blocks_count}) exceeds size of device ({})\n",
+                sb.sector_count() >> (1 + block_size_bits)
+            );
+            return Err(EINVAL);
+        }
+
+        let group_count = (blocks_count - s.first_data_block.value() - 1) / blocks_per_group + 1;

fs/rust-ext2/ext2.rs line 346

Quoted 10 lines
fs/rust-ext2/ext2.rs new file +10 -0
+        if group_count * inodes_per_group != inode_count {
+            pr_err!(
+                "Unexpected inode count: {inode_count} vs {}",
+                group_count * inodes_per_group
+            );
+            return Err(EINVAL);
+        }
+
+        let mut groups = Vec::new();
+        groups.reserve(group_count as usize, GFP_NOFS)?;

Why not GFP_KERNEL here?

Oh wow the C ext2 driver pins a bunch of buffer heads doesn't it... /me runs

Quoted 55 lines
fs/rust-ext2/ext2.rs new file +55 -0
+
+        let mut remain = group_count;
+        let mut offset = (SB_OFFSET / Offset::from(block_size) + 1) * Offset::from(block_size);
+        while remain > 0 {
+            let b = mapper.mapped_folio(offset)?;
+            for g in Group::from_bytes_to_slice(&b).ok_or(EIO)? {
+                groups.push(*g, GFP_NOFS)?;
+                remain -= 1;
+                if remain == 0 {
+                    break;
+                }
+            }
+            offset += Offset::try_from(b.len())?;
+        }
+
+        Self::check_descriptors(s, &groups)?;
+
+        sb.set_magic(s.magic.value().into());
+        drop(mapped);
+        Ok(Box::new(
+            Ext2Fs {
+                mapper,
+                block_size,
+                _block_size_bits: block_size_bits,
+                has_file_type,
+                inodes_per_group,
+                inodes_per_block,
+                inode_count,
+                inode_size,
+                first_ino,
+                group: groups,
+            },
+            GFP_KERNEL,
+        )?)
+    }
+
+    fn init_root(sb: &SuperBlock<Self>) -> Result<dentry::Root<Self>> {
+        let inode = Self::iget(sb, EXT2_ROOT_INO)?;
+        dentry::Root::try_new(inode)
+    }
+}
+
+fn rec_len(d: &DirEntry) -> u32 {
+    let len = d.rec_len.value();
+
+    if PAGE_SIZE >= 65536 && len == u16::MAX {
+        1u32 << 16
+    } else {
+        len.into()
+    }
+}
+
+#[vtable]
+impl file::Operations for Ext2Fs {
+    type FileSystem = Self;

fs/rust-ext2/ext2.rs line 411

Quoted 10 lines
fs/rust-ext2/ext2.rs new file +10 -0
+
+    fn seek(file: &File<Self>, offset: Offset, whence: file::Whence) -> Result<Offset> {
+        file::generic_seek(file, offset, whence)
+    }
+
+    fn read(_: &File<Self>, _: &mut user::Writer, _: &mut Offset) -> Result<usize> {
+        Err(EISDIR)
+    }
+
+    fn read_dir(

Wait, does this imply that regular files also have read_dir that you can call?

fs/rust-ext2/ext2.rs line 418

Quoted 7 lines
fs/rust-ext2/ext2.rs new file +7 -0
+        _file: &File<Self>,
+        inode: &Locked<&INode<Self>, inode::ReadSem>,
+        emitter: &mut file::DirEmitter,
+    ) -> Result {
+        let has_file_type = inode.super_block().data().has_file_type;
+
+        inode.for_each_page(emitter.pos(), Offset::MAX, |data| {

Neat that Rust can turn an indirect call to a lambda function into a direct call. I hear C can do that now too?

Quoted 27 lines
fs/rust-ext2/ext2.rs new file +27 -0
+            let mut offset = 0usize;
+            let mut acc: Offset = 0;
+            let limit = data.len().saturating_sub(size_of::<DirEntry>());
+            while offset < limit {
+                let dirent = DirEntry::from_bytes(data, offset).ok_or(EIO)?;
+                offset += size_of::<DirEntry>();
+
+                let name_len = usize::from(dirent.name_len);
+                if data.len() - offset < name_len {
+                    return Err(EIO);
+                }
+
+                let name = &data[offset..][..name_len];
+                let rec_len = rec_len(dirent);
+                offset = offset - size_of::<DirEntry>() + rec_len as usize;
+                if rec_len == 0 || offset > data.len() {
+                    return Err(EIO);
+                }
+
+                acc += Offset::from(rec_len);
+                let ino = dirent.inode.value();
+                if ino == 0 {
+                    continue;
+                }
+
+                let t = if !has_file_type {
+                    file::DirEntryType::Unknown

fs/rust-ext2/ext2.rs line 455

Quoted 10 lines
fs/rust-ext2/ext2.rs new file +10 -0
+                } else {
+                    match dirent.file_type {
+                        FT_REG_FILE => file::DirEntryType::Reg,
+                        FT_DIR => file::DirEntryType::Dir,
+                        FT_SYMLINK => file::DirEntryType::Lnk,
+                        FT_CHRDEV => file::DirEntryType::Chr,
+                        FT_BLKDEV => file::DirEntryType::Blk,
+                        FT_FIFO => file::DirEntryType::Fifo,
+                        FT_SOCK => file::DirEntryType::Sock,
+                        _ => continue,

Isn't this a directory corruption? return Err(EFSCORRUPTED) ?

Quoted 72 lines
fs/rust-ext2/ext2.rs new file +72 -0
+                    }
+                };
+
+                if !emitter.emit(acc, name, ino.into(), t) {
+                    return Ok(Some(()));
+                }
+                acc = 0;
+            }
+            Ok(None)
+        })?;
+        Ok(())
+    }
+}
+
+#[vtable]
+impl inode::Operations for Ext2Fs {
+    type FileSystem = Self;
+
+    fn lookup(
+        parent: &Locked<&INode<Self>, inode::ReadSem>,
+        dentry: dentry::Unhashed<'_, Self>,
+    ) -> Result<Option<ARef<DEntry<Self>>>> {
+        let inode = parent.for_each_page(0, Offset::MAX, |data| {
+            let mut offset = 0usize;
+            while data.len() - offset > size_of::<DirEntry>() {
+                let dirent = DirEntry::from_bytes(data, offset).ok_or(EIO)?;
+                offset += size_of::<DirEntry>();
+
+                let name_len = usize::from(dirent.name_len);
+                if data.len() - offset < name_len {
+                    return Err(EIO);
+                }
+
+                let name = &data[offset..][..name_len];
+
+                offset = offset - size_of::<DirEntry>() + usize::from(dirent.rec_len.value());
+                if offset > data.len() {
+                    return Err(EIO);
+                }
+
+                let ino = dirent.inode.value();
+                if ino != 0 && name == dentry.name() {
+                    return Ok(Some(Self::iget(parent.super_block(), ino)?));
+                }
+            }
+            Ok(None)
+        })?;
+
+        dentry.splice_alias(inode)
+    }
+}
+
+impl iomap::Operations for Ext2Fs {
+    type FileSystem = Self;
+
+    fn begin<'a>(
+        inode: &'a INode<Self>,
+        pos: Offset,
+        length: Offset,
+        _flags: u32,
+        map: &mut iomap::Map<'a>,
+        _srcmap: &mut iomap::Map<'a>,
+    ) -> Result {
+        let size = inode.size();
+        if pos >= size {
+            map.set_offset(pos)
+                .set_length(length.try_into()?)
+                .set_flags(iomap::map_flags::MERGED)
+                .set_type(iomap::Type::Hole);
+            return Ok(());
+        }
+

fs/rust-ext2/ext2.rs line 537

Quoted 10 lines
fs/rust-ext2/ext2.rs new file +10 -0
+        let block_size = inode.super_block().data().block_size as Offset;
+        let block = pos / block_size;
+
+        let boffset = Self::offset_to_block(inode, block)?;
+        map.set_offset(block * block_size)
+            .set_length(block_size as u64)
+            .set_flags(iomap::map_flags::MERGED)
+            .set_type(iomap::Type::Mapped)
+            .set_bdev(Some(inode.super_block().bdev()))
+            .set_addr(boffset * block_size as u64);

Neat use of chaining here.

fs/rust-ext2/ext2.rs line 549

Quoted 12 lines
fs/rust-ext2/ext2.rs new file +12 -0
+
+        Ok(())
+    }
+}
+
+fn decode_dev(block: &[LE<u32>]) -> (u32, u32) {
+    let v = block[0].value();
+    if v != 0 {
+        ((v >> 8) & 255, v & 255)
+    } else {
+        let v = block[1].value();
+        ((v & 0xfff00) >> 8, (v & 0xff) | ((v >> 12) & 0xfff00))

Nice not to have leXX_to_cpu calls everywhere here.

--D

Quoted 17 lines
fs/rust-ext2/ext2.rs new file +2 -0
+    }
+}
rust/kernel/lib.rs +3 -0
index 445599d4bff6..732bc9939f7f 100644
@@ -165,3 +165,6 @@ macro_rules! container_of {
         ptr.wrapping_sub(offset) as *const $type
     }}
 }
+
+/// The size in bytes of a page of memory.
+pub const PAGE_SIZE: usize = bindings::PAGE_SIZE;
Signature · 1 line
2.34.1
#34 lore raw
In reply to Wedson Almeida Filho

Hi Wedson,

Quoted 36 lines · Wedson Almeida Filho

This series introduces Rust abstractions that allow read-only file systems to be written in Rust.

There are three file systems implementations using these abstractions
abstractions: ext2, tarfs, and puzzlefs. The first two are part of this series.

Rust file system modules can be declared with the module_fs macro and are required to implement the following functions (which are part of the FileSystem trait):

     fn fill_super(
         sb: &mut SuperBlock<Self, sb::New>,
         mapper: Option<inode::Mapper>,
     ) -> Result<Self::Data>;

     fn init_root(sb: &SuperBlock<Self>) -> Result<dentry::Root<Self>>;

They can optionally implement the following:

     fn read_xattr(
         _dentry: &DEntry<Self>,
         _inode: &INode<Self>,
         _name: &CStr,
         _outbuf: &mut [u8],
     ) -> Result<usize>;

     fn statfs(_dentry: &DEntry<Self>) -> Result<Stat>;

They may also choose the type of the data they can attach to superblocks and/or inodes.

Lastly, file systems can implement inode, file, and address space operations and attach them to inodes when they're created, similar to how C does it. They can get a ro address space operations table from an implementation of iomap operations, to be used with generic ro file operations.

Quoted 5 lines

A git tree is available here:
git://github.com/wedsonaf/linux.git vfs-v2

Web:
https://github.com/wedsonaf/linux/commits/vfs-v2

This branch indicates that this patch series might have a few more dependencies that are not upstream yet, e.g. [1].

Do you intend to send them in a separate series (soon)? In case they were already submitted somewhere and I just failed to find them, please be so kind an provide me with a pointer.

[1] https://github.com/wedsonaf/linux/commit/96ef0376887f4194ebad608f9943eb41108cf255

- Danilo

Quoted 111 lines

---

Changes in v2:

- Rebased to latest rust-next tree
- Removed buffer heads
- Added iomap support
- Removed _pin field from Registration as it's not needed anymore
- Renamed sample filesystem to match the module's name
- Using typestate instead of a separate type for superblock/new-superblock
- Created separate submodules for superblocks, inodes, dentries, and files
- Split out operations from FileSystem to inode/file/address_space ops, similar to how C does it
- Removed usages of folio_set_error
- Removed UniqueFolio, for now reading blocks from devices via the pagecache
- Changed map() to return the entire folio if not in highmem
- Added support for unlocking the folio asynchronously
- Added from_raw to all new ref-counted types
- Added explicit types in calls to cast()
- Added typestate to folio
- Added support for implementing get_link
- Fixed data race when reading inode->i_state
- Added nofs scope support during allocation
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/

---

Wedson Almeida Filho (30):
rust: fs: add registration/unregistration of file systems
rust: fs: introduce the module_fs macro
samples: rust: add initial ro file system sample
rust: fs: introduce FileSystem::fill_super
rust: fs: introduce INode<T>
rust: fs: introduce DEntry<T>
rust: fs: introduce FileSystem::init_root
rust: file: move kernel::file to kernel::fs::file
rust: fs: generalise File for different file systems
rust: fs: add empty file operations
rust: fs: introduce file::Operations::read_dir
rust: fs: introduce file::Operations::seek
rust: fs: introduce file::Operations::read
rust: fs: add empty inode operations
rust: fs: introduce inode::Operations::lookup
rust: folio: introduce basic support for folios
rust: fs: add empty address space operations
rust: fs: introduce address_space::Operations::read_folio
rust: fs: introduce FileSystem::read_xattr
rust: fs: introduce FileSystem::statfs
rust: fs: introduce more inode types
rust: fs: add per-superblock data
rust: fs: allow file systems backed by a block device
rust: fs: allow per-inode data
rust: fs: export file type from mode constants
rust: fs: allow populating i_lnk
rust: fs: add iomap module
rust: fs: add memalloc_nofs support
tarfs: introduce tar fs
WIP: fs: ext2: add rust ro ext2 implementation

  fs/Kconfig                        |   2 +
  fs/Makefile                       |   2 +
  fs/rust-ext2/Kconfig              |  13 +
  fs/rust-ext2/Makefile             |   8 +
  fs/rust-ext2/defs.rs              | 173 +++++++
  fs/rust-ext2/ext2.rs              | 551 +++++++++++++++++++++
  fs/tarfs/Kconfig                  |  15 +
  fs/tarfs/Makefile                 |   8 +
  fs/tarfs/defs.rs                  |  80 +++
  fs/tarfs/tar.rs                   | 394 +++++++++++++++
  rust/bindings/bindings_helper.h   |  11 +
  rust/helpers.c                    | 182 +++++++
  rust/kernel/block.rs              |  10 +-
  rust/kernel/error.rs              |   8 +-
  rust/kernel/file.rs               | 251 ----------
  rust/kernel/folio.rs              | 305 ++++++++++++
  rust/kernel/fs.rs                 | 492 +++++++++++++++++++
  rust/kernel/fs/address_space.rs   |  90 ++++
  rust/kernel/fs/dentry.rs          | 136 ++++++
  rust/kernel/fs/file.rs            | 607 +++++++++++++++++++++++
  rust/kernel/fs/inode.rs           | 780 ++++++++++++++++++++++++++++++
  rust/kernel/fs/iomap.rs           | 281 +++++++++++
  rust/kernel/fs/sb.rs              | 194 ++++++++
  rust/kernel/lib.rs                |   6 +-
  rust/kernel/mem_cache.rs          |   2 -
  rust/kernel/user.rs               |   1 -
  samples/rust/Kconfig              |  10 +
  samples/rust/Makefile             |   1 +
  samples/rust/rust_rofs.rs         | 202 ++++++++
  scripts/generate_rust_analyzer.py |   2 +-
  30 files changed, 4555 insertions(+), 262 deletions(-)

create mode 100644 fs/rust-ext2/Kconfig create mode 100644 fs/rust-ext2/Makefile create mode 100644 fs/rust-ext2/defs.rs create mode 100644 fs/rust-ext2/ext2.rs create mode 100644 fs/tarfs/Kconfig
create mode 100644 fs/tarfs/Makefile create mode 100644 fs/tarfs/defs.rs
create mode 100644 fs/tarfs/tar.rs
delete mode 100644 rust/kernel/file.rs create mode 100644 rust/kernel/folio.rs create mode 100644 rust/kernel/fs.rs create mode 100644 rust/kernel/fs/address_space.rs create mode 100644 rust/kernel/fs/dentry.rs create mode 100644 rust/kernel/fs/file.rs create mode 100644 rust/kernel/fs/inode.rs create mode 100644 rust/kernel/fs/iomap.rs create mode 100644 rust/kernel/fs/sb.rs create mode 100644 samples/rust/rust_rofs.rs

base-commit: 183ea65d1fcd71039cf4d111a22d69c337bfd344