linux-kernel.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v3 0/4] Rust support for `struct iov_iter`
@ 2025-07-22 12:33 Alice Ryhl
  2025-07-22 12:33 ` [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE Alice Ryhl
                   ` (3 more replies)
  0 siblings, 4 replies; 10+ messages in thread
From: Alice Ryhl @ 2025-07-22 12:33 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann, Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Trevor Gross, Danilo Krummrich, Matthew Maurer, Lee Jones,
	linux-kernel, rust-for-linux, Alice Ryhl, Benno Lossin,
	Christian Brauner

This series adds support for the `struct iov_iter` type. This type
represents an IO buffer for reading or writing, and can be configured
for either direction of communication.

In Rust, we define separate types for reading and writing. This will
ensure that you cannot mix them up and e.g. call copy_from_iter in a
read_iter syscall.

To use the new abstractions, miscdevices are given new methods read_iter
and write_iter that can be used to implement the read/write syscalls on
a miscdevice. The miscdevice sample is updated to provide read/write
operations.

Based on rust-next for this dependency:
https://lore.kernel.org/all/20250612-pointed-to-v3-0-b009006d86a1@kernel.org/

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
Changes in v3:
- Rebase on rust-next.
- Use ptr::from_mut to silence warning.
- Move Kiocb to rust::fs.
- Rename Kiocb::device() to Kiocb::file() as it's no longer miscdevice
  specific.
- Significant rewording of docs and safety comments, especially patch 1
  and 2.
- Link to v2: https://lore.kernel.org/r/20250704-iov-iter-v2-0-e69aa7c1f40e@google.com

Changes in v2:
- Remove Send/Sync/Copy impls.
- Reword docs significantly.
- Rename Kiocb::private_data() to Kiocb::device().
- Rebase on v6.16-rc2.
- Link to v1: https://lore.kernel.org/r/20250311-iov-iter-v1-0-f6c9134ea824@google.com

---
Alice Ryhl (3):
      rust: iov: add iov_iter abstractions for ITER_SOURCE
      rust: iov: add iov_iter abstractions for ITER_DEST
      rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures

Lee Jones (1):
      samples: rust_misc_device: Expand the sample to support read()ing from userspace

 rust/kernel/fs.rs                |   3 +
 rust/kernel/fs/kiocb.rs          |  67 +++++++++
 rust/kernel/iov.rs               | 310 +++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs               |   1 +
 rust/kernel/miscdevice.rs        |  63 +++++++-
 samples/rust/rust_misc_device.rs |  36 ++++-
 6 files changed, 477 insertions(+), 3 deletions(-)
---
base-commit: 07dad44aa9a93b16af19e8609a10b241c352b440
change-id: 20250311-iov-iter-c984aea07d18

Best regards,
-- 
Alice Ryhl <aliceryhl@google.com>


^ permalink raw reply	[flat|nested] 10+ messages in thread

