public inbox for stable@vger.kernel.org
 help / color / mirror / Atom feed
From: Miguel Ojeda <ojeda@kernel.org>
To: Greg Kroah-Hartman <gregkh@linuxfoundation.org>,
	Sasha Levin <sashal@kernel.org>,
	stable@vger.kernel.org
Cc: Danilo Krummrich <dakr@kernel.org>,
	Alice Ryhl <aliceryhl@google.com>, Alyssa Ross <hi@alyssa.is>,
	NoisyCoil <noisycoil@disroot.org>,
	patches@lists.linux.dev, Miguel Ojeda <ojeda@kernel.org>
Subject: [PATCH 6.12.y 2/2] rust: map `long` to `isize` and `char` to `u8`
Date: Sun,  9 Mar 2025 21:42:17 +0100	[thread overview]
Message-ID: <20250309204217.1553389-3-ojeda@kernel.org> (raw)
In-Reply-To: <20250309204217.1553389-1-ojeda@kernel.org>

From: Gary Guo <gary@garyguo.net>

commit 1bae8729e50a900f41e9a1c17ae81113e4cf62b8 upstream.

The following FFI types are replaced compared to `core::ffi`:

1. `char` type is now always mapped to `u8`, since kernel uses
   `-funsigned-char` on the C code. `core::ffi` maps it to platform
   default ABI, which can be either signed or unsigned.

2. `long` is now always mapped to `isize`. It's very common in the
   kernel to use `long` to represent a pointer-sized integer, and in
   fact `intptr_t` is a typedef of `long` in the kernel. Enforce this
   mapping rather than mapping to `i32/i64` depending on platform can
   save us a lot of unnecessary casts.

Signed-off-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240913213041.395655-5-gary@garyguo.net
[ Moved `uaccess` changes from the next commit, since they were
  irrefutable patterns that Rust >= 1.82.0 warns about. Reworded
  slightly and reformatted a few documentation comments. Rebased on
  top of `rust-next`. Added the removal of two casts to avoid Clippy
  warnings. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
---
 rust/ffi.rs             | 37 ++++++++++++++++++++++++++++++++++++-
 rust/kernel/error.rs    |  5 +----
 rust/kernel/firmware.rs |  2 +-
 rust/kernel/uaccess.rs  | 27 +++++++--------------------
 4 files changed, 45 insertions(+), 26 deletions(-)

diff --git a/rust/ffi.rs b/rust/ffi.rs
index be153c4d551b..584f75b49862 100644
--- a/rust/ffi.rs
+++ b/rust/ffi.rs
@@ -10,4 +10,39 @@
 
 #![no_std]
 
-pub use core::ffi::*;
+macro_rules! alias {
+    ($($name:ident = $ty:ty;)*) => {$(
+        #[allow(non_camel_case_types, missing_docs)]
+        pub type $name = $ty;
+
+        // Check size compatibility with `core`.
+        const _: () = assert!(
+            core::mem::size_of::<$name>() == core::mem::size_of::<core::ffi::$name>()
+        );
+    )*}
+}
+
+alias! {
+    // `core::ffi::c_char` is either `i8` or `u8` depending on architecture. In the kernel, we use
+    // `-funsigned-char` so it's always mapped to `u8`.
+    c_char = u8;
+
+    c_schar = i8;
+    c_uchar = u8;
+
+    c_short = i16;
+    c_ushort = u16;
+
+    c_int = i32;
+    c_uint = u32;
+
+    // In the kernel, `intptr_t` is defined to be `long` in all platforms, so we can map the type to
+    // `isize`.
+    c_long = isize;
+    c_ulong = usize;
+
+    c_longlong = i64;
+    c_ulonglong = u64;
+}
+
+pub use core::ffi::c_void;
diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs
index 52c502432447..5fece574ec02 100644
--- a/rust/kernel/error.rs
+++ b/rust/kernel/error.rs
@@ -153,11 +153,8 @@ pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
 
     /// Returns the error encoded as a pointer.
     pub fn to_ptr<T>(self) -> *mut T {
-        #[cfg_attr(target_pointer_width = "32", allow(clippy::useless_conversion))]
         // SAFETY: `self.0` is a valid error due to its invariant.
-        unsafe {
-            bindings::ERR_PTR(self.0.get().into()) as *mut _
-        }
+        unsafe { bindings::ERR_PTR(self.0.get() as _) as *mut _ }
     }
 
     /// Returns a string representing the error, if one exists.
diff --git a/rust/kernel/firmware.rs b/rust/kernel/firmware.rs
index 13a374a5cdb7..c5162fdc95ff 100644
--- a/rust/kernel/firmware.rs
+++ b/rust/kernel/firmware.rs
@@ -12,7 +12,7 @@
 /// One of the following: `bindings::request_firmware`, `bindings::firmware_request_nowarn`,
 /// `bindings::firmware_request_platform`, `bindings::request_firmware_direct`.
 struct FwFunc(
-    unsafe extern "C" fn(*mut *const bindings::firmware, *const i8, *mut bindings::device) -> i32,
+    unsafe extern "C" fn(*mut *const bindings::firmware, *const u8, *mut bindings::device) -> i32,
 );
 
 impl FwFunc {
diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs
index 66cc76e68428..5a3c2d4df65f 100644
--- a/rust/kernel/uaccess.rs
+++ b/rust/kernel/uaccess.rs
@@ -8,7 +8,7 @@
     alloc::Flags,
     bindings,
     error::Result,
-    ffi::{c_ulong, c_void},
+    ffi::c_void,
     prelude::*,
     types::{AsBytes, FromBytes},
 };
@@ -224,13 +224,9 @@ pub fn read_raw(&mut self, out: &mut [MaybeUninit<u8>]) -> Result {
         if len > self.length {
             return Err(EFAULT);
         }
-        let Ok(len_ulong) = c_ulong::try_from(len) else {
-            return Err(EFAULT);
-        };
-        // SAFETY: `out_ptr` points into a mutable slice of length `len_ulong`, so we may write
+        // SAFETY: `out_ptr` points into a mutable slice of length `len`, so we may write
         // that many bytes to it.
-        let res =
-            unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len_ulong) };
+        let res = unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len) };
         if res != 0 {
             return Err(EFAULT);
         }
