Rust support for `struct iov_iter`
Subsystems (3)
Alice Ryhl
reviewerv4 cover Rust support for `struct iov_iter`
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.
Intended for Greg's miscdevice tree.
---
Changes in v4:
- Rebase on v6.17-rc1. No longer any dependencies.
- Adjust wording of revert safety comment.
- Adjust "deinitialize" wording to "write uninitialized".
- Adjust several comments' wording in rust/kernel/fs/kiocb.rs.
- Link to v3: https://lore.kernel.org/r/[email protected]
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/[email protected]
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/[email protected]
---
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 | 68 +++++++++ rust/kernel/iov.rs | 311 +++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + rust/kernel/miscdevice.rs | 63 +++++++- samples/rust/rust_misc_device.rs | 36 ++++- 6 files changed, 479 insertions(+), 3 deletions(-)
---
base-commit: 062b3e4a1f880f104a8d4b90b767788786aa7b78
change-id: 20250311-iov-iter-c984aea07d18
Best regards,
Signature · 1 line
Alice Ryhl <[email protected]>
Alice Ryhl
reviewerPATCH v4 1/4 rust: iov: add iov_iter abstractions for ITER_SOURCE
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.
--- rust/kernel/iov.rs | 168 +++++++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 169 insertions(+)
rust/kernel/iov.rs new file +168 -0
@@ -0,0 +1,168 @@ +// 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 ) -> &'iovmut 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 the caller +// ensures that `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 write any uninitialized +// 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 write uninitialized bytes to 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 write uninitialized bytes to 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) } + } +}
rust/kernel/lib.rs +1 -0
@@ -92,6 +92,7 @@pub mod init;pub mod io;pub mod ioctl; +pub mod iov;pub mod jump_label;#[cfg( CONFIG_KUNIT )] pub mod kunit;
Signature · 1 line
2.51.0.rc0.205.g4a044479a3-goog
Re: [PATCH v4 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
rust/kernel/iov.rs line 140
Quoted 13 lines · Alice Ryhl
rust/kernel/iov.rs new file +13
-0+/// 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.
Technically, this covers the safety requirements from inc_len(). However, do we want to provide a list of justifications if the unsafe functions has a list of requirements, such that they are easier to match?
rust/kernel/iov.rs line 143
Quoted 3 lines
rust/kernel/iov.rs new file +3
-0+unsafe { out.inc_len (len) }; +Ok (len) + }
Either way,
Re: [PATCH v4 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
Quoted 4 lines · Danilo Krummrich
Technically, this covers the safety requirements from
inc_len(). However, do we want to provide a list of justifications if the unsafe functions has a list of requirements, such that they are easier to match?
Yeah, I think we should at least try in places where people is OK with it, to see how it goes, and then we can apply it elsewhere, especially if we get a way to automate checking for it eventually.
After all, if we never start and get the ball rolling, we will never get there.
Cheers,
Miguel
Alice Ryhl
reviewerRe: [PATCH v4 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
In reply to Danilo KrummrichQuoted 15 lines · Danilo Krummrich
rust/kernel/iov.rs line 140
Quoted 13 lines · Alice Ryhl
rust/kernel/iov.rs new file +13
-0+/// 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.
Quoted 3 lines
Technically, this covers the safety requirements from
inc_len(). However, do we want to provide a list of justifications if the unsafe functions has a list of requirements, such that they are easier to match?
I will reword to:
// SAFETY:
// - len is the length of a subslice of the spare capacity, so len
// is at most the length of the spare capacity.
// - Self::copy_from_iter_raw guarantees that the first len bytes of
// the spare capacity have been initialized.
Ok?
Quoted 7 lines
rust/kernel/iov.rs line 143
Quoted 3 lines
rust/kernel/iov.rs new file +3
-0+unsafe { out.inc_len (len) }; +Ok (len) + }Either way,
Reviewed-by Danilo Krummrich <[email protected]>
Thanks!
Alice
Alice Ryhl
reviewerPATCH v4 2/4 rust: iov: add iov_iter abstractions for ITER_DEST
In reply to Alice RyhlThis 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.
--- rust/kernel/iov.rs | 143 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+)
rust/kernel/iov.rs +143 -0
@@ -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. ///
@@ -166,3 +175,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 <&'datamut [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 ) -> &'iovmut 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 the caller +// ensures that `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) + } +}
Signature · 1 line
2.51.0.rc0.205.g4a044479a3-goog
Re: [PATCH v4 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
rust/kernel/iov.rs pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] { · line 280
Quoted 8 lines · Alice Ryhl
rust/kernel/iov.rs +8
-0+/// 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.
NIT: I think we usually say type invariants.
Quoted 13 lines
rust/kernel/iov.rs +13
-0+// * `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 {
rust/kernel/iov.rs pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] { · line 303
Quoted 10 lines
rust/kernel/iov.rs +10
-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.
I like this one (and the one below). It would be nice to have a lint asking for such comments, such as I'd like to have a "FORGET" one. :)
rust/kernel/iov.rs pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] { · line 311
Quoted 8 lines
rust/kernel/iov.rs +8
-0+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) + } +}
Re: [PATCH v4 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
In reply to Alice RyhlQuoted 10 lines · On Wed, 13 Aug 2025 08:27:18 +0000 Alice Ryhl <[email protected]> wrote:
rust/kernel/iov.rs +10
-0+/// 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 );
rust/kernel/iov.rs pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] { · line 304
Quoted 10 lines
rust/kernel/iov.rs +10
-0+ } +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..]);
This should use contents.get(..pos) instead of doing the bound check manually.
rust/kernel/iov.rs pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] { · line 310
Quoted 6 lines
rust/kernel/iov.rs +6
-0+ +// OVERFLOW: `pos+num_written <= contents.len() <= isize::MAX <= i64::MAX`. + *ppos = (pos + num_written)as i64 ; + +Ok (num_written) + }
Benoît du Garreau
Alice Ryhl
reviewerRe: [PATCH v4 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
Quoted 23 lines · Benoît du Garreau
Quoted 10 lines · On Wed, 13 Aug 2025 08:27:18 +0000 Alice Ryhl <[email protected]> wrote:
rust/kernel/iov.rs +10
-0+/// 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 );rust/kernel/iov.rs pub fn copy_from_iter_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> &mut [u8] { · line 304
Quoted 10 lines
rust/kernel/iov.rs +10
-0+ } +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..]);
Quoted 1 line
This should use
contents.get(..pos)instead of doing the bound check manually.
Using contents.get(pos..) does not have the same behavior as the bounds check, because the bounds check exits early with Ok(0) if pos is equal to contents.len(), whereas the proposed change would pass an empty array to copy_to_iter.
Alice
Alice Ryhl
reviewerPATCH v4 3/4 rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures
In reply to Alice RyhlThese 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.
--- rust/kernel/fs.rs | 3 +++ rust/kernel/fs/kiocb.rs | 68 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/miscdevice.rs | 63 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 133 insertions(+), 1 deletion(-)
rust/kernel/fs.rs +3 -0
@@ -6,3 +6,6 @@pub mod file;pub use self::file::{File ,LocalFile }; + +mod kiocb; +pub use self::kiocb::Kiocb ;
rust/kernel/fs/kiocb.rs new file +68 -0
68 lines not on this page · raw message
rust/kernel/miscdevice.rs +62 -1
87 lines not on this page · raw message
Signature · 1 line
2.51.0.rc0.205.g4a044479a3-goog
Danilo Krummrich
reviewerRe: [PATCH v4 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures
Quoted 75 lines · Alice Ryhl
rust/kernel/fs.rs +3
-0@@ -6,3 +6,6 @@pub mod file;pub use self::file::{File ,LocalFile }; + +mod kiocb; +pub use self::kiocb::Kiocb ;rust/kernel/fs/kiocb.rs new file +58
-0@@ -0,0 +1,68 @@ +// 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 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 <&'aT >, +} + +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 filesystem or driver specific data associated with the file. +pub fn file (&self) -> <T as ForeignOwnable >::Borrowed <'a> { +// SAFETY: We have shared access to this kiocb and hence the underlying file, so we can +// read the file's 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 {
rust/kernel/fs/kiocb.rs line 68
Quoted 10 lines
rust/kernel/fs/kiocb.rs new file +10
-0+// SAFETY: We have shared access to the kiocb, so we can read its `ki_pos` field. +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: We have exclusive access to the kiocb, so we can write to `ki_pos`. +unsafe { &mut (*self.as_raw ()).ki_pos } + } +}
I think this should be a separate commit.
Alice Ryhl
reviewerRe: [PATCH v4 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures
Quoted 41 lines · Danilo Krummrich
Quoted 40 lines · Alice Ryhl
rust/kernel/fs/kiocb.rs new file +40
-0+pub struct Kiocb <'a,T > { + inner:NonNull <bindings::kiocb >, + _phantom:PhantomData <&'aT >, +} + +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 filesystem or driver specific data associated with the file. +pub fn file (&self) -> <T as ForeignOwnable >::Borrowed <'a> { +// SAFETY: We have shared access to this kiocb and hence the underlying file, so we can +// read the file's 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: We have shared access to the kiocb, so we can read its `ki_pos` field. +unsafe { (*self.as_raw ()).ki_pos } + } +
Quoted 8 lines
rust/kernel/fs/kiocb.rs line 68
Quoted 6 lines
rust/kernel/fs/kiocb.rs new file +6
-0+/// Gets a mutable reference to the `ki_pos` field. +pub fn ki_pos_mut (&mut self) -> &mut i64 { +// SAFETY: We have exclusive access to the kiocb, so we can write to `ki_pos`. +unsafe { &mut (*self.as_raw ()).ki_pos } + } +}I think this should be a separate commit.
I can split it.
Alice
Re: [PATCH v4 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures
In reply to Alice RyhlQuoted 8 lines · Alice Ryhl
These will be used for the
read_iter()andwrite_iter()callbacks, which are now the preferred back-ends for when a user operates on a char device withread()andwrite()respectively.Cc Christian Brauner <[email protected]>Co-developed-by Lee Jones <[email protected]>Signed-off-by Lee Jones <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
Best regards,
Andreas Hindborg
Alice Ryhl
reviewerPATCH v4 4/4 samples: rust_misc_device: Expand the sample to support read()ing from userspace
In reply to Alice RyhlFrom: Lee Jones <[email protected]>
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.
--- samples/rust/rust_misc_device.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-)
samples/rust/rust_misc_device.rs +34 -2
@@ -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<SeKBox ::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" );
Signature · 1 line
2.51.0.rc0.205.g4a044479a3-goog
Danilo Krummrich
reviewerQuoted 1 line · Alice Ryhl
rust/kernel/iov.rs | 311 +++++++++++++++++++++++++++++++++++++++
Does this need an entry in MAINTAINERS?
Alice Ryhl
reviewerQuoted 5 lines · Danilo Krummrich
Quoted 1 line · Alice Ryhl
rust/kernel/iov.rs | 311 +++++++++++++++++++++++++++++++++++++++Does this need an entry in
MAINTAINERS?
I think it goes together with the existing uaccess.rs file. We don't currently have an entry for it. I guess one could be added.
Alice