* [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
  2025-07-22 12:33 [PATCH v3 0/4] Rust support for `struct iov_iter` Alice Ryhl
@ 2025-07-22 12:33 ` Alice Ryhl
  2025-08-05 11:17   ` Andreas Hindborg
  2025-07-22 12:33 ` [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST Alice Ryhl
                   ` (2 subsequent siblings)
  3 siblings, 1 reply; 10+ messages in thread
From: Alice Ryhl @ 2025-07-22 12:33 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann, Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Trevor Gross, Danilo Krummrich, Matthew Maurer, Lee Jones,
	linux-kernel, rust-for-linux, Alice Ryhl, Benno Lossin

This adds abstractions for the iov_iter type in the case where
data_source is ITER_SOURCE. This will make Rust implementations of
fops->write_iter possible.

This series only has support for using existing IO vectors created by C
code. Additional abstractions will be needed to support the creation of
IO vectors in Rust code.

These abstractions make the assumption that `struct iov_iter` does not
have internal self-references, which implies that it is valid to move it
between different local variables.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/kernel/iov.rs | 167 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs |   1 +
 2 files changed, 168 insertions(+)

diff --git a/rust/kernel/iov.rs b/rust/kernel/iov.rs
new file mode 100644
index 0000000000000000000000000000000000000000..a92fa22c856a506f836a15c74a29e82dc90a4721
--- /dev/null
+++ b/rust/kernel/iov.rs
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: GPL-2.0
+
+// Copyright (C) 2025 Google LLC.
+
+//! IO vectors.
+//!
+//! C headers: [`include/linux/iov_iter.h`](srctree/include/linux/iov_iter.h),
+//! [`include/linux/uio.h`](srctree/include/linux/uio.h)
+
+use crate::{
+    alloc::{Allocator, Flags},
+    bindings,
+    prelude::*,
+    types::Opaque,
+};
+use core::{marker::PhantomData, mem::MaybeUninit, ptr, slice};
+
+const ITER_SOURCE: bool = bindings::ITER_SOURCE != 0;
+
+/// An IO vector that acts as a source of data.
+///
+/// The data may come from many different sources. This includes both things in kernel-space and
+/// reading from userspace. It's not necessarily the case that the data source is immutable, so
+/// rewinding the IO vector to read the same data twice is not guaranteed to result in the same
+/// bytes. It's also possible that the data source is mapped in a thread-local manner using e.g.
+/// `kmap_local_page()`, so this type is not `Send` to ensure that the mapping is read from the
+/// right context in that scenario.
+///
+/// # Invariants
+///
+/// Must hold a valid `struct iov_iter` with `data_source` set to `ITER_SOURCE`. For the duration
+/// of `'data`, it must be safe to read from this IO vector using the standard C methods for this
+/// purpose.
+#[repr(transparent)]
+pub struct IovIterSource<'data> {
+    iov: Opaque<bindings::iov_iter>,
+    /// Represent to the type system that this value contains a pointer to readable data it does
+    /// not own.
+    _source: PhantomData<&'data [u8]>,
+}
+
+impl<'data> IovIterSource<'data> {
+    /// Obtain an `IovIterSource` from a raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// * The referenced `struct iov_iter` must be valid and must only be accessed through the
+    ///   returned reference for the duration of `'iov`.
+    /// * The referenced `struct iov_iter` must have `data_source` set to `ITER_SOURCE`.
+    /// * For the duration of `'data`, it must be safe to read from this IO vector using the
+    ///   standard C methods for this purpose.
+    #[track_caller]
+    #[inline]
+    pub unsafe fn from_raw<'iov>(ptr: *mut bindings::iov_iter) -> &'iov mut IovIterSource<'data> {
+        // SAFETY: The caller ensures that `ptr` is valid.
+        let data_source = unsafe { (*ptr).data_source };
+        assert_eq!(data_source, ITER_SOURCE);
+
+        // SAFETY: The caller ensures the struct invariants for the right durations, and
+        // `IovIterSource` is layout compatible with `struct iov_iter`.
+        unsafe { &mut *ptr.cast::<IovIterSource<'data>>() }
+    }
+
+    /// Access this as a raw `struct iov_iter`.
+    #[inline]
+    pub fn as_raw(&mut self) -> *mut bindings::iov_iter {
+        self.iov.get()
+    }
+
+    /// Returns the number of bytes available in this IO vector.
+    ///
+    /// Note that this may overestimate the number of bytes. For example, reading from userspace
+    /// memory could fail with `EFAULT`, which will be treated as the end of the IO vector.
+    #[inline]
+    pub fn len(&self) -> usize {
+        // SAFETY: We have shared access to this IO vector, so we can read its `count` field.
+        unsafe {
+            (*self.iov.get())
+                .__bindgen_anon_1
+                .__bindgen_anon_1
+                .as_ref()
+                .count
+        }
+    }
+
+    /// Returns whether there are any bytes left in this IO vector.
+    ///
+    /// This may return `true` even if there are no more bytes available. For example, reading from
+    /// userspace memory could fail with `EFAULT`, which will be treated as the end of the IO vector.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    /// Advance this IO vector by `bytes` bytes.
+    ///
+    /// If `bytes` is larger than the size of this IO vector, it is advanced to the end.
+    #[inline]
+    pub fn advance(&mut self, bytes: usize) {
+        // SAFETY: By the struct invariants, `self.iov` is a valid IO vector.
+        unsafe { bindings::iov_iter_advance(self.as_raw(), bytes) };
+    }
+
+    /// Advance this IO vector backwards by `bytes` bytes.
+    ///
+    /// # Safety
+    ///
+    /// The IO vector must not be reverted to before its beginning.
+    #[inline]
+    pub unsafe fn revert(&mut self, bytes: usize) {
+        // SAFETY: By the struct invariants, `self.iov` is a valid IO vector, and `bytes` is in
+        // bounds.
+        unsafe { bindings::iov_iter_revert(self.as_raw(), bytes) };
+    }
+
+    /// Read data from this IO vector.
+    ///
+    /// Returns the number of bytes that have been copied.
+    #[inline]
+    pub fn copy_from_iter(&mut self, out: &mut [u8]) -> usize {
+        // SAFETY: `Self::copy_from_iter_raw` guarantees that it will not deinitialize any bytes in
+        // the provided buffer, so `out` is still a valid `u8` slice after this call.
+        let out = unsafe { &mut *(ptr::from_mut(out) as *mut [MaybeUninit<u8>]) };
+
+        self.copy_from_iter_raw(out).len()
+    }
+
+    /// Read data from this IO vector and append it to a vector.
+    ///
+    /// Returns the number of bytes that have been copied.
+    #[inline]
+    pub fn copy_from_iter_vec<A: Allocator>(
+        &mut self,
+        out: &mut Vec<u8, A>,
+        flags: Flags,
+    ) -> Result<usize> {
+        out.reserve(self.len(), flags)?;
+        let len = self.copy_from_iter_raw(out.spare_capacity_mut()).len();
+        // SAFETY: `Self::copy_from_iter_raw` guarantees that the first `len` bytes of the spare
+        // capacity have been initialized.
+        unsafe { out.inc_len(len) };
+        Ok(len)
+    }
+
+    /// Read data from this IO vector into potentially uninitialized memory.
+    ///
+    /// Returns the sub-slice of the output that has been initialized. If the returned slice is
+    /// shorter than the input buffer, then the entire IO vector has been read.
+    ///
+    /// This will never deinitialize any bytes in the provided buffer.
+    #[inline]
+    pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] {
+        let capacity = out.len();
+        let out = out.as_mut_ptr().cast::<u8>();
+
+        // GUARANTEES: The C API guarantees that it does not deinitialize the provided buffer.
+        // SAFETY:
+        // * By the struct invariants, it is still valid to read from this IO vector.
+        // * `out` is valid for writing for `capacity` bytes because it comes from a slice of
+        //   that length.
+        let len = unsafe { bindings::_copy_from_iter(out.cast(), capacity, self.as_raw()) };
+
+        // SAFETY: The underlying C api guarantees that initialized bytes have been written to the
+        // first `len` bytes of the spare capacity.
+        unsafe { slice::from_raw_parts_mut(out, len) }
+    }
+}
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index e88bc4b27d6e367f0296381c8d6b22de21d69f54..8ee29bd340027be855bcab9c3b315fa2b89ca9f3 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -83,6 +83,7 @@
 pub mod init;
 pub mod io;
 pub mod ioctl;
+pub mod iov;
 pub mod jump_label;
 #[cfg(CONFIG_KUNIT)]
 pub mod kunit;

