Rust support for `struct iov_iter`
Subsystems (3)
Alice Ryhl
reviewerv3 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.
Based on rust-next for this dependency:
https://lore.kernel.org/all/[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 | 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,
Signature · 1 line
Alice Ryhl <[email protected]>
Alice Ryhl
reviewerPATCH v3 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 | 167 +++++++++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 168 insertions(+)
rust/kernel/iov.rs new file +167 -0
@@ -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 ) -> &'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 `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) } + } +}
rust/kernel/lib.rs +1 -0
@@ -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;
Signature · 1 line
2.50.0.727.gbf7dc18ff4-goog
Re: [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
Quoted 14 lines · Alice Ryhl
This adds abstractions for the
iov_itertype in the case wheredata_sourceisITER_SOURCE. This will make Rust implementations offops->write_iterpossible.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_iterdoes not have internal self-references, which implies that it is valid to move it between different local variables.Signed-off-by Alice Ryhl <[email protected]>---
..
rust/kernel/iov.rs line 112
Quoted 10 lines
rust/kernel/iov.rs new file +10
-0+ +/// 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?
rust/kernel/iov.rs line 122
Quoted 10 lines
rust/kernel/iov.rs new file +10
-0+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.
Best regards,
Andreas Hindborg
Alice Ryhl
reviewerRe: [PATCH v3 1/4] rust: iov: add iov_iter abstractions for ITER_SOURCE
Quoted 11 lines · Andreas Hindborg
rust/kernel/iov.rs line 112
Quoted 10 lines
rust/kernel/iov.rs new file +10
-0+ +/// 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.
Quoted 1 line
"... and by method safety requirements
bytesis in bounds", right?
Will reword.
Quoted 11 lines
rust/kernel/iov.rs line 122
Quoted 10 lines
rust/kernel/iov.rs new file +10
-0+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.
Quoted 3 lines
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
Alice Ryhl
reviewerPATCH v3 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. ///
@@ -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 <&'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 `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.50.0.727.gbf7dc18ff4-goog
Re: [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
Quoted 12 lines · Alice Ryhl
This adds abstractions for the
iov_itertype in the case wheredata_sourceisITER_DEST. This will make Rust implementations offops->read_iterpossible.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_iterdoes not have internal self-references, which implies that it is valid to move it between different local variables.
Quoted 5 lines
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.
Best regards,
Andreas Hindborg
Alice Ryhl
reviewerRe: [PATCH v3 2/4] rust: iov: add iov_iter abstractions for ITER_DEST
Quoted 21 lines · Andreas Hindborg
Quoted 12 lines · Alice Ryhl
This adds abstractions for the
iov_itertype in the case wheredata_sourceisITER_DEST. This will make Rust implementations offops->read_iterpossible.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_iterdoes not have internal self-references, which implies that it is valid to move it between different local variables.Quoted 5 lines
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.
Quoted 3 lines
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.
Quoted 1 line
Reviewed-by Andreas Hindborg <[email protected]>
Thanks!
Alice Ryhl
reviewerPATCH v3 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 | 67 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/miscdevice.rs | 63 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 132 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 +67 -0
67 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.50.0.727.gbf7dc18ff4-goog
Andreas Hindborg
reviewerRe: [PATCH v3 3/4] rust: miscdevice: Provide additional abstractions for iov_iter and kiocb structures
Quoted 39 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]>--- rust/kernel/fs.rs | 3 +++ rust/kernel/fs/kiocb.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/miscdevice.rs | 63 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 132 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 +8
-0@@ -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) +
rust/kernel/fs/kiocb.rs line 18
Quoted 10 lines
rust/kernel/fs/kiocb.rs new file +10
-0+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.
Quoted 20 lines
rust/kernel/fs/kiocb.rs new file +20
-0+/// +/// # 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) },
rust/kernel/fs/kiocb.rs line 48
Quoted 10 lines
rust/kernel/fs/kiocb.rs new file +10
-0+ _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.
rust/kernel/fs/kiocb.rs line 50
Quoted 2 lines
rust/kernel/fs/kiocb.rs new file +2
-0+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.
rust/kernel/fs/kiocb.rs line 58
Quoted 8 lines
rust/kernel/fs/kiocb.rs new file +8
-0+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.
rust/kernel/fs/kiocb.rs line 64
Quoted 6 lines
rust/kernel/fs/kiocb.rs new file +6
-0+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
Alice Ryhl
reviewerPATCH v3 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.50.0.727.gbf7dc18ff4-goog