Skip to contentSkip to conversation

drm/tyr: allow mismatched buffers for dev_query

PATCH Applied Deborah Brouwer 4 participants 11 messages Oct 21 – Nov 22

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v4 cover drm/tyr: allow mismatched buffers for dev_query

Panthor UAPI for DRM_IOCTL_PANTHOR_DEV_QUERY allows userspace to provide a smaller or larger buffer than the kernel needs. Revise Tyr's implementation to match the expected UAPI behaviour.

---
This series depends on:
[PATCH v5 0/2] drm/tyr: safely write GpuInfo to userspace
https://lore.kernel.org/rust-for-linux/[email protected]

Changes in v4:
- add new UserPtr method to accept u64 address
- replace write_truncated() with write_slice_partial()
- replace AsBytes with IntoBytes + Immutable in set_uobj
- replace u32_as_usize with usize::from_safe_cast
- remove redundant import size_of_val
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- replace "as" cast with lossless u32_as_usize()
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Added #[inline] to UserSliceWriter::clear()
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Deborah Brouwer (3):
rust: uaccess: add UserSliceWriter::clear()
rust: uaccess: add method to get UserPtr from u64 drm/tyr: allow userspace buffers to be mismatched

 drivers/gpu/drm/tyr/file.rs | 49 +++++++++++++++++++++++++++++++++++++--------
 rust/helpers/uaccess.c      |  6 ++++++
 rust/kernel/uaccess.rs      | 33 ++++++++++++++++++++++++++++++
 3 files changed, 80 insertions(+), 8 deletions(-)

---
base-commit: 3497a403264b094ebd61b8b755165d56e7d9dc37
change-id: 20261014-b4-dev_query_fixes-4e0ab024294a
prerequisite-change-id: 20260923-b4-gpu_info_intobytes-c2d45f2935c8:v5
prerequisite-patch-id: 0ff3c9871f563680d2888d489cc155cc52788048
prerequisite-patch-id: ecf0aed0bd7e4f8d3bc1bbaabb02976fc8d5fa4d

Best regards,

Signature · 1 line
Deborah Brouwer <[email protected]>
#1 lore raw

PATCH v4 1/3 rust: uaccess: add UserSliceWriter::clear()

Add a method to zero the remaining bytes in a UserSliceWriter.

If userspace provides a buffer that is larger than necessary, provide a method to zero out the remaining UserSliceWriter buffer. This avoids userspace consuming potentially uninitialized memory and/or mistaking it for data intentionally provided by the kernel.

Use the #[inline] annotation to make this clear() method available for inlining outside of the kernel crate.

Since clear_user() is architecturally defined and may be a macro or inline function, add a rust helper to make clear_user() callable from rust.

---
 rust/helpers/uaccess.c |  6 ++++++
 rust/kernel/uaccess.rs | 24 ++++++++++++++++++++++++
 2 files changed, 30 insertions(+)
rust/helpers/uaccess.c +6 -0
index 6e59cc9c665c..e799d9ac9804 100644
@@ -27,3 +27,9 @@ unsigned long rust_helper__copy_to_user(void __user *to, const void *from, unsig
 	return _inline_copy_to_user(to, from, n);
 }
 #endif
+
+__rust_helper unsigned long
+rust_helper_clear_user(void __user *to, unsigned long n)
+{
+	return clear_user(to, n);
+}
rust/kernel/uaccess.rs +24 -0
index f1aecda7a90c..8e18285ec44b 100644
@@ -638,6 +638,30 @@ pub fn write<T: AsBytes>(&mut self, value: &T) -> Result {
     pub fn write_truncated<T: AsBytes>(&mut self, value: &T) -> Result<usize> {
         self.write_slice_partial(value.as_bytes(), 0)
     }
+
+    /// Zeros remaining bytes in the userspace buffer.
+    ///
+    /// Fails with [`EFAULT`] if the userspace memory cannot be cleared.
+    #[inline]
+    pub fn clear(&mut self) -> Result {
+        let len = self.length;
+
+        if len == 0 {
+            return Ok(());
+        }
+        // SAFETY: `clear_user` checks the userspace address and range and handles
+        // faults when accessing userspace memory
+        let res = unsafe { bindings::clear_user(self.ptr.as_mut_ptr(), len) };
+
+        if res != 0 {
+            return Err(EFAULT);
+        }
+
+        self.ptr = self.ptr.wrapping_byte_add(len);
+        self.length = 0;
+
+        Ok(())
+    }
 }
 
 /// Reads a nul-terminated string into `dst` and returns the length.
Signature · 1 line
2.56.0
reviewer Reviewed-by on v4 1/3
#2 lore raw