-- 
2.50.0.727.gbf7dc18ff4-goog


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
  2025-07-22 12:33 [PATCH v3 0/4] Rust support for `struct iov_iter` Alice Ryhl
  2025-07-22 12:33 ` [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE Alice Ryhl
@ 2025-07-22 12:33 ` Alice Ryhl
  2025-08-05 11:31   ` Andreas Hindborg
  2025-07-22 12:33 ` [PATCH v3 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures Alice Ryhl
  2025-07-22 12:33 ` [PATCH v3 4/4] samples: rust_misc_device: Expand the sample to support read()ing from userspace Alice Ryhl
  3 siblings, 1 reply; 10+ messages in thread
From: Alice Ryhl @ 2025-07-22 12:33 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann, Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Trevor Gross, Danilo Krummrich, Matthew Maurer, Lee Jones,
	linux-kernel, rust-for-linux, Alice Ryhl, Benno Lossin

This adds abstractions for the iov_iter type in the case where
data_source is ITER_DEST. This will make Rust implementations of
fops->read_iter possible.

This series only has support for using existing IO vectors created by C
code. Additional abstractions will be needed to support the creation of
IO vectors in Rust code.

These abstractions make the assumption that `struct iov_iter` does not
have internal self-references, which implies that it is valid to move it
between different local variables.

This patch adds an IovIterDest struct that is very similar to the
IovIterSource from the previous patch. However, as the methods on the
two structs have very little overlap (just getting the length and
advance/revert), I do not think it is worth it to try and deduplicate
this logic.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/kernel/iov.rs | 143 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 143 insertions(+)

diff --git a/rust/kernel/iov.rs b/rust/kernel/iov.rs
index a92fa22c856a506f836a15c74a29e82dc90a4721..e31a7947677c0603764648c06418697b2be2af18 100644
--- a/rust/kernel/iov.rs
+++ b/rust/kernel/iov.rs
@@ -16,6 +16,15 @@
 use core::{marker::PhantomData, mem::MaybeUninit, ptr, slice};
 
 const ITER_SOURCE: bool = bindings::ITER_SOURCE != 0;
+const ITER_DEST: bool = bindings::ITER_DEST != 0;
+
+// Compile-time assertion for the above constants.
+const _: () = {
+    build_assert!(
+        ITER_SOURCE != ITER_DEST,
+        "ITER_DEST and ITER_SOURCE should be different."
+    );
+};
 
 /// An IO vector that acts as a source of data.
 ///
@@ -165,3 +174,137 @@ pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] {
         unsafe { slice::from_raw_parts_mut(out, len) }
     }
 }
+
+/// An IO vector that acts as a destination for data.
+///
+/// IO vectors support many different types of destinations. This includes both buffers in
+/// kernel-space and writing to userspace. It's possible that the destination buffer is mapped in a
+/// thread-local manner using e.g. `kmap_local_page()`, so this type is not `Send` to ensure that
+/// the mapping is written to the right context in that scenario.
+///
+/// # Invariants
+///
+/// Must hold a valid `struct iov_iter` with `data_source` set to `ITER_DEST`. For the duration of
+/// `'data`, it must be safe to write to this IO vector using the standard C methods for this
+/// purpose.
+#[repr(transparent)]
+pub struct IovIterDest<'data> {
+    iov: Opaque<bindings::iov_iter>,
+    /// Represent to the type system that this value contains a pointer to writable data it does
+    /// not own.
+    _source: PhantomData<&'data mut [u8]>,
+}
+
+impl<'data> IovIterDest<'data> {
+    /// Obtain an `IovIterDest` from a raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// * The referenced `struct iov_iter` must be valid and must only be accessed through the
+    ///   returned reference for the duration of `'iov`.
+    /// * The referenced `struct iov_iter` must have `data_source` set to `ITER_DEST`.
+    /// * For the duration of `'data`, it must be safe to write to this IO vector using the
+    ///   standard C methods for this purpose.
+    #[track_caller]
+    #[inline]
+    pub unsafe fn from_raw<'iov>(ptr: *mut bindings::iov_iter) -> &'iov mut IovIterDest<'data> {
+        // SAFETY: The caller ensures that `ptr` is valid.
+        let data_source = unsafe { (*ptr).data_source };
+        assert_eq!(data_source, ITER_DEST);
+
+        // SAFETY: The caller ensures the struct invariants for the right durations, and
+        // `IovIterSource` is layout compatible with `struct iov_iter`.
+        unsafe { &mut *ptr.cast::<IovIterDest<'data>>() }
+    }
+
+    /// Access this as a raw `struct iov_iter`.
+    #[inline]
+    pub fn as_raw(&mut self) -> *mut bindings::iov_iter {
+        self.iov.get()
+    }
+
+    /// Returns the number of bytes available in this IO vector.
+    ///
+    /// Note that this may overestimate the number of bytes. For example, reading from userspace
+    /// memory could fail with EFAULT, which will be treated as the end of the IO vector.
+    #[inline]
+    pub fn len(&self) -> usize {
+        // SAFETY: We have shared access to this IO vector, so we can read its `count` field.
+        unsafe {
+            (*self.iov.get())
+                .__bindgen_anon_1
+                .__bindgen_anon_1
+                .as_ref()
+                .count
+        }
+    }
+
+    /// Returns whether there are any bytes left in this IO vector.
+    ///
+    /// This may return `true` even if there are no more bytes available. For example, reading from
+    /// userspace memory could fail with EFAULT, which will be treated as the end of the IO vector.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    /// Advance this IO vector by `bytes` bytes.
+    ///
+    /// If `bytes` is larger than the size of this IO vector, it is advanced to the end.
+    #[inline]
+    pub fn advance(&mut self, bytes: usize) {
+        // SAFETY: By the struct invariants, `self.iov` is a valid IO vector.
+        unsafe { bindings::iov_iter_advance(self.as_raw(), bytes) };
+    }
+
+    /// Advance this IO vector backwards by `bytes` bytes.
+    ///
+    /// # Safety
+    ///
+    /// The IO vector must not be reverted to before its beginning.
+    #[inline]
+    pub unsafe fn revert(&mut self, bytes: usize) {
+        // SAFETY: By the struct invariants, `self.iov` is a valid IO vector, and `bytes` is in
+        // bounds.
+        unsafe { bindings::iov_iter_revert(self.as_raw(), bytes) };
+    }
+
+    /// Write data to this IO vector.
+    ///
+    /// Returns the number of bytes that were written. If this is shorter than the provided slice,
+    /// then no more bytes can be written.
+    #[inline]
+    pub fn copy_to_iter(&mut self, input: &[u8]) -> usize {
+        // SAFETY:
+        // * By the struct invariants, it is still valid to write to this IO vector.
+        // * `input` is valid for `input.len()` bytes.
+        unsafe { bindings::_copy_to_iter(input.as_ptr().cast(), input.len(), self.as_raw()) }
+    }
+
+    /// Utility for implementing `read_iter` given the full contents of the file.
+    ///
+    /// The full contents of the file being read from is represented by `contents`. This call will
+    /// write the appropriate sub-slice of `contents` and update the file position in `ppos` so
+    /// that the file will appear to contain `contents` even if takes multiple reads to read the
+    /// entire file.
+    #[inline]
+    pub fn simple_read_from_buffer(&mut self, ppos: &mut i64, contents: &[u8]) -> Result<usize> {
+        if *ppos < 0 {
+            return Err(EINVAL);
+        }
+        let Ok(pos) = usize::try_from(*ppos) else {
+            return Ok(0);
+        };
+        if pos >= contents.len() {
+            return Ok(0);
+        }
+
+        // BOUNDS: We just checked that `pos < contents.len()` above.
+        let num_written = self.copy_to_iter(&contents[pos..]);
+
+        // OVERFLOW: `pos+num_written <= contents.len() <= isize::MAX <= i64::MAX`.
+        *ppos = (pos + num_written) as i64;
+
+        Ok(num_written)
+    }
+}

