Re: [PATCH 4/8] rust: io: add view type

Gary Guo
2026-04-02T13:01:36Z

On Thu Mar 26, 2026 at 2:31 PM GMT, Andreas Hindborg wrote:
> "Gary Guo" <gary@kernel.org> writes:
>
>> From: Gary Guo <gary@garyguo.net>
>>
>> The view may be created statically via I/O projection using `io_project!()`
>> macro to perform compile-time checks, or created by type-casting an
>> existing view type with `try_cast()` function, where the size and alignment
>> checks are performed at runtime.
>>
>> Signed-off-by: Gary Guo <gary@garyguo.net>
>> ---
>> rust/kernel/io.rs | 147 +++++++++++++++++++++++++++++++++++++++++++++-
>> 1 file changed, 146 insertions(+), 1 deletion(-)
>>
>> diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs
>> index 72902a4a343d..8166e47f1381 100644
>> --- a/rust/kernel/io.rs
>> +++ b/rust/kernel/io.rs
>> @@ -7,7 +7,11 @@
>> use crate::{
>> bindings,
>> prelude::*,
>> - ptr::KnownSize, //
>> + ptr::KnownSize,
>> + transmute::{
>> + AsBytes,
>> + FromBytes, //
>> + }, //
>> };
>>
>> pub mod mem;
>> @@ -296,6 +300,13 @@ pub trait Io {
>> /// Type of this I/O region. For untyped I/O regions, [`Region`] type can be used.
>> type Type: ?Sized + KnownSize;
>>
>> + /// Get a [`View`] covering the entire region.
>> + #[inline]
>> + fn as_view(&self) -> View<'_, Self, Self::Type> {
>> + // SAFETY: Trivially satisfied.
>
> What might be trivial to you is not necessarily obvious to others.
> Please explain why we are satisfying safety requirements.

This is what language model produces:

Analysis: Io::as_view()

fn as_view(&self) -> View<'_, Self, Self::Type> {
// SAFETY: Trivially satisfied
unsafe { View::new_unchecked(self, self.as_ptr()) }
}

The View invariants are:
1. ptr is aligned for T
2. ptr has same provenance as io.as_ptr()
3. ptr.byte_offset_from(io.as_ptr()) is between 0 to KnownSize::size(io.as_ptr()) - KnownSize::size(ptr)

For as_view():
- ptr = self.as_ptr() which is Self::Type
- Invariant 1: self.as_ptr() should be aligned for Self::Type - assumed true from the Io trait
- Invariant 2: Same pointer, same provenance - trivially true
- Invariant 3: ptr.byte_offset_from(io.as_ptr()) = 0, and we need 0 <= size_io - size_ptr which is 0 <= 0, true

The safety comment "Trivially satisfied" is correct.

I think the verbosity here is really because we have the safety requirement
listed item by item, rather than just defining a new concept.

If we, for example, coin an idea of `IO valid pointers`, then we can just say
the `self.as_ptr()` is trivially I/O valid.

Perhaps, for this case, we can use the "projection trivially satisfy the
invariants" that I've already mentioned in the doc, and just write

// SAFETY: This is an empty projection, so it trivially satisfies the
// invariant.

?

Best,
Gary

>
> Otherwise looks good, with the above fixed, please add:
>
> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
>
> Best regards,
> Andreas Hindborg