Re: [PATCH v4 1/3] rust: uaccess: add UserSliceWriter::clear()

Quoted 7 lines · Deborah Brouwer

Add a method to zero the remaining bytes in a UserSliceWriter.

If userspace provides a buffer that is larger than necessary, provide a method to zero out the remaining UserSliceWriter buffer. This avoids userspace consuming potentially uninitialized memory and/or mistaking it for data intentionally provided by the kernel.

Quoted 8 lines

Use the #[inline] annotation to make this clear() method available for inlining outside of the kernel crate.

Since clear_user() is architecturally defined and may be a macro or inline function, add a rust helper to make clear_user() callable from rust.

Quoted 4 lines
---
 rust/helpers/uaccess.c |  6 ++++++
 rust/kernel/uaccess.rs | 24 ++++++++++++++++++++++++
 2 files changed, 30 insertions(+)
#3 lore raw

PATCH v4 2/3 rust: uaccess: add method to get UserPtr from u64

In reply to Deborah Brouwer

Currently a UserPtr can be created from a usize integer representing a userspace address. To create a UserPtr from a u64 integer, the u64 must be cast to usize. On 32-bit systems, this cast will discard the upper 32 bits of the address.

Provide a new method to create a UserPtr from a u64 integer. This avoids the caller having to cast before creating a UserPtr and also clarifies that the truncation is intended. This is equivalent to the C-side macro u64_to_user_ptr() that provides typechecking and casting to a __user pointer.

---
 rust/kernel/uaccess.rs | 9 +++++++++
 1 file changed, 9 insertions(+)
rust/kernel/uaccess.rs +9 -0
index 8e18285ec44b..a6fd1af155b3 100644
@@ -31,6 +31,15 @@ pub fn from_addr(addr: usize) -> Self {
         Self(addr as *mut c_void)
     }
 