-- 
2.50.0.727.gbf7dc18ff4-goog


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v3 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures
  2025-07-22 12:33 [PATCH v3 0/4] Rust support for `struct iov_iter` Alice Ryhl
  2025-07-22 12:33 ` [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE Alice Ryhl
  2025-07-22 12:33 ` [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST Alice Ryhl
@ 2025-07-22 12:33 ` Alice Ryhl
  2025-08-05 12:10   ` Andreas Hindborg
  2025-07-22 12:33 ` [PATCH v3 4/4] samples: rust_misc_device: Expand the sample to support read()ing from userspace Alice Ryhl
  3 siblings, 1 reply; 10+ messages in thread
From: Alice Ryhl @ 2025-07-22 12:33 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann, Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Trevor Gross, Danilo Krummrich, Matthew Maurer, Lee Jones,
	linux-kernel, rust-for-linux, Alice Ryhl, Benno Lossin,
	Christian Brauner

These will be used for the read_iter() and write_iter() callbacks, which
are now the preferred back-ends for when a user operates on a char device
with read() and write() respectively.

Cc: Christian Brauner <brauner@kernel.org>
Co-developed-by: Lee Jones <lee@kernel.org>
Signed-off-by: Lee Jones <lee@kernel.org>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/kernel/fs.rs         |  3 +++
 rust/kernel/fs/kiocb.rs   | 67 +++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/miscdevice.rs | 63 +++++++++++++++++++++++++++++++++++++++++++-
 3 files changed, 132 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/fs.rs b/rust/kernel/fs.rs
index 0121b38c59e63d01a89f22c8ef6983ef5c3234de..6ba6bdf143cb991c6e78215178eb585260215da0 100644
--- a/rust/kernel/fs.rs
+++ b/rust/kernel/fs.rs
@@ -6,3 +6,6 @@
 
 pub mod file;
 pub use self::file::{File, LocalFile};
+
+mod kiocb;
+pub use self::kiocb::Kiocb;
diff --git a/rust/kernel/fs/kiocb.rs b/rust/kernel/fs/kiocb.rs
new file mode 100644
index 0000000000000000000000000000000000000000..837f4be7cb8fbca6e3f9aeff74d1c904df3ff7ff
--- /dev/null
+++ b/rust/kernel/fs/kiocb.rs
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: GPL-2.0
+
+// Copyright (C) 2024 Google LLC.
+
+//! Kernel IO callbacks.
+//!
+//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
+
+use core::marker::PhantomData;
+use core::ptr::NonNull;
+use kernel::types::ForeignOwnable;
+
+/// Wrapper for the kernel's `struct kiocb`.
+///
+/// Currently this abstractions is incomplete and is essentially just a tuple containing a
+/// reference to a file and a file position.
+///
+/// The type `T` represents the private data of the underlying file.
+///
+/// # Invariants
+///
+/// `inner` points at a valid `struct kiocb` whose file has the type `T` as its private data.
+pub struct Kiocb<'a, T> {
+    inner: NonNull<bindings::kiocb>,
+    _phantom: PhantomData<&'a T>,
+}
+
+impl<'a, T: ForeignOwnable> Kiocb<'a, T> {
+    /// Create a `Kiocb` from a raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// The pointer must reference a valid `struct kiocb` for the duration of `'a`. The private
+    /// data of the file must be `T`.
+    pub unsafe fn from_raw(kiocb: *mut bindings::kiocb) -> Self {
+        Self {
+            // SAFETY: If a pointer is valid it is not null.
+            inner: unsafe { NonNull::new_unchecked(kiocb) },
+            _phantom: PhantomData,
+        }
+    }
+
+    /// Access the underlying `struct kiocb` directly.
+    pub fn as_raw(&self) -> *mut bindings::kiocb {
+        self.inner.as_ptr()
+    }
+
+    /// Get the Rust data stored in the private data of the file.
+    pub fn file(&self) -> <T as ForeignOwnable>::Borrowed<'a> {
+        // SAFETY: The `kiocb` lets us access the private data.
+        let private = unsafe { (*(*self.as_raw()).ki_filp).private_data };
+        // SAFETY: The kiocb has shared access to the private data.
+        unsafe { <T as ForeignOwnable>::borrow(private) }
+    }
+
+    /// Gets the current value of `ki_pos`.
+    pub fn ki_pos(&self) -> i64 {
+        // SAFETY: The `kiocb` can access `ki_pos`.
+        unsafe { (*self.as_raw()).ki_pos }
+    }
+
+    /// Gets a mutable reference to the `ki_pos` field.
+    pub fn ki_pos_mut(&mut self) -> &mut i64 {
+        // SAFETY: The `kiocb` can access `ki_pos`.
+        unsafe { &mut (*self.as_raw()).ki_pos }
+    }
+}
diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs
index ad51ffc549b85da9b71ed866bf0afd4c4cb76f07..eaa626277cc39d84761a2228f5aee05640323094 100644
--- a/rust/kernel/miscdevice.rs
+++ b/rust/kernel/miscdevice.rs
@@ -13,7 +13,8 @@
     device::Device,
     error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR},
     ffi::{c_int, c_long, c_uint, c_ulong},