@@ -259,9 +255,6 @@ pub fn read<T: FromBytes>(&mut self) -> Result<T> {
         if len > self.length {
             return Err(EFAULT);
         }
-        let Ok(len_ulong) = c_ulong::try_from(len) else {
-            return Err(EFAULT);
-        };
         let mut out: MaybeUninit<T> = MaybeUninit::uninit();
         // SAFETY: The local variable `out` is valid for writing `size_of::<T>()` bytes.
         //
@@ -272,7 +265,7 @@ pub fn read<T: FromBytes>(&mut self) -> Result<T> {
             bindings::_copy_from_user(
                 out.as_mut_ptr().cast::<c_void>(),
                 self.ptr as *const c_void,
-                len_ulong,
+                len,
             )
         };
         if res != 0 {
@@ -335,12 +328,9 @@ pub fn write_slice(&mut self, data: &[u8]) -> Result {
         if len > self.length {
             return Err(EFAULT);
         }
-        let Ok(len_ulong) = c_ulong::try_from(len) else {
-            return Err(EFAULT);
-        };
-        // SAFETY: `data_ptr` points into an immutable slice of length `len_ulong`, so we may read
+        // SAFETY: `data_ptr` points into an immutable slice of length `len`, so we may read
         // that many bytes from it.
-        let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len_ulong) };
+        let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len) };
         if res != 0 {
             return Err(EFAULT);
         }