+    /// Create a `UserPtr` from a u64 userspace address.
+    ///
+    /// Deliberately truncate upper bits for 32-bit systems.
+    #[doc(alias = "u64_to_user_ptr")]
+    #[inline]
+    pub fn from_u64(addr: u64) -> Self {
+        Self::from_addr(addr as usize)
+    }
+
     /// Create a `UserPtr` from a pointer representing the userspace address.
     #[inline]
     pub fn from_ptr(addr: *mut c_void) -> Self {
Signature · 1 line
2.56.0
maintainer Reviewed-by on v4 2/3
#4 lore raw

Re: [PATCH v4 2/3] rust: uaccess: add method to get UserPtr from u64

Quoted 5 lines · Deborah Brouwer

Currently a UserPtr can be created from a usize integer representing a userspace address. To create a UserPtr from a u64 integer, the u64 must be cast to usize. On 32-bit systems, this cast will discard the upper 32 bits of the address.

Quoted 7 lines

Provide a new method to create a UserPtr from a u64 integer. This avoids the caller having to cast before creating a UserPtr and also clarifies that the truncation is intended. This is equivalent to the C-side macro u64_to_user_ptr() that provides typechecking and casting to a __user pointer.

reviewer Reviewed-by on v4 2/3
#5 lore raw

Re: [PATCH v4 2/3] rust: uaccess: add method to get UserPtr from u64

In reply to Deborah Brouwer
Quoted 5 lines · Deborah Brouwer

Currently a UserPtr can be created from a usize integer representing a userspace address. To create a UserPtr from a u64 integer, the u64 must be cast to usize. On 32-bit systems, this cast will discard the upper 32 bits of the address.

Quoted 7 lines

Provide a new method to create a UserPtr from a u64 integer. This avoids the caller having to cast before creating a UserPtr and also clarifies that the truncation is intended. This is equivalent to the C-side macro u64_to_user_ptr() that provides typechecking and casting to a __user pointer.

Quoted 3 lines
---
 rust/kernel/uaccess.rs | 9 +++++++++
 1 file changed, 9 insertions(+)
#6 lore raw

PATCH v4 3/3 drm/tyr: allow userspace buffers to be mismatched

In reply to Deborah Brouwer

Allow userspace to provide a buffer that is smaller or larger than the object that the kernel expects to write into it.

Set a minimum buffer size to match those in PANTHOR_UOBJ_MIN_SIZE. If userspace provides at least the minimum buffer size, then simply write until the buffer is full.

If userspace provides a larger buffer than necessary, then zero out the remaining buffer.

This ensures UAPI compatibility with Panthor.

---
 drivers/gpu/drm/tyr/file.rs | 49 +++++++++++++++++++++++++++++++++++++--------
 1 file changed, 41 insertions(+), 8 deletions(-)
drivers/gpu/drm/tyr/file.rs +41 -8
index ceadde976502..bf66238ea4c6 100644
@@ -1,14 +1,18 @@
 // SPDX-License-Identifier: GPL-2.0 or MIT
 
+use core::mem::offset_of;
+
 use kernel::{
     drm::{
         self,
         Registered, //
     },
+    num::casts::FromSafeCast,
     prelude::*,
     uaccess::UserSlice,
     uapi, //
 };
+use zerocopy::Immutable;
 
 use crate::driver::{
     TyrDrmDevice,
@@ -16,6 +20,37 @@
     TyrDrmRegistrationData, //
 };
 
+trait UobjMinSize {
+    fn min_size(&self) -> usize;
+}
+
+impl UobjMinSize for uapi::drm_panthor_gpu_info {
+    fn min_size(&self) -> usize {
+        offset_of!(Self, tiler_present) + size_of_val(&self.tiler_present)
+    }
+}
+
+// If the user buffer is at least the minimum required size, then
+// copy as much of the kernel object as will fit into the user buffer.
+// Don't fail if the user buffer is smaller than the kernel object.
+// If the user buffer is bigger than needed, zero out the remainder.
+fn set_uobj<T: IntoBytes + Immutable>(
+    usr_dst: u64,
+    size: u32,
+    min_size: usize,
+    src_obj: &T,
+) -> Result {
+    let size = usize::from_safe_cast(size);
+    if size < min_size {
+        return Err(EINVAL);
+    }
+
+    let mut writer = UserSlice::new(UserPtr::from_u64(usr_dst), size).writer();
+    writer.write_slice_partial(src_obj.as_bytes(), 0)?;
+    writer.clear()?;
+    Ok(())
+}
+
 #[pin_data]
 pub(crate) struct TyrDrmFileData {}
 
@@ -48,14 +83,12 @@ pub(crate) fn dev_query(
         } else {
             match devquery.type_ {
                 uapi::drm_panthor_dev_query_type_DRM_PANTHOR_DEV_QUERY_GPU_INFO => {
-                    let mut writer = UserSlice::new(
-                        UserPtr::from_addr(devquery.pointer as usize),
-                        devquery.size as usize,
-                    )
-                    .writer();
-
-                    writer.write_slice(reg_data.gpu_info.as_bytes())?;
-
+                    set_uobj(
+                        devquery.pointer,
+                        devquery.size,
+                        reg_data.gpu_info.min_size(),
+                        &reg_data.gpu_info,
+                    )?;
                     Ok(0)
                 }
                 _ => Err(EINVAL),
Signature · 1 line
2.56.0
maintainer Reviewed-by on v4 3/3
#7 lore raw

Re: [PATCH v4 3/3] drm/tyr: allow userspace buffers to be mismatched

Quoted 7 lines · Deborah Brouwer

Allow userspace to provide a buffer that is smaller or larger than the object that the kernel expects to write into it.

Set a minimum buffer size to match those in PANTHOR_UOBJ_MIN_SIZE. If userspace provides at least the minimum buffer size, then simply write until the buffer is full.

Quoted 6 lines

If userspace provides a larger buffer than necessary, then zero out the remaining buffer.

This ensures UAPI compatibility with Panthor.

Acked-by
#9 lore raw
Quoted 2 lines · Alice Ryhl

Miguel, are you ok with me taking these uaccess changes through drm-rust-next?

Sure:

A couple notes:

- rust: uaccess: add UserSliceWriter::clear(): Newline before `//
SAFETY comment? I am actually not sure why the newlines are placed like that -- if one wants to compress the code, then I would place the early exit if`s adjacent to the variables they check, saving 2 lines:

      let len = self.length;
      if len == 0 {
          return Ok(());
      }

      // SAFETY: `clear_user` checks the userspace address and range and handles
      // faults when accessing userspace memory
      let res = unsafe { bindings::clear_user(self.ptr.as_mut_ptr(), len) };
      if res != 0 {
          return Err(EFAULT);
      }

- rust: uaccess: add method to get UserPtr from u64: Intra-doc link
on UserPtr, and span and intra-doc link on u64.

- drm/tyr: allow userspace buffers to be mismatched: set_uobj has
a bunch of comments, should they be documentation even if private?

Thanks!

Cheers,
Miguel

maintainer Applied
#10 lore raw
In reply to Deborah Brouwer
Quoted 5 lines · Deborah Brouwer

Panthor UAPI for DRM_IOCTL_PANTHOR_DEV_QUERY allows userspace to provide a smaller or larger buffer than the kernel needs. Revise Tyr's implementation to match the expected UAPI behaviour.

Applied to drm-rust-next. Thanks!

I folded in Miguel's style and doc suggestions when applying.

Alice