mbox series

[v9,0/6] rust: reduce `as` casts, enable related lints

Message ID 20250416-ptr-as-ptr-v9-0-18ec29b1b1f3@gmail.com
Headers show
Series rust: reduce `as` casts, enable related lints | expand

Message

Tamir Duberstein April 16, 2025, 5:36 p.m. UTC
This started with a patch that enabled `clippy::ptr_as_ptr`. Benno
Lossin suggested I also look into `clippy::ptr_cast_constness` and I
discovered `clippy::as_ptr_cast_mut`. This series now enables all 3
lints. It also enables `clippy::as_underscore` which ensures other
pointer casts weren't missed.

As a later addition, `clippy::cast_lossless` and `clippy::ref_as_ptr`
are also enabled.

This series depends on "rust: retain pointer mut-ness in
`container_of!`"[1].

Link: https://lore.kernel.org/all/20250409-container-of-mutness-v1-1-64f472b94534@gmail.com/ [1]

Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
Changes in v9:
- Replace ref-to-ptr coercion using `let` bindings with
  `core::ptr::from_{ref,mut}`. (Boqun Feng).
- Link to v8: https://lore.kernel.org/r/20250409-ptr-as-ptr-v8-0-3738061534ef@gmail.com

Changes in v8:
- Use coercion to go ref -> ptr.
- rustfmt.
- Rebase on v6.15-rc1.
- Extract first commit to its own series as it is shared with other
  series.
- Link to v7: https://lore.kernel.org/r/20250325-ptr-as-ptr-v7-0-87ab452147b9@gmail.com

Changes in v7:
- Add patch to enable `clippy::ref_as_ptr`.
- Link to v6: https://lore.kernel.org/r/20250324-ptr-as-ptr-v6-0-49d1b7fd4290@gmail.com

Changes in v6:
- Drop strict provenance patch.
- Fix URLs in doc comments.
- Add patch to enable `clippy::cast_lossless`.
- Rebase on rust-next.
- Link to v5: https://lore.kernel.org/r/20250317-ptr-as-ptr-v5-0-5b5f21fa230a@gmail.com

Changes in v5:
- Use `pointer::addr` in OF. (Boqun Feng)
- Add documentation on stubs. (Benno Lossin)
- Mark stubs `#[inline]`.
- Pick up Alice's RB on a shared commit from
  https://lore.kernel.org/all/Z9f-3Aj3_FWBZRrm@google.com/.
- Link to v4: https://lore.kernel.org/r/20250315-ptr-as-ptr-v4-0-b2d72c14dc26@gmail.com

Changes in v4:
- Add missing SoB. (Benno Lossin)
- Use `without_provenance_mut` in alloc. (Boqun Feng)
- Limit strict provenance lints to the `kernel` crate to avoid complex
  logic in the build system. This can be revisited on MSRV >= 1.84.0.
- Rebase on rust-next.
- Link to v3: https://lore.kernel.org/r/20250314-ptr-as-ptr-v3-0-e7ba61048f4a@gmail.com

Changes in v3:
- Fixed clippy warning in rust/kernel/firmware.rs. (kernel test robot)
  Link: https://lore.kernel.org/all/202503120332.YTCpFEvv-lkp@intel.com/
- s/as u64/as bindings::phys_addr_t/g. (Benno Lossin)
- Use strict provenance APIs and enable lints. (Benno Lossin)
- Link to v2: https://lore.kernel.org/r/20250309-ptr-as-ptr-v2-0-25d60ad922b7@gmail.com

Changes in v2:
- Fixed typo in first commit message.
- Added additional patches, converted to series.
- Link to v1: https://lore.kernel.org/r/20250307-ptr-as-ptr-v1-1-582d06514c98@gmail.com