@@ -359,9 +349,6 @@ pub fn write<T: AsBytes>(&mut self, value: &T) -> Result {
         if len > self.length {
             return Err(EFAULT);
         }
-        let Ok(len_ulong) = c_ulong::try_from(len) else {
-            return Err(EFAULT);
-        };
         // SAFETY: The reference points to a value of type `T`, so it is valid for reading
         // `size_of::<T>()` bytes.
         //
@@ -372,7 +359,7 @@ pub fn write<T: AsBytes>(&mut self, value: &T) -> Result {
             bindings::_copy_to_user(
                 self.ptr as *mut c_void,
                 (value as *const T).cast::<c_void>(),
-                len_ulong,
+                len,
             )
         };
         if res != 0 {
-- 
2.48.1


  parent reply	other threads:[~2025-03-09 20:42 UTC|newest]

Thread overview: 72+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-03-07 22:49 [PATCH 6.12.y 00/60] `alloc`, `#[expect]` and "Custom FFI" Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 01/60] rust: workqueue: remove unneeded ``#[allow(clippy::new_ret_no_self)]` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 02/60] rust: sort global Rust flags Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 03/60] rust: types: avoid repetition in `{As,From}Bytes` impls Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 04/60] rust: enable `clippy::undocumented_unsafe_blocks` lint Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 05/60] rust: enable `clippy::unnecessary_safety_comment` lint Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 06/60] rust: enable `clippy::unnecessary_safety_doc` lint Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 07/60] rust: enable `clippy::ignored_unit_patterns` lint Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 08/60] rust: enable `rustdoc::unescaped_backticks` lint Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 09/60] rust: init: remove unneeded `#[allow(clippy::disallowed_names)]` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 10/60] rust: sync: remove unneeded `#[allow(clippy::non_send_fields_in_send_ty)]` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 11/60] rust: introduce `.clippy.toml` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 12/60] rust: replace `clippy::dbg_macro` with `disallowed_macros` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 13/60] rust: provide proper code documentation titles Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 14/60] rust: enable Clippy's `check-private-items` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 15/60] Documentation: rust: add coding guidelines on lints Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 16/60] rust: start using the `#[expect(...)]` attribute Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 17/60] Documentation: rust: discuss `#[expect(...)]` in the guidelines Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 18/60] rust: error: make conversion functions public Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 19/60] rust: error: optimize error type to use nonzero Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 20/60] rust: alloc: add `Allocator` trait Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 21/60] rust: alloc: separate `aligned_size` from `krealloc_aligned` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 22/60] rust: alloc: rename `KernelAllocator` to `Kmalloc` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 23/60] rust: alloc: implement `ReallocFunc` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 24/60] rust: alloc: make `allocator` module public Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 25/60] rust: alloc: implement `Allocator` for `Kmalloc` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 26/60] rust: alloc: add module `allocator_test` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 27/60] rust: alloc: implement `Vmalloc` allocator Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 28/60] rust: alloc: implement `KVmalloc` allocator Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 29/60] rust: alloc: add __GFP_NOWARN to `Flags` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 30/60] rust: alloc: implement kernel `Box` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 31/60] rust: treewide: switch to our kernel `Box` type Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 32/60] rust: alloc: remove extension of std's `Box` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 33/60] rust: alloc: add `Box` to prelude Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 34/60] rust: alloc: introduce `ArrayLayout` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 35/60] rust: alloc: implement kernel `Vec` type Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 36/60] rust: alloc: implement `IntoIterator` for `Vec` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 37/60] rust: alloc: implement `collect` for `IntoIter` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 38/60] rust: treewide: switch to the kernel `Vec` type Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 39/60] rust: alloc: remove `VecExt` extension Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 40/60] rust: alloc: add `Vec` to prelude Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 41/60] rust: error: use `core::alloc::LayoutError` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 42/60] rust: error: check for config `test` in `Error::name` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 43/60] rust: alloc: implement `contains` for `Flags` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 44/60] rust: alloc: implement `Cmalloc` in module allocator_test Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 45/60] rust: str: test: replace `alloc::format` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 46/60] rust: alloc: update module comment of alloc.rs Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 47/60] kbuild: rust: remove the `alloc` crate and `GlobalAlloc` Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 48/60] MAINTAINERS: add entry for the Rust `alloc` module Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 49/60] drm/panic: avoid reimplementing Iterator::find Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 50/60] drm/panic: remove unnecessary borrow in alignment_pattern Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 51/60] drm/panic: prefer eliding lifetimes Miguel Ojeda
2025-03-07 22:49 ` [PATCH 6.12.y 52/60] drm/panic: remove redundant field when assigning value Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 53/60] drm/panic: correctly indent continuation of line in list item Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 54/60] drm/panic: allow verbose boolean for clarity Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 55/60] drm/panic: allow verbose version check Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 56/60] rust: kbuild: expand rusttest target for macros Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 57/60] rust: fix size_t in bindgen prototypes of C builtins Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 58/60] rust: map `__kernel_size_t` and friends also to usize/isize Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 59/60] rust: use custom FFI integer types Miguel Ojeda
2025-03-07 22:50 ` [PATCH 6.12.y 60/60] rust: alloc: Fix `ArrayLayout` allocations Miguel Ojeda
2025-03-09  9:47 ` [PATCH 6.12.y 00/60] `alloc`, `#[expect]` and "Custom FFI" Greg Kroah-Hartman
2025-03-09 12:41 ` Ilya K
2025-03-09 14:20   ` Miguel Ojeda
2025-03-09 16:27     ` Greg Kroah-Hartman
2025-03-09 20:42       ` [PATCH 6.12.y 0/2] The two missing ones Miguel Ojeda
2025-03-09 20:42         ` [PATCH 6.12.y 1/2] rust: finish using custom FFI integer types Miguel Ojeda
2025-03-13  9:01           ` Sasha Levin
2025-03-09 20:42         ` Miguel Ojeda [this message]
2025-03-13  9:01           ` [PATCH 6.12.y 2/2] rust: map `long` to `isize` and `char` to `u8` Sasha Levin
2025-03-13 10:59             ` Miguel Ojeda
2025-03-09 21:02         ` [PATCH 6.12.y 0/2] The two missing ones Greg Kroah-Hartman

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20250309204217.1553389-3-ojeda@kernel.org \
    --to=ojeda@kernel.org \
    --cc=aliceryhl@google.com \
    --cc=dakr@kernel.org \
    --cc=gregkh@linuxfoundation.org \
    --cc=hi@alyssa.is \
    --cc=noisycoil@disroot.org \
    --cc=patches@lists.linux.dev \
    --cc=sashal@kernel.org \
    --cc=stable@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox