Skip to contentSkip to conversation

rust: uaccess: generalize write_dma() to accept any Coherent<T>

PATCH Applied Danilo Krummrich 5 participants 13 messages Mar 25 – Mar 27

Subsystems (6)
lore
Share & tools
lore

Danilo Krummrich

author maintainer
#0 lore raw

PATCH 1/3 rust: uaccess: generalize write_dma() to accept any Coherent<T>

Generalize write_dma() from &Coherent<[u8]> to &Coherent<T> where
T: KnownSize + AsBytes + ?Sized. The function body only uses as_ptr() and size(), which work for any such T, so there is no reason to restrict it to byte slices.

---
 rust/kernel/uaccess.rs | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
rust/kernel/uaccess.rs +7 -1
index e26ef90ba8ad..6c9c1cce3c63 100644
@@ -12,6 +12,7 @@
     ffi::{c_char, c_void},
     fs::file,
     prelude::*,
+    ptr::KnownSize,
     transmute::{AsBytes, FromBytes},
 };
 use core::mem::{size_of, MaybeUninit};
@@ -524,7 +525,12 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result {
     ///     writer.write_dma(alloc, 0, 256)
     /// }
     /// ```
-    pub fn write_dma(&mut self, alloc: &Coherent<[u8]>, offset: usize, count: usize) -> Result {
+    pub fn write_dma<T: KnownSize + AsBytes + ?Sized>(
+        &mut self,
+        alloc: &Coherent<T>,
+        offset: usize,
+        count: usize,
+    ) -> Result {
         let len = alloc.size();
         if offset.checked_add(count).ok_or(EOVERFLOW)? > len {
             return Err(ERANGE);

base-commit: dff8302ca1d0e773c90dbeeb05e759f995c95482

Signature · 1 line
2.53.0
author maintainer
#1 lore raw

PATCH 2/3 rust: dma: generalize BinaryWriter impl for Coherent<T>

Generalize the BinaryWriter implementation from Coherent<[u8]> to Coherent<T> where T: KnownSize + AsBytes + ?Sized. The implementation only uses size() and write_dma(), neither of which depends on the inner type being a byte slice.

This allows any Coherent allocation with an AsBytes inner type to be exposed as a debugfs binary file.

---
 rust/kernel/dma.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/dma.rs +1 -1
index 3eef7c2396bb..7bc97f9f83fd 100644
@@ -885,7 +885,7 @@ unsafe impl<T: KnownSize + Send + ?Sized> Send for Coherent<T> {}
 // The safe methods only return metadata or raw pointers whose use requires `unsafe`.
 unsafe impl<T: KnownSize + ?Sized + AsBytes + FromBytes + Sync> Sync for Coherent<T> {}
 
-impl debugfs::BinaryWriter for Coherent<[u8]> {
+impl<T: KnownSize + AsBytes + ?Sized> debugfs::BinaryWriter for Coherent<T> {
     fn write_to_slice(
         &self,
         writer: &mut UserSliceWriter,
Signature · 1 line
2.53.0
author maintainer Applied
#2 lore raw

Re: [PATCH 2/3] rust: dma: generalize BinaryWriter impl for Coherent<T>

Quoted 9 lines · Danilo Krummrich

Generalize the BinaryWriter implementation from Coherent<[u8]> to Coherent<T> where T: KnownSize + AsBytes + ?Sized. The implementation only uses size() and write_dma(), neither of which depends on the inner type being a byte slice.

This allows any Coherent allocation with an AsBytes inner type to be exposed as a debugfs binary file.

Applied to drm-rust-next, thanks!

author maintainer
#3 lore raw

PATCH 3/3 gpu: nova-core: use sized array for GSP log buffers

In reply to Danilo Krummrich

Switch LogBuffer from Coherent<[u8]> (unsized) to Coherent<[u8; LOG_BUFFER_SIZE]> (sized). The buffer size is a compile-time constant (RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE), so a fixed-size array is more precise and avoids the need for the runtime length parameter of zeroed_slice().

---
 drivers/gpu/nova-core/gsp.rs | 16 ++++++----------
 1 file changed, 6 insertions(+), 10 deletions(-)
drivers/gpu/nova-core/gsp.rs +6 -10
index 04e3976127cc..ba5b7f990031 100644
@@ -42,6 +42,7 @@
 
 /// Number of GSP pages to use in a RM log buffer.
 const RM_LOG_BUFFER_NUM_PAGES: usize = 0x10;
+const LOG_BUFFER_SIZE: usize = RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE;
 
 /// Array of page table entries, as understood by the GSP bootloader.
 #[repr(C)]
@@ -77,24 +78,19 @@ fn entry(start: DmaAddress, index: usize) -> Result<u64> {
 /// then pp points to index into the buffer where the next logging entry will
 /// be written. Therefore, the logging data is valid if:
 ///   1 <= pp < sizeof(buffer)/sizeof(u64)
-struct LogBuffer(Coherent<[u8]>);
+struct LogBuffer(Coherent<[u8; LOG_BUFFER_SIZE]>);
 
 impl LogBuffer {
     /// Creates a new `LogBuffer` mapped on `dev`.
     fn new(dev: &device::Device<device::Bound>) -> Result<Self> {
-        const NUM_PAGES: usize = RM_LOG_BUFFER_NUM_PAGES;
-
-        let obj = Self(Coherent::<u8>::zeroed_slice(
-            dev,
-            NUM_PAGES * GSP_PAGE_SIZE,
-            GFP_KERNEL,
-        )?);
+        let obj = Self(Coherent::zeroed(dev, GFP_KERNEL)?);
 
         let start_addr = obj.0.dma_handle();
 
         // SAFETY: `obj` has just been created and we are its sole user.
-        let pte_region =
-            unsafe { &mut obj.0.as_mut()[size_of::<u64>()..][..NUM_PAGES * size_of::<u64>()] };
+        let pte_region = unsafe {
+            &mut obj.0.as_mut()[size_of::<u64>()..][..RM_LOG_BUFFER_NUM_PAGES * size_of::<u64>()]
+        };
 
         // Write values one by one to avoid an on-stack instance of `PteArray`.
         for (i, chunk) in pte_region.chunks_exact_mut(size_of::<u64>()).enumerate() {
Signature · 1 line
2.53.0
author maintainer Applied
#4 lore raw

Re: [PATCH 3/3] gpu: nova-core: use sized array for GSP log buffers

Quoted 7 lines · Danilo Krummrich

Switch LogBuffer from Coherent<[u8]> (unsized) to Coherent<[u8; LOG_BUFFER_SIZE]> (sized). The buffer size is a compile-time constant (RM_LOG_BUFFER_NUM_PAGES * GSP_PAGE_SIZE), so a fixed-size array is more precise and avoids the need for the runtime length parameter of zeroed_slice().

Applied to drm-rust-next, thanks!

reviewer
#6 lore raw
In reply to Danilo Krummrich
Quoted 4 lines · Danilo Krummrich

Generalize write_dma() from &Coherent<[u8]> to &Coherent<T> where
T: KnownSize + AsBytes + ?Sized. The function body only uses as_ptr() and size(), which work for any such T, so there is no reason to restrict it to byte slices.

I think there is a reason, which is that it weakens the strong typing that we have. I think it'll be better to have this be

    fn write_dma<T>(&mut self, view: View<'_, Coherent<T>, [u8]>, offset: usize) -> Result

once we have I/O view and expect people to create cast views into bytes explicitly.

Although, given that we already have APIs like

fn write<T: AsBytes>(&mut self, value: &T)

I'm okay with putting this in until we have a replacement solution.

The fact that our current uaccess mechanism is untyped itself is something that I dislike (it feels a step back that C can represent arbitary_type __user* and we just have a void __user*). It's on my list of things to fix to make a generic UserPtr<T>.

Best,
Gary

Quoted 34 lines
---
 rust/kernel/uaccess.rs | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
rust/kernel/uaccess.rs +7 -1
index e26ef90ba8ad..6c9c1cce3c63 100644
@@ -12,6 +12,7 @@
     ffi::{c_char, c_void},
     fs::file,
     prelude::*,
+    ptr::KnownSize,
     transmute::{AsBytes, FromBytes},
 };
 use core::mem::{size_of, MaybeUninit};
@@ -524,7 +525,12 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result {
     ///     writer.write_dma(alloc, 0, 256)
     /// }
     /// ```
-    pub fn write_dma(&mut self, alloc: &Coherent<[u8]>, offset: usize, count: usize) -> Result {
+    pub fn write_dma<T: KnownSize + AsBytes + ?Sized>(
+        &mut self,
+        alloc: &Coherent<T>,
+        offset: usize,
+        count: usize,
+    ) -> Result {
         let len = alloc.size();
         if offset.checked_add(count).ok_or(EOVERFLOW)? > len {
             return Err(ERANGE);

base-commit: dff8302ca1d0e773c90dbeeb05e759f995c95482

author maintainer
#7 lore raw
Quoted 8 lines · Gary Guo

I think there is a reason, which is that it weakens the strong typing that we have. I think it'll be better to have this be

    fn write_dma<T>(&mut self, view: View<'_, Coherent<T>, [u8]>, offset: usize) -> Result

once we have I/O view and expect people to create cast views into bytes explicitly.

There is technically no difference between the above and the below, except that for the above the user has to create the View first, i.e. it needs additional code. What's the advantage?

Quoted 6 lines
Quoted 6 lines
rust/kernel/uaccess.rs +6 -0
+    pub fn write_dma<T: KnownSize + AsBytes + ?Sized>(
+        &mut self,
+        alloc: &Coherent<T>,
+        offset: usize,
+        count: usize,
+    ) -> Result {

<snip>

Quoted 5 lines

Although, given that we already have APIs like

fn write<T: AsBytes>(&mut self, value: &T)

I'm okay with putting this in until we have a replacement solution.

Sounds good.

reviewer
#8 lore raw
Quoted 5 lines · Danilo Krummrich
Quoted 4 lines · Gary Guo

I think there is a reason, which is that it weakens the strong typing that we have. I think it'll be better to have this be

    fn write_dma<T>(&mut self, view: View<'_, Coherent<T>, [u8]>, offset: usize) -> Result

Correcting myself, this will be

    fn write_dma<T>(&mut self, view: View<'_, Coherent<T>, [u8]>) -> Result

(without offset, similar to the write_slice).

Quoted 8 lines
Quoted 4 lines

once we have I/O view and expect people to create cast views into bytes explicitly.

There is technically no difference between the above and the below, except that for the above the user has to create the View first, i.e. it needs additional code. What's the advantage?

It prevents misuses. If you have a [u8] or [u8; SIZE] already, the change is going to be small:

u.write_dma(c, offset, count)

vs.

    u.write_dma(io_project!(c, [offset..][..count]))

[
PS. it looks like with current proposals w/ virtual places, we might be able to get this written as

u.write_dma(c[offset..][..count])

a few years down the road if we're successful.
]

However, using a view will prevent you from feeding an arbitary Coherent<FooBar> and just write it to user space. offset and count in the API really doesn't make too much sense at all if T is not array/slice of u8.

Best,
Gary

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
rust/kernel/uaccess.rs +6 -0
+    pub fn write_dma<T: KnownSize + AsBytes + ?Sized>(
+        &mut self,
+        alloc: &Coherent<T>,
+        offset: usize,
+        count: usize,
+    ) -> Result {
reviewer Acked-by on v1 1/3
#10 lore raw
In reply to Danilo Krummrich
Quoted 6 lines · Danilo Krummrich

Generalize write_dma() from &Coherent<[u8]> to &Coherent<T> where
T: KnownSize + AsBytes + ?Sized. The function body only uses as_ptr() and size(), which work for any such T, so there is no reason to restrict it to byte slices.

For the series:

Quoted 32 lines
---
 rust/kernel/uaccess.rs | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
rust/kernel/uaccess.rs +7 -1
index e26ef90ba8ad..6c9c1cce3c63 100644
@@ -12,6 +12,7 @@
     ffi::{c_char, c_void},
     fs::file,
     prelude::*,
+    ptr::KnownSize,
     transmute::{AsBytes, FromBytes},
 };
 use core::mem::{size_of, MaybeUninit};
@@ -524,7 +525,12 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result {
     ///     writer.write_dma(alloc, 0, 256)
     /// }
     /// ```
-    pub fn write_dma(&mut self, alloc: &Coherent<[u8]>, offset: usize, count: usize) -> Result {
+    pub fn write_dma<T: KnownSize + AsBytes + ?Sized>(
+        &mut self,
+        alloc: &Coherent<T>,
+        offset: usize,
+        count: usize,
+    ) -> Result {
         let len = alloc.size();
         if offset.checked_add(count).ok_or(EOVERFLOW)? > len {
             return Err(ERANGE);

base-commit: dff8302ca1d0e773c90dbeeb05e759f995c95482