---
Tamir Duberstein (6):
      rust: enable `clippy::ptr_as_ptr` lint
      rust: enable `clippy::ptr_cast_constness` lint
      rust: enable `clippy::as_ptr_cast_mut` lint
      rust: enable `clippy::as_underscore` lint
      rust: enable `clippy::cast_lossless` lint
      rust: enable `clippy::ref_as_ptr` lint

 Makefile                               |  6 ++++++
 drivers/gpu/drm/drm_panic_qr.rs        |  2 +-
 rust/bindings/lib.rs                   |  3 +++
 rust/kernel/alloc/allocator_test.rs    |  2 +-
 rust/kernel/alloc/kvec.rs              |  4 ++--
 rust/kernel/block/mq/operations.rs     |  2 +-
 rust/kernel/block/mq/request.rs        |  6 +++---
 rust/kernel/device.rs                  |  4 ++--
 rust/kernel/device_id.rs               |  4 ++--
 rust/kernel/devres.rs                  | 19 ++++++++++---------
 rust/kernel/dma.rs                     |  6 +++---
 rust/kernel/error.rs                   |  2 +-
 rust/kernel/firmware.rs                |  3 ++-
 rust/kernel/fs/file.rs                 |  2 +-
 rust/kernel/io.rs                      | 18 +++++++++---------
 rust/kernel/kunit.rs                   | 11 +++++++----
 rust/kernel/list/impl_list_item_mod.rs |  2 +-
 rust/kernel/miscdevice.rs              |  2 +-
 rust/kernel/net/phy.rs                 |  4 ++--
 rust/kernel/of.rs                      |  6 +++---
 rust/kernel/pci.rs                     | 11 +++++++----
 rust/kernel/platform.rs                |  4 +++-
 rust/kernel/print.rs                   |  6 +++---
 rust/kernel/seq_file.rs                |  2 +-
 rust/kernel/str.rs                     | 14 +++++++-------
 rust/kernel/sync/poll.rs               |  2 +-
 rust/kernel/time/hrtimer/pin.rs        |  2 +-
 rust/kernel/time/hrtimer/pin_mut.rs    |  2 +-
 rust/kernel/uaccess.rs                 |  4 ++--
 rust/kernel/workqueue.rs               | 12 ++++++------
 rust/uapi/lib.rs                       |  3 +++
 31 files changed, 96 insertions(+), 74 deletions(-)
---
base-commit: 0af2f6be1b4281385b618cb86ad946eded089ac8
change-id: 20250307-ptr-as-ptr-21b1867fc4d4
prerequisite-change-id: 20250409-container-of-mutness-b153dab4388d:v1
prerequisite-patch-id: 53d5889db599267f87642bb0ae3063c29bc24863

Best regards,

Comments