-    fs::File,
+    fs::{File, Kiocb},
+    iov::{IovIterDest, IovIterSource},
     mm::virt::VmaNew,
     prelude::*,
     seq_file::SeqFile,
@@ -136,6 +137,16 @@ fn mmap(
         build_error!(VTABLE_DEFAULT_ERROR)
     }
 
+    /// Read from this miscdevice.
+    fn read_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterDest<'_>) -> Result<usize> {
+        build_error!(VTABLE_DEFAULT_ERROR)
+    }
+
+    /// Write to this miscdevice.
+    fn write_iter(_kiocb: Kiocb<'_, Self::Ptr>, _iov: &mut IovIterSource<'_>) -> Result<usize> {
+        build_error!(VTABLE_DEFAULT_ERROR)
+    }
+
     /// Handler for ioctls.
     ///
     /// The `cmd` argument is usually manipulated using the utilities in [`kernel::ioctl`].
@@ -240,6 +251,46 @@ impl<T: MiscDevice> MiscdeviceVTable<T> {
         0
     }
 
+    /// # Safety
+    ///
+    /// `kiocb` must be correspond to a valid file that is associated with a
+    /// `MiscDeviceRegistration<T>`. `iter` must be a valid `struct iov_iter` for writing.
+    unsafe extern "C" fn read_iter(
+        kiocb: *mut bindings::kiocb,
+        iter: *mut bindings::iov_iter,
+    ) -> isize {
+        // SAFETY: The caller provides a valid `struct kiocb` associated with a
+        // `MiscDeviceRegistration<T>` file.
+        let kiocb = unsafe { Kiocb::from_raw(kiocb) };
+        // SAFETY: This is a valid `struct iov_iter` for writing.
+        let iov = unsafe { IovIterDest::from_raw(iter) };
+
+        match T::read_iter(kiocb, iov) {
+            Ok(res) => res as isize,
+            Err(err) => err.to_errno() as isize,
+        }
+    }
+
+    /// # Safety
+    ///
+    /// `kiocb` must be correspond to a valid file that is associated with a
+    /// `MiscDeviceRegistration<T>`. `iter` must be a valid `struct iov_iter` for writing.
+    unsafe extern "C" fn write_iter(
+        kiocb: *mut bindings::kiocb,
+        iter: *mut bindings::iov_iter,
+    ) -> isize {
+        // SAFETY: The caller provides a valid `struct kiocb` associated with a
+        // `MiscDeviceRegistration<T>` file.
+        let kiocb = unsafe { Kiocb::from_raw(kiocb) };
+        // SAFETY: This is a valid `struct iov_iter` for reading.
+        let iov = unsafe { IovIterSource::from_raw(iter) };
+
+        match T::write_iter(kiocb, iov) {
+            Ok(res) => res as isize,
+            Err(err) => err.to_errno() as isize,
+        }
+    }
+
     /// # Safety
     ///
     /// `file` must be a valid file that is associated with a `MiscDeviceRegistration<T>`.
