VFIO PCI drivers need to bound user-buffer transfers delegated to C
and traverse device-specific fields without fetching preceding bytes.
UserSlice should cover that use without a separate VFIO buffer type.

Suggested-by: Danilo Krummrich <[email protected]>
Signed-off-by: Simon Song <[email protected]>
---
 rust/kernel/uaccess.rs | 44 ++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 42 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs
index ab6b34a0fc97..d002769f21e9 100644
--- a/rust/kernel/uaccess.rs
+++ b/rust/kernel/uaccess.rs
@@ -15,7 +15,13 @@
     ptr::KnownSize,
     transmute::{AsBytes, FromBytes},
 };
-use core::mem::{size_of, MaybeUninit};
+use core::{
+    cmp,
+    mem::{
+        size_of,
+        MaybeUninit, //
+    }, //
+};
 
 /// A pointer into userspace.
 ///
@@ -226,13 +232,25 @@ pub struct UserSliceReader {
 }
 
 impl UserSliceReader {
+    /// Returns the current userspace pointer.
+    #[inline]
+    pub(crate) fn as_ptr(&self) -> UserPtr {
+        self.ptr
+    }
+
+    /// Limits the remaining buffer to at most `length` bytes, keeping its 
current address.
+    #[inline]
+    pub fn truncate(&mut self, length: usize) {
+        self.length = cmp::min(self.length, length);
+    }
+
     /// Skip the provided number of bytes.
     ///
     /// Returns an error if skipping more than the length of the buffer.
     pub fn skip(&mut self, num_skip: usize) -> Result {
         // Update `self.length` first since that's the fallible part of this 
operation.
         self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?;
-        self.ptr = self.ptr.wrapping_byte_add(num_skip);
+        self.ptr = self.as_ptr().wrapping_byte_add(num_skip);
         Ok(())
     }
 
@@ -458,6 +476,28 @@ pub struct UserSliceWriter {
 }
 
 impl UserSliceWriter {
+    /// Returns the current userspace pointer.
+    #[inline]
+    pub(crate) fn as_ptr(&self) -> UserPtr {
+        self.ptr
+    }
+
+    /// Limits the remaining buffer to at most `length` bytes, keeping its 
current address.
+    #[inline]
+    pub fn truncate(&mut self, length: usize) {
+        self.length = cmp::min(self.length, length);
+    }
+
+    /// Skips the provided number of bytes without writing to them.
+    ///
+    /// Returns an error if skipping more than the length of the buffer.
+    #[inline]
+    pub fn skip(&mut self, num_skip: usize) -> Result {
+        self.length = self.length.checked_sub(num_skip).ok_or(EFAULT)?;
+        self.ptr = self.as_ptr().wrapping_byte_add(num_skip);
+        Ok(())
+    }
+
     /// Returns the amount of space remaining in this buffer.
     ///
     /// Note that even writing less than this number of bytes may fail.
-- 
2.43.7

Reply via email to