Boqun Feng April 17, 2025, 4:48 p.m. UTC | #1
On Wed, Apr 16, 2025 at 01:36:05PM -0400, Tamir Duberstein wrote:
> In Rust 1.51.0, Clippy introduced the `ptr_as_ptr` lint [1]:
> 
> > Though `as` casts between raw pointers are not terrible,
> > `pointer::cast` is safer because it cannot accidentally change the
> > pointer's mutability, nor cast the pointer to other types like `usize`.
> 
> There are a few classes of changes required:
> - Modules generated by bindgen are marked
>   `#[allow(clippy::ptr_as_ptr)]`.
> - Inferred casts (` as _`) are replaced with `.cast()`.
> - Ascribed casts (` as *... T`) are replaced with `.cast::<T>()`.
> - Multistep casts from references (` as *const _ as *const T`) are
>   replaced with `core::ptr::from_ref(&x).cast()` with or without `::<T>`
>   according to the previous rules. The `core::ptr::from_ref` call is
>   required because `(x as *const _).cast::<T>()` results in inference
>   failure.
> - Native literal C strings are replaced with `c_str!().as_char_ptr()`.
> - `*mut *mut T as _` is replaced with `let *mut *const T = (*mut *mut
>   T)`.cast();` since pointer to pointer can be confusing.
> 
> Apply these changes and enable the lint -- no functional change
> intended.
> 
> Link: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr [1]
> Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>

Reviewed-by: Boqun Feng <boqun.feng@gmail.com>

A few nits below though...

> ---
>  Makefile                               |  1 +
>  rust/bindings/lib.rs                   |  1 +
>  rust/kernel/alloc/allocator_test.rs    |  2 +-
>  rust/kernel/alloc/kvec.rs              |  4 ++--
>  rust/kernel/device.rs                  |  4 ++--
>  rust/kernel/devres.rs                  |  2 +-
>  rust/kernel/dma.rs                     |  4 ++--
>  rust/kernel/error.rs                   |  2 +-
>  rust/kernel/firmware.rs                |  3 ++-
>  rust/kernel/fs/file.rs                 |  2 +-
>  rust/kernel/kunit.rs                   | 11 +++++++----
>  rust/kernel/list/impl_list_item_mod.rs |  2 +-
>  rust/kernel/pci.rs                     |  2 +-
>  rust/kernel/platform.rs                |  4 +++-
>  rust/kernel/print.rs                   |  6 +++---
>  rust/kernel/seq_file.rs                |  2 +-
>  rust/kernel/str.rs                     |  2 +-
>  rust/kernel/sync/poll.rs               |  2 +-
>  rust/kernel/time/hrtimer/pin.rs        |  2 +-
>  rust/kernel/time/hrtimer/pin_mut.rs    |  2 +-
>  rust/kernel/workqueue.rs               | 10 +++++-----
>  rust/uapi/lib.rs                       |  1 +
>  22 files changed, 40 insertions(+), 31 deletions(-)
> 
[...]
> diff --git a/rust/kernel/list/impl_list_item_mod.rs b/rust/kernel/list/impl_list_item_mod.rs
> index a0438537cee1..1f9498c1458f 100644
> --- a/rust/kernel/list/impl_list_item_mod.rs
> +++ b/rust/kernel/list/impl_list_item_mod.rs
> @@ -34,7 +34,7 @@ pub unsafe trait HasListLinks<const ID: u64 = 0> {
>      unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut ListLinks<ID> {
>          // SAFETY: The caller promises that the pointer is valid. The implementer promises that the
>          // `OFFSET` constant is correct.
> -        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut ListLinks<ID> }
> +        unsafe { ptr.cast::<u8>().add(Self::OFFSET).cast() }

I think we better do:

	unsafe { ptr.byte_add(Self::OFFSET).cast() }

here, similar for a few instances below. Maybe in a follow-up patch?
byte_add() is way more clear about what is done here.

Regards,
Boqun

>      }
>  }
>  
[...]
> @@ -457,7 +457,7 @@ fn get_work_offset(&self) -> usize {
>      #[inline]
>      unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
>          // SAFETY: The caller promises that the pointer is valid.
> -        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
> +        unsafe { ptr.cast::<u8>().add(Self::OFFSET).cast::<Work<T, ID>>() }
>      }
>  
>      /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
> @@ -472,7 +472,7 @@ unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *mut Self
>      {
>          // SAFETY: The caller promises that the pointer points at a field of the right type in the
>          // right kind of struct.
> -        unsafe { (ptr as *mut u8).sub(Self::OFFSET) as *mut Self }
> +        unsafe { ptr.cast::<u8>().sub(Self::OFFSET).cast::<Self>() }
>      }
>  }
>  
[...]
Tamir Duberstein April 17, 2025, 5 p.m. UTC | #2
On Thu, Apr 17, 2025 at 12:48 PM Boqun Feng <boqun.feng@gmail.com> wrote:
>
> On Wed, Apr 16, 2025 at 01:36:05PM -0400, Tamir Duberstein wrote:
> > In Rust 1.51.0, Clippy introduced the `ptr_as_ptr` lint [1]:
> >
> > > Though `as` casts between raw pointers are not terrible,
> > > `pointer::cast` is safer because it cannot accidentally change the
> > > pointer's mutability, nor cast the pointer to other types like `usize`.
> >
> > There are a few classes of changes required:
> > - Modules generated by bindgen are marked
> >   `#[allow(clippy::ptr_as_ptr)]`.
> > - Inferred casts (` as _`) are replaced with `.cast()`.
> > - Ascribed casts (` as *... T`) are replaced with `.cast::<T>()`.
> > - Multistep casts from references (` as *const _ as *const T`) are
> >   replaced with `core::ptr::from_ref(&x).cast()` with or without `::<T>`
> >   according to the previous rules. The `core::ptr::from_ref` call is
> >   required because `(x as *const _).cast::<T>()` results in inference
> >   failure.
> > - Native literal C strings are replaced with `c_str!().as_char_ptr()`.
> > - `*mut *mut T as _` is replaced with `let *mut *const T = (*mut *mut
> >   T)`.cast();` since pointer to pointer can be confusing.
> >
> > Apply these changes and enable the lint -- no functional change
> > intended.
> >
> > Link: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr [1]
> > Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> > Signed-off-by: Tamir Duberstein <tamird@gmail.com>
>
> Reviewed-by: Boqun Feng <boqun.feng@gmail.com>

Thanks!

> A few nits below though...
>
> > ---
> >  Makefile                               |  1 +
> >  rust/bindings/lib.rs                   |  1 +
> >  rust/kernel/alloc/allocator_test.rs    |  2 +-
> >  rust/kernel/alloc/kvec.rs              |  4 ++--
> >  rust/kernel/device.rs                  |  4 ++--
> >  rust/kernel/devres.rs                  |  2 +-
> >  rust/kernel/dma.rs                     |  4 ++--
> >  rust/kernel/error.rs                   |  2 +-
> >  rust/kernel/firmware.rs                |  3 ++-
> >  rust/kernel/fs/file.rs                 |  2 +-
> >  rust/kernel/kunit.rs                   | 11 +++++++----
> >  rust/kernel/list/impl_list_item_mod.rs |  2 +-
> >  rust/kernel/pci.rs                     |  2 +-
> >  rust/kernel/platform.rs                |  4 +++-
> >  rust/kernel/print.rs                   |  6 +++---
> >  rust/kernel/seq_file.rs                |  2 +-
> >  rust/kernel/str.rs                     |  2 +-
> >  rust/kernel/sync/poll.rs               |  2 +-
> >  rust/kernel/time/hrtimer/pin.rs        |  2 +-
> >  rust/kernel/time/hrtimer/pin_mut.rs    |  2 +-
> >  rust/kernel/workqueue.rs               | 10 +++++-----
> >  rust/uapi/lib.rs                       |  1 +
> >  22 files changed, 40 insertions(+), 31 deletions(-)
> >
> [...]
> > diff --git a/rust/kernel/list/impl_list_item_mod.rs b/rust/kernel/list/impl_list_item_mod.rs
> > index a0438537cee1..1f9498c1458f 100644
> > --- a/rust/kernel/list/impl_list_item_mod.rs
> > +++ b/rust/kernel/list/impl_list_item_mod.rs
> > @@ -34,7 +34,7 @@ pub unsafe trait HasListLinks<const ID: u64 = 0> {
> >      unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut ListLinks<ID> {
> >          // SAFETY: The caller promises that the pointer is valid. The implementer promises that the
> >          // `OFFSET` constant is correct.
> > -        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut ListLinks<ID> }
> > +        unsafe { ptr.cast::<u8>().add(Self::OFFSET).cast() }
>
> I think we better do:
>
>         unsafe { ptr.byte_add(Self::OFFSET).cast() }
>
> here, similar for a few instances below. Maybe in a follow-up patch?
> byte_add() is way more clear about what is done here.

This code is deleted in
https://lore.kernel.org/all/20250409-list-no-offset-v2-4-0bab7e3c9fd8@gmail.com/,
which could also use a review!

Cheers.
Tamir
Tamir Duberstein April 17, 2025, 7:28 p.m. UTC | #3
On Thu, Apr 17, 2025 at 1:29 PM Boqun Feng <boqun.feng@gmail.com> wrote:
>
> On Wed, Apr 16, 2025 at 01:36:09PM -0400, Tamir Duberstein wrote:
> > Before Rust 1.29.0, Clippy introduced the `cast_lossless` lint [1]:
> >
> > > Rust’s `as` keyword will perform many kinds of conversions, including
> > > silently lossy conversions. Conversion functions such as `i32::from`
> > > will only perform lossless conversions. Using the conversion functions
> > > prevents conversions from becoming silently lossy if the input types
> > > ever change, and makes it clear for people reading the code that the
> > > conversion is lossless.
> >
> > While this doesn't eliminate unchecked `as` conversions, it makes such
> > conversions easier to scrutinize.  It also has the slight benefit of
> > removing a degree of freedom on which to bikeshed. Thus apply the
> > changes and enable the lint -- no functional change intended.
> >
> > Link: https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless [1]
>
> Hmm.. I agree with the solution mentioned from the lint URL, using
> `from()` is better, so..
>
> > Suggested-by: Benno Lossin <benno.lossin@proton.me>
> > Link: https://lore.kernel.org/all/D8ORTXSUTKGL.1KOJAGBM8F8TN@proton.me/
> > Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> > Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> > ---
> >  Makefile                        | 1 +
> >  drivers/gpu/drm/drm_panic_qr.rs | 2 +-
> >  rust/bindings/lib.rs            | 1 +
> >  rust/kernel/net/phy.rs          | 4 ++--
> >  rust/uapi/lib.rs                | 1 +
> >  5 files changed, 6 insertions(+), 3 deletions(-)
> >
> > diff --git a/Makefile b/Makefile
> > index 57080a64913f..eb5a942241a2 100644
> > --- a/Makefile
> > +++ b/Makefile
> > @@ -476,6 +476,7 @@ export rust_common_flags := --edition=2021 \
> >                           -Wclippy::all \
> >                           -Wclippy::as_ptr_cast_mut \
> >                           -Wclippy::as_underscore \
> > +                         -Wclippy::cast_lossless \
> >                           -Wclippy::ignored_unit_patterns \
> >                           -Wclippy::mut_mut \
> >                           -Wclippy::needless_bitwise_bool \
> > diff --git a/drivers/gpu/drm/drm_panic_qr.rs b/drivers/gpu/drm/drm_panic_qr.rs
> > index f2a99681b998..d28e8f199d11 100644
> > --- a/drivers/gpu/drm/drm_panic_qr.rs
> > +++ b/drivers/gpu/drm/drm_panic_qr.rs
> > @@ -386,7 +386,7 @@ fn next(&mut self) -> Option<Self::Item> {
> >          match self.segment {
> >              Segment::Binary(data) => {
> >                  if self.offset < data.len() {
> > -                    let byte = data[self.offset] as u16;
> > +                    let byte = data[self.offset].into();
>
>         let byte = u16::from(data[self.offset]);
>
> otherwise, the code has not local indicator saying what type the byte
> is, and given its name is "byte" but it's really a `u16`, I think it's
> better we mention the type here.
>
> >                      self.offset += 1;
> >                      Some((byte, 8))
> >                  } else {
> > diff --git a/rust/bindings/lib.rs b/rust/bindings/lib.rs
> > index 0486a32ed314..b105a0d899cc 100644
> > --- a/rust/bindings/lib.rs
> > +++ b/rust/bindings/lib.rs
> > @@ -25,6 +25,7 @@
> >  )]
> >
> >  #[allow(dead_code)]
> > +#[allow(clippy::cast_lossless)]
> >  #[allow(clippy::ptr_as_ptr)]
> >  #[allow(clippy::undocumented_unsafe_blocks)]
> >  mod bindings_raw {
> > diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
> > index a59469c785e3..abc58b4d1bf4 100644
> > --- a/rust/kernel/net/phy.rs
> > +++ b/rust/kernel/net/phy.rs
> > @@ -142,7 +142,7 @@ pub fn is_autoneg_enabled(&self) -> bool {
> >          // SAFETY: The struct invariant ensures that we may access
> >          // this field without additional synchronization.
> >          let bit_field = unsafe { &(*self.0.get())._bitfield_1 };
> > -        bit_field.get(13, 1) == bindings::AUTONEG_ENABLE as u64
> > +        bit_field.get(13, 1) == bindings::AUTONEG_ENABLE.into()
>
>         bit_field.get(13, 1) == u64::from(bindings::AUTONEG_ENABLE)
>
> >      }
> >
> >      /// Gets the current auto-negotiation state.
> > @@ -426,7 +426,7 @@ impl<T: Driver> Adapter<T> {
> >          // where we hold `phy_device->lock`, so the accessors on
> >          // `Device` are okay to call.
> >          let dev = unsafe { Device::from_raw(phydev) };
> > -        T::match_phy_device(dev) as i32
> > +        T::match_phy_device(dev).into()
>
>         i32::from(T::match_phy_device(dev))
>
> Thoughts? Better be explicit in these cases, IMO.

I changed the first two. This one I'll leave as `into()` because the
destination type is in the method signature, which is 5 lines above.

Thanks for the review!