@@ -336,6 +387,16 @@ impl<T: MiscDevice> MiscdeviceVTable<T> {
         open: Some(Self::open),
         release: Some(Self::release),
         mmap: if T::HAS_MMAP { Some(Self::mmap) } else { None },
+        read_iter: if T::HAS_READ_ITER {
+            Some(Self::read_iter)
+        } else {
+            None
+        },
+        write_iter: if T::HAS_WRITE_ITER {
+            Some(Self::write_iter)
+        } else {
+            None
+        },
         unlocked_ioctl: if T::HAS_IOCTL {
             Some(Self::ioctl)
         } else {

-- 
2.50.0.727.gbf7dc18ff4-goog


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH v3 4/4] samples: rust_misc_device: Expand the sample to support read()ing from userspace
  2025-07-22 12:33 [PATCH v3 0/4] Rust support for `struct iov_iter` Alice Ryhl
                   ` (2 preceding siblings ...)
  2025-07-22 12:33 ` [PATCH v3 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures Alice Ryhl
@ 2025-07-22 12:33 ` Alice Ryhl
  3 siblings, 0 replies; 10+ messages in thread
From: Alice Ryhl @ 2025-07-22 12:33 UTC (permalink / raw)
  To: Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann, Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Trevor Gross, Danilo Krummrich, Matthew Maurer, Lee Jones,
	linux-kernel, rust-for-linux, Alice Ryhl, Benno Lossin

From: Lee Jones <lee@kernel.org>

A userland application can now operate on the char device with read() in
order to consume a locally held buffer.  Memory for the buffer is to be
provisioned and the buffer populated in its subsequently provided
write() counterpart.

Signed-off-by: Lee Jones <lee@kernel.org>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 samples/rust/rust_misc_device.rs | 36 ++++++++++++++++++++++++++++++++++--
 1 file changed, 34 insertions(+), 2 deletions(-)

diff --git a/samples/rust/rust_misc_device.rs b/samples/rust/rust_misc_device.rs
index e7ab77448f754906615b6f89d72b51fa268f6c41..9e4005e337969af764e57a937ae5481d7710cfc9 100644
--- a/samples/rust/rust_misc_device.rs
+++ b/samples/rust/rust_misc_device.rs
@@ -100,8 +100,9 @@
 use kernel::{
     c_str,
     device::Device,
-    fs::File,
+    fs::{File, Kiocb},
     ioctl::{_IO, _IOC_SIZE, _IOR, _IOW},
+    iov::{IovIterDest, IovIterSource},
     miscdevice::{MiscDevice, MiscDeviceOptions, MiscDeviceRegistration},
     new_mutex,
     prelude::*,
@@ -144,6 +145,7 @@ fn init(_module: &'static ThisModule) -> impl PinInit<Self, Error> {
 
 struct Inner {
     value: i32,
+    buffer: KVVec<u8>,
 }
 
 #[pin_data(PinnedDrop)]
@@ -165,7 +167,10 @@ fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Se
         KBox::try_pin_init(
             try_pin_init! {
                 RustMiscDevice {
-                    inner <- new_mutex!( Inner{ value: 0_i32 } ),
+                    inner <- new_mutex!(Inner {
+                        value: 0_i32,
+                        buffer: KVVec::new(),
+                    }),
                     dev: dev,
                 }
             },
@@ -173,6 +178,33 @@ fn open(_file: &File, misc: &MiscDeviceRegistration<Self>) -> Result<Pin<KBox<Se
         )
     }
 
+    fn read_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterDest<'_>) -> Result<usize> {
+        let me = kiocb.file();
+        dev_info!(me.dev, "Reading from Rust Misc Device Sample\n");
+
+        let inner = me.inner.lock();
+        // Read the buffer contents, taking the file position into account.
+        let read = iov.simple_read_from_buffer(kiocb.ki_pos_mut(), &inner.buffer)?;
+
+        Ok(read)
+    }
+
+    fn write_iter(mut kiocb: Kiocb<'_, Self::Ptr>, iov: &mut IovIterSource<'_>) -> Result<usize> {
+        let me = kiocb.file();
+        dev_info!(me.dev, "Writing to Rust Misc Device Sample\n");
+
+        let mut inner = me.inner.lock();
+
+        // Replace buffer contents.
+        inner.buffer.clear();
+        let len = iov.copy_from_iter_vec(&mut inner.buffer, GFP_KERNEL)?;
+
+        // Set position to zero so that future `read` calls will see the new contents.
+        *kiocb.ki_pos_mut() = 0;
+
+        Ok(len)
+    }
+
     fn ioctl(me: Pin<&RustMiscDevice>, _file: &File, cmd: u32, arg: usize) -> Result<isize> {
         dev_info!(me.dev, "IOCTLing Rust Misc Device Sample\n");
 

-- 
2.50.0.727.gbf7dc18ff4-goog


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* Re: [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
  2025-07-22 12:33 ` [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE Alice Ryhl
@ 2025-08-05 11:17   ` Andreas Hindborg
  2025-08-13  8:24     ` Alice Ryhl
  0 siblings, 1 reply; 10+ messages in thread
From: Andreas Hindborg @ 2025-08-05 11:17 UTC (permalink / raw)
  To: Alice Ryhl, Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann,
	Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Trevor Gross,
	Danilo Krummrich, Matthew Maurer, Lee Jones, linux-kernel,
	rust-for-linux, Alice Ryhl, Benno Lossin

"Alice Ryhl" <aliceryhl@google.com> writes:

> This adds abstractions for the iov_iter type in the case where
> data_source is ITER_SOURCE. This will make Rust implementations of
> fops->write_iter possible.
>
> This series only has support for using existing IO vectors created by C
> code. Additional abstractions will be needed to support the creation of
> IO vectors in Rust code.
>
> These abstractions make the assumption that `struct iov_iter` does not
> have internal self-references, which implies that it is valid to move it
> between different local variables.
>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---

..

> +
> +    /// Advance this IO vector backwards by `bytes` bytes.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The IO vector must not be reverted to before its beginning.
> +    #[inline]
> +    pub unsafe fn revert(&mut self, bytes: usize) {
> +        // SAFETY: By the struct invariants, `self.iov` is a valid IO vector, and `bytes` is in
> +        // bounds.

"... and by method safety requirements `bytes` is in bounds", right?

> +        unsafe { bindings::iov_iter_revert(self.as_raw(), bytes) };
> +    }
> +
> +    /// Read data from this IO vector.
> +    ///
> +    /// Returns the number of bytes that have been copied.
> +    #[inline]
> +    pub fn copy_from_iter(&mut self, out: &mut [u8]) -> usize {
> +        // SAFETY: `Self::copy_from_iter_raw` guarantees that it will not deinitialize any bytes in
> +        // the provided buffer, so `out` is still a valid `u8` slice after this call.

I am curious if there is a particular reason you chose "deinitialize"
over "write uninitialized" for the wording throughout this patch? It's
an unfamiliar phrasing to me.


Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>


Best regards,
Andreas Hindborg




^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
  2025-07-22 12:33 ` [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST Alice Ryhl
@ 2025-08-05 11:31   ` Andreas Hindborg
  2025-08-13  8:25     ` Alice Ryhl
  0 siblings, 1 reply; 10+ messages in thread
From: Andreas Hindborg @ 2025-08-05 11:31 UTC (permalink / raw)
  To: Alice Ryhl, Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann,
	Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Trevor Gross,
	Danilo Krummrich, Matthew Maurer, Lee Jones, linux-kernel,
	rust-for-linux, Alice Ryhl, Benno Lossin

"Alice Ryhl" <aliceryhl@google.com> writes:

> This adds abstractions for the iov_iter type in the case where
> data_source is ITER_DEST. This will make Rust implementations of
> fops->read_iter possible.
>
> This series only has support for using existing IO vectors created by C
> code. Additional abstractions will be needed to support the creation of
> IO vectors in Rust code.
>
> These abstractions make the assumption that `struct iov_iter` does not
> have internal self-references, which implies that it is valid to move it
> between different local variables.
>
> This patch adds an IovIterDest struct that is very similar to the
> IovIterSource from the previous patch. However, as the methods on the
> two structs have very little overlap (just getting the length and
> advance/revert), I do not think it is worth it to try and deduplicate
> this logic.

Is it not like 50% duplication? `as_raw`, `len`, `is_empty`, `advance`,
`revert`. It looks like it makes sense to me, but 🤷 We can always do it
later.

Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>


Best regards,
Andreas Hindborg



^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [PATCH v3 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures
  2025-07-22 12:33 ` [PATCH v3 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures Alice Ryhl
@ 2025-08-05 12:10   ` Andreas Hindborg
  0 siblings, 0 replies; 10+ messages in thread
From: Andreas Hindborg @ 2025-08-05 12:10 UTC (permalink / raw)
  To: Alice Ryhl, Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann,
	Miguel Ojeda
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Trevor Gross,
	Danilo Krummrich, Matthew Maurer, Lee Jones, linux-kernel,
	rust-for-linux, Alice Ryhl, Benno Lossin, Christian Brauner

"Alice Ryhl" <aliceryhl@google.com> writes:

> These will be used for the read_iter() and write_iter() callbacks, which
> are now the preferred back-ends for when a user operates on a char device
> with read() and write() respectively.
>
> Cc: Christian Brauner <brauner@kernel.org>
> Co-developed-by: Lee Jones <lee@kernel.org>
> Signed-off-by: Lee Jones <lee@kernel.org>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
>  rust/kernel/fs.rs         |  3 +++
>  rust/kernel/fs/kiocb.rs   | 67 +++++++++++++++++++++++++++++++++++++++++++++++
>  rust/kernel/miscdevice.rs | 63 +++++++++++++++++++++++++++++++++++++++++++-
>  3 files changed, 132 insertions(+), 1 deletion(-)
>
> diff --git a/rust/kernel/fs.rs b/rust/kernel/fs.rs
> index 0121b38c59e63d01a89f22c8ef6983ef5c3234de..6ba6bdf143cb991c6e78215178eb585260215da0 100644
> --- a/rust/kernel/fs.rs
> +++ b/rust/kernel/fs.rs
> @@ -6,3 +6,6 @@
>
>  pub mod file;
>  pub use self::file::{File, LocalFile};
> +
> +mod kiocb;
> +pub use self::kiocb::Kiocb;
> diff --git a/rust/kernel/fs/kiocb.rs b/rust/kernel/fs/kiocb.rs
> new file mode 100644
> index 0000000000000000000000000000000000000000..837f4be7cb8fbca6e3f9aeff74d1c904df3ff7ff
> --- /dev/null
> +++ b/rust/kernel/fs/kiocb.rs
> @@ -0,0 +1,67 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +// Copyright (C) 2024 Google LLC.
> +
> +//! Kernel IO callbacks.
> +//!
> +//! C headers: [`include/linux/fs.h`](srctree/include/linux/fs.h)
> +
> +use core::marker::PhantomData;
> +use core::ptr::NonNull;
> +use kernel::types::ForeignOwnable;
> +
> +/// Wrapper for the kernel's `struct kiocb`.
> +///
> +/// Currently this abstractions is incomplete and is essentially just a tuple containing a
> +/// reference to a file and a file position.
> +///
> +/// The type `T` represents the private data of the underlying file.

In my opinion, this paragraph could use some clarification:

  The type `T` represents the filesystem or driver specific data
  associated with the file.

> +///
> +/// # Invariants
> +///
> +/// `inner` points at a valid `struct kiocb` whose file has the type `T` as its private data.
> +pub struct Kiocb<'a, T> {
> +    inner: NonNull<bindings::kiocb>,
> +    _phantom: PhantomData<&'a T>,
> +}
> +
> +impl<'a, T: ForeignOwnable> Kiocb<'a, T> {
> +    /// Create a `Kiocb` from a raw pointer.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The pointer must reference a valid `struct kiocb` for the duration of `'a`. The private
> +    /// data of the file must be `T`.
> +    pub unsafe fn from_raw(kiocb: *mut bindings::kiocb) -> Self {
> +        Self {
> +            // SAFETY: If a pointer is valid it is not null.
> +            inner: unsafe { NonNull::new_unchecked(kiocb) },
> +            _phantom: PhantomData,
> +        }
> +    }
> +
> +    /// Access the underlying `struct kiocb` directly.
> +    pub fn as_raw(&self) -> *mut bindings::kiocb {
> +        self.inner.as_ptr()
> +    }
> +
> +    /// Get the Rust data stored in the private data of the file.

I would suggest:

  Get the filesystem or driver specific data associated with the file.

> +    pub fn file(&self) -> <T as ForeignOwnable>::Borrowed<'a> {
> +        // SAFETY: The `kiocb` lets us access the private data.

This safety comment is strange. I like what you did in patch 1:

++        // SAFETY: We have shared access to this IO vector, so we can read its `count` field.

> +        let private = unsafe { (*(*self.as_raw()).ki_filp).private_data };
> +        // SAFETY: The kiocb has shared access to the private data.
> +        unsafe { <T as ForeignOwnable>::borrow(private) }
> +    }
> +
> +    /// Gets the current value of `ki_pos`.
> +    pub fn ki_pos(&self) -> i64 {
> +        // SAFETY: The `kiocb` can access `ki_pos`.

Same.

> +        unsafe { (*self.as_raw()).ki_pos }
> +    }
> +
> +    /// Gets a mutable reference to the `ki_pos` field.
> +    pub fn ki_pos_mut(&mut self) -> &mut i64 {
> +        // SAFETY: The `kiocb` can access `ki_pos`.

Same.


Best regards,
Andreas Hindborg



^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
  2025-08-05 11:17   ` Andreas Hindborg
@ 2025-08-13  8:24     ` Alice Ryhl
  0 siblings, 0 replies; 10+ messages in thread
From: Alice Ryhl @ 2025-08-13  8:24 UTC (permalink / raw)
  To: Andreas Hindborg
  Cc: Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Trevor Gross,
	Danilo Krummrich, Matthew Maurer, Lee Jones, linux-kernel,
	rust-for-linux, Benno Lossin

On Tue, Aug 5, 2025 at 1:18 PM Andreas Hindborg <a.hindborg@kernel.org> wrote:
> > +
> > +    /// Advance this IO vector backwards by `bytes` bytes.
> > +    ///
> > +    /// # Safety
> > +    ///
> > +    /// The IO vector must not be reverted to before its beginning.
> > +    #[inline]
> > +    pub unsafe fn revert(&mut self, bytes: usize) {
> > +        // SAFETY: By the struct invariants, `self.iov` is a valid IO vector, and `bytes` is in
> > +        // bounds.
>
> "... and by method safety requirements `bytes` is in bounds", right?

Will reword.

> > +        unsafe { bindings::iov_iter_revert(self.as_raw(), bytes) };
> > +    }
> > +
> > +    /// Read data from this IO vector.
> > +    ///
> > +    /// Returns the number of bytes that have been copied.
> > +    #[inline]
> > +    pub fn copy_from_iter(&mut self, out: &mut [u8]) -> usize {
> > +        // SAFETY: `Self::copy_from_iter_raw` guarantees that it will not deinitialize any bytes in
> > +        // the provided buffer, so `out` is still a valid `u8` slice after this call.
>
> I am curious if there is a particular reason you chose "deinitialize"
> over "write uninitialized" for the wording throughout this patch? It's
> an unfamiliar phrasing to me.

I've seen it a fair number of times, but I'll change it to less niche wording.

Alice

^ permalink raw reply	[flat|nested] 10+ messages in thread

* Re: [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
  2025-08-05 11:31   ` Andreas Hindborg
@ 2025-08-13  8:25     ` Alice Ryhl
  0 siblings, 0 replies; 10+ messages in thread
From: Alice Ryhl @ 2025-08-13  8:25 UTC (permalink / raw)
  To: Andreas Hindborg
  Cc: Greg Kroah-Hartman, Alexander Viro, Arnd Bergmann, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Trevor Gross,
	Danilo Krummrich, Matthew Maurer, Lee Jones, linux-kernel,
	rust-for-linux, Benno Lossin

On Tue, Aug 5, 2025 at 1:31 PM Andreas Hindborg <a.hindborg@kernel.org> wrote:
>
> "Alice Ryhl" <aliceryhl@google.com> writes:
>
> > This adds abstractions for the iov_iter type in the case where
> > data_source is ITER_DEST. This will make Rust implementations of
> > fops->read_iter possible.
> >
> > This series only has support for using existing IO vectors created by C
> > code. Additional abstractions will be needed to support the creation of
> > IO vectors in Rust code.
> >
> > These abstractions make the assumption that `struct iov_iter` does not
> > have internal self-references, which implies that it is valid to move it
> > between different local variables.
> >
> > This patch adds an IovIterDest struct that is very similar to the
> > IovIterSource from the previous patch. However, as the methods on the
> > two structs have very little overlap (just getting the length and
> > advance/revert), I do not think it is worth it to try and deduplicate
> > this logic.
>
> Is it not like 50% duplication? `as_raw`, `len`, `is_empty`, `advance`,
> `revert`. It looks like it makes sense to me, but 🤷 We can always do it
> later.

Well, maybe. But I think having those be duplicated leads to a simpler
API for the end-user.

> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>

Thanks!

^ permalink raw reply	[flat|nested] 10+ messages in thread

end of thread, other threads:[~2025-08-13  8:25 UTC | newest]

Thread overview: 10+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-07-22 12:33 [PATCH v3 0/4] Rust support for `struct iov_iter` Alice Ryhl
2025-07-22 12:33 ` [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE Alice Ryhl
2025-08-05 11:17   ` Andreas Hindborg
2025-08-13  8:24     ` Alice Ryhl
2025-07-22 12:33 ` [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST Alice Ryhl
2025-08-05 11:31   ` Andreas Hindborg
2025-08-13  8:25     ` Alice Ryhl
2025-07-22 12:33 ` [PATCH v3 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures Alice Ryhl
2025-08-05 12:10   ` Andreas Hindborg
2025-07-22 12:33 ` [PATCH v3 4/4] samples: rust_misc_device: Expand the sample to support read()ing from userspace Alice Ryhl

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).