Skip to contentSkip to conversation

`alloc`, `#[expect]` and "Custom FFI"

PATCH Applied Miguel Ojeda 5 participants 134 messages Mar 7, 2025 – Mar 13, 2025 Page 1 of 2

Subsystems (20)
lore
Share & tools
lore

Miguel Ojeda

author maintainer
#0 lore raw

cover `alloc`, `#[expect]` and "Custom FFI"

Hi Greg, Sasha,

Please consider this series for 6.12.y. It should apply cleanly on top of v6.12.18.

These are the patches to backport the alloc series for Rust, which will be useful for Rust Android Binder and others. It also means that, with this applied, we will not rely on the standard library alloc (and the unstable cfg option we used) anymore in any stable kernel that supports several Rust versions, so e.g. upstream Rust could consider removing that cfg if they needed.

The entire series of cherry-picks apply almost cleanly (only 2 trivial conflicts) -- to achieve that, I included the #[expect] support, which will make future backports that use that feature easier anyway. That series also enabled some Clippy warnings. We could reduce the series, but the end result is warning-free and Clippy is opt-in anyway. Out-of-tree code could, of course, see some warnings if they use it.

I also included a bunch of Clippy warnings cleanups for the DRM QR Code to have this series clean up to Rust 1.85.0 (the latest stable), but I could send them separately if needed.

Finally, I included the "Custom FFI" series backport, which in turn solves the arm64 + Rust 1.85.0 + CONFIG_RUST_FW_LOADER_ABSTRACTIONS=y issue. It will also make future patches easier to backport, since we will have the same ffi:: types.

I tested that the entire series builds between every commit for x86_64 LLVM=1 with the latest stable and minimum supported Rust compiler versions. I also ran my usual stable kernel tests on the end result; that is, boot-tested in QEMU for several architectures etc. In v6.12.18 for loongarch there is an unrelated error that was not there in v6.12.17 when I did a previous test run -- reported separately.

Things could still break, so extra tests on the next -rc from users in Cc here would be welcome -- thanks!

Cheers,
Miguel

Asahi Lina (1):
rust: alloc: Fix ArrayLayout allocations

Benno Lossin (1):
rust: alloc: introduce ArrayLayout

Danilo Krummrich (28):
rust: alloc: add Allocator trait
rust: alloc: separate aligned_size from krealloc_aligned
rust: alloc: rename KernelAllocator to Kmalloc
rust: alloc: implement ReallocFunc
rust: alloc: make allocator module public
rust: alloc: implement Allocator for Kmalloc
rust: alloc: add module allocator_test
rust: alloc: implement Vmalloc allocator
rust: alloc: implement KVmalloc allocator
rust: alloc: add __GFP_NOWARN to Flags
rust: alloc: implement kernel Box
rust: treewide: switch to our kernel Box type
rust: alloc: remove extension of std's Box
rust: alloc: add Box to prelude
rust: alloc: implement kernel Vec type
rust: alloc: implement IntoIterator for Vec
rust: alloc: implement collect for IntoIter
rust: treewide: switch to the kernel Vec type
rust: alloc: remove VecExt extension
rust: alloc: add Vec to prelude
rust: error: use core::alloc::LayoutError
rust: error: check for config test in Error::name
rust: alloc: implement contains for Flags
rust: alloc: implement Cmalloc in module allocator_test
rust: str: test: replace alloc::format
rust: alloc: update module comment of alloc.rs
kbuild: rust: remove the alloc crate and GlobalAlloc
MAINTAINERS: add entry for the Rust alloc module

Ethan D. Twardy (1):
rust: kbuild: expand rusttest target for macros

Filipe Xavier (2):
rust: error: make conversion functions public
rust: error: optimize error type to use nonzero

Gary Guo (3):
rust: fix size_t in bindgen prototypes of C builtins
rust: map __kernel_size_t and friends also to usize/isize
rust: use custom FFI integer types

Miguel Ojeda (17):
rust: workqueue: remove unneeded ``#[allow(clippy::new_ret_no_self)]`
rust: sort global Rust flags
rust: types: avoid repetition in {As,From}Bytes impls
rust: enable clippy::undocumented_unsafe_blocks lint
rust: enable clippy::unnecessary_safety_comment lint
rust: enable clippy::unnecessary_safety_doc lint
rust: enable clippy::ignored_unit_patterns lint
rust: enable rustdoc::unescaped_backticks lint
rust: init: remove unneeded #[allow(clippy::disallowed_names)]
rust: sync: remove unneeded

    `#[allow(clippy::non_send_fields_in_send_ty)]`

rust: introduce .clippy.toml
rust: replace clippy::dbg_macro with disallowed_macros
rust: provide proper code documentation titles
rust: enable Clippy's check-private-items
Documentation: rust: add coding guidelines on lints
rust: start using the #[expect(...)] attribute
Documentation: rust: discuss #[expect(...)] in the guidelines

Thomas Böhler (7):
drm/panic: avoid reimplementing Iterator::find drm/panic: remove unnecessary borrow in alignment_pattern drm/panic: prefer eliding lifetimes
drm/panic: remove redundant field when assigning value drm/panic: correctly indent continuation of line in list item drm/panic: allow verbose boolean for clarity drm/panic: allow verbose version check

 .clippy.toml                             |   9 +
 .gitignore                               |   1 +
 Documentation/rust/coding-guidelines.rst | 148 ++++
 MAINTAINERS                              |   8 +
 Makefile                                 |  15 +-
 drivers/block/rnull.rs                   |   4 +-
 drivers/gpu/drm/drm_panic_qr.rs          |  23 +-
 mm/kasan/kasan_test_rust.rs              |   3 +-
 rust/Makefile                            |  92 +--
 rust/bindgen_parameters                  |   5 +
 rust/bindings/bindings_helper.h          |   1 +
 rust/bindings/lib.rs                     |   6 +
 rust/exports.c                           |   1 -
 rust/ffi.rs                              |  13 +
 rust/helpers/helpers.c                   |   1 +
 rust/helpers/slab.c                      |   6 +
 rust/helpers/vmalloc.c                   |   9 +
 rust/kernel/alloc.rs                     | 150 +++-
 rust/kernel/alloc/allocator.rs           | 208 ++++--
 rust/kernel/alloc/allocator_test.rs      |  95 +++
 rust/kernel/alloc/box_ext.rs             |  89 ---
 rust/kernel/alloc/kbox.rs                | 456 +++++++++++
 rust/kernel/alloc/kvec.rs                | 913 +++++++++++++++++++++++
 rust/kernel/alloc/layout.rs              |  91 +++
 rust/kernel/alloc/vec_ext.rs             | 185 -----
 rust/kernel/block/mq/operations.rs       |  18 +-
 rust/kernel/block/mq/raw_writer.rs       |   2 +-
 rust/kernel/block/mq/tag_set.rs          |   2 +-
 rust/kernel/error.rs                     |  79 +-
 rust/kernel/init.rs                      | 127 ++--
 rust/kernel/init/__internal.rs           |  13 +-
 rust/kernel/init/macros.rs               |  18 +-
 rust/kernel/ioctl.rs                     |   2 +-
 rust/kernel/lib.rs                       |   5 +-
 rust/kernel/list.rs                      |   1 +
 rust/kernel/list/arc_field.rs            |   2 +-
 rust/kernel/net/phy.rs                   |  16 +-
 rust/kernel/prelude.rs                   |   5 +-
 rust/kernel/print.rs                     |   5 +-
 rust/kernel/rbtree.rs                    |  49 +-
 rust/kernel/std_vendor.rs                |  12 +-
 rust/kernel/str.rs                       |  46 +-
 rust/kernel/sync/arc.rs                  |  25 +-
 rust/kernel/sync/arc/std_vendor.rs       |   2 +
 rust/kernel/sync/condvar.rs              |   7 +-
 rust/kernel/sync/lock.rs                 |   8 +-
 rust/kernel/sync/lock/mutex.rs           |   4 +-
 rust/kernel/sync/lock/spinlock.rs        |   4 +-
 rust/kernel/sync/locked_by.rs            |   2 +-
 rust/kernel/task.rs                      |   8 +-
 rust/kernel/time.rs                      |   4 +-
 rust/kernel/types.rs                     | 140 ++--
 rust/kernel/uaccess.rs                   |  23 +-
 rust/kernel/workqueue.rs                 |  29 +-
 rust/macros/lib.rs                       |  14 +-
 rust/macros/module.rs                    |   8 +-
 rust/uapi/lib.rs                         |   6 +
 samples/rust/rust_minimal.rs             |   4 +-
 samples/rust/rust_print.rs               |   1 +
 scripts/Makefile.build                   |   4 +-
 scripts/generate_rust_analyzer.py        |  11 +-
 61 files changed, 2482 insertions(+), 756 deletions(-)
 create mode 100644 .clippy.toml
 create mode 100644 rust/ffi.rs
 create mode 100644 rust/helpers/vmalloc.c
 create mode 100644 rust/kernel/alloc/allocator_test.rs
 delete mode 100644 rust/kernel/alloc/box_ext.rs
 create mode 100644 rust/kernel/alloc/kbox.rs
 create mode 100644 rust/kernel/alloc/kvec.rs
 create mode 100644 rust/kernel/alloc/layout.rs
 delete mode 100644 rust/kernel/alloc/vec_ext.rs

--
2.48.1

author maintainer
#1 lore raw

PATCH 1/60 rust: workqueue: remove unneeded ``#[allow(clippy::new_ret_no_self)]`

commit 024f9676a6d236132119832a90fb9a1a9115b41a upstream.

Perform the same clean commit b2516f7af9d2 ("rust: kernel: remove #[allow(clippy::new_ret_no_self)]") did for a case that appeared in workqueue in parallel in commit 7324b88975c5 ("rust: workqueue: add helper for defining work_struct fields"):

Clippy triggered a false positive on its new_ret_no_self lint when using the pin_init! macro. Since Rust 1.67.0, that does not happen anymore, since Clippy learnt to not warn about -> impl Trait<Self> [1][2].

The kernel nowadays uses Rust 1.72.1, thus remove the #[allow].

---
 rust/kernel/workqueue.rs | 1 -
 1 file changed, 1 deletion(-)
rust/kernel/workqueue.rs +0 -1
index 553a5cba2adc..493288dc1de0 100644
@@ -366,7 +366,6 @@ unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
 impl<T: ?Sized, const ID: u64> Work<T, ID> {
     /// Creates a new instance of [`Work`].
     #[inline]
-    #[allow(clippy::new_ret_no_self)]
     pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self>
     where
         T: WorkItem<ID>,
Signature · 1 line
2.48.1
maintainer Applied
#2 lore raw

Patch "rust: workqueue: remove unneeded ``#[allow(clippy::new_ret_no_self)]`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: workqueue: remove unneeded ``#[allow(clippy::new_ret_no_self)]`

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-workqueue-remove-unneeded.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:50:44 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:08 +0100
Subject: rust: workqueue: remove unneeded ``#[allow(clippy::new_ret_no_self)]`
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 024f9676a6d236132119832a90fb9a1a9115b41a upstream.

Perform the same clean commit b2516f7af9d2 ("rust: kernel: remove #[allow(clippy::new_ret_no_self)]") did for a case that appeared in workqueue in parallel in commit 7324b88975c5 ("rust: workqueue: add helper for defining work_struct fields"):

Clippy triggered a false positive on its new_ret_no_self lint when using the pin_init! macro. Since Rust 1.67.0, that does not happen anymore, since Clippy learnt to not warn about -> impl Trait<Self> [1][2].

The kernel nowadays uses Rust 1.72.1, thus remove the #[allow].

---
 rust/kernel/workqueue.rs |    1 -
 1 file changed, 1 deletion(-)
rust/kernel/workqueue.rs +0 -1
@@ -366,7 +366,6 @@ unsafe impl<T: ?Sized, const ID: u64> Sy
 impl<T: ?Sized, const ID: u64> Work<T, ID> {
     /// Creates a new instance of [`Work`].
     #[inline]
-    #[allow(clippy::new_ret_no_self)]
     pub fn new(name: &'static CStr, key: &'static LockClassKey) -> impl PinInit<Self>
     where
         T: WorkItem<ID>,

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#3 lore raw

PATCH 2/60 rust: sort global Rust flags

In reply to Miguel Ojeda

commit a135aa3d30d28f26eb28a0ff5d48b387b0e0755f upstream.

Sort the global Rust flags so that it is easier to follow along when we have more, like this patch series does.

---
 Makefile | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
Makefile +4 -4
index 17dfe0a8ca8f..6fbdb2e8ffff 100644
@@ -446,19 +446,19 @@ KBUILD_USERLDFLAGS := $(USERLDFLAGS)
 export rust_common_flags := --edition=2021 \
 			    -Zbinary_dep_depinfo=y \
 			    -Astable_features \
-			    -Dunsafe_op_in_unsafe_fn \
 			    -Dnon_ascii_idents \
+			    -Dunsafe_op_in_unsafe_fn \
+			    -Wmissing_docs \
 			    -Wrust_2018_idioms \
 			    -Wunreachable_pub \
-			    -Wmissing_docs \
-			    -Wrustdoc::missing_crate_level_docs \
 			    -Wclippy::all \
+			    -Wclippy::dbg_macro \
 			    -Wclippy::mut_mut \
 			    -Wclippy::needless_bitwise_bool \
 			    -Wclippy::needless_continue \
 			    -Aclippy::needless_lifetimes \
 			    -Wclippy::no_mangle_with_rust_abi \
-			    -Wclippy::dbg_macro
+			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
 		       $(HOSTCFLAGS) -I $(srctree)/scripts/include
Signature · 1 line
2.48.1
maintainer Applied
#4 lore raw

Patch "rust: sort global Rust flags" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: sort global Rust flags

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-sort-global-rust-flags.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:50:49 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:09 +0100
Subject: rust: sort global Rust flags
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit a135aa3d30d28f26eb28a0ff5d48b387b0e0755f upstream.

Sort the global Rust flags so that it is easier to follow along when we have more, like this patch series does.

---
 Makefile |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
Makefile +4 -4
@@ -446,19 +446,19 @@ KBUILD_USERLDFLAGS := $(USERLDFLAGS)
 export rust_common_flags := --edition=2021 \
 			    -Zbinary_dep_depinfo=y \
 			    -Astable_features \
-			    -Dunsafe_op_in_unsafe_fn \
 			    -Dnon_ascii_idents \
+			    -Dunsafe_op_in_unsafe_fn \
+			    -Wmissing_docs \
 			    -Wrust_2018_idioms \
 			    -Wunreachable_pub \
-			    -Wmissing_docs \
-			    -Wrustdoc::missing_crate_level_docs \
 			    -Wclippy::all \
+			    -Wclippy::dbg_macro \
 			    -Wclippy::mut_mut \
 			    -Wclippy::needless_bitwise_bool \
 			    -Wclippy::needless_continue \
 			    -Aclippy::needless_lifetimes \
 			    -Wclippy::no_mangle_with_rust_abi \
-			    -Wclippy::dbg_macro
+			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
 		       $(HOSTCFLAGS) -I $(srctree)/scripts/include

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#5 lore raw

PATCH 3/60 rust: types: avoid repetition in `{As,From}Bytes` impls

In reply to Miguel Ojeda

commit 567cdff53e71de56ae67eaf4309db38778b7bcd3 upstream.

In order to provide // SAFETY comments for every unsafe impl, we would need to repeat them, which is not very useful and would be harder to read.

We could perhaps allow the lint (ideally within a small module), but we can take the chance to avoid the repetition of the impls themselves too by using a small local macro, like in other places where we have had to do this sort of thing.

Thus add the straightforward impl_{from,as}bytes! macros and use them to implement FromBytes.

This, in turn, will allow us in the next patch to place a // SAFETY comment that defers to the actual invocation of the macro.

---
 rust/kernel/types.rs | 68 +++++++++++++++++++++++---------------------
 1 file changed, 35 insertions(+), 33 deletions(-)
rust/kernel/types.rs +35 -33
index 9e7ca066355c..70e173f15d87 100644
@@ -481,21 +481,22 @@ pub enum Either<L, R> {
 /// All bit-patterns must be valid for this type. This type must not have interior mutability.
 pub unsafe trait FromBytes {}
 
-// SAFETY: All bit patterns are acceptable values of the types below.
-unsafe impl FromBytes for u8 {}
-unsafe impl FromBytes for u16 {}
-unsafe impl FromBytes for u32 {}
-unsafe impl FromBytes for u64 {}
-unsafe impl FromBytes for usize {}
-unsafe impl FromBytes for i8 {}
-unsafe impl FromBytes for i16 {}
-unsafe impl FromBytes for i32 {}
-unsafe impl FromBytes for i64 {}
-unsafe impl FromBytes for isize {}
-// SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
-// patterns are also acceptable for arrays of that type.
-unsafe impl<T: FromBytes> FromBytes for [T] {}
-unsafe impl<T: FromBytes, const N: usize> FromBytes for [T; N] {}
+macro_rules! impl_frombytes {
+    ($($({$($generics:tt)*})? $t:ty, )*) => {
+        $(unsafe impl$($($generics)*)? FromBytes for $t {})*
+    };
+}
+
+impl_frombytes! {
+    // SAFETY: All bit patterns are acceptable values of the types below.
+    u8, u16, u32, u64, usize,
+    i8, i16, i32, i64, isize,
+
+    // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
+    // patterns are also acceptable for arrays of that type.
+    {<T: FromBytes>} [T],
+    {<T: FromBytes, const N: usize>} [T; N],
+}
 
 /// Types that can be viewed as an immutable slice of initialized bytes.
 ///
@@ -514,21 +515,22 @@ unsafe impl<T: FromBytes> FromBytes for [T] {}
 /// mutability.
 pub unsafe trait AsBytes {}
 
-// SAFETY: Instances of the following types have no uninitialized portions.
-unsafe impl AsBytes for u8 {}
-unsafe impl AsBytes for u16 {}
-unsafe impl AsBytes for u32 {}
-unsafe impl AsBytes for u64 {}
-unsafe impl AsBytes for usize {}
-unsafe impl AsBytes for i8 {}
-unsafe impl AsBytes for i16 {}
-unsafe impl AsBytes for i32 {}
-unsafe impl AsBytes for i64 {}
-unsafe impl AsBytes for isize {}
-unsafe impl AsBytes for bool {}
-unsafe impl AsBytes for char {}
-unsafe impl AsBytes for str {}
-// SAFETY: If individual values in an array have no uninitialized portions, then the array itself
-// does not have any uninitialized portions either.
-unsafe impl<T: AsBytes> AsBytes for [T] {}
-unsafe impl<T: AsBytes, const N: usize> AsBytes for [T; N] {}
+macro_rules! impl_asbytes {
+    ($($({$($generics:tt)*})? $t:ty, )*) => {
+        $(unsafe impl$($($generics)*)? AsBytes for $t {})*
+    };
+}
+
+impl_asbytes! {
+    // SAFETY: Instances of the following types have no uninitialized portions.
+    u8, u16, u32, u64, usize,
+    i8, i16, i32, i64, isize,
+    bool,
+    char,
+    str,
+
+    // SAFETY: If individual values in an array have no uninitialized portions, then the array
+    // itself does not have any uninitialized portions either.
+    {<T: AsBytes>} [T],
+    {<T: AsBytes, const N: usize>} [T; N],
+}
Signature · 1 line
2.48.1
maintainer Applied
#6 lore raw

Patch "rust: types: avoid repetition in `{As,From}Bytes` impls" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: types: avoid repetition in {As,From}Bytes impls

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-types-avoid-repetition-in-as-from-bytes-impls.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:50:48 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:10 +0100
Subject: rust: types: avoid repetition in {As,From}Bytes impls
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 567cdff53e71de56ae67eaf4309db38778b7bcd3 upstream.

In order to provide // SAFETY comments for every unsafe impl, we would need to repeat them, which is not very useful and would be harder to read.

We could perhaps allow the lint (ideally within a small module), but we can take the chance to avoid the repetition of the impls themselves too by using a small local macro, like in other places where we have had to do this sort of thing.

Thus add the straightforward impl_{from,as}bytes! macros and use them to implement FromBytes.

This, in turn, will allow us in the next patch to place a // SAFETY comment that defers to the actual invocation of the macro.

---
 rust/kernel/types.rs |   68 ++++++++++++++++++++++++++-------------------------
 1 file changed, 35 insertions(+), 33 deletions(-)
rust/kernel/types.rs +35 -33
@@ -481,21 +481,22 @@ pub enum Either<L, R> {
 /// All bit-patterns must be valid for this type. This type must not have interior mutability.
 pub unsafe trait FromBytes {}
 
-// SAFETY: All bit patterns are acceptable values of the types below.
-unsafe impl FromBytes for u8 {}
-unsafe impl FromBytes for u16 {}
-unsafe impl FromBytes for u32 {}
-unsafe impl FromBytes for u64 {}
-unsafe impl FromBytes for usize {}
-unsafe impl FromBytes for i8 {}
-unsafe impl FromBytes for i16 {}
-unsafe impl FromBytes for i32 {}
-unsafe impl FromBytes for i64 {}
-unsafe impl FromBytes for isize {}
-// SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
-// patterns are also acceptable for arrays of that type.
-unsafe impl<T: FromBytes> FromBytes for [T] {}
-unsafe impl<T: FromBytes, const N: usize> FromBytes for [T; N] {}
+macro_rules! impl_frombytes {
+    ($($({$($generics:tt)*})? $t:ty, )*) => {
+        $(unsafe impl$($($generics)*)? FromBytes for $t {})*
+    };
+}
+
+impl_frombytes! {
+    // SAFETY: All bit patterns are acceptable values of the types below.
+    u8, u16, u32, u64, usize,
+    i8, i16, i32, i64, isize,
+
+    // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
+    // patterns are also acceptable for arrays of that type.
+    {<T: FromBytes>} [T],
+    {<T: FromBytes, const N: usize>} [T; N],
+}
 
 /// Types that can be viewed as an immutable slice of initialized bytes.
 ///
@@ -514,21 +515,22 @@ unsafe impl<T: FromBytes, const N: usize
 /// mutability.
 pub unsafe trait AsBytes {}
 
-// SAFETY: Instances of the following types have no uninitialized portions.
-unsafe impl AsBytes for u8 {}
-unsafe impl AsBytes for u16 {}
-unsafe impl AsBytes for u32 {}
-unsafe impl AsBytes for u64 {}
-unsafe impl AsBytes for usize {}
-unsafe impl AsBytes for i8 {}
-unsafe impl AsBytes for i16 {}
-unsafe impl AsBytes for i32 {}
-unsafe impl AsBytes for i64 {}
-unsafe impl AsBytes for isize {}
-unsafe impl AsBytes for bool {}
-unsafe impl AsBytes for char {}
-unsafe impl AsBytes for str {}
-// SAFETY: If individual values in an array have no uninitialized portions, then the array itself
-// does not have any uninitialized portions either.
-unsafe impl<T: AsBytes> AsBytes for [T] {}
-unsafe impl<T: AsBytes, const N: usize> AsBytes for [T; N] {}
+macro_rules! impl_asbytes {
+    ($($({$($generics:tt)*})? $t:ty, )*) => {
+        $(unsafe impl$($($generics)*)? AsBytes for $t {})*
+    };
+}
+
+impl_asbytes! {
+    // SAFETY: Instances of the following types have no uninitialized portions.
+    u8, u16, u32, u64, usize,
+    i8, i16, i32, i64, isize,
+    bool,
+    char,
+    str,
+
+    // SAFETY: If individual values in an array have no uninitialized portions, then the array
+    // itself does not have any uninitialized portions either.
+    {<T: AsBytes>} [T],
+    {<T: AsBytes, const N: usize>} [T; N],
+}

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#7 lore raw

PATCH 4/60 rust: enable `clippy::undocumented_unsafe_blocks` lint

In reply to Miguel Ojeda

commit db4f72c904cb116e2bf56afdd67fc5167a607a7b upstream.

Checking that we are not missing any // SAFETY comments in our unsafe blocks is something we have wanted to do for a long time, as well as cleaning up the remaining cases that were not documented [1].

Back when Rust for Linux started, this was something that could have been done via a script, like Rust's tidy. Soon after, in Rust 1.58.0, Clippy implemented the undocumented_unsafe_blocks lint [2].

Even though the lint has a few false positives, e.g. in some cases where attributes appear between the comment and the unsafe block [3], there are workarounds and the lint seems quite usable already.

Thus enable the lint now.

We still have a few cases to clean up, so just allow those for the moment by writing a TODO comment -- some of those may be good candidates for new contributors.

---
 Makefile                       | 1 +
 mm/kasan/kasan_test_rust.rs    | 1 +
 rust/bindings/lib.rs           | 1 +
 rust/kernel/alloc/allocator.rs | 2 ++
 rust/kernel/error.rs           | 9 ++++++---
 rust/kernel/init.rs            | 5 +++++
 rust/kernel/init/__internal.rs | 2 ++
 rust/kernel/init/macros.rs     | 9 +++++++++
 rust/kernel/list.rs            | 1 +
 rust/kernel/print.rs           | 2 ++
 rust/kernel/str.rs             | 7 ++++---
 rust/kernel/sync/condvar.rs    | 2 +-
 rust/kernel/sync/lock.rs       | 6 +++---
 rust/kernel/types.rs           | 4 ++++
 rust/kernel/workqueue.rs       | 4 ++++
 rust/uapi/lib.rs               | 1 +
 16 files changed, 47 insertions(+), 10 deletions(-)
Makefile +1 -0
index 6fbdb2e8ffff..a491ba904601 100644
@@ -458,6 +458,7 @@ export rust_common_flags := --edition=2021 \
 			    -Wclippy::needless_continue \
 			    -Aclippy::needless_lifetimes \
 			    -Wclippy::no_mangle_with_rust_abi \
+			    -Wclippy::undocumented_unsafe_blocks \
 			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
mm/kasan/kasan_test_rust.rs +1 -0
index caa7175964ef..47bcf033dd4f 100644
@@ -17,5 +17,6 @@ pub extern "C" fn kasan_test_rust_uaf() -> u8 {
     }
     let ptr: *mut u8 = addr_of_mut!(v[2048]);
     drop(v);
+    // SAFETY: Incorrect, on purpose.
     unsafe { *ptr }
 }
rust/bindings/lib.rs +1 -0
index 93a1a3fc97bc..d6da3011281a 100644
@@ -25,6 +25,7 @@
 )]
 
 #[allow(dead_code)]
+#[allow(clippy::undocumented_unsafe_blocks)]
 mod bindings_raw {
     // Use glob import here to expose all helpers.
     // Symbols defined within the module will take precedence to the glob import.
rust/kernel/alloc/allocator.rs +2 -0
index e6ea601f38c6..91216b36af69 100644
@@ -31,6 +31,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F
     unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 }
 }
 
+// SAFETY: TODO.
 unsafe impl GlobalAlloc for KernelAllocator {
     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
         // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety
@@ -39,6 +40,7 @@ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
     }
 
     unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
+        // SAFETY: TODO.
         unsafe {
             bindings::kfree(ptr as *const core::ffi::c_void);
         }
rust/kernel/error.rs +6 -3
index 6f1587a2524e..639bc7572f90 100644
@@ -171,9 +171,11 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self.name() {
             // Print out number if no name can be found.
             None => f.debug_tuple("Error").field(&-self.0).finish(),
-            // SAFETY: These strings are ASCII-only.
             Some(name) => f
-                .debug_tuple(unsafe { core::str::from_utf8_unchecked(name) })
+                .debug_tuple(
+                    // SAFETY: These strings are ASCII-only.
+                    unsafe { core::str::from_utf8_unchecked(name) },
+                )
                 .finish(),
         }
     }
@@ -277,6 +279,8 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
     if unsafe { bindings::IS_ERR(const_ptr) } {
         // SAFETY: The FFI function does not deref the pointer.
         let err = unsafe { bindings::PTR_ERR(const_ptr) };
+
+        #[allow(clippy::unnecessary_cast)]
         // CAST: If `IS_ERR()` returns `true`,
         // then `PTR_ERR()` is guaranteed to return a
         // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
@@ -286,7 +290,6 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
         //
         // SAFETY: `IS_ERR()` ensures `err` is a
         // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
-        #[allow(clippy::unnecessary_cast)]
         return Err(unsafe { Error::from_errno_unchecked(err as core::ffi::c_int) });
     }
     Ok(ptr)
rust/kernel/init.rs +5 -0
index 789f80f71ca7..a5857883e044 100644
@@ -541,6 +541,7 @@ macro_rules! stack_try_pin_init {
 /// }
 /// pin_init!(&this in Buf {
 ///     buf: [0; 64],
+///     // SAFETY: TODO.
 ///     ptr: unsafe { addr_of_mut!((*this.as_ptr()).buf).cast() },
 ///     pin: PhantomPinned,
 /// });
@@ -875,6 +876,7 @@ pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
     /// }
     ///
     /// let foo = pin_init!(Foo {
+    ///     // SAFETY: TODO.
     ///     raw <- unsafe {
     ///         Opaque::ffi_init(|s| {
     ///             init_foo(s);
@@ -1162,6 +1164,7 @@ pub fn pin_init_array_from_fn<I, const N: usize, T, E>(
 // SAFETY: Every type can be initialized by-value.
 unsafe impl<T, E> Init<T, E> for T {
     unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
+        // SAFETY: TODO.
         unsafe { slot.write(self) };
         Ok(())
     }
@@ -1170,6 +1173,7 @@ unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
 // SAFETY: Every type can be initialized by-value. `__pinned_init` calls `__init`.
 unsafe impl<T, E> PinInit<T, E> for T {
     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
+        // SAFETY: TODO.
         unsafe { self.__init(slot) }
     }
 }
@@ -1411,6 +1415,7 @@ pub fn zeroed<T: Zeroable>() -> impl Init<T> {
 
 macro_rules! impl_zeroable {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
+        // SAFETY: Safety comments written in the macro invocation.
         $(unsafe impl$($($generics)*)? Zeroable for $t {})*
     };
 }
rust/kernel/init/__internal.rs +2 -0
index 13cefd37512f..29f4fd00df3d 100644
@@ -112,10 +112,12 @@ fn clone(&self) -> Self {
 
 impl<T: ?Sized> Copy for AllData<T> {}
 
+// SAFETY: TODO.
 unsafe impl<T: ?Sized> InitData for AllData<T> {
     type Datee = T;
 }
 
+// SAFETY: TODO.
 unsafe impl<T: ?Sized> HasInitData for T {
     type InitData = AllData<T>;
 
rust/kernel/init/macros.rs +9 -0
index 9a0c4650ef67..736fe0ce0cd9 100644
@@ -513,6 +513,7 @@ fn drop($($sig:tt)*) {
             }
         ),
     ) => {
+        // SAFETY: TODO.
         unsafe $($impl_sig)* {
             // Inherit all attributes and the type/ident tokens for the signature.
             $(#[$($attr)*])*
@@ -872,6 +873,7 @@ unsafe fn __pin_data() -> Self::PinData {
                 }
             }
 
+            // SAFETY: TODO.
             unsafe impl<$($impl_generics)*>
                 $crate::init::__internal::PinData for __ThePinData<$($ty_generics)*>
             where $($whr)*
@@ -997,6 +999,7 @@ impl<$($impl_generics)*> $pin_data<$($ty_generics)*>
                     slot: *mut $p_type,
                     init: impl $crate::init::PinInit<$p_type, E>,
                 ) -> ::core::result::Result<(), E> {
+                    // SAFETY: TODO.
                     unsafe { $crate::init::PinInit::__pinned_init(init, slot) }
                 }
             )*
@@ -1007,6 +1010,7 @@ impl<$($impl_generics)*> $pin_data<$($ty_generics)*>
                     slot: *mut $type,
                     init: impl $crate::init::Init<$type, E>,
                 ) -> ::core::result::Result<(), E> {
+                    // SAFETY: TODO.
                     unsafe { $crate::init::Init::__init(init, slot) }
                 }
             )*
@@ -1121,6 +1125,8 @@ macro_rules! __init_internal {
         // no possibility of returning without `unsafe`.
         struct __InitOk;
         // Get the data about fields from the supplied type.
+        //
+        // SAFETY: TODO.
         let data = unsafe {
             use $crate::init::__internal::$has_data;
             // Here we abuse `paste!` to retokenize `$t`. Declarative macros have some internal
@@ -1176,6 +1182,7 @@ fn assert_zeroable<T: $crate::init::Zeroable>(_: *mut T) {}
         let init = move |slot| -> ::core::result::Result<(), $err> {
             init(slot).map(|__InitOk| ())
         };
+        // SAFETY: TODO.
         let init = unsafe { $crate::init::$construct_closure::<_, $err>(init) };
         init
     }};
@@ -1324,6 +1331,8 @@ fn assert_zeroable<T: $crate::init::Zeroable>(_: *mut T) {}
         // Endpoint, nothing more to munch, create the initializer.
         // Since we are in the closure that is never called, this will never get executed.
         // We abuse `slot` to get the correct type inference here:
+        //
+        // SAFETY: TODO.
         unsafe {
             // Here we abuse `paste!` to retokenize `$t`. Declarative macros have some internal
             // information that is associated to already parsed fragments, so a path fragment
rust/kernel/list.rs +1 -0
index 5b4aec29eb67..fb93330f4af4 100644
@@ -354,6 +354,7 @@ pub fn pop_front(&mut self) -> Option<ListArc<T, ID>> {
     ///
     /// `item` must not be in a different linked list (with the same id).
     pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {
+        // SAFETY: TODO.
         let mut item = unsafe { ListLinks::fields(T::view_links(item)) };
         // SAFETY: The user provided a reference, and reference are never dangling.
         //
rust/kernel/print.rs +2 -0
index 508b0221256c..fe53fc469c4f 100644
@@ -23,6 +23,7 @@
     use fmt::Write;
     // SAFETY: The C contract guarantees that `buf` is valid if it's less than `end`.
     let mut w = unsafe { RawFormatter::from_ptrs(buf.cast(), end.cast()) };
+    // SAFETY: TODO.
     let _ = w.write_fmt(unsafe { *(ptr as *const fmt::Arguments<'_>) });
     w.pos().cast()
 }
@@ -102,6 +103,7 @@ pub unsafe fn call_printk(
 ) {
     // `_printk` does not seem to fail in any path.
     #[cfg(CONFIG_PRINTK)]
+    // SAFETY: TODO.
     unsafe {
         bindings::_printk(
             format_string.as_ptr() as _,
rust/kernel/str.rs +4 -3
index bb8d4f41475b..66d4527f6c6f 100644
@@ -162,10 +162,10 @@ pub const fn len(&self) -> usize {
     /// Returns the length of this string with `NUL`.
     #[inline]
     pub const fn len_with_nul(&self) -> usize {
-        // SAFETY: This is one of the invariant of `CStr`.
-        // We add a `unreachable_unchecked` here to hint the optimizer that
-        // the value returned from this function is non-zero.
         if self.0.is_empty() {
+            // SAFETY: This is one of the invariant of `CStr`.
+            // We add a `unreachable_unchecked` here to hint the optimizer that
+            // the value returned from this function is non-zero.
             unsafe { core::hint::unreachable_unchecked() };
         }
         self.0.len()
@@ -301,6 +301,7 @@ pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
     /// ```
     #[inline]
     pub unsafe fn as_str_unchecked(&self) -> &str {
+        // SAFETY: TODO.
         unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
     }
 
rust/kernel/sync/condvar.rs +1 -1
index 2b306afbe56d..7e00048bf4b1 100644
@@ -92,8 +92,8 @@ pub struct CondVar {
     _pin: PhantomPinned,
 }
 
-// SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
 #[allow(clippy::non_send_fields_in_send_ty)]
+// SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
 unsafe impl Send for CondVar {}
 
 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on multiple threads
rust/kernel/sync/lock.rs +3 -3
index f6c34ca4d819..07fcf2d8efc6 100644
@@ -150,9 +150,9 @@ pub(crate) fn do_unlocked<U>(&mut self, cb: impl FnOnce() -> U) -> U {
         // SAFETY: The caller owns the lock, so it is safe to unlock it.
         unsafe { B::unlock(self.lock.state.get(), &self.state) };
 
-        // SAFETY: The lock was just unlocked above and is being relocked now.
-        let _relock =
-            ScopeGuard::new(|| unsafe { B::relock(self.lock.state.get(), &mut self.state) });
+        let _relock = ScopeGuard::new(||
+                // SAFETY: The lock was just unlocked above and is being relocked now.
+                unsafe { B::relock(self.lock.state.get(), &mut self.state) });
 
         cb()
     }
rust/kernel/types.rs +4 -0
index 70e173f15d87..6c2d5fa9bce3 100644
@@ -410,6 +410,7 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
     ///
     /// struct Empty {}
     ///
+    /// # // SAFETY: TODO.
     /// unsafe impl AlwaysRefCounted for Empty {
     ///     fn inc_ref(&self) {}
     ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
@@ -417,6 +418,7 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
     ///
     /// let mut data = Empty {};
     /// let ptr = NonNull::<Empty>::new(&mut data as *mut _).unwrap();
+    /// # // SAFETY: TODO.
     /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };
     /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref);
     ///
@@ -483,6 +485,7 @@ pub unsafe trait FromBytes {}
 
 macro_rules! impl_frombytes {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
+        // SAFETY: Safety comments written in the macro invocation.
         $(unsafe impl$($($generics)*)? FromBytes for $t {})*
     };
 }
@@ -517,6 +520,7 @@ pub unsafe trait AsBytes {}
 
 macro_rules! impl_asbytes {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
+        // SAFETY: Safety comments written in the macro invocation.
         $(unsafe impl$($($generics)*)? AsBytes for $t {})*
     };
 }
rust/kernel/workqueue.rs +4 -0
index 493288dc1de0..3b3f1dbe8192 100644
@@ -519,6 +519,7 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ
     impl{T} HasWork<Self> for ClosureWork<T> { self.work }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
 where
     T: WorkItem<ID, Pointer = Self>,
@@ -536,6 +537,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
     }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
 where
     T: WorkItem<ID, Pointer = Self>,
@@ -564,6 +566,7 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
     }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
@@ -583,6 +586,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
     }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
rust/uapi/lib.rs +1 -0
index 80a00260e3e7..fea2de330d19 100644
@@ -14,6 +14,7 @@
 #![cfg_attr(test, allow(unsafe_op_in_unsafe_fn))]
 #![allow(
     clippy::all,
+    clippy::undocumented_unsafe_blocks,
     dead_code,
     missing_docs,
     non_camel_case_types,
Signature · 1 line
2.48.1
maintainer Applied
#8 lore raw

Patch "rust: enable `clippy::undocumented_unsafe_blocks` lint" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: enable clippy::undocumented_unsafe_blocks lint

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-enable-clippy-undocumented_unsafe_blocks-lint.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:50:50 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:11 +0100
Subject: rust: enable clippy::undocumented_unsafe_blocks lint
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit db4f72c904cb116e2bf56afdd67fc5167a607a7b upstream.

Checking that we are not missing any // SAFETY comments in our unsafe blocks is something we have wanted to do for a long time, as well as cleaning up the remaining cases that were not documented [1].

Back when Rust for Linux started, this was something that could have been done via a script, like Rust's tidy. Soon after, in Rust 1.58.0, Clippy implemented the undocumented_unsafe_blocks lint [2].

Even though the lint has a few false positives, e.g. in some cases where attributes appear between the comment and the unsafe block [3], there are workarounds and the lint seems quite usable already.

Thus enable the lint now.

We still have a few cases to clean up, so just allow those for the moment by writing a TODO comment -- some of those may be good candidates for new contributors.

---
 Makefile                       |    1 +
 mm/kasan/kasan_test_rust.rs    |    1 +
 rust/bindings/lib.rs           |    1 +
 rust/kernel/alloc/allocator.rs |    2 ++
 rust/kernel/error.rs           |    9 ++++++---
 rust/kernel/init.rs            |    5 +++++
 rust/kernel/init/__internal.rs |    2 ++
 rust/kernel/init/macros.rs     |    9 +++++++++
 rust/kernel/list.rs            |    1 +
 rust/kernel/print.rs           |    2 ++
 rust/kernel/str.rs             |    7 ++++---
 rust/kernel/sync/condvar.rs    |    2 +-
 rust/kernel/sync/lock.rs       |    6 +++---
 rust/kernel/types.rs           |    4 ++++
 rust/kernel/workqueue.rs       |    4 ++++
 rust/uapi/lib.rs               |    1 +
 16 files changed, 47 insertions(+), 10 deletions(-)
Makefile +1 -0
@@ -458,6 +458,7 @@ export rust_common_flags := --edition=20
 			    -Wclippy::needless_continue \
 			    -Aclippy::needless_lifetimes \
 			    -Wclippy::no_mangle_with_rust_abi \
+			    -Wclippy::undocumented_unsafe_blocks \
 			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
mm/kasan/kasan_test_rust.rs +1 -0
@@ -17,5 +17,6 @@ pub extern "C" fn kasan_test_rust_uaf()
     }
     let ptr: *mut u8 = addr_of_mut!(v[2048]);
     drop(v);
+    // SAFETY: Incorrect, on purpose.
     unsafe { *ptr }
 }
rust/bindings/lib.rs +1 -0
@@ -25,6 +25,7 @@
 )]
 
 #[allow(dead_code)]
+#[allow(clippy::undocumented_unsafe_blocks)]
 mod bindings_raw {
     // Use glob import here to expose all helpers.
     // Symbols defined within the module will take precedence to the glob import.
rust/kernel/alloc/allocator.rs +2 -0
@@ -31,6 +31,7 @@ pub(crate) unsafe fn krealloc_aligned(pt
     unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 }
 }
 
+// SAFETY: TODO.
 unsafe impl GlobalAlloc for KernelAllocator {
     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
         // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety
@@ -39,6 +40,7 @@ unsafe impl GlobalAlloc for KernelAlloca
     }
 
     unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
+        // SAFETY: TODO.
         unsafe {
             bindings::kfree(ptr as *const core::ffi::c_void);
         }
rust/kernel/error.rs +6 -3
@@ -171,9 +171,11 @@ impl fmt::Debug for Error {
         match self.name() {
             // Print out number if no name can be found.
             None => f.debug_tuple("Error").field(&-self.0).finish(),
-            // SAFETY: These strings are ASCII-only.
             Some(name) => f
-                .debug_tuple(unsafe { core::str::from_utf8_unchecked(name) })
+                .debug_tuple(
+                    // SAFETY: These strings are ASCII-only.
+                    unsafe { core::str::from_utf8_unchecked(name) },
+                )
                 .finish(),
         }
     }
@@ -277,6 +279,8 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut
     if unsafe { bindings::IS_ERR(const_ptr) } {
         // SAFETY: The FFI function does not deref the pointer.
         let err = unsafe { bindings::PTR_ERR(const_ptr) };
+
+        #[allow(clippy::unnecessary_cast)]
         // CAST: If `IS_ERR()` returns `true`,
         // then `PTR_ERR()` is guaranteed to return a
         // negative value greater-or-equal to `-bindings::MAX_ERRNO`,
@@ -286,7 +290,6 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut
         //
         // SAFETY: `IS_ERR()` ensures `err` is a
         // negative value greater-or-equal to `-bindings::MAX_ERRNO`.
-        #[allow(clippy::unnecessary_cast)]
         return Err(unsafe { Error::from_errno_unchecked(err as core::ffi::c_int) });
     }
     Ok(ptr)
rust/kernel/init.rs +5 -0
@@ -541,6 +541,7 @@ macro_rules! stack_try_pin_init {
 /// }
 /// pin_init!(&this in Buf {
 ///     buf: [0; 64],
+///     // SAFETY: TODO.
 ///     ptr: unsafe { addr_of_mut!((*this.as_ptr()).buf).cast() },
 ///     pin: PhantomPinned,
 /// });
@@ -875,6 +876,7 @@ pub unsafe trait PinInit<T: ?Sized, E =
     /// }
     ///
     /// let foo = pin_init!(Foo {
+    ///     // SAFETY: TODO.
     ///     raw <- unsafe {
     ///         Opaque::ffi_init(|s| {
     ///             init_foo(s);
@@ -1162,6 +1164,7 @@ where
 // SAFETY: Every type can be initialized by-value.
 unsafe impl<T, E> Init<T, E> for T {
     unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
+        // SAFETY: TODO.
         unsafe { slot.write(self) };
         Ok(())
     }
@@ -1170,6 +1173,7 @@ unsafe impl<T, E> Init<T, E> for T {
 // SAFETY: Every type can be initialized by-value. `__pinned_init` calls `__init`.
 unsafe impl<T, E> PinInit<T, E> for T {
     unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
+        // SAFETY: TODO.
         unsafe { self.__init(slot) }
     }
 }
@@ -1411,6 +1415,7 @@ pub fn zeroed<T: Zeroable>() -> impl Ini
 
 macro_rules! impl_zeroable {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
+        // SAFETY: Safety comments written in the macro invocation.
         $(unsafe impl$($($generics)*)? Zeroable for $t {})*
     };
 }
rust/kernel/init/__internal.rs +2 -0
@@ -112,10 +112,12 @@ impl<T: ?Sized> Clone for AllData<T> {
 
 impl<T: ?Sized> Copy for AllData<T> {}
 
+// SAFETY: TODO.
 unsafe impl<T: ?Sized> InitData for AllData<T> {
     type Datee = T;
 }
 
+// SAFETY: TODO.
 unsafe impl<T: ?Sized> HasInitData for T {
     type InitData = AllData<T>;
 
rust/kernel/init/macros.rs +9 -0
@@ -513,6 +513,7 @@ macro_rules! __pinned_drop {
             }
         ),
     ) => {
+        // SAFETY: TODO.
         unsafe $($impl_sig)* {
             // Inherit all attributes and the type/ident tokens for the signature.
             $(#[$($attr)*])*
@@ -872,6 +873,7 @@ macro_rules! __pin_data {
                 }
             }
 
+            // SAFETY: TODO.
             unsafe impl<$($impl_generics)*>
                 $crate::init::__internal::PinData for __ThePinData<$($ty_generics)*>
             where $($whr)*
@@ -997,6 +999,7 @@ macro_rules! __pin_data {
                     slot: *mut $p_type,
                     init: impl $crate::init::PinInit<$p_type, E>,
                 ) -> ::core::result::Result<(), E> {
+                    // SAFETY: TODO.
                     unsafe { $crate::init::PinInit::__pinned_init(init, slot) }
                 }
             )*
@@ -1007,6 +1010,7 @@ macro_rules! __pin_data {
                     slot: *mut $type,
                     init: impl $crate::init::Init<$type, E>,
                 ) -> ::core::result::Result<(), E> {
+                    // SAFETY: TODO.
                     unsafe { $crate::init::Init::__init(init, slot) }
                 }
             )*
@@ -1121,6 +1125,8 @@ macro_rules! __init_internal {
         // no possibility of returning without `unsafe`.
         struct __InitOk;
         // Get the data about fields from the supplied type.
+        //
+        // SAFETY: TODO.
         let data = unsafe {
             use $crate::init::__internal::$has_data;
             // Here we abuse `paste!` to retokenize `$t`. Declarative macros have some internal
@@ -1176,6 +1182,7 @@ macro_rules! __init_internal {
         let init = move |slot| -> ::core::result::Result<(), $err> {
             init(slot).map(|__InitOk| ())
         };
+        // SAFETY: TODO.
         let init = unsafe { $crate::init::$construct_closure::<_, $err>(init) };
         init
     }};
@@ -1324,6 +1331,8 @@ macro_rules! __init_internal {
         // Endpoint, nothing more to munch, create the initializer.
         // Since we are in the closure that is never called, this will never get executed.
         // We abuse `slot` to get the correct type inference here:
+        //
+        // SAFETY: TODO.
         unsafe {
             // Here we abuse `paste!` to retokenize `$t`. Declarative macros have some internal
             // information that is associated to already parsed fragments, so a path fragment
rust/kernel/list.rs +1 -0
@@ -354,6 +354,7 @@ impl<T: ?Sized + ListItem<ID>, const ID:
     ///
     /// `item` must not be in a different linked list (with the same id).
     pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {
+        // SAFETY: TODO.
         let mut item = unsafe { ListLinks::fields(T::view_links(item)) };
         // SAFETY: The user provided a reference, and reference are never dangling.
         //
rust/kernel/print.rs +2 -0
@@ -23,6 +23,7 @@ unsafe extern "C" fn rust_fmt_argument(
     use fmt::Write;
     // SAFETY: The C contract guarantees that `buf` is valid if it's less than `end`.
     let mut w = unsafe { RawFormatter::from_ptrs(buf.cast(), end.cast()) };
+    // SAFETY: TODO.
     let _ = w.write_fmt(unsafe { *(ptr as *const fmt::Arguments<'_>) });
     w.pos().cast()
 }
@@ -102,6 +103,7 @@ pub unsafe fn call_printk(
 ) {
     // `_printk` does not seem to fail in any path.
     #[cfg(CONFIG_PRINTK)]
+    // SAFETY: TODO.
     unsafe {
         bindings::_printk(
             format_string.as_ptr() as _,
rust/kernel/str.rs +4 -3
@@ -162,10 +162,10 @@ impl CStr {
     /// Returns the length of this string with `NUL`.
     #[inline]
     pub const fn len_with_nul(&self) -> usize {
-        // SAFETY: This is one of the invariant of `CStr`.
-        // We add a `unreachable_unchecked` here to hint the optimizer that
-        // the value returned from this function is non-zero.
         if self.0.is_empty() {
+            // SAFETY: This is one of the invariant of `CStr`.
+            // We add a `unreachable_unchecked` here to hint the optimizer that
+            // the value returned from this function is non-zero.
             unsafe { core::hint::unreachable_unchecked() };
         }
         self.0.len()
@@ -301,6 +301,7 @@ impl CStr {
     /// ```
     #[inline]
     pub unsafe fn as_str_unchecked(&self) -> &str {
+        // SAFETY: TODO.
         unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
     }
 
rust/kernel/sync/condvar.rs +1 -1
@@ -92,8 +92,8 @@ pub struct CondVar {
     _pin: PhantomPinned,
 }
 
-// SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
 #[allow(clippy::non_send_fields_in_send_ty)]
+// SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
 unsafe impl Send for CondVar {}
 
 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on multiple threads
rust/kernel/sync/lock.rs +3 -3
@@ -150,9 +150,9 @@ impl<T: ?Sized, B: Backend> Guard<'_, T,
         // SAFETY: The caller owns the lock, so it is safe to unlock it.
         unsafe { B::unlock(self.lock.state.get(), &self.state) };
 
-        // SAFETY: The lock was just unlocked above and is being relocked now.
-        let _relock =
-            ScopeGuard::new(|| unsafe { B::relock(self.lock.state.get(), &mut self.state) });
+        let _relock = ScopeGuard::new(||
+                // SAFETY: The lock was just unlocked above and is being relocked now.
+                unsafe { B::relock(self.lock.state.get(), &mut self.state) });
 
         cb()
     }
rust/kernel/types.rs +4 -0
@@ -410,6 +410,7 @@ impl<T: AlwaysRefCounted> ARef<T> {
     ///
     /// struct Empty {}
     ///
+    /// # // SAFETY: TODO.
     /// unsafe impl AlwaysRefCounted for Empty {
     ///     fn inc_ref(&self) {}
     ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
@@ -417,6 +418,7 @@ impl<T: AlwaysRefCounted> ARef<T> {
     ///
     /// let mut data = Empty {};
     /// let ptr = NonNull::<Empty>::new(&mut data as *mut _).unwrap();
+    /// # // SAFETY: TODO.
     /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };
     /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref);
     ///
@@ -483,6 +485,7 @@ pub unsafe trait FromBytes {}
 
 macro_rules! impl_frombytes {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
+        // SAFETY: Safety comments written in the macro invocation.
         $(unsafe impl$($($generics)*)? FromBytes for $t {})*
     };
 }
@@ -517,6 +520,7 @@ pub unsafe trait AsBytes {}
 
 macro_rules! impl_asbytes {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
+        // SAFETY: Safety comments written in the macro invocation.
         $(unsafe impl$($($generics)*)? AsBytes for $t {})*
     };
 }
rust/kernel/workqueue.rs +4 -0
@@ -519,6 +519,7 @@ impl_has_work! {
     impl{T} HasWork<Self> for ClosureWork<T> { self.work }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
 where
     T: WorkItem<ID, Pointer = Self>,
@@ -536,6 +537,7 @@ where
     }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
 where
     T: WorkItem<ID, Pointer = Self>,
@@ -564,6 +566,7 @@ where
     }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
@@ -583,6 +586,7 @@ where
     }
 }
 
+// SAFETY: TODO.
 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
rust/uapi/lib.rs +1 -0
@@ -14,6 +14,7 @@
 #![cfg_attr(test, allow(unsafe_op_in_unsafe_fn))]
 #![allow(
     clippy::all,
+    clippy::undocumented_unsafe_blocks,
     dead_code,
     missing_docs,
     non_camel_case_types,

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#9 lore raw

PATCH 5/60 rust: enable `clippy::unnecessary_safety_comment` lint

In reply to Miguel Ojeda

commit c28bfe76e4ba707775a205b0274710de7aa1e31c upstream.

In Rust 1.67.0, Clippy added the unnecessary_safety_comment lint [1], which is the "inverse" of undocumented_unsafe_blocks: it finds places where safe code has a // SAFETY comment attached.

The lint currently finds 3 places where we had such mistakes, thus it seems already quite useful.

Thus clean those and enable it.

---
 Makefile                 | 1 +
 rust/kernel/sync/arc.rs  | 2 +-
 rust/kernel/workqueue.rs | 4 ++--
 3 files changed, 4 insertions(+), 3 deletions(-)
Makefile +1 -0
index a491ba904601..295d52b677f8 100644
@@ -459,6 +459,7 @@ export rust_common_flags := --edition=2021 \
 			    -Aclippy::needless_lifetimes \
 			    -Wclippy::no_mangle_with_rust_abi \
 			    -Wclippy::undocumented_unsafe_blocks \
+			    -Wclippy::unnecessary_safety_comment \
 			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
rust/kernel/sync/arc.rs +1 -1
index 28743a7c74a8..9325cc5a16a4 100644
@@ -338,7 +338,7 @@ fn into_foreign(self) -> *const core::ffi::c_void {
     }
 
     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> {
-        // SAFETY: By the safety requirement of this function, we know that `ptr` came from
+        // By the safety requirement of this function, we know that `ptr` came from
         // a previous call to `Arc::into_foreign`.
         let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
 
rust/kernel/workqueue.rs +2 -2
index 3b3f1dbe8192..10d2bc62e2cf 100644
@@ -526,7 +526,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
     T: HasWork<T, ID>,
 {
     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
-        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
+        // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
         let ptr = ptr as *mut Work<T, ID>;
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
         let ptr = unsafe { T::work_container_of(ptr) };
@@ -573,7 +573,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
     T: HasWork<T, ID>,
 {
     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
-        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
+        // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
         let ptr = ptr as *mut Work<T, ID>;
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
         let ptr = unsafe { T::work_container_of(ptr) };
Signature · 1 line
2.48.1
maintainer Applied
#10 lore raw

Patch "rust: enable `clippy::unnecessary_safety_comment` lint" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: enable clippy::unnecessary_safety_comment lint

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-enable-clippy-unnecessary_safety_comment-lint.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:50:52 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:12 +0100
Subject: rust: enable clippy::unnecessary_safety_comment lint
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit c28bfe76e4ba707775a205b0274710de7aa1e31c upstream.

In Rust 1.67.0, Clippy added the unnecessary_safety_comment lint [1], which is the "inverse" of undocumented_unsafe_blocks: it finds places where safe code has a // SAFETY comment attached.

The lint currently finds 3 places where we had such mistakes, thus it seems already quite useful.

Thus clean those and enable it.

---
 Makefile                 |    1 +
 rust/kernel/sync/arc.rs  |    2 +-
 rust/kernel/workqueue.rs |    4 ++--
 3 files changed, 4 insertions(+), 3 deletions(-)
Makefile +1 -0
@@ -459,6 +459,7 @@ export rust_common_flags := --edition=20
 			    -Aclippy::needless_lifetimes \
 			    -Wclippy::no_mangle_with_rust_abi \
 			    -Wclippy::undocumented_unsafe_blocks \
+			    -Wclippy::unnecessary_safety_comment \
 			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
rust/kernel/sync/arc.rs +1 -1
@@ -338,7 +338,7 @@ impl<T: 'static> ForeignOwnable for Arc<
     }
 
     unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> {
-        // SAFETY: By the safety requirement of this function, we know that `ptr` came from
+        // By the safety requirement of this function, we know that `ptr` came from
         // a previous call to `Arc::into_foreign`.
         let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap();
 
rust/kernel/workqueue.rs +2 -2
@@ -526,7 +526,7 @@ where
     T: HasWork<T, ID>,
 {
     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
-        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
+        // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
         let ptr = ptr as *mut Work<T, ID>;
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
         let ptr = unsafe { T::work_container_of(ptr) };
@@ -573,7 +573,7 @@ where
     T: HasWork<T, ID>,
 {
     unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
-        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
+        // The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
         let ptr = ptr as *mut Work<T, ID>;
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
         let ptr = unsafe { T::work_container_of(ptr) };

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#11 lore raw

PATCH 6/60 rust: enable `clippy::unnecessary_safety_doc` lint

In reply to Miguel Ojeda

commit 23f42dc054b3c550373eae0c9ae97f1ce1501e0a upstream.

In Rust 1.67.0, Clippy added the unnecessary_safety_doc lint [1], which is similar to unnecessary_safety_comment, but for # Safety sections, i.e. safety preconditions in the documentation.

This is something that should not happen with our coding guidelines in mind. Thus enable the lint to have it machine-checked.

---
 Makefile | 1 +
 1 file changed, 1 insertion(+)
Makefile +1 -0
index 295d52b677f8..13d8aa4a41d3 100644
@@ -460,6 +460,7 @@ export rust_common_flags := --edition=2021 \
 			    -Wclippy::no_mangle_with_rust_abi \
 			    -Wclippy::undocumented_unsafe_blocks \
 			    -Wclippy::unnecessary_safety_comment \
+			    -Wclippy::unnecessary_safety_doc \
 			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
Signature · 1 line
2.48.1
maintainer Applied
#12 lore raw

Patch "rust: enable `clippy::unnecessary_safety_doc` lint" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: enable clippy::unnecessary_safety_doc lint

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-enable-clippy-unnecessary_safety_doc-lint.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:50:58 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:13 +0100
Subject: rust: enable clippy::unnecessary_safety_doc lint
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 23f42dc054b3c550373eae0c9ae97f1ce1501e0a upstream.

In Rust 1.67.0, Clippy added the unnecessary_safety_doc lint [1], which is similar to unnecessary_safety_comment, but for # Safety sections, i.e. safety preconditions in the documentation.

This is something that should not happen with our coding guidelines in mind. Thus enable the lint to have it machine-checked.

---
 Makefile |    1 +
 1 file changed, 1 insertion(+)
Makefile +1 -0
@@ -460,6 +460,7 @@ export rust_common_flags := --edition=20
 			    -Wclippy::no_mangle_with_rust_abi \
 			    -Wclippy::undocumented_unsafe_blocks \
 			    -Wclippy::unnecessary_safety_comment \
+			    -Wclippy::unnecessary_safety_doc \
 			    -Wrustdoc::missing_crate_level_docs
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#13 lore raw

PATCH 7/60 rust: enable `clippy::ignored_unit_patterns` lint

In reply to Miguel Ojeda

commit 3fcc23397628c2357dbe66df59644e09f72ac725 upstream.

In Rust 1.73.0, Clippy introduced the ignored_unit_patterns lint [1]:

Quoted 3 lines

Matching with () explicitly instead of _ outlines the fact that the pattern contains no data. Also it would detect a type change that _ would ignore.

There is only a single case that requires a change:

error: matching over () is more explicit
--> rust/kernel/types.rs:176:45
|
176 | ScopeGuard::new_with_data((), move |_| cleanup())
| ^ help: use () instead of _: ()
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ignored_unit_patterns
= note: requested on the command line with -D clippy::ignored-unit-patterns

Thus clean it up and enable the lint -- no functional change intended.

---
 Makefile             | 1 +
 rust/kernel/types.rs | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)
Makefile +1 -0
index 13d8aa4a41d3..7433df4d22f9 100644
@@ -453,6 +453,7 @@ export rust_common_flags := --edition=2021 \
 			    -Wunreachable_pub \
 			    -Wclippy::all \
 			    -Wclippy::dbg_macro \
+			    -Wclippy::ignored_unit_patterns \
 			    -Wclippy::mut_mut \
 			    -Wclippy::needless_bitwise_bool \
 			    -Wclippy::needless_continue \
rust/kernel/types.rs +1 -1
index 6c2d5fa9bce3..4e03df725f3f 100644
@@ -225,7 +225,7 @@ pub fn dismiss(mut self) -> T {
 impl ScopeGuard<(), fn(())> {
     /// Creates a new guarded object with the given cleanup function.
     pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> {
-        ScopeGuard::new_with_data((), move |_| cleanup())
+        ScopeGuard::new_with_data((), move |()| cleanup())
     }
 }
 
Signature · 1 line
2.48.1
maintainer Applied
#14 lore raw

Patch "rust: enable `clippy::ignored_unit_patterns` lint" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: enable clippy::ignored_unit_patterns lint

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-enable-clippy-ignored_unit_patterns-lint.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:50:59 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:14 +0100
Subject: rust: enable clippy::ignored_unit_patterns lint
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 3fcc23397628c2357dbe66df59644e09f72ac725 upstream.

In Rust 1.73.0, Clippy introduced the ignored_unit_patterns lint [1]:

Quoted 3 lines

Matching with () explicitly instead of _ outlines the fact that the pattern contains no data. Also it would detect a type change that _ would ignore.

There is only a single case that requires a change:

error: matching over () is more explicit
--> rust/kernel/types.rs:176:45
|
176 | ScopeGuard::new_with_data((), move |_| cleanup())
| ^ help: use () instead of _: ()
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ignored_unit_patterns
= note: requested on the command line with -D clippy::ignored-unit-patterns

Thus clean it up and enable the lint -- no functional change intended.

---
 Makefile             |    1 +
 rust/kernel/types.rs |    2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)
Makefile +1 -0
@@ -453,6 +453,7 @@ export rust_common_flags := --edition=20
 			    -Wunreachable_pub \
 			    -Wclippy::all \
 			    -Wclippy::dbg_macro \
+			    -Wclippy::ignored_unit_patterns \
 			    -Wclippy::mut_mut \
 			    -Wclippy::needless_bitwise_bool \
 			    -Wclippy::needless_continue \
rust/kernel/types.rs +1 -1
@@ -225,7 +225,7 @@ impl<T, F: FnOnce(T)> ScopeGuard<T, F> {
 impl ScopeGuard<(), fn(())> {
     /// Creates a new guarded object with the given cleanup function.
     pub fn new(cleanup: impl FnOnce()) -> ScopeGuard<(), impl FnOnce(())> {
-        ScopeGuard::new_with_data((), move |_| cleanup())
+        ScopeGuard::new_with_data((), move |()| cleanup())
     }
 }
 

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#15 lore raw

PATCH 8/60 rust: enable `rustdoc::unescaped_backticks` lint

In reply to Miguel Ojeda

commit bef83245f5ed434932aaf07f890142b576dc5d85 upstream.

In Rust 1.71.0, rustdoc added the unescaped_backticks lint, which detects what are typically typos in Markdown formatting regarding inline code [1], e.g. from the Rust standard library:

    /// ... to `deref`/`deref_mut`` must ...

    /// ... use [`from_mut`]`. Specifically, ...

It does not seem to have almost any false positives, from the experience of enabling it in the Rust standard library [2], which will be checked starting with Rust 1.82.0. The maintainers also confirmed it is ready to be used.

Thus enable it.

---
 Makefile      | 3 ++-
 rust/Makefile | 5 ++++-
 2 files changed, 6 insertions(+), 2 deletions(-)
Makefile +2 -1
index 7433df4d22f9..8748aa1b2f79 100644
@@ -462,7 +462,8 @@ export rust_common_flags := --edition=2021 \
 			    -Wclippy::undocumented_unsafe_blocks \
 			    -Wclippy::unnecessary_safety_comment \
 			    -Wclippy::unnecessary_safety_doc \
-			    -Wrustdoc::missing_crate_level_docs
+			    -Wrustdoc::missing_crate_level_docs \
+			    -Wrustdoc::unescaped_backticks
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
 		       $(HOSTCFLAGS) -I $(srctree)/scripts/include
rust/Makefile +4 -1
index 45779a064fa4..b16456ac5d77 100644
@@ -61,7 +61,7 @@ alloc-cfgs = \
 quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $<
       cmd_rustdoc = \
 	OBJTREE=$(abspath $(objtree)) \
-	$(RUSTDOC) $(if $(rustdoc_host),$(rust_common_flags),$(rust_flags)) \
+	$(RUSTDOC) $(filter-out $(skip_flags),$(if $(rustdoc_host),$(rust_common_flags),$(rust_flags))) \
 		$(rustc_target_flags) -L$(objtree)/$(obj) \
 		-Zunstable-options --generate-link-to-definition \
 		--output $(rustdoc_output) \
@@ -98,6 +98,9 @@ rustdoc-macros: private rustc_target_flags = --crate-type proc-macro \
 rustdoc-macros: $(src)/macros/lib.rs FORCE
 	+$(call if_changed,rustdoc)
 
+# Starting with Rust 1.82.0, skipping `-Wrustdoc::unescaped_backticks` should
+# not be needed -- see https://github.com/rust-lang/rust/pull/128307.
+rustdoc-core: private skip_flags = -Wrustdoc::unescaped_backticks
 rustdoc-core: private rustc_target_flags = $(core-cfgs)
 rustdoc-core: $(RUST_LIB_SRC)/core/src/lib.rs FORCE
 	+$(call if_changed,rustdoc)
Signature · 1 line
2.48.1
maintainer Applied
#16 lore raw

Patch "rust: enable `rustdoc::unescaped_backticks` lint" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: enable rustdoc::unescaped_backticks lint

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-enable-rustdoc-unescaped_backticks-lint.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:00 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:15 +0100
Subject: rust: enable rustdoc::unescaped_backticks lint
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit bef83245f5ed434932aaf07f890142b576dc5d85 upstream.

In Rust 1.71.0, rustdoc added the unescaped_backticks lint, which detects what are typically typos in Markdown formatting regarding inline code [1], e.g. from the Rust standard library:

    /// ... to `deref`/`deref_mut`` must ...

    /// ... use [`from_mut`]`. Specifically, ...

It does not seem to have almost any false positives, from the experience of enabling it in the Rust standard library [2], which will be checked starting with Rust 1.82.0. The maintainers also confirmed it is ready to be used.

Thus enable it.

---
 Makefile      |    3 ++-
 rust/Makefile |    5 ++++-
 2 files changed, 6 insertions(+), 2 deletions(-)
Makefile +2 -1
@@ -462,7 +462,8 @@ export rust_common_flags := --edition=20
 			    -Wclippy::undocumented_unsafe_blocks \
 			    -Wclippy::unnecessary_safety_comment \
 			    -Wclippy::unnecessary_safety_doc \
-			    -Wrustdoc::missing_crate_level_docs
+			    -Wrustdoc::missing_crate_level_docs \
+			    -Wrustdoc::unescaped_backticks
 
 KBUILD_HOSTCFLAGS   := $(KBUILD_USERHOSTCFLAGS) $(HOST_LFS_CFLAGS) \
 		       $(HOSTCFLAGS) -I $(srctree)/scripts/include
rust/Makefile +4 -1
@@ -61,7 +61,7 @@ alloc-cfgs = \
 quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $<
       cmd_rustdoc = \
 	OBJTREE=$(abspath $(objtree)) \
-	$(RUSTDOC) $(if $(rustdoc_host),$(rust_common_flags),$(rust_flags)) \
+	$(RUSTDOC) $(filter-out $(skip_flags),$(if $(rustdoc_host),$(rust_common_flags),$(rust_flags))) \
 		$(rustc_target_flags) -L$(objtree)/$(obj) \
 		-Zunstable-options --generate-link-to-definition \
 		--output $(rustdoc_output) \
@@ -98,6 +98,9 @@ rustdoc-macros: private rustc_target_fla
 rustdoc-macros: $(src)/macros/lib.rs FORCE
 	+$(call if_changed,rustdoc)
 
+# Starting with Rust 1.82.0, skipping `-Wrustdoc::unescaped_backticks` should
+# not be needed -- see https://github.com/rust-lang/rust/pull/128307.
+rustdoc-core: private skip_flags = -Wrustdoc::unescaped_backticks
 rustdoc-core: private rustc_target_flags = $(core-cfgs)
 rustdoc-core: $(RUST_LIB_SRC)/core/src/lib.rs FORCE
 	+$(call if_changed,rustdoc)

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#17 lore raw

PATCH 9/60 rust: init: remove unneeded `#[allow(clippy::disallowed_names)]`

In reply to Miguel Ojeda

commit d5cc7ab0a0a99496de1bd933dac242699a417809 upstream.

These few cases, unlike others in the same file, did not need the allow.

Thus clean them up.

---
 rust/kernel/init.rs | 4 ----
 1 file changed, 4 deletions(-)
rust/kernel/init.rs +0 -4
index a5857883e044..0330a8756fa5 100644
@@ -87,7 +87,6 @@
 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
 //!
 //! ```rust
-//! # #![allow(clippy::disallowed_names)]
 //! # use kernel::{sync::Mutex, new_mutex, init::PinInit, try_pin_init};
 //! #[pin_data]
 //! struct DriverData {
@@ -368,7 +367,6 @@ macro_rules! stack_try_pin_init {
 /// The syntax is almost identical to that of a normal `struct` initializer:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
 /// # use core::pin::Pin;
 /// #[pin_data]
@@ -413,7 +411,6 @@ macro_rules! stack_try_pin_init {
 /// To create an initializer function, simply declare it like this:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, init::*};
 /// # use core::pin::Pin;
 /// # #[pin_data]
@@ -468,7 +465,6 @@ macro_rules! stack_try_pin_init {
 /// They can also easily embed it into their own `struct`s:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
 /// # use core::pin::Pin;
 /// # #[pin_data]
Signature · 1 line
2.48.1
maintainer Applied
#18 lore raw

Patch "rust: init: remove unneeded `#[allow(clippy::disallowed_names)]`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: init: remove unneeded #[allow(clippy::disallowed_names)]

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-init-remove-unneeded.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:07 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:16 +0100
Subject: rust: init: remove unneeded #[allow(clippy::disallowed_names)]
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit d5cc7ab0a0a99496de1bd933dac242699a417809 upstream.

These few cases, unlike others in the same file, did not need the allow.

Thus clean them up.

---
 rust/kernel/init.rs |    4 ----
 1 file changed, 4 deletions(-)
rust/kernel/init.rs +0 -4
@@ -87,7 +87,6 @@
 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]:
 //!
 //! ```rust
-//! # #![allow(clippy::disallowed_names)]
 //! # use kernel::{sync::Mutex, new_mutex, init::PinInit, try_pin_init};
 //! #[pin_data]
 //! struct DriverData {
@@ -368,7 +367,6 @@ macro_rules! stack_try_pin_init {
 /// The syntax is almost identical to that of a normal `struct` initializer:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
 /// # use core::pin::Pin;
 /// #[pin_data]
@@ -413,7 +411,6 @@ macro_rules! stack_try_pin_init {
 /// To create an initializer function, simply declare it like this:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, init::*};
 /// # use core::pin::Pin;
 /// # #[pin_data]
@@ -468,7 +465,6 @@ macro_rules! stack_try_pin_init {
 /// They can also easily embed it into their own `struct`s:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
 /// # use core::pin::Pin;
 /// # #[pin_data]

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#19 lore raw

PATCH 10/60 rust: sync: remove unneeded `#[allow(clippy::non_send_fields_in_send_ty)]`

In reply to Miguel Ojeda

commit 5e7c9b84ad08cc7a41b2ddbbbaccb60057da3860 upstream.

Rust 1.58.0 (before Rust was merged into the kernel) made Clippy's non_send_fields_in_send_ty lint part of the suspicious lint group for a brief window of time [1] until the minor version 1.58.1 got released a week after, where the lint was moved back to nursery.

By that time, we had already upgraded to that Rust version, and thus we had allowed the lint here for CondVar.

Nowadays, Clippy's non_send_fields_in_send_ty would still trigger here if it were enabled.

Moreover, if enabled, Lock<T, B> and Task would also require an allow. Therefore, it does not seem like someone is actually enabling it (in, e.g., a custom flags build).

Finally, the lint does not appear to have had major improvements since then [2].

Thus remove the allow since it is unneeded.

---
 rust/kernel/sync/condvar.rs | 1 -
 1 file changed, 1 deletion(-)
rust/kernel/sync/condvar.rs +0 -1
index 7e00048bf4b1..dec2e5ffc919 100644
@@ -92,7 +92,6 @@ pub struct CondVar {
     _pin: PhantomPinned,
 }
 
-#[allow(clippy::non_send_fields_in_send_ty)]
 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
 unsafe impl Send for CondVar {}
 
Signature · 1 line
2.48.1
maintainer Applied
#20 lore raw

Patch "rust: sync: remove unneeded `#[allow(clippy::non_send_fields_in_send_ty)]`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: sync: remove unneeded #[allow(clippy::non_send_fields_in_send_ty)]

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-sync-remove-unneeded.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:07 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:17 +0100
Subject: rust: sync: remove unneeded #[allow(clippy::non_send_fields_in_send_ty)]
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 5e7c9b84ad08cc7a41b2ddbbbaccb60057da3860 upstream.

Rust 1.58.0 (before Rust was merged into the kernel) made Clippy's non_send_fields_in_send_ty lint part of the suspicious lint group for a brief window of time [1] until the minor version 1.58.1 got released a week after, where the lint was moved back to nursery.

By that time, we had already upgraded to that Rust version, and thus we had allowed the lint here for CondVar.

Nowadays, Clippy's non_send_fields_in_send_ty would still trigger here if it were enabled.

Moreover, if enabled, Lock<T, B> and Task would also require an allow. Therefore, it does not seem like someone is actually enabling it (in, e.g., a custom flags build).

Finally, the lint does not appear to have had major improvements since then [2].

Thus remove the allow since it is unneeded.

---
 rust/kernel/sync/condvar.rs |    1 -
 1 file changed, 1 deletion(-)
rust/kernel/sync/condvar.rs +0 -1
@@ -92,7 +92,6 @@ pub struct CondVar {
     _pin: PhantomPinned,
 }
 
-#[allow(clippy::non_send_fields_in_send_ty)]
 // SAFETY: `CondVar` only uses a `struct wait_queue_head`, which is safe to use on any thread.
 unsafe impl Send for CondVar {}
 

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#21 lore raw

PATCH 11/60 rust: introduce `.clippy.toml`

In reply to Miguel Ojeda

commit 7d56786edcbdf58b6367fd7f01d5861214ad1c95 upstream.

Some Clippy lints can be configured/tweaked. We will use these knobs to our advantage in later commits.

This is done via a configuration file, .clippy.toml [1]. The file is currently unstable. This may be a problem in the future, but we can adapt as needed. In addition, we proposed adding Clippy to the Rust CI's RFL job [2], so we should be able to catch issues pre-merge.

Thus introduce the file.

---
 .clippy.toml | 1 +
 .gitignore   | 1 +
 MAINTAINERS  | 1 +
 Makefile     | 3 +++
 4 files changed, 6 insertions(+)
 create mode 100644 .clippy.toml
.clippy.toml new file +1 -0
new file mode 100644
index 000000000000..f66554cd5c45
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-2.0
.gitignore +1 -0
index 56972adb5031..a61e4778d011 100644
@@ -103,6 +103,7 @@ modules.order
 # We don't want to ignore the following even if they are dot-files
 #
 !.clang-format
+!.clippy.toml
 !.cocciconfig
 !.editorconfig
 !.get_maintainer.ignore
MAINTAINERS +1 -0
index 6bb4ec0c162a..f4e08a0851bd 100644
@@ -20175,6 +20175,7 @@ B:	https://github.com/Rust-for-Linux/linux/issues
 C:	zulip://rust-for-linux.zulipchat.com
 P:	https://rust-for-linux.com/contributing
 T:	git https://github.com/Rust-for-Linux/linux.git rust-next
+F:	.clippy.toml
 F:	Documentation/rust/
 F:	rust/
 F:	samples/rust/
Makefile +3 -0
index 8748aa1b2f79..43cc17c514dc 100644
@@ -588,6 +588,9 @@ endif
 # Allows the usage of unstable features in stable compilers.
 export RUSTC_BOOTSTRAP := 1
 
+# Allows finding `.clippy.toml` in out-of-srctree builds.
+export CLIPPY_CONF_DIR := $(srctree)
+
 export ARCH SRCARCH CONFIG_SHELL BASH HOSTCC KBUILD_HOSTCFLAGS CROSS_COMPILE LD CC HOSTPKG_CONFIG
 export RUSTC RUSTDOC RUSTFMT RUSTC_OR_CLIPPY_QUIET RUSTC_OR_CLIPPY BINDGEN
 export HOSTRUSTC KBUILD_HOSTRUSTFLAGS
Signature · 1 line
2.48.1
maintainer Applied
#22 lore raw

Patch "rust: introduce `.clippy.toml`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: introduce .clippy.toml

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-introduce-.clippy.toml.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:09 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:18 +0100
Subject: rust: introduce .clippy.toml
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 7d56786edcbdf58b6367fd7f01d5861214ad1c95 upstream.

Some Clippy lints can be configured/tweaked. We will use these knobs to our advantage in later commits.

This is done via a configuration file, .clippy.toml [1]. The file is currently unstable. This may be a problem in the future, but we can adapt as needed. In addition, we proposed adding Clippy to the Rust CI's RFL job [2], so we should be able to catch issues pre-merge.

Thus introduce the file.

---
 .clippy.toml |    1 +
 .gitignore   |    1 +
 MAINTAINERS  |    1 +
 Makefile     |    3 +++
 4 files changed, 6 insertions(+)
 create mode 100644 .clippy.toml
.clippy.toml new file +1 -0
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-2.0
.gitignore +1 -0
@@ -103,6 +103,7 @@ modules.order
 # We don't want to ignore the following even if they are dot-files
 #
 !.clang-format
+!.clippy.toml
 !.cocciconfig
 !.editorconfig
 !.get_maintainer.ignore
MAINTAINERS +1 -0
@@ -20175,6 +20175,7 @@ B:	https://github.com/Rust-for-Linux/lin
 C:	zulip://rust-for-linux.zulipchat.com
 P:	https://rust-for-linux.com/contributing
 T:	git https://github.com/Rust-for-Linux/linux.git rust-next
+F:	.clippy.toml
 F:	Documentation/rust/
 F:	rust/
 F:	samples/rust/
Makefile +3 -0
@@ -588,6 +588,9 @@ endif
 # Allows the usage of unstable features in stable compilers.
 export RUSTC_BOOTSTRAP := 1
 
+# Allows finding `.clippy.toml` in out-of-srctree builds.
+export CLIPPY_CONF_DIR := $(srctree)
+
 export ARCH SRCARCH CONFIG_SHELL BASH HOSTCC KBUILD_HOSTCFLAGS CROSS_COMPILE LD CC HOSTPKG_CONFIG
 export RUSTC RUSTDOC RUSTFMT RUSTC_OR_CLIPPY_QUIET RUSTC_OR_CLIPPY BINDGEN
 export HOSTRUSTC KBUILD_HOSTRUSTFLAGS

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#23 lore raw

PATCH 12/60 rust: replace `clippy::dbg_macro` with `disallowed_macros`

In reply to Miguel Ojeda

commit 8577c9dca799bd74377f7c30015d8cdc53a53ca2 upstream.

Back when we used Rust 1.60.0 (before Rust was merged in the kernel), we added -Wclippy::dbg_macro to the compilation flags. This worked great with our custom dbg! macro (vendored from std, but slightly modified to use the kernel printing facilities).

However, in the very next version, 1.61.0, it stopped working [1] since the lint started to use a Rust diagnostic item rather than a path to find the dbg! macro [1]. This behavior remains until the current nightly (1.83.0).

Therefore, currently, the dbg_macro is not doing anything, which explains why we can invoke dbg! in samples/rust/rust_print.rs, as well as why changing the #[allow()]s to #[expect()]s in std_vendor.rs` doctests does not work since they are not fulfilled.

One possible workaround is using rustc_attrs like the standard library does. However, this is intended to be internal, and we just started supporting several Rust compiler versions, so it is best to avoid it.

Therefore, instead, use disallowed_macros. It is a stable lint and is more flexible (in that we can provide different macros), although its diagnostic message(s) are not as nice as the specialized one (yet), and does not allow to set different lint levels per macro/path [2].

In turn, this requires allowing the (intentional) dbg! use in the sample, as one would have expected.

Finally, in a single case, the allow is fixed to be an inner attribute, since otherwise it was not being applied.

---
 .clippy.toml               |  6 ++++++
 Makefile                   |  1 -
 rust/kernel/std_vendor.rs  | 10 +++++-----
 samples/rust/rust_print.rs |  1 +
 4 files changed, 12 insertions(+), 6 deletions(-)
.clippy.toml +6 -0
index f66554cd5c45..ad9f804fb677 100644
@@ -1 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
+
+disallowed-macros = [
+    # The `clippy::dbg_macro` lint only works with `std::dbg!`, thus we simulate
+    # it here, see: https://github.com/rust-lang/rust-clippy/issues/11303.
+    { path = "kernel::dbg", reason = "the `dbg!` macro is intended as a debugging tool" },
+]
Makefile +0 -1
index 43cc17c514dc..d005a439a67c 100644
@@ -452,7 +452,6 @@ export rust_common_flags := --edition=2021 \
 			    -Wrust_2018_idioms \
 			    -Wunreachable_pub \
 			    -Wclippy::all \
-			    -Wclippy::dbg_macro \
 			    -Wclippy::ignored_unit_patterns \
 			    -Wclippy::mut_mut \
 			    -Wclippy::needless_bitwise_bool \
rust/kernel/std_vendor.rs +5 -5
index 67bf9d37ddb5..085b23312c65 100644
@@ -14,7 +14,7 @@
 ///
 /// ```rust
 /// let a = 2;
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// let b = dbg!(a * 2) + 1;
 /// //      ^-- prints: [src/main.rs:2] a * 2 = 4
 /// assert_eq!(b, 5);
@@ -52,7 +52,7 @@
 /// With a method call:
 ///
 /// ```rust
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// fn foo(n: usize) {
 ///     if dbg!(n.checked_sub(4)).is_some() {
 ///         // ...
@@ -71,7 +71,7 @@
 /// Naive factorial implementation:
 ///
 /// ```rust
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// # {
 /// fn factorial(n: u32) -> u32 {
 ///     if dbg!(n <= 1) {
@@ -118,7 +118,7 @@
 /// a tuple (and return it, too):
 ///
 /// ```
-/// # #[allow(clippy::dbg_macro)]
+/// # #![allow(clippy::disallowed_macros)]
 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
 /// ```
 ///
@@ -127,7 +127,7 @@
 /// invocations. You can use a 1-tuple directly if you need one:
 ///
 /// ```
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// # {
 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
samples/rust/rust_print.rs +1 -0
index 6eabb0d79ea3..ed1137ab2018 100644
@@ -15,6 +15,7 @@
 
 struct RustPrint;
 
+#[allow(clippy::disallowed_macros)]
 fn arc_print() -> Result {
     use kernel::sync::*;
 
Signature · 1 line
2.48.1
maintainer Applied
#24 lore raw

Patch "rust: replace `clippy::dbg_macro` with `disallowed_macros`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: replace clippy::dbg_macro with disallowed_macros

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-replace-clippy-dbg_macro-with-disallowed_macros.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:13 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:19 +0100
Subject: rust: replace clippy::dbg_macro with disallowed_macros
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 8577c9dca799bd74377f7c30015d8cdc53a53ca2 upstream.

Back when we used Rust 1.60.0 (before Rust was merged in the kernel), we added -Wclippy::dbg_macro to the compilation flags. This worked great with our custom dbg! macro (vendored from std, but slightly modified to use the kernel printing facilities).

However, in the very next version, 1.61.0, it stopped working [1] since the lint started to use a Rust diagnostic item rather than a path to find the dbg! macro [1]. This behavior remains until the current nightly (1.83.0).

Therefore, currently, the dbg_macro is not doing anything, which explains why we can invoke dbg! in samples/rust/rust_print.rs, as well as why changing the #[allow()]s to #[expect()]s in std_vendor.rs` doctests does not work since they are not fulfilled.

One possible workaround is using rustc_attrs like the standard library does. However, this is intended to be internal, and we just started supporting several Rust compiler versions, so it is best to avoid it.

Therefore, instead, use disallowed_macros. It is a stable lint and is more flexible (in that we can provide different macros), although its diagnostic message(s) are not as nice as the specialized one (yet), and does not allow to set different lint levels per macro/path [2].

In turn, this requires allowing the (intentional) dbg! use in the sample, as one would have expected.

Finally, in a single case, the allow is fixed to be an inner attribute, since otherwise it was not being applied.

---
 .clippy.toml               |    6 ++++++
 Makefile                   |    1 -
 rust/kernel/std_vendor.rs  |   10 +++++-----
 samples/rust/rust_print.rs |    1 +
 4 files changed, 12 insertions(+), 6 deletions(-)
.clippy.toml +6 -0
@@ -1 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
+
+disallowed-macros = [
+    # The `clippy::dbg_macro` lint only works with `std::dbg!`, thus we simulate
+    # it here, see: https://github.com/rust-lang/rust-clippy/issues/11303.
+    { path = "kernel::dbg", reason = "the `dbg!` macro is intended as a debugging tool" },
+]
Makefile +0 -1
@@ -452,7 +452,6 @@ export rust_common_flags := --edition=20
 			    -Wrust_2018_idioms \
 			    -Wunreachable_pub \
 			    -Wclippy::all \
-			    -Wclippy::dbg_macro \
 			    -Wclippy::ignored_unit_patterns \
 			    -Wclippy::mut_mut \
 			    -Wclippy::needless_bitwise_bool \
rust/kernel/std_vendor.rs +5 -5
@@ -14,7 +14,7 @@
 ///
 /// ```rust
 /// let a = 2;
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// let b = dbg!(a * 2) + 1;
 /// //      ^-- prints: [src/main.rs:2] a * 2 = 4
 /// assert_eq!(b, 5);
@@ -52,7 +52,7 @@
 /// With a method call:
 ///
 /// ```rust
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// fn foo(n: usize) {
 ///     if dbg!(n.checked_sub(4)).is_some() {
 ///         // ...
@@ -71,7 +71,7 @@
 /// Naive factorial implementation:
 ///
 /// ```rust
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// # {
 /// fn factorial(n: u32) -> u32 {
 ///     if dbg!(n <= 1) {
@@ -118,7 +118,7 @@
 /// a tuple (and return it, too):
 ///
 /// ```
-/// # #[allow(clippy::dbg_macro)]
+/// # #![allow(clippy::disallowed_macros)]
 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
 /// ```
 ///
@@ -127,7 +127,7 @@
 /// invocations. You can use a 1-tuple directly if you need one:
 ///
 /// ```
-/// # #[allow(clippy::dbg_macro)]
+/// # #[allow(clippy::disallowed_macros)]
 /// # {
 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
samples/rust/rust_print.rs +1 -0
@@ -15,6 +15,7 @@ module! {
 
 struct RustPrint;
 
+#[allow(clippy::disallowed_macros)]
 fn arc_print() -> Result {
     use kernel::sync::*;
 

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#25 lore raw

PATCH 13/60 rust: provide proper code documentation titles

In reply to Miguel Ojeda

commit 2f390cc589433dfcfedc307a141e103929a6fd4d upstream.

Rust 1.82.0's Clippy is introducing [1][2] a new warn-by-default lint, too_long_first_doc_paragraph [3], which is intended to catch titles of code documentation items that are too long (likely because no title was provided and the item documentation starts with a paragraph).

This lint does not currently trigger anywhere, but it does detect a couple cases if checking for private items gets enabled (which we will do in the next commit):

error: first doc comment paragraph is too long
--> rust/kernel/init/__internal.rs:18:1
|
18 | / /// This is the module-internal type implementing PinInit and Init. It is unsafe to create this 19 | | /// type, since the closure needs to fulfill the same safety requirement as the
20 | | /// __pinned_init/__init functions.
| |_
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#too_long_first_doc_paragraph
= note: -D clippy::too-long-first-doc-paragraph implied by -D warnings
= help: to override -D warnings add #[allow(clippy::too_long_first_doc_paragraph)]

error: first doc comment paragraph is too long
--> rust/kernel/sync/arc/std_vendor.rs:3:1
|
3 | / //! The contents of this file come from the Rust standard library, hosted in
4 | | //! the <https://github.com/rust-lang/rust> repository, licensed under
5 | | //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
6 | | //! see <https://github.com/rust-lang/rust/blob/master/COPYRIGHT>.
| |_
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#too_long_first_doc_paragraph

Thus clean those two instances.

In addition, since we have a second std_vendor.rs file with a similar header, do the same there too (even if that one does not trigger the lint, because it is doc(hidden)).

---
 rust/kernel/init/__internal.rs     | 7 ++++---
 rust/kernel/std_vendor.rs          | 2 ++
 rust/kernel/sync/arc/std_vendor.rs | 2 ++
 3 files changed, 8 insertions(+), 3 deletions(-)
rust/kernel/init/__internal.rs +4 -3
index 29f4fd00df3d..163eb072f296 100644
@@ -15,9 +15,10 @@
 /// [this table]: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
 pub(super) type Invariant<T> = PhantomData<fn(*mut T) -> *mut T>;
 
-/// This is the module-internal type implementing `PinInit` and `Init`. It is unsafe to create this
-/// type, since the closure needs to fulfill the same safety requirement as the
-/// `__pinned_init`/`__init` functions.
+/// Module-internal type implementing `PinInit` and `Init`.
+///
+/// It is unsafe to create this type, since the closure needs to fulfill the same safety
+/// requirement as the `__pinned_init`/`__init` functions.
 pub(crate) struct InitClosure<F, T: ?Sized, E>(pub(crate) F, pub(crate) Invariant<(E, T)>);
 
 // SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
rust/kernel/std_vendor.rs +2 -0
index 085b23312c65..d59e4cf4b252 100644
@@ -1,5 +1,7 @@
 // SPDX-License-Identifier: Apache-2.0 OR MIT
 
+//! Rust standard library vendored code.
+//!
 //! The contents of this file come from the Rust standard library, hosted in
 //! the <https://github.com/rust-lang/rust> repository, licensed under
 //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
rust/kernel/sync/arc/std_vendor.rs +2 -0
index a66a0c2831b3..11b3f4ecca5f 100644
@@ -1,5 +1,7 @@
 // SPDX-License-Identifier: Apache-2.0 OR MIT
 
+//! Rust standard library vendored code.
+//!
 //! The contents of this file come from the Rust standard library, hosted in
 //! the <https://github.com/rust-lang/rust> repository, licensed under
 //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
Signature · 1 line
2.48.1
maintainer Applied
#26 lore raw

Patch "rust: provide proper code documentation titles" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: provide proper code documentation titles

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-provide-proper-code-documentation-titles.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:16 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:20 +0100
Subject: rust: provide proper code documentation titles
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 2f390cc589433dfcfedc307a141e103929a6fd4d upstream.

Rust 1.82.0's Clippy is introducing [1][2] a new warn-by-default lint, too_long_first_doc_paragraph [3], which is intended to catch titles of code documentation items that are too long (likely because no title was provided and the item documentation starts with a paragraph).

This lint does not currently trigger anywhere, but it does detect a couple cases if checking for private items gets enabled (which we will do in the next commit):

error: first doc comment paragraph is too long
--> rust/kernel/init/__internal.rs:18:1
|
18 | / /// This is the module-internal type implementing PinInit and Init. It is unsafe to create this 19 | | /// type, since the closure needs to fulfill the same safety requirement as the
20 | | /// __pinned_init/__init functions.
| |_
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#too_long_first_doc_paragraph
= note: -D clippy::too-long-first-doc-paragraph implied by -D warnings
= help: to override -D warnings add #[allow(clippy::too_long_first_doc_paragraph)]

error: first doc comment paragraph is too long
--> rust/kernel/sync/arc/std_vendor.rs:3:1
|
3 | / //! The contents of this file come from the Rust standard library, hosted in
4 | | //! the <https://github.com/rust-lang/rust> repository, licensed under
5 | | //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
6 | | //! see <https://github.com/rust-lang/rust/blob/master/COPYRIGHT>.
| |_
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#too_long_first_doc_paragraph

Thus clean those two instances.

In addition, since we have a second std_vendor.rs file with a similar header, do the same there too (even if that one does not trigger the lint, because it is doc(hidden)).

---
 rust/kernel/init/__internal.rs     |    7 ++++---
 rust/kernel/std_vendor.rs          |    2 ++
 rust/kernel/sync/arc/std_vendor.rs |    2 ++
 3 files changed, 8 insertions(+), 3 deletions(-)
rust/kernel/init/__internal.rs +4 -3
@@ -15,9 +15,10 @@ use super::*;
 /// [this table]: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
 pub(super) type Invariant<T> = PhantomData<fn(*mut T) -> *mut T>;
 
-/// This is the module-internal type implementing `PinInit` and `Init`. It is unsafe to create this
-/// type, since the closure needs to fulfill the same safety requirement as the
-/// `__pinned_init`/`__init` functions.
+/// Module-internal type implementing `PinInit` and `Init`.
+///
+/// It is unsafe to create this type, since the closure needs to fulfill the same safety
+/// requirement as the `__pinned_init`/`__init` functions.
 pub(crate) struct InitClosure<F, T: ?Sized, E>(pub(crate) F, pub(crate) Invariant<(E, T)>);
 
 // SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
rust/kernel/std_vendor.rs +2 -0
@@ -1,5 +1,7 @@
 // SPDX-License-Identifier: Apache-2.0 OR MIT
 
+//! Rust standard library vendored code.
+//!
 //! The contents of this file come from the Rust standard library, hosted in
 //! the <https://github.com/rust-lang/rust> repository, licensed under
 //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,
rust/kernel/sync/arc/std_vendor.rs +2 -0
@@ -1,5 +1,7 @@
 // SPDX-License-Identifier: Apache-2.0 OR MIT
 
+//! Rust standard library vendored code.
+//!
 //! The contents of this file come from the Rust standard library, hosted in
 //! the <https://github.com/rust-lang/rust> repository, licensed under
 //! "Apache-2.0 OR MIT" and adapted for kernel use. For copyright details,

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#27 lore raw

PATCH 14/60 rust: enable Clippy's `check-private-items`

In reply to Miguel Ojeda

commit 624063b9ac97f40cadca32a896aafeb28b1220fd upstream.

In Rust 1.76.0, Clippy added the check-private-items lint configuration option. When turned on (the default is off), it makes several lints check private items as well.

In our case, it affects two lints we have enabled [1]:
missing_safety_doc and unnecessary_safety_doc.

It also seems to affect the new too_long_first_doc_paragraph lint [2], even though the documentation does not mention it.

Thus allow the few instances remaining we currently hit and enable the lint.

---
 .clippy.toml                   | 2 ++
 rust/kernel/init.rs            | 1 +
 rust/kernel/init/__internal.rs | 2 ++
 rust/kernel/init/macros.rs     | 1 +
 rust/kernel/print.rs           | 1 +
 5 files changed, 7 insertions(+)
.clippy.toml +2 -0
index ad9f804fb677..e4c4eef10b28 100644
@@ -1,5 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
 
+check-private-items = true
+
 disallowed-macros = [
     # The `clippy::dbg_macro` lint only works with `std::dbg!`, thus we simulate
     # it here, see: https://github.com/rust-lang/rust-clippy/issues/11303.
rust/kernel/init.rs +1 -0
index 0330a8756fa5..fdbf0857ba20 100644
@@ -125,6 +125,7 @@
 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin};
 //! # mod bindings {
 //! #     #![allow(non_camel_case_types)]
+//! #     #![allow(clippy::missing_safety_doc)]
 //! #     pub struct foo;
 //! #     pub unsafe fn init_foo(_ptr: *mut foo) {}
 //! #     pub unsafe fn destroy_foo(_ptr: *mut foo) {}
rust/kernel/init/__internal.rs +2 -0
index 163eb072f296..549ae227c2ea 100644
@@ -54,6 +54,7 @@ unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
 pub unsafe trait HasPinData {
     type PinData: PinData;
 
+    #[allow(clippy::missing_safety_doc)]
     unsafe fn __pin_data() -> Self::PinData;
 }
 
@@ -83,6 +84,7 @@ fn make_closure<F, O, E>(self, f: F) -> F
 pub unsafe trait HasInitData {
     type InitData: InitData;
 
+    #[allow(clippy::missing_safety_doc)]
     unsafe fn __init_data() -> Self::InitData;
 }
 
rust/kernel/init/macros.rs +1 -0
index 736fe0ce0cd9..193d39886b1f 100644
@@ -989,6 +989,7 @@ fn drop(&mut self) {
         //
         // The functions are `unsafe` to prevent accidentally calling them.
         #[allow(dead_code)]
+        #[allow(clippy::missing_safety_doc)]
         impl<$($impl_generics)*> $pin_data<$($ty_generics)*>
         where $($whr)*
         {
rust/kernel/print.rs +1 -0
index fe53fc469c4f..45af17095a24 100644
@@ -14,6 +14,7 @@
 use crate::str::RawFormatter;
 
 // Called from `vsprintf` with format specifier `%pA`.
+#[allow(clippy::missing_safety_doc)]
 #[no_mangle]
 unsafe extern "C" fn rust_fmt_argument(
     buf: *mut c_char,
Signature · 1 line
2.48.1
maintainer Applied
#28 lore raw

Patch "rust: enable Clippy's `check-private-items`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: enable Clippy's check-private-items

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-enable-clippy-s-check-private-items.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:20 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:21 +0100
Subject: rust: enable Clippy's check-private-items
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 624063b9ac97f40cadca32a896aafeb28b1220fd upstream.

In Rust 1.76.0, Clippy added the check-private-items lint configuration option. When turned on (the default is off), it makes several lints check private items as well.

In our case, it affects two lints we have enabled [1]:
missing_safety_doc and unnecessary_safety_doc.

It also seems to affect the new too_long_first_doc_paragraph lint [2], even though the documentation does not mention it.

Thus allow the few instances remaining we currently hit and enable the lint.

---
 .clippy.toml                   |    2 ++
 rust/kernel/init.rs            |    1 +
 rust/kernel/init/__internal.rs |    2 ++
 rust/kernel/init/macros.rs     |    1 +
 rust/kernel/print.rs           |    1 +
 5 files changed, 7 insertions(+)
.clippy.toml +2 -0
@@ -1,5 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
 
+check-private-items = true
+
 disallowed-macros = [
     # The `clippy::dbg_macro` lint only works with `std::dbg!`, thus we simulate
     # it here, see: https://github.com/rust-lang/rust-clippy/issues/11303.
rust/kernel/init.rs +1 -0
@@ -125,6 +125,7 @@
 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin};
 //! # mod bindings {
 //! #     #![allow(non_camel_case_types)]
+//! #     #![allow(clippy::missing_safety_doc)]
 //! #     pub struct foo;
 //! #     pub unsafe fn init_foo(_ptr: *mut foo) {}
 //! #     pub unsafe fn destroy_foo(_ptr: *mut foo) {}
rust/kernel/init/__internal.rs +2 -0
@@ -54,6 +54,7 @@ where
 pub unsafe trait HasPinData {
     type PinData: PinData;
 
+    #[allow(clippy::missing_safety_doc)]
     unsafe fn __pin_data() -> Self::PinData;
 }
 
@@ -83,6 +84,7 @@ pub unsafe trait PinData: Copy {
 pub unsafe trait HasInitData {
     type InitData: InitData;
 
+    #[allow(clippy::missing_safety_doc)]
     unsafe fn __init_data() -> Self::InitData;
 }
 
rust/kernel/init/macros.rs +1 -0
@@ -989,6 +989,7 @@ macro_rules! __pin_data {
         //
         // The functions are `unsafe` to prevent accidentally calling them.
         #[allow(dead_code)]
+        #[allow(clippy::missing_safety_doc)]
         impl<$($impl_generics)*> $pin_data<$($ty_generics)*>
         where $($whr)*
         {
rust/kernel/print.rs +1 -0
@@ -14,6 +14,7 @@ use core::{
 use crate::str::RawFormatter;
 
 // Called from `vsprintf` with format specifier `%pA`.
+#[allow(clippy::missing_safety_doc)]
 #[no_mangle]
 unsafe extern "C" fn rust_fmt_argument(
     buf: *mut c_char,

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#29 lore raw

PATCH 15/60 Documentation: rust: add coding guidelines on lints

In reply to Miguel Ojeda

commit 139d396572ec4ba6e8cc5c02f5c8d5d1139be4b7 upstream.

In the C side, disabling diagnostics locally, i.e. within the source code, is rare (at least in the kernel). Sometimes warnings are manipulated via the flags at the translation unit level, but that is about it.

In Rust, it is easier to change locally the "level" of lints (e.g. allowing them locally). In turn, this means it is easier to globally enable more lints that may trigger a few false positives here and there that need to be allowed locally, but that generally can spot issues or bugs.

Thus document this.

---
 Documentation/rust/coding-guidelines.rst | 38 ++++++++++++++++++++++++
 1 file changed, 38 insertions(+)
Documentation/rust/coding-guidelines.rst +38 -0
index 329b070a1d47..6db0420f0cea 100644
@@ -227,3 +227,41 @@ The equivalent in Rust may look like (ignoring documentation):
 That is, the equivalent of ``GPIO_LINE_DIRECTION_IN`` would be referred to as
 ``gpio::LineDirection::In``. In particular, it should not be named
 ``gpio::gpio_line_direction::GPIO_LINE_DIRECTION_IN``.
+
+
+Lints
+-----
+
+In Rust, it is possible to ``allow`` particular warnings (diagnostics, lints)
+locally, making the compiler ignore instances of a given warning within a given
+function, module, block, etc.
+
+It is similar to ``#pragma GCC diagnostic push`` + ``ignored`` + ``pop`` in C
+[#]_:
+
+.. code-block:: c
+
+	#pragma GCC diagnostic push
+	#pragma GCC diagnostic ignored "-Wunused-function"
+	static void f(void) {}
+	#pragma GCC diagnostic pop
+
+.. [#] In this particular case, the kernel's ``__{always,maybe}_unused``
+       attributes (C23's ``[[maybe_unused]]``) may be used; however, the example
+       is meant to reflect the equivalent lint in Rust discussed afterwards.
+
+But way less verbose:
+
+.. code-block:: rust
+
+	#[allow(dead_code)]
+	fn f() {}
+
+By that virtue, it makes it possible to comfortably enable more diagnostics by
+default (i.e. outside ``W=`` levels). In particular, those that may have some
+false positives but that are otherwise quite useful to keep enabled to catch
+potential mistakes.
+
+For more information about diagnostics in Rust, please see:
+
+	https://doc.rust-lang.org/stable/reference/attributes/diagnostics.html
Signature · 1 line
2.48.1
maintainer Applied
#30 lore raw

Patch "Documentation: rust: add coding guidelines on lints" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

Documentation: rust: add coding guidelines on lints

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
documentation-rust-add-coding-guidelines-on-lints.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:23 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:22 +0100
Subject: Documentation: rust: add coding guidelines on lints
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 139d396572ec4ba6e8cc5c02f5c8d5d1139be4b7 upstream.

In the C side, disabling diagnostics locally, i.e. within the source code, is rare (at least in the kernel). Sometimes warnings are manipulated via the flags at the translation unit level, but that is about it.

In Rust, it is easier to change locally the "level" of lints (e.g. allowing them locally). In turn, this means it is easier to globally enable more lints that may trigger a few false positives here and there that need to be allowed locally, but that generally can spot issues or bugs.

Thus document this.

---
 Documentation/rust/coding-guidelines.rst |   38 +++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)
Documentation/rust/coding-guidelines.rst +38 -0
@@ -227,3 +227,41 @@ The equivalent in Rust may look like (ig
 That is, the equivalent of ``GPIO_LINE_DIRECTION_IN`` would be referred to as
 ``gpio::LineDirection::In``. In particular, it should not be named
 ``gpio::gpio_line_direction::GPIO_LINE_DIRECTION_IN``.
+
+
+Lints
+-----
+
+In Rust, it is possible to ``allow`` particular warnings (diagnostics, lints)
+locally, making the compiler ignore instances of a given warning within a given
+function, module, block, etc.
+
+It is similar to ``#pragma GCC diagnostic push`` + ``ignored`` + ``pop`` in C
+[#]_:
+
+.. code-block:: c
+
+	#pragma GCC diagnostic push
+	#pragma GCC diagnostic ignored "-Wunused-function"
+	static void f(void) {}
+	#pragma GCC diagnostic pop
+
+.. [#] In this particular case, the kernel's ``__{always,maybe}_unused``
+       attributes (C23's ``[[maybe_unused]]``) may be used; however, the example
+       is meant to reflect the equivalent lint in Rust discussed afterwards.
+
+But way less verbose:
+
+.. code-block:: rust
+
+	#[allow(dead_code)]
+	fn f() {}
+
+By that virtue, it makes it possible to comfortably enable more diagnostics by
+default (i.e. outside ``W=`` levels). In particular, those that may have some
+false positives but that are otherwise quite useful to keep enabled to catch
+potential mistakes.
+
+For more information about diagnostics in Rust, please see:
+
+	https://doc.rust-lang.org/stable/reference/attributes/diagnostics.html

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#31 lore raw

PATCH 16/60 rust: start using the `#[expect(...)]` attribute

In reply to Miguel Ojeda

commit 1f9ed172545687e5c04c77490a45896be6d2e459 upstream.

In Rust, it is possible to allow particular warnings (diagnostics, lints) locally, making the compiler ignore instances of a given warning within a given function, module, block, etc.

It is similar to #pragma GCC diagnostic push + ignored + pop in C:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function" static void f(void) {}
#pragma GCC diagnostic pop

But way less verbose:

    #[allow(dead_code)]
    fn f() {}

By that virtue, it makes it possible to comfortably enable more diagnostics by default (i.e. outside W= levels) that may have some false positives but that are otherwise quite useful to keep enabled to catch potential mistakes.

The #[expect(...)] attribute [1] takes this further, and makes the compiler warn if the diagnostic was _not_ produced. For instance, the following will ensure that, when f() is called somewhere, we will have to remove the attribute:

    #[expect(dead_code)]
    fn f() {}

If we do not, we get a warning from the compiler:

    warning: this lint expectation is unfulfilled
     --> x.rs:3:10
      |
    3 | #[expect(dead_code)]
      |          ^^^^^^^^^
      |
      = note: `#[warn(unfulfilled_lint_expectations)]` on by default

This means that expects do not get forgotten when they are not needed.

See the next commit for more details, nuances on its usage and documentation on the feature.

The attribute requires the lint_reasons [2] unstable feature, but it is becoming stable in 1.81.0 (to be released on 2024-09-05) and it has already been useful to clean things up in this patch series, finding cases where the allows should not have been there.

Thus, enable lint_reasons and convert some of our allows to expects where possible.

This feature was also an example of the ongoing collaboration between Rust and the kernel -- we tested it in the kernel early on and found an issue that was quickly resolved [3].

---
 rust/kernel/error.rs           |  2 +-
 rust/kernel/init.rs            | 22 +++++++++++-----------
 rust/kernel/init/__internal.rs |  4 ++--
 rust/kernel/init/macros.rs     | 10 +++++-----
 rust/kernel/ioctl.rs           |  2 +-
 rust/kernel/lib.rs             |  1 +
 rust/kernel/list/arc_field.rs  |  2 +-
 rust/kernel/print.rs           |  4 ++--
 rust/kernel/std_vendor.rs      | 10 +++++-----
 samples/rust/rust_print.rs     |  2 +-
 scripts/Makefile.build         |  2 +-
 11 files changed, 31 insertions(+), 30 deletions(-)
rust/kernel/error.rs +1 -1
index 639bc7572f90..a681acda87ce 100644
@@ -133,7 +133,7 @@ pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
     }
 
     /// Returns the error encoded as a pointer.
-    #[allow(dead_code)]
+    #[expect(dead_code)]
     pub(crate) 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.
rust/kernel/init.rs +11 -11
index fdbf0857ba20..44e829b61243 100644
@@ -35,7 +35,7 @@
 //! that you need to write `<-` instead of `:` for fields that you want to initialize in-place.
 //!
 //! ```rust
-//! # #![allow(clippy::disallowed_names)]
+//! # #![expect(clippy::disallowed_names)]
 //! use kernel::sync::{new_mutex, Mutex};
 //! # use core::pin::Pin;
 //! #[pin_data]
@@ -55,7 +55,7 @@
 //! (or just the stack) to actually initialize a `Foo`:
 //!
 //! ```rust
-//! # #![allow(clippy::disallowed_names)]
+//! # #![expect(clippy::disallowed_names)]
 //! # use kernel::sync::{new_mutex, Mutex};
 //! # use core::pin::Pin;
 //! # #[pin_data]
@@ -120,12 +120,12 @@
 //!   `slot` gets called.
 //!
 //! ```rust
-//! # #![allow(unreachable_pub, clippy::disallowed_names)]
+//! # #![expect(unreachable_pub, clippy::disallowed_names)]
 //! use kernel::{init, types::Opaque};
 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin};
 //! # mod bindings {
-//! #     #![allow(non_camel_case_types)]
-//! #     #![allow(clippy::missing_safety_doc)]
+//! #     #![expect(non_camel_case_types)]
+//! #     #![expect(clippy::missing_safety_doc)]
 //! #     pub struct foo;
 //! #     pub unsafe fn init_foo(_ptr: *mut foo) {}
 //! #     pub unsafe fn destroy_foo(_ptr: *mut foo) {}
@@ -238,7 +238,7 @@
 /// # Examples
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, macros::pin_data, pin_init, stack_pin_init, init::*, sync::Mutex, new_mutex};
 /// # use core::pin::Pin;
 /// #[pin_data]
@@ -290,7 +290,7 @@ macro_rules! stack_pin_init {
 /// # Examples
 ///
 /// ```rust,ignore
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
 /// # use macros::pin_data;
 /// # use core::{alloc::AllocError, pin::Pin};
@@ -316,7 +316,7 @@ macro_rules! stack_pin_init {
 /// ```
 ///
 /// ```rust,ignore
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
 /// # use macros::pin_data;
 /// # use core::{alloc::AllocError, pin::Pin};
@@ -438,7 +438,7 @@ macro_rules! stack_try_pin_init {
 /// Users of `Foo` can now create it like this:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
 /// # use core::pin::Pin;
 /// # #[pin_data]
@@ -852,7 +852,7 @@ pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized {
     /// # Examples
     ///
     /// ```rust
-    /// # #![allow(clippy::disallowed_names)]
+    /// # #![expect(clippy::disallowed_names)]
     /// use kernel::{types::Opaque, init::pin_init_from_closure};
     /// #[repr(C)]
     /// struct RawFoo([u8; 16]);
@@ -964,7 +964,7 @@ pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> {
     /// # Examples
     ///
     /// ```rust
-    /// # #![allow(clippy::disallowed_names)]
+    /// # #![expect(clippy::disallowed_names)]
     /// use kernel::{types::Opaque, init::{self, init_from_closure}};
     /// struct Foo {
     ///     buf: [u8; 1_000_000],
rust/kernel/init/__internal.rs +2 -2
index 549ae227c2ea..44431fba7aab 100644
@@ -54,7 +54,7 @@ unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
 pub unsafe trait HasPinData {
     type PinData: PinData;
 
-    #[allow(clippy::missing_safety_doc)]
+    #[expect(clippy::missing_safety_doc)]
     unsafe fn __pin_data() -> Self::PinData;
 }
 
@@ -84,7 +84,7 @@ fn make_closure<F, O, E>(self, f: F) -> F
 pub unsafe trait HasInitData {
     type InitData: InitData;
 
-    #[allow(clippy::missing_safety_doc)]
+    #[expect(clippy::missing_safety_doc)]
     unsafe fn __init_data() -> Self::InitData;
 }
 
rust/kernel/init/macros.rs +5 -5
index 193d39886b1f..1fd146a83241 100644
@@ -182,13 +182,13 @@
 //!     // Normally `Drop` bounds do not have the correct semantics, but for this purpose they do
 //!     // (normally people want to know if a type has any kind of drop glue at all, here we want
 //!     // to know if it has any kind of custom drop glue, which is exactly what this bound does).
-//!     #[allow(drop_bounds)]
+//!     #[expect(drop_bounds)]
 //!     impl<T: ::core::ops::Drop> MustNotImplDrop for T {}
 //!     impl<T> MustNotImplDrop for Bar<T> {}
 //!     // Here comes a convenience check, if one implemented `PinnedDrop`, but forgot to add it to
 //!     // `#[pin_data]`, then this will error with the same mechanic as above, this is not needed
 //!     // for safety, but a good sanity check, since no normal code calls `PinnedDrop::drop`.
-//!     #[allow(non_camel_case_types)]
+//!     #[expect(non_camel_case_types)]
 //!     trait UselessPinnedDropImpl_you_need_to_specify_PinnedDrop {}
 //!     impl<
 //!         T: ::kernel::init::PinnedDrop,
@@ -925,14 +925,14 @@ impl<'__pin, $($impl_generics)*> ::core::marker::Unpin for $name<$($ty_generics)
         // `Drop`. Additionally we will implement this trait for the struct leading to a conflict,
         // if it also implements `Drop`
         trait MustNotImplDrop {}
-        #[allow(drop_bounds)]
+        #[expect(drop_bounds)]
         impl<T: ::core::ops::Drop> MustNotImplDrop for T {}
         impl<$($impl_generics)*> MustNotImplDrop for $name<$($ty_generics)*>
         where $($whr)* {}
         // We also take care to prevent users from writing a useless `PinnedDrop` implementation.
         // They might implement `PinnedDrop` correctly for the struct, but forget to give
         // `PinnedDrop` as the parameter to `#[pin_data]`.
-        #[allow(non_camel_case_types)]
+        #[expect(non_camel_case_types)]
         trait UselessPinnedDropImpl_you_need_to_specify_PinnedDrop {}
         impl<T: $crate::init::PinnedDrop>
             UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for T {}
@@ -989,7 +989,7 @@ fn drop(&mut self) {
         //
         // The functions are `unsafe` to prevent accidentally calling them.
         #[allow(dead_code)]
-        #[allow(clippy::missing_safety_doc)]
+        #[expect(clippy::missing_safety_doc)]
         impl<$($impl_generics)*> $pin_data<$($ty_generics)*>
         where $($whr)*
         {
rust/kernel/ioctl.rs +1 -1
index cfa7d080b531..2fc7662339e5 100644
@@ -4,7 +4,7 @@
 //!
 //! C header: [`include/asm-generic/ioctl.h`](srctree/include/asm-generic/ioctl.h)
 
-#![allow(non_snake_case)]
+#![expect(non_snake_case)]
 
 use crate::build_assert;
 
rust/kernel/lib.rs +1 -0
index e936254531fd..b6395b4209d7 100644
@@ -15,6 +15,7 @@
 #![feature(arbitrary_self_types)]
 #![feature(coerce_unsized)]
 #![feature(dispatch_from_dyn)]
+#![feature(lint_reasons)]
 #![feature(new_uninit)]
 #![feature(unsize)]
 
rust/kernel/list/arc_field.rs +1 -1
index 2330f673427a..c4b9dd503982 100644
@@ -56,7 +56,7 @@ pub unsafe fn assert_ref(&self) -> &T {
     ///
     /// The caller must have mutable access to the `ListArc<ID>` containing the struct with this
     /// field for the duration of the returned reference.
-    #[allow(clippy::mut_from_ref)]
+    #[expect(clippy::mut_from_ref)]
     pub unsafe fn assert_mut(&self) -> &mut T {
         // SAFETY: The caller has exclusive access to the `ListArc`, so they also have exclusive
         // access to this field.
rust/kernel/print.rs +2 -2
index 45af17095a24..a28077a7cb30 100644
@@ -14,7 +14,7 @@
 use crate::str::RawFormatter;
 
 // Called from `vsprintf` with format specifier `%pA`.
-#[allow(clippy::missing_safety_doc)]
+#[expect(clippy::missing_safety_doc)]
 #[no_mangle]
 unsafe extern "C" fn rust_fmt_argument(
     buf: *mut c_char,
@@ -140,7 +140,7 @@ pub fn call_printk_cont(args: fmt::Arguments<'_>) {
 #[doc(hidden)]
 #[cfg(not(testlib))]
 #[macro_export]
-#[allow(clippy::crate_in_macro_def)]
+#[expect(clippy::crate_in_macro_def)]
 macro_rules! print_macro (
     // The non-continuation cases (most of them, e.g. `INFO`).
     ($format_string:path, false, $($arg:tt)+) => (
rust/kernel/std_vendor.rs +5 -5
index d59e4cf4b252..8b4872b48e97 100644
@@ -16,7 +16,7 @@
 ///
 /// ```rust
 /// let a = 2;
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// let b = dbg!(a * 2) + 1;
 /// //      ^-- prints: [src/main.rs:2] a * 2 = 4
 /// assert_eq!(b, 5);
@@ -54,7 +54,7 @@
 /// With a method call:
 ///
 /// ```rust
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// fn foo(n: usize) {
 ///     if dbg!(n.checked_sub(4)).is_some() {
 ///         // ...
@@ -73,7 +73,7 @@
 /// Naive factorial implementation:
 ///
 /// ```rust
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// # {
 /// fn factorial(n: u32) -> u32 {
 ///     if dbg!(n <= 1) {
@@ -120,7 +120,7 @@
 /// a tuple (and return it, too):
 ///
 /// ```
-/// # #![allow(clippy::disallowed_macros)]
+/// # #![expect(clippy::disallowed_macros)]
 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
 /// ```
 ///
@@ -129,7 +129,7 @@
 /// invocations. You can use a 1-tuple directly if you need one:
 ///
 /// ```
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// # {
 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
samples/rust/rust_print.rs +1 -1
index ed1137ab2018..ba1606bdbd75 100644
@@ -15,7 +15,7 @@
 
 struct RustPrint;
 
-#[allow(clippy::disallowed_macros)]
+#[expect(clippy::disallowed_macros)]
 fn arc_print() -> Result {
     use kernel::sync::*;
 
scripts/Makefile.build +1 -1
index 880785b52c04..64518c2f3d9c 100644
@@ -248,7 +248,7 @@ $(obj)/%.lst: $(obj)/%.c FORCE
 # Compile Rust sources (.rs)
 # ---------------------------------------------------------------------------
 
-rust_allowed_features := arbitrary_self_types,new_uninit
+rust_allowed_features := arbitrary_self_types,lint_reasons,new_uninit
 
 # `--out-dir` is required to avoid temporaries being created by `rustc` in the
 # current working directory, which may be not accessible in the out-of-tree
Signature · 1 line
2.48.1
maintainer Applied
#32 lore raw

Patch "rust: start using the `#[expect(...)]` attribute" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: start using the #[expect(...)] attribute

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-start-using-the-attribute.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:25 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:23 +0100
Subject: rust: start using the #[expect(...)] attribute
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 1f9ed172545687e5c04c77490a45896be6d2e459 upstream.

In Rust, it is possible to allow particular warnings (diagnostics, lints) locally, making the compiler ignore instances of a given warning within a given function, module, block, etc.

It is similar to #pragma GCC diagnostic push + ignored + pop in C:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function" static void f(void) {}
#pragma GCC diagnostic pop

But way less verbose:

    #[allow(dead_code)]
    fn f() {}

By that virtue, it makes it possible to comfortably enable more diagnostics by default (i.e. outside W= levels) that may have some false positives but that are otherwise quite useful to keep enabled to catch potential mistakes.

The #[expect(...)] attribute [1] takes this further, and makes the compiler warn if the diagnostic was _not_ produced. For instance, the following will ensure that, when f() is called somewhere, we will have to remove the attribute:

    #[expect(dead_code)]
    fn f() {}

If we do not, we get a warning from the compiler:

    warning: this lint expectation is unfulfilled
     --> x.rs:3:10
      |
    3 | #[expect(dead_code)]
      |          ^^^^^^^^^
      |
      = note: `#[warn(unfulfilled_lint_expectations)]` on by default

This means that expects do not get forgotten when they are not needed.

See the next commit for more details, nuances on its usage and documentation on the feature.

The attribute requires the lint_reasons [2] unstable feature, but it is becoming stable in 1.81.0 (to be released on 2024-09-05) and it has already been useful to clean things up in this patch series, finding cases where the allows should not have been there.

Thus, enable lint_reasons and convert some of our allows to expects where possible.

This feature was also an example of the ongoing collaboration between Rust and the kernel -- we tested it in the kernel early on and found an issue that was quickly resolved [3].

---
 rust/kernel/error.rs           |    2 +-
 rust/kernel/init.rs            |   22 +++++++++++-----------
 rust/kernel/init/__internal.rs |    4 ++--
 rust/kernel/init/macros.rs     |   10 +++++-----
 rust/kernel/ioctl.rs           |    2 +-
 rust/kernel/lib.rs             |    1 +
 rust/kernel/list/arc_field.rs  |    2 +-
 rust/kernel/print.rs           |    4 ++--
 rust/kernel/std_vendor.rs      |   10 +++++-----
 samples/rust/rust_print.rs     |    2 +-
 scripts/Makefile.build         |    2 +-
 11 files changed, 31 insertions(+), 30 deletions(-)
rust/kernel/error.rs +1 -1
@@ -133,7 +133,7 @@ impl Error {
     }
 
     /// Returns the error encoded as a pointer.
-    #[allow(dead_code)]
+    #[expect(dead_code)]
     pub(crate) 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.
rust/kernel/init.rs +11 -11
@@ -35,7 +35,7 @@
 //! that you need to write `<-` instead of `:` for fields that you want to initialize in-place.
 //!
 //! ```rust
-//! # #![allow(clippy::disallowed_names)]
+//! # #![expect(clippy::disallowed_names)]
 //! use kernel::sync::{new_mutex, Mutex};
 //! # use core::pin::Pin;
 //! #[pin_data]
@@ -55,7 +55,7 @@
 //! (or just the stack) to actually initialize a `Foo`:
 //!
 //! ```rust
-//! # #![allow(clippy::disallowed_names)]
+//! # #![expect(clippy::disallowed_names)]
 //! # use kernel::sync::{new_mutex, Mutex};
 //! # use core::pin::Pin;
 //! # #[pin_data]
@@ -120,12 +120,12 @@
 //!   `slot` gets called.
 //!
 //! ```rust
-//! # #![allow(unreachable_pub, clippy::disallowed_names)]
+//! # #![expect(unreachable_pub, clippy::disallowed_names)]
 //! use kernel::{init, types::Opaque};
 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin};
 //! # mod bindings {
-//! #     #![allow(non_camel_case_types)]
-//! #     #![allow(clippy::missing_safety_doc)]
+//! #     #![expect(non_camel_case_types)]
+//! #     #![expect(clippy::missing_safety_doc)]
 //! #     pub struct foo;
 //! #     pub unsafe fn init_foo(_ptr: *mut foo) {}
 //! #     pub unsafe fn destroy_foo(_ptr: *mut foo) {}
@@ -238,7 +238,7 @@ pub mod macros;
 /// # Examples
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, macros::pin_data, pin_init, stack_pin_init, init::*, sync::Mutex, new_mutex};
 /// # use core::pin::Pin;
 /// #[pin_data]
@@ -290,7 +290,7 @@ macro_rules! stack_pin_init {
 /// # Examples
 ///
 /// ```rust,ignore
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
 /// # use macros::pin_data;
 /// # use core::{alloc::AllocError, pin::Pin};
@@ -316,7 +316,7 @@ macro_rules! stack_pin_init {
 /// ```
 ///
 /// ```rust,ignore
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex};
 /// # use macros::pin_data;
 /// # use core::{alloc::AllocError, pin::Pin};
@@ -438,7 +438,7 @@ macro_rules! stack_try_pin_init {
 /// Users of `Foo` can now create it like this:
 ///
 /// ```rust
-/// # #![allow(clippy::disallowed_names)]
+/// # #![expect(clippy::disallowed_names)]
 /// # use kernel::{init, pin_init, macros::pin_data, init::*};
 /// # use core::pin::Pin;
 /// # #[pin_data]
@@ -852,7 +852,7 @@ pub unsafe trait PinInit<T: ?Sized, E =
     /// # Examples
     ///
     /// ```rust
-    /// # #![allow(clippy::disallowed_names)]
+    /// # #![expect(clippy::disallowed_names)]
     /// use kernel::{types::Opaque, init::pin_init_from_closure};
     /// #[repr(C)]
     /// struct RawFoo([u8; 16]);
@@ -964,7 +964,7 @@ pub unsafe trait Init<T: ?Sized, E = Inf
     /// # Examples
     ///
     /// ```rust
-    /// # #![allow(clippy::disallowed_names)]
+    /// # #![expect(clippy::disallowed_names)]
     /// use kernel::{types::Opaque, init::{self, init_from_closure}};
     /// struct Foo {
     ///     buf: [u8; 1_000_000],
rust/kernel/init/__internal.rs +2 -2
@@ -54,7 +54,7 @@ where
 pub unsafe trait HasPinData {
     type PinData: PinData;
 
-    #[allow(clippy::missing_safety_doc)]
+    #[expect(clippy::missing_safety_doc)]
     unsafe fn __pin_data() -> Self::PinData;
 }
 
@@ -84,7 +84,7 @@ pub unsafe trait PinData: Copy {
 pub unsafe trait HasInitData {
     type InitData: InitData;
 
-    #[allow(clippy::missing_safety_doc)]
+    #[expect(clippy::missing_safety_doc)]
     unsafe fn __init_data() -> Self::InitData;
 }
 
rust/kernel/init/macros.rs +5 -5
@@ -182,13 +182,13 @@
 //!     // Normally `Drop` bounds do not have the correct semantics, but for this purpose they do
 //!     // (normally people want to know if a type has any kind of drop glue at all, here we want
 //!     // to know if it has any kind of custom drop glue, which is exactly what this bound does).
-//!     #[allow(drop_bounds)]
+//!     #[expect(drop_bounds)]
 //!     impl<T: ::core::ops::Drop> MustNotImplDrop for T {}
 //!     impl<T> MustNotImplDrop for Bar<T> {}
 //!     // Here comes a convenience check, if one implemented `PinnedDrop`, but forgot to add it to
 //!     // `#[pin_data]`, then this will error with the same mechanic as above, this is not needed
 //!     // for safety, but a good sanity check, since no normal code calls `PinnedDrop::drop`.
-//!     #[allow(non_camel_case_types)]
+//!     #[expect(non_camel_case_types)]
 //!     trait UselessPinnedDropImpl_you_need_to_specify_PinnedDrop {}
 //!     impl<
 //!         T: ::kernel::init::PinnedDrop,
@@ -925,14 +925,14 @@ macro_rules! __pin_data {
         // `Drop`. Additionally we will implement this trait for the struct leading to a conflict,
         // if it also implements `Drop`
         trait MustNotImplDrop {}
-        #[allow(drop_bounds)]
+        #[expect(drop_bounds)]
         impl<T: ::core::ops::Drop> MustNotImplDrop for T {}
         impl<$($impl_generics)*> MustNotImplDrop for $name<$($ty_generics)*>
         where $($whr)* {}
         // We also take care to prevent users from writing a useless `PinnedDrop` implementation.
         // They might implement `PinnedDrop` correctly for the struct, but forget to give
         // `PinnedDrop` as the parameter to `#[pin_data]`.
-        #[allow(non_camel_case_types)]
+        #[expect(non_camel_case_types)]
         trait UselessPinnedDropImpl_you_need_to_specify_PinnedDrop {}
         impl<T: $crate::init::PinnedDrop>
             UselessPinnedDropImpl_you_need_to_specify_PinnedDrop for T {}
@@ -989,7 +989,7 @@ macro_rules! __pin_data {
         //
         // The functions are `unsafe` to prevent accidentally calling them.
         #[allow(dead_code)]
-        #[allow(clippy::missing_safety_doc)]
+        #[expect(clippy::missing_safety_doc)]
         impl<$($impl_generics)*> $pin_data<$($ty_generics)*>
         where $($whr)*
         {
rust/kernel/ioctl.rs +1 -1
@@ -4,7 +4,7 @@
 //!
 //! C header: [`include/asm-generic/ioctl.h`](srctree/include/asm-generic/ioctl.h)
 
-#![allow(non_snake_case)]
+#![expect(non_snake_case)]
 
 use crate::build_assert;
 
rust/kernel/lib.rs +1 -0
@@ -15,6 +15,7 @@
 #![feature(arbitrary_self_types)]
 #![feature(coerce_unsized)]
 #![feature(dispatch_from_dyn)]
+#![feature(lint_reasons)]
 #![feature(new_uninit)]
 #![feature(unsize)]
 
rust/kernel/list/arc_field.rs +1 -1
@@ -56,7 +56,7 @@ impl<T, const ID: u64> ListArcField<T, I
     ///
     /// The caller must have mutable access to the `ListArc<ID>` containing the struct with this
     /// field for the duration of the returned reference.
-    #[allow(clippy::mut_from_ref)]
+    #[expect(clippy::mut_from_ref)]
     pub unsafe fn assert_mut(&self) -> &mut T {
         // SAFETY: The caller has exclusive access to the `ListArc`, so they also have exclusive
         // access to this field.
rust/kernel/print.rs +2 -2
@@ -14,7 +14,7 @@ use core::{
 use crate::str::RawFormatter;
 
 // Called from `vsprintf` with format specifier `%pA`.
-#[allow(clippy::missing_safety_doc)]
+#[expect(clippy::missing_safety_doc)]
 #[no_mangle]
 unsafe extern "C" fn rust_fmt_argument(
     buf: *mut c_char,
@@ -140,7 +140,7 @@ pub fn call_printk_cont(args: fmt::Argum
 #[doc(hidden)]
 #[cfg(not(testlib))]
 #[macro_export]
-#[allow(clippy::crate_in_macro_def)]
+#[expect(clippy::crate_in_macro_def)]
 macro_rules! print_macro (
     // The non-continuation cases (most of them, e.g. `INFO`).
     ($format_string:path, false, $($arg:tt)+) => (
rust/kernel/std_vendor.rs +5 -5
@@ -16,7 +16,7 @@
 ///
 /// ```rust
 /// let a = 2;
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// let b = dbg!(a * 2) + 1;
 /// //      ^-- prints: [src/main.rs:2] a * 2 = 4
 /// assert_eq!(b, 5);
@@ -54,7 +54,7 @@
 /// With a method call:
 ///
 /// ```rust
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// fn foo(n: usize) {
 ///     if dbg!(n.checked_sub(4)).is_some() {
 ///         // ...
@@ -73,7 +73,7 @@
 /// Naive factorial implementation:
 ///
 /// ```rust
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// # {
 /// fn factorial(n: u32) -> u32 {
 ///     if dbg!(n <= 1) {
@@ -120,7 +120,7 @@
 /// a tuple (and return it, too):
 ///
 /// ```
-/// # #![allow(clippy::disallowed_macros)]
+/// # #![expect(clippy::disallowed_macros)]
 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
 /// ```
 ///
@@ -129,7 +129,7 @@
 /// invocations. You can use a 1-tuple directly if you need one:
 ///
 /// ```
-/// # #[allow(clippy::disallowed_macros)]
+/// # #[expect(clippy::disallowed_macros)]
 /// # {
 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
samples/rust/rust_print.rs +1 -1
@@ -15,7 +15,7 @@ module! {
 
 struct RustPrint;
 
-#[allow(clippy::disallowed_macros)]
+#[expect(clippy::disallowed_macros)]
 fn arc_print() -> Result {
     use kernel::sync::*;
 
scripts/Makefile.build +1 -1
@@ -248,7 +248,7 @@ $(obj)/%.lst: $(obj)/%.c FORCE
 # Compile Rust sources (.rs)
 # ---------------------------------------------------------------------------
 
-rust_allowed_features := arbitrary_self_types,new_uninit
+rust_allowed_features := arbitrary_self_types,lint_reasons,new_uninit
 
 # `--out-dir` is required to avoid temporaries being created by `rustc` in the
 # current working directory, which may be not accessible in the out-of-tree

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#33 lore raw

PATCH 17/60 Documentation: rust: discuss `#[expect(...)]` in the guidelines

In reply to Miguel Ojeda

commit 04866494e936d041fd196d3a36aecd979e4ef078 upstream.

Discuss #[expect(...)] in the Lints sections of the coding guidelines document, which is an upcoming feature in Rust 1.81.0, and explain that it is generally to be preferred over allow unless there is a reason not to use it (e.g. conditional compilation being involved).

---
 Documentation/rust/coding-guidelines.rst | 110 +++++++++++++++++++++++
 1 file changed, 110 insertions(+)
Documentation/rust/coding-guidelines.rst +110 -0
index 6db0420f0cea..f7194f7124b0 100644
@@ -262,6 +262,116 @@ default (i.e. outside ``W=`` levels). In particular, those that may have some
 false positives but that are otherwise quite useful to keep enabled to catch
 potential mistakes.
 
+On top of that, Rust provides the ``expect`` attribute which takes this further.
+It makes the compiler warn if the warning was not produced. For instance, the
+following will ensure that, when ``f()`` is called somewhere, we will have to
+remove the attribute:
+
+.. code-block:: rust
+
+	#[expect(dead_code)]
+	fn f() {}
+
+If we do not, we get a warning from the compiler::
+
+	warning: this lint expectation is unfulfilled
+	 --> x.rs:3:10
+	  |
+	3 | #[expect(dead_code)]
+	  |          ^^^^^^^^^
+	  |
+	  = note: `#[warn(unfulfilled_lint_expectations)]` on by default
+
+This means that ``expect``\ s do not get forgotten when they are not needed, which
+may happen in several situations, e.g.:
+
+- Temporary attributes added while developing.
+
+- Improvements in lints in the compiler, Clippy or custom tools which may
+  remove a false positive.
+
+- When the lint is not needed anymore because it was expected that it would be
+  removed at some point, such as the ``dead_code`` example above.
+
+It also increases the visibility of the remaining ``allow``\ s and reduces the
+chance of misapplying one.
+
+Thus prefer ``except`` over ``allow`` unless:
+
+- The lint attribute is intended to be temporary, e.g. while developing.
+
+- Conditional compilation triggers the warning in some cases but not others.
+
+  If there are only a few cases where the warning triggers (or does not
+  trigger) compared to the total number of cases, then one may consider using
+  a conditional ``expect`` (i.e. ``cfg_attr(..., expect(...))``). Otherwise,
+  it is likely simpler to just use ``allow``.
+
+- Inside macros, when the different invocations may create expanded code that
+  triggers the warning in some cases but not in others.
+
+- When code may trigger a warning for some architectures but not others, such
+  as an ``as`` cast to a C FFI type.
+
+As a more developed example, consider for instance this program:
+
+.. code-block:: rust
+
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+Here, function ``g()`` is dead code if ``CONFIG_X`` is not set. Can we use
+``expect`` here?
+
+.. code-block:: rust
+
+	#[expect(dead_code)]
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+This would emit a lint if ``CONFIG_X`` is set, since it is not dead code in that
+configuration. Therefore, in cases like this, we cannot use ``expect`` as-is.
+
+A simple possibility is using ``allow``:
+
+.. code-block:: rust
+
+	#[allow(dead_code)]
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+An alternative would be using a conditional ``expect``:
+
+.. code-block:: rust
+
+	#[cfg_attr(not(CONFIG_X), expect(dead_code))]
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+This would ensure that, if someone introduces another call to ``g()`` somewhere
+(e.g. unconditionally), then it would be spotted that it is not dead code
+anymore. However, the ``cfg_attr`` is more complex than a simple ``allow``.
+
+Therefore, it is likely that it is not worth using conditional ``expect``\ s when
+more than one or two configurations are involved or when the lint may be
+triggered due to non-local changes (such as ``dead_code``).
+
 For more information about diagnostics in Rust, please see:
 
 	https://doc.rust-lang.org/stable/reference/attributes/diagnostics.html
Signature · 1 line
2.48.1
maintainer Applied
#34 lore raw

Patch "Documentation: rust: discuss `#[expect(...)]` in the guidelines" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

Documentation: rust: discuss #[expect(...)] in the guidelines

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
documentation-rust-discuss-in-the-guidelines.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:27 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:24 +0100
Subject: Documentation: rust: discuss #[expect(...)] in the guidelines
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Miguel Ojeda <[email protected]>

commit 04866494e936d041fd196d3a36aecd979e4ef078 upstream.

Discuss #[expect(...)] in the Lints sections of the coding guidelines document, which is an upcoming feature in Rust 1.81.0, and explain that it is generally to be preferred over allow unless there is a reason not to use it (e.g. conditional compilation being involved).

---
 Documentation/rust/coding-guidelines.rst |  110 +++++++++++++++++++++++++++++++
 1 file changed, 110 insertions(+)
Documentation/rust/coding-guidelines.rst +110 -0
@@ -262,6 +262,116 @@ default (i.e. outside ``W=`` levels). In
 false positives but that are otherwise quite useful to keep enabled to catch
 potential mistakes.
 
+On top of that, Rust provides the ``expect`` attribute which takes this further.
+It makes the compiler warn if the warning was not produced. For instance, the
+following will ensure that, when ``f()`` is called somewhere, we will have to
+remove the attribute:
+
+.. code-block:: rust
+
+	#[expect(dead_code)]
+	fn f() {}
+
+If we do not, we get a warning from the compiler::
+
+	warning: this lint expectation is unfulfilled
+	 --> x.rs:3:10
+	  |
+	3 | #[expect(dead_code)]
+	  |          ^^^^^^^^^
+	  |
+	  = note: `#[warn(unfulfilled_lint_expectations)]` on by default
+
+This means that ``expect``\ s do not get forgotten when they are not needed, which
+may happen in several situations, e.g.:
+
+- Temporary attributes added while developing.
+
+- Improvements in lints in the compiler, Clippy or custom tools which may
+  remove a false positive.
+
+- When the lint is not needed anymore because it was expected that it would be
+  removed at some point, such as the ``dead_code`` example above.
+
+It also increases the visibility of the remaining ``allow``\ s and reduces the
+chance of misapplying one.
+
+Thus prefer ``except`` over ``allow`` unless:
+
+- The lint attribute is intended to be temporary, e.g. while developing.
+
+- Conditional compilation triggers the warning in some cases but not others.
+
+  If there are only a few cases where the warning triggers (or does not
+  trigger) compared to the total number of cases, then one may consider using
+  a conditional ``expect`` (i.e. ``cfg_attr(..., expect(...))``). Otherwise,
+  it is likely simpler to just use ``allow``.
+
+- Inside macros, when the different invocations may create expanded code that
+  triggers the warning in some cases but not in others.
+
+- When code may trigger a warning for some architectures but not others, such
+  as an ``as`` cast to a C FFI type.
+
+As a more developed example, consider for instance this program:
+
+.. code-block:: rust
+
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+Here, function ``g()`` is dead code if ``CONFIG_X`` is not set. Can we use
+``expect`` here?
+
+.. code-block:: rust
+
+	#[expect(dead_code)]
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+This would emit a lint if ``CONFIG_X`` is set, since it is not dead code in that
+configuration. Therefore, in cases like this, we cannot use ``expect`` as-is.
+
+A simple possibility is using ``allow``:
+
+.. code-block:: rust
+
+	#[allow(dead_code)]
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+An alternative would be using a conditional ``expect``:
+
+.. code-block:: rust
+
+	#[cfg_attr(not(CONFIG_X), expect(dead_code))]
+	fn g() {}
+
+	fn main() {
+	    #[cfg(CONFIG_X)]
+	    g();
+	}
+
+This would ensure that, if someone introduces another call to ``g()`` somewhere
+(e.g. unconditionally), then it would be spotted that it is not dead code
+anymore. However, the ``cfg_attr`` is more complex than a simple ``allow``.
+
+Therefore, it is likely that it is not worth using conditional ``expect``\ s when
+more than one or two configurations are involved or when the lint may be
+triggered due to non-local changes (such as ``dead_code``).
+
 For more information about diagnostics in Rust, please see:
 
 	https://doc.rust-lang.org/stable/reference/attributes/diagnostics.html

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#35 lore raw

PATCH 18/60 rust: error: make conversion functions public

In reply to Miguel Ojeda

From: Filipe Xavier <[email protected]>

commit 5ed147473458f8c20f908a03227d8f5bb3cb8f7d upstream.

Change visibility to public of functions in error.rs:
from_err_ptr, from_errno, from_result and to_ptr. Additionally, remove dead_code annotations.

---
 rust/kernel/error.rs | 13 ++++---------
 1 file changed, 4 insertions(+), 9 deletions(-)
rust/kernel/error.rs +4 -9
index a681acda87ce..2f1e4b783bfb 100644
@@ -95,7 +95,7 @@ impl Error {
     ///
     /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
     /// be returned in such a case.
-    pub(crate) fn from_errno(errno: core::ffi::c_int) -> Error {
+    pub fn from_errno(errno: core::ffi::c_int) -> Error {
         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
             // TODO: Make it a `WARN_ONCE` once available.
             crate::pr_warn!(
@@ -133,8 +133,7 @@ pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
     }
 
     /// Returns the error encoded as a pointer.
-    #[expect(dead_code)]
-    pub(crate) fn to_ptr<T>(self) -> *mut T {
+    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 {
@@ -270,9 +269,7 @@ pub fn to_result(err: core::ffi::c_int) -> Result {
 ///     from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
 /// }
 /// ```
-// TODO: Remove `dead_code` marker once an in-kernel client is available.
-#[allow(dead_code)]
-pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
+pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
     // CAST: Casting a pointer to `*const core::ffi::c_void` is always valid.
     let const_ptr: *const core::ffi::c_void = ptr.cast();
     // SAFETY: The FFI function does not deref the pointer.
@@ -318,9 +315,7 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
 ///     })
 /// }
 /// ```
-// TODO: Remove `dead_code` marker once an in-kernel client is available.
-#[allow(dead_code)]
-pub(crate) fn from_result<T, F>(f: F) -> T
+pub fn from_result<T, F>(f: F) -> T
 where
     T: From<i16>,
     F: FnOnce() -> Result<T>,
Signature · 1 line
2.48.1
maintainer Applied
#36 lore raw

Patch "rust: error: make conversion functions public" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: error: make conversion functions public

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-error-make-conversion-functions-public.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:29 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:25 +0100
Subject: rust: error: make conversion functions public
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Filipe Xavier <[email protected]>

commit 5ed147473458f8c20f908a03227d8f5bb3cb8f7d upstream.

Change visibility to public of functions in error.rs:
from_err_ptr, from_errno, from_result and to_ptr. Additionally, remove dead_code annotations.

---
 rust/kernel/error.rs |   13 ++++---------
 1 file changed, 4 insertions(+), 9 deletions(-)
rust/kernel/error.rs +4 -9
@@ -95,7 +95,7 @@ impl Error {
     ///
     /// It is a bug to pass an out-of-range `errno`. `EINVAL` would
     /// be returned in such a case.
-    pub(crate) fn from_errno(errno: core::ffi::c_int) -> Error {
+    pub fn from_errno(errno: core::ffi::c_int) -> Error {
         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
             // TODO: Make it a `WARN_ONCE` once available.
             crate::pr_warn!(
@@ -133,8 +133,7 @@ impl Error {
     }
 
     /// Returns the error encoded as a pointer.
-    #[expect(dead_code)]
-    pub(crate) fn to_ptr<T>(self) -> *mut T {
+    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 {
@@ -270,9 +269,7 @@ pub fn to_result(err: core::ffi::c_int)
 ///     from_err_ptr(unsafe { bindings::devm_platform_ioremap_resource(pdev.to_ptr(), index) })
 /// }
 /// ```
-// TODO: Remove `dead_code` marker once an in-kernel client is available.
-#[allow(dead_code)]
-pub(crate) fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
+pub fn from_err_ptr<T>(ptr: *mut T) -> Result<*mut T> {
     // CAST: Casting a pointer to `*const core::ffi::c_void` is always valid.
     let const_ptr: *const core::ffi::c_void = ptr.cast();
     // SAFETY: The FFI function does not deref the pointer.
@@ -318,9 +315,7 @@ pub(crate) fn from_err_ptr<T>(ptr: *mut
 ///     })
 /// }
 /// ```
-// TODO: Remove `dead_code` marker once an in-kernel client is available.
-#[allow(dead_code)]
-pub(crate) fn from_result<T, F>(f: F) -> T
+pub fn from_result<T, F>(f: F) -> T
 where
     T: From<i16>,
     F: FnOnce() -> Result<T>,

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#37 lore raw

PATCH 19/60 rust: error: optimize error type to use nonzero

In reply to Miguel Ojeda

From: Filipe Xavier <[email protected]>

commit e9759c5b9ea555d09f426c70c880e9522e9b0576 upstream.

Optimize Result<(), Error> size by changing Error type to NonZero* for niche optimization.

This reduces the space used by the Result type, as the NonZero* type enables the compiler to apply more efficient memory layout. For example, the Result<(), Error> changes size from 8 to 4 bytes.

[ Removed unneeded block around match, added backticks in panic
message and added intra-doc link. - Miguel ]

---
 rust/kernel/error.rs | 37 ++++++++++++++++++++++++++++---------
 1 file changed, 28 insertions(+), 9 deletions(-)
rust/kernel/error.rs +28 -9
index 2f1e4b783bfb..be6509d5f4a4 100644
@@ -9,6 +9,7 @@
 use alloc::alloc::LayoutError;
 
 use core::fmt;
+use core::num::NonZeroI32;
 use core::num::TryFromIntError;
 use core::str::Utf8Error;
 
@@ -20,7 +21,11 @@ macro_rules! declare_err {
             $(
             #[doc = $doc]
             )*
-            pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32));
+            pub const $err: super::Error =
+                match super::Error::try_from_errno(-(crate::bindings::$err as i32)) {
+                    Some(err) => err,
+                    None => panic!("Invalid errno in `declare_err!`"),
+                };
         };
     }
 
@@ -88,7 +93,7 @@ macro_rules! declare_err {
 ///
 /// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
 #[derive(Clone, Copy, PartialEq, Eq)]
-pub struct Error(core::ffi::c_int);
+pub struct Error(NonZeroI32);
 
 impl Error {
     /// Creates an [`Error`] from a kernel error code.
@@ -107,7 +112,20 @@ pub fn from_errno(errno: core::ffi::c_int) -> Error {
 
         // INVARIANT: The check above ensures the type invariant
         // will hold.
-        Error(errno)
+        // SAFETY: `errno` is checked above to be in a valid range.
+        unsafe { Error::from_errno_unchecked(errno) }
+    }
+
+    /// Creates an [`Error`] from a kernel error code.
+    ///
+    /// Returns [`None`] if `errno` is out-of-range.
+    const fn try_from_errno(errno: core::ffi::c_int) -> Option<Error> {
+        if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
+            return None;
+        }
+
+        // SAFETY: `errno` is checked above to be in a valid range.
+        Some(unsafe { Error::from_errno_unchecked(errno) })
     }
 
     /// Creates an [`Error`] from a kernel error code.
@@ -115,21 +133,22 @@ pub fn from_errno(errno: core::ffi::c_int) -> Error {
     /// # Safety
     ///
     /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
-    unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
+    const unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
         // INVARIANT: The contract ensures the type invariant
         // will hold.
-        Error(errno)
+        // SAFETY: The caller guarantees `errno` is non-zero.
+        Error(unsafe { NonZeroI32::new_unchecked(errno) })
     }
 
     /// Returns the kernel error code.
     pub fn to_errno(self) -> core::ffi::c_int {
-        self.0
+        self.0.get()
     }
 
     #[cfg(CONFIG_BLOCK)]
     pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
         // SAFETY: `self.0` is a valid error due to its invariant.
-        unsafe { bindings::errno_to_blk_status(self.0) }
+        unsafe { bindings::errno_to_blk_status(self.0.get()) }
     }
 
     /// Returns the error encoded as a pointer.
@@ -137,7 +156,7 @@ 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.into()) as *mut _
+            bindings::ERR_PTR(self.0.get().into()) as *mut _
         }
     }
 
@@ -145,7 +164,7 @@ pub fn to_ptr<T>(self) -> *mut T {
     #[cfg(not(testlib))]
     pub fn name(&self) -> Option<&'static CStr> {
         // SAFETY: Just an FFI call, there are no extra safety requirements.
-        let ptr = unsafe { bindings::errname(-self.0) };
+        let ptr = unsafe { bindings::errname(-self.0.get()) };
         if ptr.is_null() {
             None
         } else {
Signature · 1 line
2.48.1
maintainer Applied
#38 lore raw

Patch "rust: error: optimize error type to use nonzero" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: error: optimize error type to use nonzero

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-error-optimize-error-type-to-use-nonzero.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:30 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:26 +0100
Subject: rust: error: optimize error type to use nonzero
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Filipe Xavier <[email protected]>

commit e9759c5b9ea555d09f426c70c880e9522e9b0576 upstream.

Optimize Result<(), Error> size by changing Error type to NonZero* for niche optimization.

This reduces the space used by the Result type, as the NonZero* type enables the compiler to apply more efficient memory layout. For example, the Result<(), Error> changes size from 8 to 4 bytes.

[ Removed unneeded block around match, added backticks in panic
message and added intra-doc link. - Miguel ]

---
 rust/kernel/error.rs |   37 ++++++++++++++++++++++++++++---------
 1 file changed, 28 insertions(+), 9 deletions(-)
rust/kernel/error.rs +28 -9
@@ -9,6 +9,7 @@ use crate::{alloc::AllocError, str::CStr
 use alloc::alloc::LayoutError;
 
 use core::fmt;
+use core::num::NonZeroI32;
 use core::num::TryFromIntError;
 use core::str::Utf8Error;
 
@@ -20,7 +21,11 @@ pub mod code {
             $(
             #[doc = $doc]
             )*
-            pub const $err: super::Error = super::Error(-(crate::bindings::$err as i32));
+            pub const $err: super::Error =
+                match super::Error::try_from_errno(-(crate::bindings::$err as i32)) {
+                    Some(err) => err,
+                    None => panic!("Invalid errno in `declare_err!`"),
+                };
         };
     }
 
@@ -88,7 +93,7 @@ pub mod code {
 ///
 /// The value is a valid `errno` (i.e. `>= -MAX_ERRNO && < 0`).
 #[derive(Clone, Copy, PartialEq, Eq)]
-pub struct Error(core::ffi::c_int);
+pub struct Error(NonZeroI32);
 
 impl Error {
     /// Creates an [`Error`] from a kernel error code.
@@ -107,7 +112,20 @@ impl Error {
 
         // INVARIANT: The check above ensures the type invariant
         // will hold.
-        Error(errno)
+        // SAFETY: `errno` is checked above to be in a valid range.
+        unsafe { Error::from_errno_unchecked(errno) }
+    }
+
+    /// Creates an [`Error`] from a kernel error code.
+    ///
+    /// Returns [`None`] if `errno` is out-of-range.
+    const fn try_from_errno(errno: core::ffi::c_int) -> Option<Error> {
+        if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
+            return None;
+        }
+
+        // SAFETY: `errno` is checked above to be in a valid range.
+        Some(unsafe { Error::from_errno_unchecked(errno) })
     }
 
     /// Creates an [`Error`] from a kernel error code.
@@ -115,21 +133,22 @@ impl Error {
     /// # Safety
     ///
     /// `errno` must be within error code range (i.e. `>= -MAX_ERRNO && < 0`).
-    unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
+    const unsafe fn from_errno_unchecked(errno: core::ffi::c_int) -> Error {
         // INVARIANT: The contract ensures the type invariant
         // will hold.
-        Error(errno)
+        // SAFETY: The caller guarantees `errno` is non-zero.
+        Error(unsafe { NonZeroI32::new_unchecked(errno) })
     }
 
     /// Returns the kernel error code.
     pub fn to_errno(self) -> core::ffi::c_int {
-        self.0
+        self.0.get()
     }
 
     #[cfg(CONFIG_BLOCK)]
     pub(crate) fn to_blk_status(self) -> bindings::blk_status_t {
         // SAFETY: `self.0` is a valid error due to its invariant.
-        unsafe { bindings::errno_to_blk_status(self.0) }
+        unsafe { bindings::errno_to_blk_status(self.0.get()) }
     }
 
     /// Returns the error encoded as a pointer.
@@ -137,7 +156,7 @@ impl Error {
         #[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.into()) as *mut _
+            bindings::ERR_PTR(self.0.get().into()) as *mut _
         }
     }
 
@@ -145,7 +164,7 @@ impl Error {
     #[cfg(not(testlib))]
     pub fn name(&self) -> Option<&'static CStr> {
         // SAFETY: Just an FFI call, there are no extra safety requirements.
-        let ptr = unsafe { bindings::errname(-self.0) };
+        let ptr = unsafe { bindings::errname(-self.0.get()) };
         if ptr.is_null() {
             None
         } else {

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#39 lore raw

PATCH 20/60 rust: alloc: add `Allocator` trait

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit b7a084ba4fbb8f416ce8d19c93a3a2bee63c9c89 upstream.

Add a kernel specific Allocator trait, that in contrast to the one in Rust's core library doesn't require unstable features and supports GFP flags.

Subsequent patches add the following trait implementors: Kmalloc, Vmalloc and KVmalloc.

---
 rust/kernel/alloc.rs | 101 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 101 insertions(+)
rust/kernel/alloc.rs +101 -0
index 1966bd407017..998779cc6976 100644
@@ -11,6 +11,7 @@
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
+use core::{alloc::Layout, ptr::NonNull};
 
 /// Flags to be used when allocating memory.
 ///
@@ -86,3 +87,103 @@ pub mod flags {
     /// small allocations.
     pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT);
 }
+
+/// The kernel's [`Allocator`] trait.
+///
+/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described
+/// via [`Layout`].
+///
+/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on
+/// an object instance.
+///
+/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design
+/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind
+/// of `self` parameter.
+///
+/// # Safety
+///
+/// - A memory allocation returned from an allocator must remain valid until it is explicitly freed.
+///
+/// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`]
+///   function of the same type.
+///
+/// - Implementers must ensure that all trait functions abide by the guarantees documented in the
+///   `# Guarantees` sections.
+pub unsafe trait Allocator {
+    /// Allocate memory based on `layout` and `flags`.
+    ///
+    /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout
+    /// constraints (i.e. minimum size and alignment as specified by `layout`).
+    ///
+    /// This function is equivalent to `realloc` when called with `None`.
+    ///
+    /// # Guarantees
+    ///
+    /// When the return value is `Ok(ptr)`, then `ptr` is
+    /// - valid for reads and writes for `layout.size()` bytes, until it is passed to
+    ///   [`Allocator::free`] or [`Allocator::realloc`],
+    /// - aligned to `layout.align()`,
+    ///
+    /// Additionally, `Flags` are honored as documented in
+    /// <https://docs.kernel.org/core-api/mm-api.html#mm-api-gfp-flags>.
+    fn alloc(layout: Layout, flags: Flags) -> Result<NonNull<[u8]>, AllocError> {
+        // SAFETY: Passing `None` to `realloc` is valid by its safety requirements and asks for a
+        // new memory allocation.
+        unsafe { Self::realloc(None, layout, Layout::new::<()>(), flags) }
+    }
+
+    /// Re-allocate an existing memory allocation to satisfy the requested `layout`.
+    ///
+    /// If the requested size is zero, `realloc` behaves equivalent to `free`.
+    ///
+    /// If the requested size is larger than the size of the existing allocation, a successful call
+    /// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but
+    /// may also be larger.
+    ///
+    /// If the requested size is smaller than the size of the existing allocation, `realloc` may or
+    /// may not shrink the buffer; this is implementation specific to the allocator.
+    ///
+    /// On allocation failure, the existing buffer, if any, remains valid.
+    ///
+    /// The buffer is represented as `NonNull<[u8]>`.
+    ///
+    /// # Safety
+    ///
+    /// - If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation
+    ///   created by this [`Allocator`]; if `old_layout` is zero-sized `p` does not need to be a
+    ///   pointer returned by this [`Allocator`].
+    /// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and
+    ///   `old_layout` is ignored.
+    /// - `old_layout` must match the `Layout` the allocation has been created with.
+    ///
+    /// # Guarantees
+    ///
+    /// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then
+    /// it additionally guarantees that:
+    /// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new
+    ///   and old size, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] ==
+    ///   p[0..min(layout.size(), old_layout.size())]`.
+    /// - when the return value is `Err(AllocError)`, then `ptr` is still valid.
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError>;
+
+    /// Free an existing memory allocation.
+    ///
+    /// # Safety
+    ///
+    /// - `ptr` must point to an existing and valid memory allocation created by this [`Allocator`];
+    ///   if `old_layout` is zero-sized `p` does not need to be a pointer returned by this
+    ///   [`Allocator`].
+    /// - `layout` must match the `Layout` the allocation has been created with.
+    /// - The memory allocation at `ptr` must never again be read from or written to.
+    unsafe fn free(ptr: NonNull<u8>, layout: Layout) {
+        // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this
+        // allocator. We are passing a `Layout` with the smallest possible alignment, so it is
+        // smaller than or equal to the alignment previously used with this allocation.
+        let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) };
+    }
+}
Signature · 1 line
2.48.1
maintainer Applied
#40 lore raw

Patch "rust: alloc: add `Allocator` trait" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: add Allocator trait

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-add-allocator-trait.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:36 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:27 +0100
Subject: rust: alloc: add Allocator trait
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit b7a084ba4fbb8f416ce8d19c93a3a2bee63c9c89 upstream.

Add a kernel specific Allocator trait, that in contrast to the one in Rust's core library doesn't require unstable features and supports GFP flags.

Subsequent patches add the following trait implementors: Kmalloc, Vmalloc and KVmalloc.

---
 rust/kernel/alloc.rs |  101 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 101 insertions(+)
rust/kernel/alloc.rs +101 -0
@@ -11,6 +11,7 @@ pub mod vec_ext;
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
+use core::{alloc::Layout, ptr::NonNull};
 
 /// Flags to be used when allocating memory.
 ///
@@ -86,3 +87,103 @@ pub mod flags {
     /// small allocations.
     pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT);
 }
+
+/// The kernel's [`Allocator`] trait.
+///
+/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described
+/// via [`Layout`].
+///
+/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on
+/// an object instance.
+///
+/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design
+/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind
+/// of `self` parameter.
+///
+/// # Safety
+///
+/// - A memory allocation returned from an allocator must remain valid until it is explicitly freed.
+///
+/// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`]
+///   function of the same type.
+///
+/// - Implementers must ensure that all trait functions abide by the guarantees documented in the
+///   `# Guarantees` sections.
+pub unsafe trait Allocator {
+    /// Allocate memory based on `layout` and `flags`.
+    ///
+    /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout
+    /// constraints (i.e. minimum size and alignment as specified by `layout`).
+    ///
+    /// This function is equivalent to `realloc` when called with `None`.
+    ///
+    /// # Guarantees
+    ///
+    /// When the return value is `Ok(ptr)`, then `ptr` is
+    /// - valid for reads and writes for `layout.size()` bytes, until it is passed to
+    ///   [`Allocator::free`] or [`Allocator::realloc`],
+    /// - aligned to `layout.align()`,
+    ///
+    /// Additionally, `Flags` are honored as documented in
+    /// <https://docs.kernel.org/core-api/mm-api.html#mm-api-gfp-flags>.
+    fn alloc(layout: Layout, flags: Flags) -> Result<NonNull<[u8]>, AllocError> {
+        // SAFETY: Passing `None` to `realloc` is valid by its safety requirements and asks for a
+        // new memory allocation.
+        unsafe { Self::realloc(None, layout, Layout::new::<()>(), flags) }
+    }
+
+    /// Re-allocate an existing memory allocation to satisfy the requested `layout`.
+    ///
+    /// If the requested size is zero, `realloc` behaves equivalent to `free`.
+    ///
+    /// If the requested size is larger than the size of the existing allocation, a successful call
+    /// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but
+    /// may also be larger.
+    ///
+    /// If the requested size is smaller than the size of the existing allocation, `realloc` may or
+    /// may not shrink the buffer; this is implementation specific to the allocator.
+    ///
+    /// On allocation failure, the existing buffer, if any, remains valid.
+    ///
+    /// The buffer is represented as `NonNull<[u8]>`.
+    ///
+    /// # Safety
+    ///
+    /// - If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation
+    ///   created by this [`Allocator`]; if `old_layout` is zero-sized `p` does not need to be a
+    ///   pointer returned by this [`Allocator`].
+    /// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and
+    ///   `old_layout` is ignored.
+    /// - `old_layout` must match the `Layout` the allocation has been created with.
+    ///
+    /// # Guarantees
+    ///
+    /// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then
+    /// it additionally guarantees that:
+    /// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new
+    ///   and old size, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] ==
+    ///   p[0..min(layout.size(), old_layout.size())]`.
+    /// - when the return value is `Err(AllocError)`, then `ptr` is still valid.
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError>;
+
+    /// Free an existing memory allocation.
+    ///
+    /// # Safety
+    ///
+    /// - `ptr` must point to an existing and valid memory allocation created by this [`Allocator`];
+    ///   if `old_layout` is zero-sized `p` does not need to be a pointer returned by this
+    ///   [`Allocator`].
+    /// - `layout` must match the `Layout` the allocation has been created with.
+    /// - The memory allocation at `ptr` must never again be read from or written to.
+    unsafe fn free(ptr: NonNull<u8>, layout: Layout) {
+        // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this
+        // allocator. We are passing a `Layout` with the smallest possible alignment, so it is
+        // smaller than or equal to the alignment previously used with this allocation.
+        let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) };
+    }
+}

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#41 lore raw

PATCH 21/60 rust: alloc: separate `aligned_size` from `krealloc_aligned`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit a654a6e09644266e38ac05415ef7737d299c4497 upstream.

Separate aligned_size from krealloc_aligned.

Subsequent patches implement Allocator derivates, such as Kmalloc, that require aligned_size and replace the original krealloc_aligned.

---
 rust/kernel/alloc/allocator.rs | 19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)
rust/kernel/alloc/allocator.rs +12 -7
index 91216b36af69..765f72d5bc21 100644
@@ -8,6 +8,17 @@
 
 struct KernelAllocator;
 
+/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
+fn aligned_size(new_layout: Layout) -> usize {
+    // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
+    let layout = new_layout.pad_to_align();
+
+    // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()`
+    // which together with the slab guarantees means the `krealloc` will return a properly aligned
+    // object (see comments in `kmalloc()` for more information).
+    layout.size()
+}
+
 /// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment.
 ///
 /// # Safety
@@ -15,13 +26,7 @@
 /// - `ptr` can be either null or a pointer which has been allocated by this allocator.
 /// - `new_layout` must have a non-zero size.
 pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 {
-    // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
-    let layout = new_layout.pad_to_align();
-
-    // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()`
-    // which together with the slab guarantees means the `krealloc` will return a properly aligned
-    // object (see comments in `kmalloc()` for more information).
-    let size = layout.size();
+    let size = aligned_size(new_layout);
 
     // SAFETY:
     // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the
Signature · 1 line
2.48.1
maintainer Applied
#42 lore raw

Patch "rust: alloc: separate `aligned_size` from `krealloc_aligned`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: separate aligned_size from krealloc_aligned

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-separate-aligned_size-from-krealloc_aligned.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:37 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:28 +0100
Subject: rust: alloc: separate aligned_size from krealloc_aligned
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit a654a6e09644266e38ac05415ef7737d299c4497 upstream.

Separate aligned_size from krealloc_aligned.

Subsequent patches implement Allocator derivates, such as Kmalloc, that require aligned_size and replace the original krealloc_aligned.

---
 rust/kernel/alloc/allocator.rs |   19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)
rust/kernel/alloc/allocator.rs +12 -7
@@ -8,6 +8,17 @@ use core::ptr;
 
 struct KernelAllocator;
 
+/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
+fn aligned_size(new_layout: Layout) -> usize {
+    // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
+    let layout = new_layout.pad_to_align();
+
+    // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()`
+    // which together with the slab guarantees means the `krealloc` will return a properly aligned
+    // object (see comments in `kmalloc()` for more information).
+    layout.size()
+}
+
 /// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment.
 ///
 /// # Safety
@@ -15,13 +26,7 @@ struct KernelAllocator;
 /// - `ptr` can be either null or a pointer which has been allocated by this allocator.
 /// - `new_layout` must have a non-zero size.
 pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 {
-    // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
-    let layout = new_layout.pad_to_align();
-
-    // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()`
-    // which together with the slab guarantees means the `krealloc` will return a properly aligned
-    // object (see comments in `kmalloc()` for more information).
-    let size = layout.size();
+    let size = aligned_size(new_layout);
 
     // SAFETY:
     // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#43 lore raw

PATCH 22/60 rust: alloc: rename `KernelAllocator` to `Kmalloc`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 941e65531446c1eb5d573c5d30172117ebe96112 upstream.

Subsequent patches implement Vmalloc and KVmalloc allocators, hence align KernelAllocator to this naming scheme.

---
 rust/kernel/alloc/allocator.rs | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
rust/kernel/alloc/allocator.rs +3 -3
index 765f72d5bc21..3b1c735ba409 100644
@@ -6,7 +6,7 @@
 use core::alloc::{GlobalAlloc, Layout};
 use core::ptr;
 
-struct KernelAllocator;
+struct Kmalloc;
 
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
@@ -37,7 +37,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F
 }
 
 // SAFETY: TODO.
-unsafe impl GlobalAlloc for KernelAllocator {
+unsafe impl GlobalAlloc for Kmalloc {
     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
         // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety
         // requirement.
@@ -74,7 +74,7 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
 }
 
 #[global_allocator]
-static ALLOCATOR: KernelAllocator = KernelAllocator;
+static ALLOCATOR: Kmalloc = Kmalloc;
 
 // See <https://github.com/rust-lang/rust/pull/86844>.
 #[no_mangle]
Signature · 1 line
2.48.1
maintainer Applied
#44 lore raw

Patch "rust: alloc: rename `KernelAllocator` to `Kmalloc`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: rename KernelAllocator to Kmalloc

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-rename-kernelallocator-to-kmalloc.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:40 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:29 +0100
Subject: rust: alloc: rename KernelAllocator to Kmalloc
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 941e65531446c1eb5d573c5d30172117ebe96112 upstream.

Subsequent patches implement Vmalloc and KVmalloc allocators, hence align KernelAllocator to this naming scheme.

---
 rust/kernel/alloc/allocator.rs |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
rust/kernel/alloc/allocator.rs +3 -3
@@ -6,7 +6,7 @@ use super::{flags::*, Flags};
 use core::alloc::{GlobalAlloc, Layout};
 use core::ptr;
 
-struct KernelAllocator;
+struct Kmalloc;
 
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
@@ -37,7 +37,7 @@ pub(crate) unsafe fn krealloc_aligned(pt
 }
 
 // SAFETY: TODO.
-unsafe impl GlobalAlloc for KernelAllocator {
+unsafe impl GlobalAlloc for Kmalloc {
     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
         // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety
         // requirement.
@@ -74,7 +74,7 @@ unsafe impl GlobalAlloc for KernelAlloca
 }
 
 #[global_allocator]
-static ALLOCATOR: KernelAllocator = KernelAllocator;
+static ALLOCATOR: Kmalloc = Kmalloc;
 
 // See <https://github.com/rust-lang/rust/pull/86844>.
 #[no_mangle]

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#45 lore raw

PATCH 23/60 rust: alloc: implement `ReallocFunc`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 8a799831fc63c988eec90d334fdd68ff5f2c7eb5 upstream.

ReallocFunc is an abstraction for the kernel's realloc derivates, such as krealloc, vrealloc and kvrealloc.

All of the named functions share the same function signature and implement the same semantics. The ReallocFunc abstractions provides a generalized wrapper around those, to trivialize the implementation of Kmalloc, Vmalloc and KVmalloc in subsequent patches.

[ Added temporary allow(dead_code) for dangling_from_layout to clean
warning in rusttest target as discussed in the list (but it is needed earlier, i.e. in this patch already). Added colon. - Miguel ]

---
 rust/kernel/alloc.rs           |  9 +++++
 rust/kernel/alloc/allocator.rs | 70 ++++++++++++++++++++++++++++++++++
 2 files changed, 79 insertions(+)
rust/kernel/alloc.rs +9 -0
index 998779cc6976..95d402feb6ff 100644
@@ -187,3 +187,12 @@ unsafe fn free(ptr: NonNull<u8>, layout: Layout) {
         let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) };
     }
 }
+
+#[allow(dead_code)]
+/// Returns a properly aligned dangling pointer from the given `layout`.
+pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> {
+    let ptr = layout.align() as *mut u8;
+
+    // SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero.
+    unsafe { NonNull::new_unchecked(ptr) }
+}
rust/kernel/alloc/allocator.rs +70 -0

86 lines not on this page · raw message

Signature · 1 line
2.48.1
maintainer Applied
#46 lore raw

Patch "rust: alloc: implement `ReallocFunc`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement ReallocFunc

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-reallocfunc.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:42 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:30 +0100
Subject: rust: alloc: implement ReallocFunc
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 8a799831fc63c988eec90d334fdd68ff5f2c7eb5 upstream.

ReallocFunc is an abstraction for the kernel's realloc derivates, such as krealloc, vrealloc and kvrealloc.

All of the named functions share the same function signature and implement the same semantics. The ReallocFunc abstractions provides a generalized wrapper around those, to trivialize the implementation of Kmalloc, Vmalloc and KVmalloc in subsequent patches.

[ Added temporary allow(dead_code) for dangling_from_layout to clean
warning in rusttest target as discussed in the list (but it is needed earlier, i.e. in this patch already). Added colon. - Miguel ]

---
 rust/kernel/alloc.rs           |    9 +++++
 rust/kernel/alloc/allocator.rs |   70 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 79 insertions(+)
rust/kernel/alloc.rs +9 -0
@@ -187,3 +187,12 @@ pub unsafe trait Allocator {
         let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) };
     }
 }
+
+#[allow(dead_code)]
+/// Returns a properly aligned dangling pointer from the given `layout`.
+pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> {
+    let ptr = layout.align() as *mut u8;
+
+    // SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero.
+    unsafe { NonNull::new_unchecked(ptr) }
+}
rust/kernel/alloc/allocator.rs +70 -0

86 lines not on this page · raw message

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#47 lore raw

PATCH 24/60 rust: alloc: make `allocator` module public

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit a87a36f0bf517dae22f3e3790b05c979070f776a upstream.

Subsequent patches implement allocators such as Kmalloc, Vmalloc, KVmalloc; we need them to be available outside of the kernel crate as well.

---
 rust/kernel/alloc.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/alloc.rs +1 -1
index 95d402feb6ff..2203852c3712 100644
@@ -4,7 +4,7 @@
 
 #[cfg(not(test))]
 #[cfg(not(testlib))]
-mod allocator;
+pub mod allocator;
 pub mod box_ext;
 pub mod vec_ext;
 
Signature · 1 line
2.48.1
maintainer Applied
#48 lore raw

Patch "rust: alloc: make `allocator` module public" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: make allocator module public

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-make-allocator-module-public.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:46 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:31 +0100
Subject: rust: alloc: make allocator module public
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit a87a36f0bf517dae22f3e3790b05c979070f776a upstream.

Subsequent patches implement allocators such as Kmalloc, Vmalloc, KVmalloc; we need them to be available outside of the kernel crate as well.

---
 rust/kernel/alloc.rs |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/alloc.rs +1 -1
@@ -4,7 +4,7 @@
 
 #[cfg(not(test))]
 #[cfg(not(testlib))]
-mod allocator;
+pub mod allocator;
 pub mod box_ext;
 pub mod vec_ext;
 

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#49 lore raw

PATCH 25/60 rust: alloc: implement `Allocator` for `Kmalloc`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit a34822d1c4c93085f635b922441a017bd7e959b0 upstream.

Implement Allocator for Kmalloc, the kernel's default allocator, typically used for objects smaller than page size.

All memory allocations made with Kmalloc end up in krealloc().

It serves as allocator for the subsequently introduced types KBox and KVec.

---
 rust/kernel/alloc/allocator.rs | 31 ++++++++++++++++++++++++++++---
 1 file changed, 28 insertions(+), 3 deletions(-)
rust/kernel/alloc/allocator.rs +28 -3
index 9ed122401e8a..272c581e24a0 100644
@@ -13,10 +13,16 @@
 use core::ptr;
 use core::ptr::NonNull;
 
-use crate::alloc::AllocError;
+use crate::alloc::{AllocError, Allocator};
 use crate::bindings;
 
-struct Kmalloc;
+/// The contiguous kernel allocator.
+///
+/// `Kmalloc` is typically used for physically contiguous allocations up to page size, but also
+/// supports larger allocations up to `bindings::KMALLOC_MAX_SIZE`, which is hardware specific.
+///
+/// For more details see [self].
+pub struct Kmalloc;
 
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
@@ -53,8 +59,10 @@ struct ReallocFunc(
     unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void,
 );
 
-#[expect(dead_code)]
 impl ReallocFunc {
+    // INVARIANT: `krealloc` satisfies the type invariants.
+    const KREALLOC: Self = Self(bindings::krealloc);
+
     /// # Safety
     ///
     /// This method has the same safety requirements as [`Allocator::realloc`].
@@ -106,6 +114,23 @@ unsafe fn call(
     }
 }
 
+// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that
+// - memory remains valid until it is explicitly freed,
+// - passing a pointer to a valid memory allocation is OK,
+// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
+unsafe impl Allocator for Kmalloc {
+    #[inline]
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // SAFETY: `ReallocFunc::call` has the same safety requirements as `Allocator::realloc`.
+        unsafe { ReallocFunc::KREALLOC.call(ptr, layout, old_layout, flags) }
+    }
+}
+
 // SAFETY: TODO.
 unsafe impl GlobalAlloc for Kmalloc {
     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
Signature · 1 line
2.48.1
maintainer Applied
#50 lore raw

Patch "rust: alloc: implement `Allocator` for `Kmalloc`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement Allocator for Kmalloc

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-allocator-for-kmalloc.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:53 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:32 +0100
Subject: rust: alloc: implement Allocator for Kmalloc
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit a34822d1c4c93085f635b922441a017bd7e959b0 upstream.

Implement Allocator for Kmalloc, the kernel's default allocator, typically used for objects smaller than page size.

All memory allocations made with Kmalloc end up in krealloc().

It serves as allocator for the subsequently introduced types KBox and KVec.

---
 rust/kernel/alloc/allocator.rs |   31 ++++++++++++++++++++++++++++---
 1 file changed, 28 insertions(+), 3 deletions(-)
rust/kernel/alloc/allocator.rs +28 -3
@@ -13,10 +13,16 @@ use core::alloc::{GlobalAlloc, Layout};
 use core::ptr;
 use core::ptr::NonNull;
 
-use crate::alloc::AllocError;
+use crate::alloc::{AllocError, Allocator};
 use crate::bindings;
 
-struct Kmalloc;
+/// The contiguous kernel allocator.
+///
+/// `Kmalloc` is typically used for physically contiguous allocations up to page size, but also
+/// supports larger allocations up to `bindings::KMALLOC_MAX_SIZE`, which is hardware specific.
+///
+/// For more details see [self].
+pub struct Kmalloc;
 
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
@@ -53,8 +59,10 @@ struct ReallocFunc(
     unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void,
 );
 
-#[expect(dead_code)]
 impl ReallocFunc {
+    // INVARIANT: `krealloc` satisfies the type invariants.
+    const KREALLOC: Self = Self(bindings::krealloc);
+
     /// # Safety
     ///
     /// This method has the same safety requirements as [`Allocator::realloc`].
@@ -106,6 +114,23 @@ impl ReallocFunc {
     }
 }
 
+// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that
+// - memory remains valid until it is explicitly freed,
+// - passing a pointer to a valid memory allocation is OK,
+// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
+unsafe impl Allocator for Kmalloc {
+    #[inline]
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // SAFETY: `ReallocFunc::call` has the same safety requirements as `Allocator::realloc`.
+        unsafe { ReallocFunc::KREALLOC.call(ptr, layout, old_layout, flags) }
+    }
+}
+
 // SAFETY: TODO.
 unsafe impl GlobalAlloc for Kmalloc {
     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#51 lore raw

PATCH 26/60 rust: alloc: add module `allocator_test`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 5a888c28e3b4ff6f54a53fca33951537d135e7f1 upstream.

Allocators, such as Kmalloc, will be used by e.g. Box and Vec in subsequent patches, and hence this dependency propagates throughout the whole kernel.

Add the allocator_test module that provides an empty implementation for all Allocators in the kernel, such that we don't break the rusttest make target in subsequent patches.

---
 rust/kernel/alloc.rs                |  9 +++++++--
 rust/kernel/alloc/allocator_test.rs | 20 ++++++++++++++++++++
 2 files changed, 27 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/alloc/allocator_test.rs
rust/kernel/alloc.rs +7 -2
index 2203852c3712..b5605aab182d 100644
@@ -2,12 +2,17 @@
 
 //! Extensions to the [`alloc`] crate.
 
-#[cfg(not(test))]
-#[cfg(not(testlib))]
+#[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod box_ext;
 pub mod vec_ext;
 
+#[cfg(any(test, testlib))]
+pub mod allocator_test;
+
+#[cfg(any(test, testlib))]
+pub use self::allocator_test as allocator;
+
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
rust/kernel/alloc/allocator_test.rs new file +20 -0
new file mode 100644
index 000000000000..c5d325506f0c
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#![allow(missing_docs)]
+
+use super::{AllocError, Allocator, Flags};
+use core::alloc::Layout;
+use core::ptr::NonNull;
+
+pub struct Kmalloc;
+
+unsafe impl Allocator for Kmalloc {
+    unsafe fn realloc(
+        _ptr: Option<NonNull<u8>>,
+        _layout: Layout,
+        _old_layout: Layout,
+        _flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        panic!();
+    }
+}
Signature · 1 line
2.48.1
maintainer Applied
#52 lore raw

Patch "rust: alloc: add module `allocator_test`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: add module allocator_test

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-add-module-allocator_test.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:53 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:33 +0100
Subject: rust: alloc: add module allocator_test
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 5a888c28e3b4ff6f54a53fca33951537d135e7f1 upstream.

Allocators, such as Kmalloc, will be used by e.g. Box and Vec in subsequent patches, and hence this dependency propagates throughout the whole kernel.

Add the allocator_test module that provides an empty implementation for all Allocators in the kernel, such that we don't break the rusttest make target in subsequent patches.

---
 rust/kernel/alloc.rs                |    9 +++++++--
 rust/kernel/alloc/allocator_test.rs |   20 ++++++++++++++++++++
 2 files changed, 27 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/alloc/allocator_test.rs
rust/kernel/alloc.rs +7 -2
@@ -2,12 +2,17 @@
 
 //! Extensions to the [`alloc`] crate.
 
-#[cfg(not(test))]
-#[cfg(not(testlib))]
+#[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod box_ext;
 pub mod vec_ext;
 
+#[cfg(any(test, testlib))]
+pub mod allocator_test;
+
+#[cfg(any(test, testlib))]
+pub use self::allocator_test as allocator;
+
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
rust/kernel/alloc/allocator_test.rs new file +20 -0
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#![allow(missing_docs)]
+
+use super::{AllocError, Allocator, Flags};
+use core::alloc::Layout;
+use core::ptr::NonNull;
+
+pub struct Kmalloc;
+
+unsafe impl Allocator for Kmalloc {
+    unsafe fn realloc(
+        _ptr: Option<NonNull<u8>>,
+        _layout: Layout,
+        _old_layout: Layout,
+        _flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        panic!();
+    }
+}

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#53 lore raw

PATCH 27/60 rust: alloc: implement `Vmalloc` allocator

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 61c004781d6b928443052e7a6cf84b35d4f61401 upstream.

Implement Allocator for Vmalloc, the kernel's virtually contiguous allocator, typically used for larger objects, (much) larger than page size.

All memory allocations made with Vmalloc end up in vrealloc().

---
 rust/helpers/helpers.c              |  1 +
 rust/helpers/vmalloc.c              |  9 +++++++
 rust/kernel/alloc/allocator.rs      | 37 +++++++++++++++++++++++++++++
 rust/kernel/alloc/allocator_test.rs |  1 +
 4 files changed, 48 insertions(+)
 create mode 100644 rust/helpers/vmalloc.c
rust/helpers/helpers.c +1 -0
index 30f40149f3a9..20a0c69d5cc7 100644
@@ -22,5 +22,6 @@
 #include "spinlock.c"
 #include "task.c"
 #include "uaccess.c"
+#include "vmalloc.c"
 #include "wait.c"
 #include "workqueue.c"
rust/helpers/vmalloc.c new file +9 -0
new file mode 100644
index 000000000000..80d34501bbc0
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/vmalloc.h>
+
+void * __must_check __realloc_size(2)
+rust_helper_vrealloc(const void *p, size_t size, gfp_t flags)
+{
+	return vrealloc(p, size, flags);
+}
rust/kernel/alloc/allocator.rs +37 -0
index 272c581e24a0..ee4c828cbd58 100644
@@ -15,6 +15,7 @@
 
 use crate::alloc::{AllocError, Allocator};
 use crate::bindings;
+use crate::pr_warn;
 
 /// The contiguous kernel allocator.
 ///
@@ -24,6 +25,15 @@
 /// For more details see [self].
 pub struct Kmalloc;
 
+/// The virtually contiguous kernel allocator.
+///
+/// `Vmalloc` allocates pages from the page level allocator and maps them into the contiguous kernel
+/// virtual space. It is typically used for large allocations. The memory allocated with this
+/// allocator is not physically contiguous.
+///
+/// For more details see [self].
+pub struct Vmalloc;
+
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
     // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
@@ -63,6 +73,9 @@ impl ReallocFunc {
     // INVARIANT: `krealloc` satisfies the type invariants.
     const KREALLOC: Self = Self(bindings::krealloc);
 
+    // INVARIANT: `vrealloc` satisfies the type invariants.
+    const VREALLOC: Self = Self(bindings::vrealloc);
+
     /// # Safety
     ///
     /// This method has the same safety requirements as [`Allocator::realloc`].
@@ -168,6 +181,30 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
     }
 }
 
+// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that
+// - memory remains valid until it is explicitly freed,
+// - passing a pointer to a valid memory allocation is OK,
+// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
+unsafe impl Allocator for Vmalloc {
+    #[inline]
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // TODO: Support alignments larger than PAGE_SIZE.
+        if layout.align() > bindings::PAGE_SIZE {
+            pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n");
+            return Err(AllocError);
+        }
+
+        // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously
+        // allocated with this `Allocator`.
+        unsafe { ReallocFunc::VREALLOC.call(ptr, layout, old_layout, flags) }
+    }
+}
+
 #[global_allocator]
 static ALLOCATOR: Kmalloc = Kmalloc;
 
rust/kernel/alloc/allocator_test.rs +1 -0
index c5d325506f0c..32a1450c4d39 100644
@@ -7,6 +7,7 @@
 use core::ptr::NonNull;
 
 pub struct Kmalloc;
+pub type Vmalloc = Kmalloc;
 
 unsafe impl Allocator for Kmalloc {
     unsafe fn realloc(
Signature · 1 line
2.48.1
maintainer Applied
#54 lore raw

Patch "rust: alloc: implement `Vmalloc` allocator" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement Vmalloc allocator

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-vmalloc-allocator.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:51:58 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:34 +0100
Subject: rust: alloc: implement Vmalloc allocator
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 61c004781d6b928443052e7a6cf84b35d4f61401 upstream.

Implement Allocator for Vmalloc, the kernel's virtually contiguous allocator, typically used for larger objects, (much) larger than page size.

All memory allocations made with Vmalloc end up in vrealloc().

---
 rust/helpers/helpers.c              |    1 
 rust/helpers/vmalloc.c              |    9 ++++++++
 rust/kernel/alloc/allocator.rs      |   37 ++++++++++++++++++++++++++++++++++++
 rust/kernel/alloc/allocator_test.rs |    1 
 4 files changed, 48 insertions(+)
 create mode 100644 rust/helpers/vmalloc.c
rust/helpers/helpers.c +1 -0
@@ -22,5 +22,6 @@
 #include "spinlock.c"
 #include "task.c"
 #include "uaccess.c"
+#include "vmalloc.c"
 #include "wait.c"
 #include "workqueue.c"
rust/helpers/vmalloc.c new file +9 -0
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/vmalloc.h>
+
+void * __must_check __realloc_size(2)
+rust_helper_vrealloc(const void *p, size_t size, gfp_t flags)
+{
+	return vrealloc(p, size, flags);
+}
rust/kernel/alloc/allocator.rs +37 -0
@@ -15,6 +15,7 @@ use core::ptr::NonNull;
 
 use crate::alloc::{AllocError, Allocator};
 use crate::bindings;
+use crate::pr_warn;
 
 /// The contiguous kernel allocator.
 ///
@@ -24,6 +25,15 @@ use crate::bindings;
 /// For more details see [self].
 pub struct Kmalloc;
 
+/// The virtually contiguous kernel allocator.
+///
+/// `Vmalloc` allocates pages from the page level allocator and maps them into the contiguous kernel
+/// virtual space. It is typically used for large allocations. The memory allocated with this
+/// allocator is not physically contiguous.
+///
+/// For more details see [self].
+pub struct Vmalloc;
+
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
     // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
@@ -63,6 +73,9 @@ impl ReallocFunc {
     // INVARIANT: `krealloc` satisfies the type invariants.
     const KREALLOC: Self = Self(bindings::krealloc);
 
+    // INVARIANT: `vrealloc` satisfies the type invariants.
+    const VREALLOC: Self = Self(bindings::vrealloc);
+
     /// # Safety
     ///
     /// This method has the same safety requirements as [`Allocator::realloc`].
@@ -168,6 +181,30 @@ unsafe impl GlobalAlloc for Kmalloc {
     }
 }
 
+// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that
+// - memory remains valid until it is explicitly freed,
+// - passing a pointer to a valid memory allocation is OK,
+// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
+unsafe impl Allocator for Vmalloc {
+    #[inline]
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // TODO: Support alignments larger than PAGE_SIZE.
+        if layout.align() > bindings::PAGE_SIZE {
+            pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n");
+            return Err(AllocError);
+        }
+
+        // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously
+        // allocated with this `Allocator`.
+        unsafe { ReallocFunc::VREALLOC.call(ptr, layout, old_layout, flags) }
+    }
+}
+
 #[global_allocator]
 static ALLOCATOR: Kmalloc = Kmalloc;
 
rust/kernel/alloc/allocator_test.rs +1 -0
@@ -7,6 +7,7 @@ use core::alloc::Layout;
 use core::ptr::NonNull;
 
 pub struct Kmalloc;
+pub type Vmalloc = Kmalloc;
 
 unsafe impl Allocator for Kmalloc {
     unsafe fn realloc(

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#55 lore raw

PATCH 28/60 rust: alloc: implement `KVmalloc` allocator

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 8362c2608ba1be635ffa22a256dfcfe51c6238cc upstream.

Implement Allocator for KVmalloc, an Allocator that tries to allocate memory with kmalloc first and, on failure, falls back to vmalloc.

All memory allocations made with KVmalloc end up in kvrealloc_noprof(); all frees in kvfree().

---
 rust/helpers/slab.c                 |  6 +++++
 rust/kernel/alloc/allocator.rs      | 36 +++++++++++++++++++++++++++++
 rust/kernel/alloc/allocator_test.rs |  1 +
 3 files changed, 43 insertions(+)
rust/helpers/slab.c +6 -0
index f043e087f9d6..a842bfbddcba 100644
@@ -7,3 +7,9 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags)
 {
 	return krealloc(objp, new_size, flags);
 }
+
+void * __must_check __realloc_size(2)
+rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags)
+{
+	return kvrealloc(p, size, flags);
+}
rust/kernel/alloc/allocator.rs +36 -0
index ee4c828cbd58..f8a1f0feb25d 100644
@@ -34,6 +34,15 @@
 /// For more details see [self].
 pub struct Vmalloc;
 
+/// The kvmalloc kernel allocator.
+///
+/// `KVmalloc` attempts to allocate memory with `Kmalloc` first, but falls back to `Vmalloc` upon
+/// failure. This allocator is typically used when the size for the requested allocation is not
+/// known and may exceed the capabilities of `Kmalloc`.
+///
+/// For more details see [self].
+pub struct KVmalloc;
+
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
     // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
@@ -76,6 +85,9 @@ impl ReallocFunc {
     // INVARIANT: `vrealloc` satisfies the type invariants.
     const VREALLOC: Self = Self(bindings::vrealloc);
 
+    // INVARIANT: `kvrealloc` satisfies the type invariants.
+    const KVREALLOC: Self = Self(bindings::kvrealloc);
+
     /// # Safety
     ///
     /// This method has the same safety requirements as [`Allocator::realloc`].
@@ -205,6 +217,30 @@ unsafe fn realloc(
     }
 }
 
+// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that
+// - memory remains valid until it is explicitly freed,
+// - passing a pointer to a valid memory allocation is OK,
+// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
+unsafe impl Allocator for KVmalloc {
+    #[inline]
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // TODO: Support alignments larger than PAGE_SIZE.
+        if layout.align() > bindings::PAGE_SIZE {
+            pr_warn!("KVmalloc does not support alignments larger than PAGE_SIZE yet.\n");
+            return Err(AllocError);
+        }
+
+        // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously
+        // allocated with this `Allocator`.
+        unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, old_layout, flags) }
+    }
+}
+
 #[global_allocator]
 static ALLOCATOR: Kmalloc = Kmalloc;
 
rust/kernel/alloc/allocator_test.rs +1 -0
index 32a1450c4d39..bd0cbcd93e52 100644
@@ -8,6 +8,7 @@
 
 pub struct Kmalloc;
 pub type Vmalloc = Kmalloc;
+pub type KVmalloc = Kmalloc;
 
 unsafe impl Allocator for Kmalloc {
     unsafe fn realloc(
Signature · 1 line
2.48.1
maintainer Applied
#56 lore raw

Patch "rust: alloc: implement `KVmalloc` allocator" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement KVmalloc allocator

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-kvmalloc-allocator.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:08 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:35 +0100
Subject: rust: alloc: implement KVmalloc allocator
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 8362c2608ba1be635ffa22a256dfcfe51c6238cc upstream.

Implement Allocator for KVmalloc, an Allocator that tries to allocate memory with kmalloc first and, on failure, falls back to vmalloc.

All memory allocations made with KVmalloc end up in kvrealloc_noprof(); all frees in kvfree().

---
 rust/helpers/slab.c                 |    6 ++++++
 rust/kernel/alloc/allocator.rs      |   36 ++++++++++++++++++++++++++++++++++++
 rust/kernel/alloc/allocator_test.rs |    1 +
 3 files changed, 43 insertions(+)
rust/helpers/slab.c +6 -0
@@ -7,3 +7,9 @@ rust_helper_krealloc(const void *objp, s
 {
 	return krealloc(objp, new_size, flags);
 }
+
+void * __must_check __realloc_size(2)
+rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags)
+{
+	return kvrealloc(p, size, flags);
+}
rust/kernel/alloc/allocator.rs +36 -0
@@ -34,6 +34,15 @@ pub struct Kmalloc;
 /// For more details see [self].
 pub struct Vmalloc;
 
+/// The kvmalloc kernel allocator.
+///
+/// `KVmalloc` attempts to allocate memory with `Kmalloc` first, but falls back to `Vmalloc` upon
+/// failure. This allocator is typically used when the size for the requested allocation is not
+/// known and may exceed the capabilities of `Kmalloc`.
+///
+/// For more details see [self].
+pub struct KVmalloc;
+
 /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment.
 fn aligned_size(new_layout: Layout) -> usize {
     // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first.
@@ -76,6 +85,9 @@ impl ReallocFunc {
     // INVARIANT: `vrealloc` satisfies the type invariants.
     const VREALLOC: Self = Self(bindings::vrealloc);
 
+    // INVARIANT: `kvrealloc` satisfies the type invariants.
+    const KVREALLOC: Self = Self(bindings::kvrealloc);
+
     /// # Safety
     ///
     /// This method has the same safety requirements as [`Allocator::realloc`].
@@ -205,6 +217,30 @@ unsafe impl Allocator for Vmalloc {
     }
 }
 
+// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that
+// - memory remains valid until it is explicitly freed,
+// - passing a pointer to a valid memory allocation is OK,
+// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
+unsafe impl Allocator for KVmalloc {
+    #[inline]
+    unsafe fn realloc(
+        ptr: Option<NonNull<u8>>,
+        layout: Layout,
+        old_layout: Layout,
+        flags: Flags,
+    ) -> Result<NonNull<[u8]>, AllocError> {
+        // TODO: Support alignments larger than PAGE_SIZE.
+        if layout.align() > bindings::PAGE_SIZE {
+            pr_warn!("KVmalloc does not support alignments larger than PAGE_SIZE yet.\n");
+            return Err(AllocError);
+        }
+
+        // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously
+        // allocated with this `Allocator`.
+        unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, old_layout, flags) }
+    }
+}
+
 #[global_allocator]
 static ALLOCATOR: Kmalloc = Kmalloc;
 
rust/kernel/alloc/allocator_test.rs +1 -0
@@ -8,6 +8,7 @@ use core::ptr::NonNull;
 
 pub struct Kmalloc;
 pub type Vmalloc = Kmalloc;
+pub type KVmalloc = Kmalloc;
 
 unsafe impl Allocator for Kmalloc {
     unsafe fn realloc(

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#57 lore raw

PATCH 29/60 rust: alloc: add __GFP_NOWARN to `Flags`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 01b2196e5aac8af9343282d0044fa0d6b07d484c upstream.

Some test cases in subsequent patches provoke allocation failures. Add __GFP_NOWARN to enable test cases to silence unpleasant warnings.

---
 rust/bindings/bindings_helper.h | 1 +
 rust/kernel/alloc.rs            | 5 +++++
 2 files changed, 6 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index ae82e9c941af..a80783fcbe04 100644
@@ -31,4 +31,5 @@ const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT = GFP_KERNEL_ACCOUNT;
 const gfp_t RUST_CONST_HELPER_GFP_NOWAIT = GFP_NOWAIT;
 const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO;
 const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM = ___GFP_HIGHMEM;
+const gfp_t RUST_CONST_HELPER___GFP_NOWARN = ___GFP_NOWARN;
 const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL;
rust/kernel/alloc.rs +5 -0
index b5605aab182d..8172106a1423 100644
@@ -91,6 +91,11 @@ pub mod flags {
     /// use any filesystem callback.  It is very likely to fail to allocate memory, even for very
     /// small allocations.
     pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT);
+
+    /// Suppresses allocation failure reports.
+    ///
+    /// This is normally or'd with other flags.
+    pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN);
 }
 
 /// The kernel's [`Allocator`] trait.
Signature · 1 line
2.48.1
maintainer Applied
#58 lore raw

Patch "rust: alloc: add __GFP_NOWARN to `Flags`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: add __GFP_NOWARN to Flags

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-add-__gfp_nowarn-to-flags.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:11 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:36 +0100
Subject: rust: alloc: add __GFP_NOWARN to Flags
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 01b2196e5aac8af9343282d0044fa0d6b07d484c upstream.

Some test cases in subsequent patches provoke allocation failures. Add __GFP_NOWARN to enable test cases to silence unpleasant warnings.

---
 rust/bindings/bindings_helper.h |    1 +
 rust/kernel/alloc.rs            |    5 +++++
 2 files changed, 6 insertions(+)
rust/bindings/bindings_helper.h +1 -0
@@ -31,4 +31,5 @@ const gfp_t RUST_CONST_HELPER_GFP_KERNEL
 const gfp_t RUST_CONST_HELPER_GFP_NOWAIT = GFP_NOWAIT;
 const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO;
 const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM = ___GFP_HIGHMEM;
+const gfp_t RUST_CONST_HELPER___GFP_NOWARN = ___GFP_NOWARN;
 const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL;
rust/kernel/alloc.rs +5 -0
@@ -91,6 +91,11 @@ pub mod flags {
     /// use any filesystem callback.  It is very likely to fail to allocate memory, even for very
     /// small allocations.
     pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT);
+
+    /// Suppresses allocation failure reports.
+    ///
+    /// This is normally or'd with other flags.
+    pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN);
 }
 
 /// The kernel's [`Allocator`] trait.

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#59 lore raw

PATCH 30/60 rust: alloc: implement kernel `Box`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit c8cfa8d0c0b10be216861fe904ea68978b1dcc97 upstream.

Box provides the simplest way to allocate memory for a generic type with one of the kernel's allocators, e.g. Kmalloc, Vmalloc or KVmalloc.

In contrast to Rust's Box type, the kernel Box type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through Result<_, AllocError> and remains independent from unstable features.

---
 rust/kernel/alloc.rs      |   6 +
 rust/kernel/alloc/kbox.rs | 456 ++++++++++++++++++++++++++++++++++++++
 rust/kernel/prelude.rs    |   2 +-
 3 files changed, 463 insertions(+), 1 deletion(-)
 create mode 100644 rust/kernel/alloc/kbox.rs
rust/kernel/alloc.rs +6 -0
index 8172106a1423..3628e16240a6 100644
@@ -5,6 +5,7 @@
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod box_ext;
+pub mod kbox;
 pub mod vec_ext;
 
 #[cfg(any(test, testlib))]
@@ -13,6 +14,11 @@
 #[cfg(any(test, testlib))]
 pub use self::allocator_test as allocator;
 
+pub use self::kbox::Box;
+pub use self::kbox::KBox;
+pub use self::kbox::KVBox;
+pub use self::kbox::VBox;
+
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
rust/kernel/alloc/kbox.rs new file +456 -0

456 lines not on this page · raw message

rust/kernel/prelude.rs +1 -1
index 4571daec0961..a9210634a8c3 100644
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt};
+pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
 
 #[doc(no_inline)]
 pub use alloc::{boxed::Box, vec::Vec};
Signature · 1 line
2.48.1
maintainer Applied
#60 lore raw

Patch "rust: alloc: implement kernel `Box`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement kernel Box

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-kernel-box.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:12 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:37 +0100
Subject: rust: alloc: implement kernel Box
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit c8cfa8d0c0b10be216861fe904ea68978b1dcc97 upstream.

Box provides the simplest way to allocate memory for a generic type with one of the kernel's allocators, e.g. Kmalloc, Vmalloc or KVmalloc.

In contrast to Rust's Box type, the kernel Box type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through Result<_, AllocError> and remains independent from unstable features.

---
 rust/kernel/alloc.rs      |    6 
 rust/kernel/alloc/kbox.rs |  456 ++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/prelude.rs    |    2 
 3 files changed, 463 insertions(+), 1 deletion(-)
 create mode 100644 rust/kernel/alloc/kbox.rs
rust/kernel/alloc.rs +6 -0
@@ -5,6 +5,7 @@
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod box_ext;
+pub mod kbox;
 pub mod vec_ext;
 
 #[cfg(any(test, testlib))]
@@ -13,6 +14,11 @@ pub mod allocator_test;
 #[cfg(any(test, testlib))]
 pub use self::allocator_test as allocator;
 
+pub use self::kbox::Box;
+pub use self::kbox::KBox;
+pub use self::kbox::KVBox;
+pub use self::kbox::VBox;
+
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
rust/kernel/alloc/kbox.rs new file +456 -0

456 lines not on this page · raw message

rust/kernel/prelude.rs +1 -1
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt};
+pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
 
 #[doc(no_inline)]
 pub use alloc::{boxed::Box, vec::Vec};

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#61 lore raw

PATCH 31/60 rust: treewide: switch to our kernel `Box` type

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 8373147ce4961665c5700016b1c76299e962d077 upstream.

Now that we got the kernel Box type in place, convert all existing Box users to make use of it.

---
 drivers/block/rnull.rs            |  4 +--
 rust/kernel/init.rs               | 51 ++++++++++++++++---------------
 rust/kernel/init/__internal.rs    |  2 +-
 rust/kernel/rbtree.rs             | 49 ++++++++++++++++-------------
 rust/kernel/sync/arc.rs           | 17 +++++------
 rust/kernel/sync/condvar.rs       |  4 +--
 rust/kernel/sync/lock/mutex.rs    |  2 +-
 rust/kernel/sync/lock/spinlock.rs |  2 +-
 rust/kernel/workqueue.rs          | 20 ++++++------
 rust/macros/lib.rs                |  6 ++--
 10 files changed, 81 insertions(+), 76 deletions(-)
drivers/block/rnull.rs +2 -2
index b0227cf9ddd3..5de7223beb4d 100644
@@ -32,7 +32,7 @@
 }
 
 struct NullBlkModule {
-    _disk: Pin<Box<Mutex<GenDisk<NullBlkDevice>>>>,
+    _disk: Pin<KBox<Mutex<GenDisk<NullBlkDevice>>>>,
 }
 
 impl kernel::Module for NullBlkModule {
@@ -47,7 +47,7 @@ fn init(_module: &'static ThisModule) -> Result<Self> {
             .rotational(false)
             .build(format_args!("rnullb{}", 0), tagset)?;
 
-        let disk = Box::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?;
+        let disk = KBox::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?;
 
         Ok(Self { _disk: disk })
     }
rust/kernel/init.rs +26 -25

178 lines not on this page · raw message

rust/kernel/init/__internal.rs +1 -1
index 44431fba7aab..74329cc3262c 100644
@@ -105,7 +105,7 @@ fn make_closure<F, O, E>(self, f: F) -> F
     }
 }
 
-pub struct AllData<T: ?Sized>(PhantomData<fn(Box<T>) -> Box<T>>);
+pub struct AllData<T: ?Sized>(PhantomData<fn(KBox<T>) -> KBox<T>>);
 
 impl<T: ?Sized> Clone for AllData<T> {
     fn clone(&self) -> Self {
rust/kernel/rbtree.rs +27 -22

139 lines not on this page · raw message

rust/kernel/sync/arc.rs +8 -9
index 9325cc5a16a4..db9da352d588 100644
@@ -17,13 +17,12 @@
 //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
 
 use crate::{
-    alloc::{box_ext::BoxExt, AllocError, Flags},
+    alloc::{AllocError, Flags, KBox},
     bindings,
     init::{self, InPlaceInit, Init, PinInit},
     try_init,
     types::{ForeignOwnable, Opaque},
 };
-use alloc::boxed::Box;
 use core::{
     alloc::Layout,
     fmt,
@@ -201,11 +200,11 @@ pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> {
             data: contents,
         };
 
-        let inner = <Box<_> as BoxExt<_>>::new(value, flags)?;
+        let inner = KBox::new(value, flags)?;
 
         // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
         // `Arc` object.
-        Ok(unsafe { Self::from_inner(Box::leak(inner).into()) })
+        Ok(unsafe { Self::from_inner(KBox::leak(inner).into()) })
     }
 }
 
@@ -398,8 +397,8 @@ fn drop(&mut self) {
         if is_zero {
             // The count reached zero, we must free the memory.
             //
-            // SAFETY: The pointer was initialised from the result of `Box::leak`.
-            unsafe { drop(Box::from_raw(self.ptr.as_ptr())) };
+            // SAFETY: The pointer was initialised from the result of `KBox::leak`.
+            unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) };
         }
     }
 }
@@ -641,7 +640,7 @@ pub fn new(value: T, flags: Flags) -> Result<Self, AllocError> {
     /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
     pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
         // INVARIANT: The refcount is initialised to a non-zero value.
-        let inner = Box::try_init::<AllocError>(
+        let inner = KBox::try_init::<AllocError>(
             try_init!(ArcInner {
                 // SAFETY: There are no safety requirements for this FFI call.
                 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
@@ -651,8 +650,8 @@ pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError>
         )?;
         Ok(UniqueArc {
             // INVARIANT: The newly-created object has a refcount of 1.
-            // SAFETY: The pointer from the `Box` is valid.
-            inner: unsafe { Arc::from_inner(Box::leak(inner).into()) },
+            // SAFETY: The pointer from the `KBox` is valid.
+            inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) },
         })
     }
 }
rust/kernel/sync/condvar.rs +2 -2
index dec2e5ffc919..a1a29c0bdb3a 100644
@@ -70,8 +70,8 @@ macro_rules! new_condvar {
 /// }
 ///
 /// /// Allocates a new boxed `Example`.
-/// fn new_example() -> Result<Pin<Box<Example>>> {
-///     Box::pin_init(pin_init!(Example {
+/// fn new_example() -> Result<Pin<KBox<Example>>> {
+///     KBox::pin_init(pin_init!(Example {
 ///         value <- new_mutex!(0),
 ///         value_changed <- new_condvar!(),
 ///     }), GFP_KERNEL)
rust/kernel/sync/lock/mutex.rs +1 -1
index 30632070ee67..f8f6d530db7d 100644
@@ -58,7 +58,7 @@ macro_rules! new_mutex {
 /// }
 ///
 /// // Allocate a boxed `Example`.
-/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?;
+/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?;
 /// assert_eq!(e.c, 10);
 /// assert_eq!(e.d.lock().a, 20);
 /// assert_eq!(e.d.lock().b, 30);
rust/kernel/sync/lock/spinlock.rs +1 -1
index ea5c5bc1ce12..a9096a4dc42a 100644
@@ -56,7 +56,7 @@ macro_rules! new_spinlock {
 /// }
 ///
 /// // Allocate a boxed `Example`.
-/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?;
+/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?;
 /// assert_eq!(e.c, 10);
 /// assert_eq!(e.d.lock().a, 20);
 /// assert_eq!(e.d.lock().b, 30);
rust/kernel/workqueue.rs +10 -10
index 10d2bc62e2cf..4d1d2062f6eb 100644
@@ -216,7 +216,7 @@ pub fn try_spawn<T: 'static + Send + FnOnce()>(
             func: Some(func),
         });
 
-        self.enqueue(Box::pin_init(init, flags).map_err(|_| AllocError)?);
+        self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?);
         Ok(())
     }
 }
@@ -239,9 +239,9 @@ fn project(self: Pin<&mut Self>) -> &mut Option<T> {
 }
 
 impl<T: FnOnce()> WorkItem for ClosureWork<T> {
-    type Pointer = Pin<Box<Self>>;
+    type Pointer = Pin<KBox<Self>>;
 
-    fn run(mut this: Pin<Box<Self>>) {
+    fn run(mut this: Pin<KBox<Self>>) {
         if let Some(func) = this.as_mut().project().take() {
             (func)()
         }
@@ -297,7 +297,7 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
 
 /// Defines the method that should be called directly when a work item is executed.
 ///
-/// This trait is implemented by `Pin<Box<T>>` and [`Arc<T>`], and is mainly intended to be
+/// This trait is implemented by `Pin<KBox<T>>` and [`Arc<T>`], and is mainly intended to be
 /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`]
 /// instead. The [`run`] method on this trait will usually just perform the appropriate
 /// `container_of` translation and then call into the [`run`][WorkItem::run] method from the
@@ -329,7 +329,7 @@ pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
 /// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
 pub trait WorkItem<const ID: u64 = 0> {
     /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
-    /// `Pin<Box<Self>>`.
+    /// `Pin<KBox<Self>>`.
     type Pointer: WorkItemPointer<ID>;
 
     /// The method that should be called when this work item is executed.
@@ -567,7 +567,7 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
 }
 
 // SAFETY: TODO.
-unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
+unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
     T: HasWork<T, ID>,
@@ -578,7 +578,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
         let ptr = unsafe { T::work_container_of(ptr) };
         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
-        let boxed = unsafe { Box::from_raw(ptr) };
+        let boxed = unsafe { KBox::from_raw(ptr) };
         // SAFETY: The box was already pinned when it was enqueued.
         let pinned = unsafe { Pin::new_unchecked(boxed) };
 
@@ -587,7 +587,7 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
 }
 
 // SAFETY: TODO.
-unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
+unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<KBox<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
     T: HasWork<T, ID>,
@@ -601,9 +601,9 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
         // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily
         // remove the `Pin` wrapper.
         let boxed = unsafe { Pin::into_inner_unchecked(self) };
-        let ptr = Box::into_raw(boxed);
+        let ptr = KBox::into_raw(boxed);
 
-        // SAFETY: Pointers into a `Box` point at a valid value.
+        // SAFETY: Pointers into a `KBox` point at a valid value.
         let work_ptr = unsafe { T::raw_get_work(ptr) };
         // SAFETY: `raw_get_work` returns a pointer to a valid value.
         let work_ptr = unsafe { Work::raw_get(work_ptr) };
rust/macros/lib.rs +3 -3
index 90e2202ba4d5..1f1d3a28032c 100644
@@ -243,7 +243,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream {
 /// struct DriverData {
 ///     #[pin]
 ///     queue: Mutex<Vec<Command>>,
-///     buf: Box<[u8; 1024 * 1024]>,
+///     buf: KBox<[u8; 1024 * 1024]>,
 /// }
 /// ```
 ///
@@ -252,7 +252,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream {
 /// struct DriverData {
 ///     #[pin]
 ///     queue: Mutex<Vec<Command>>,
-///     buf: Box<[u8; 1024 * 1024]>,
+///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
 ///
@@ -282,7 +282,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
 /// struct DriverData {
 ///     #[pin]
 ///     queue: Mutex<Vec<Command>>,
-///     buf: Box<[u8; 1024 * 1024]>,
+///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
 ///
Signature · 1 line
2.48.1
maintainer Applied
#62 lore raw

Patch "rust: treewide: switch to our kernel `Box` type" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: treewide: switch to our kernel Box type

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-treewide-switch-to-our-kernel-box-type.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:11 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:38 +0100
Subject: rust: treewide: switch to our kernel Box type
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 8373147ce4961665c5700016b1c76299e962d077 upstream.

Now that we got the kernel Box type in place, convert all existing Box users to make use of it.

---
 drivers/block/rnull.rs            |    4 +-
 rust/kernel/init.rs               |   51 +++++++++++++++++++-------------------
 rust/kernel/init/__internal.rs    |    2 -
 rust/kernel/rbtree.rs             |   49 ++++++++++++++++++++----------------
 rust/kernel/sync/arc.rs           |   17 +++++-------
 rust/kernel/sync/condvar.rs       |    4 +-
 rust/kernel/sync/lock/mutex.rs    |    2 -
 rust/kernel/sync/lock/spinlock.rs |    2 -
 rust/kernel/workqueue.rs          |   20 +++++++-------
 rust/macros/lib.rs                |    6 ++--
 10 files changed, 81 insertions(+), 76 deletions(-)
drivers/block/rnull.rs +2 -2
@@ -32,7 +32,7 @@ module! {
 }
 
 struct NullBlkModule {
-    _disk: Pin<Box<Mutex<GenDisk<NullBlkDevice>>>>,
+    _disk: Pin<KBox<Mutex<GenDisk<NullBlkDevice>>>>,
 }
 
 impl kernel::Module for NullBlkModule {
@@ -47,7 +47,7 @@ impl kernel::Module for NullBlkModule {
             .rotational(false)
             .build(format_args!("rnullb{}", 0), tagset)?;
 
-        let disk = Box::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?;
+        let disk = KBox::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?;
 
         Ok(Self { _disk: disk })
     }
rust/kernel/init.rs +26 -25

178 lines not on this page · raw message

rust/kernel/init/__internal.rs +1 -1
@@ -105,7 +105,7 @@ pub unsafe trait InitData: Copy {
     }
 }
 
-pub struct AllData<T: ?Sized>(PhantomData<fn(Box<T>) -> Box<T>>);
+pub struct AllData<T: ?Sized>(PhantomData<fn(KBox<T>) -> KBox<T>>);
 
 impl<T: ?Sized> Clone for AllData<T> {
     fn clone(&self) -> Self {
rust/kernel/rbtree.rs +27 -22

139 lines not on this page · raw message

rust/kernel/sync/arc.rs +8 -9
@@ -17,13 +17,12 @@
 //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
 
 use crate::{
-    alloc::{box_ext::BoxExt, AllocError, Flags},
+    alloc::{AllocError, Flags, KBox},
     bindings,
     init::{self, InPlaceInit, Init, PinInit},
     try_init,
     types::{ForeignOwnable, Opaque},
 };
-use alloc::boxed::Box;
 use core::{
     alloc::Layout,
     fmt,
@@ -201,11 +200,11 @@ impl<T> Arc<T> {
             data: contents,
         };
 
-        let inner = <Box<_> as BoxExt<_>>::new(value, flags)?;
+        let inner = KBox::new(value, flags)?;
 
         // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new
         // `Arc` object.
-        Ok(unsafe { Self::from_inner(Box::leak(inner).into()) })
+        Ok(unsafe { Self::from_inner(KBox::leak(inner).into()) })
     }
 }
 
@@ -398,8 +397,8 @@ impl<T: ?Sized> Drop for Arc<T> {
         if is_zero {
             // The count reached zero, we must free the memory.
             //
-            // SAFETY: The pointer was initialised from the result of `Box::leak`.
-            unsafe { drop(Box::from_raw(self.ptr.as_ptr())) };
+            // SAFETY: The pointer was initialised from the result of `KBox::leak`.
+            unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) };
         }
     }
 }
@@ -641,7 +640,7 @@ impl<T> UniqueArc<T> {
     /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet.
     pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError> {
         // INVARIANT: The refcount is initialised to a non-zero value.
-        let inner = Box::try_init::<AllocError>(
+        let inner = KBox::try_init::<AllocError>(
             try_init!(ArcInner {
                 // SAFETY: There are no safety requirements for this FFI call.
                 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }),
@@ -651,8 +650,8 @@ impl<T> UniqueArc<T> {
         )?;
         Ok(UniqueArc {
             // INVARIANT: The newly-created object has a refcount of 1.
-            // SAFETY: The pointer from the `Box` is valid.
-            inner: unsafe { Arc::from_inner(Box::leak(inner).into()) },
+            // SAFETY: The pointer from the `KBox` is valid.
+            inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) },
         })
     }
 }
rust/kernel/sync/condvar.rs +2 -2
@@ -70,8 +70,8 @@ pub use new_condvar;
 /// }
 ///
 /// /// Allocates a new boxed `Example`.
-/// fn new_example() -> Result<Pin<Box<Example>>> {
-///     Box::pin_init(pin_init!(Example {
+/// fn new_example() -> Result<Pin<KBox<Example>>> {
+///     KBox::pin_init(pin_init!(Example {
 ///         value <- new_mutex!(0),
 ///         value_changed <- new_condvar!(),
 ///     }), GFP_KERNEL)
rust/kernel/sync/lock/mutex.rs +1 -1
@@ -58,7 +58,7 @@ pub use new_mutex;
 /// }
 ///
 /// // Allocate a boxed `Example`.
-/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?;
+/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?;
 /// assert_eq!(e.c, 10);
 /// assert_eq!(e.d.lock().a, 20);
 /// assert_eq!(e.d.lock().b, 30);
rust/kernel/sync/lock/spinlock.rs +1 -1
@@ -56,7 +56,7 @@ pub use new_spinlock;
 /// }
 ///
 /// // Allocate a boxed `Example`.
-/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?;
+/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?;
 /// assert_eq!(e.c, 10);
 /// assert_eq!(e.d.lock().a, 20);
 /// assert_eq!(e.d.lock().b, 30);
rust/kernel/workqueue.rs +10 -10
@@ -216,7 +216,7 @@ impl Queue {
             func: Some(func),
         });
 
-        self.enqueue(Box::pin_init(init, flags).map_err(|_| AllocError)?);
+        self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?);
         Ok(())
     }
 }
@@ -239,9 +239,9 @@ impl<T> ClosureWork<T> {
 }
 
 impl<T: FnOnce()> WorkItem for ClosureWork<T> {
-    type Pointer = Pin<Box<Self>>;
+    type Pointer = Pin<KBox<Self>>;
 
-    fn run(mut this: Pin<Box<Self>>) {
+    fn run(mut this: Pin<KBox<Self>>) {
         if let Some(func) = this.as_mut().project().take() {
             (func)()
         }
@@ -297,7 +297,7 @@ pub unsafe trait RawWorkItem<const ID: u
 
 /// Defines the method that should be called directly when a work item is executed.
 ///
-/// This trait is implemented by `Pin<Box<T>>` and [`Arc<T>`], and is mainly intended to be
+/// This trait is implemented by `Pin<KBox<T>>` and [`Arc<T>`], and is mainly intended to be
 /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`]
 /// instead. The [`run`] method on this trait will usually just perform the appropriate
 /// `container_of` translation and then call into the [`run`][WorkItem::run] method from the
@@ -329,7 +329,7 @@ pub unsafe trait WorkItemPointer<const I
 /// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
 pub trait WorkItem<const ID: u64 = 0> {
     /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
-    /// `Pin<Box<Self>>`.
+    /// `Pin<KBox<Self>>`.
     type Pointer: WorkItemPointer<ID>;
 
     /// The method that should be called when this work item is executed.
@@ -567,7 +567,7 @@ where
 }
 
 // SAFETY: TODO.
-unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
+unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
     T: HasWork<T, ID>,
@@ -578,7 +578,7 @@ where
         // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
         let ptr = unsafe { T::work_container_of(ptr) };
         // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
-        let boxed = unsafe { Box::from_raw(ptr) };
+        let boxed = unsafe { KBox::from_raw(ptr) };
         // SAFETY: The box was already pinned when it was enqueued.
         let pinned = unsafe { Pin::new_unchecked(boxed) };
 
@@ -587,7 +587,7 @@ where
 }
 
 // SAFETY: TODO.
-unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
+unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<KBox<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
     T: HasWork<T, ID>,
@@ -601,9 +601,9 @@ where
         // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily
         // remove the `Pin` wrapper.
         let boxed = unsafe { Pin::into_inner_unchecked(self) };
-        let ptr = Box::into_raw(boxed);
+        let ptr = KBox::into_raw(boxed);
 
-        // SAFETY: Pointers into a `Box` point at a valid value.
+        // SAFETY: Pointers into a `KBox` point at a valid value.
         let work_ptr = unsafe { T::raw_get_work(ptr) };
         // SAFETY: `raw_get_work` returns a pointer to a valid value.
         let work_ptr = unsafe { Work::raw_get(work_ptr) };
rust/macros/lib.rs +3 -3
@@ -243,7 +243,7 @@ pub fn concat_idents(ts: TokenStream) ->
 /// struct DriverData {
 ///     #[pin]
 ///     queue: Mutex<Vec<Command>>,
-///     buf: Box<[u8; 1024 * 1024]>,
+///     buf: KBox<[u8; 1024 * 1024]>,
 /// }
 /// ```
 ///
@@ -252,7 +252,7 @@ pub fn concat_idents(ts: TokenStream) ->
 /// struct DriverData {
 ///     #[pin]
 ///     queue: Mutex<Vec<Command>>,
-///     buf: Box<[u8; 1024 * 1024]>,
+///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
 ///
@@ -282,7 +282,7 @@ pub fn pin_data(inner: TokenStream, item
 /// struct DriverData {
 ///     #[pin]
 ///     queue: Mutex<Vec<Command>>,
-///     buf: Box<[u8; 1024 * 1024]>,
+///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
 ///

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#63 lore raw

PATCH 32/60 rust: alloc: remove extension of std's `Box`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit e8c6ccdbcaaf31f26c0fffd4073edd0b0147cdc6 upstream.

Now that all existing Box users were moved to the kernel Box type, remove the BoxExt extension and all other related extensions.

---
 rust/kernel/alloc.rs         |  1 -
 rust/kernel/alloc/box_ext.rs | 89 ------------------------------------
 rust/kernel/init.rs          | 46 +------------------
 rust/kernel/lib.rs           |  1 -
 rust/kernel/prelude.rs       |  4 +-
 rust/kernel/types.rs         | 50 --------------------
 6 files changed, 3 insertions(+), 188 deletions(-)
 delete mode 100644 rust/kernel/alloc/box_ext.rs
rust/kernel/alloc.rs +0 -1
index 3628e16240a6..94f4de5e0cdc 100644
@@ -4,7 +4,6 @@
 
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
-pub mod box_ext;
 pub mod kbox;
 pub mod vec_ext;
 
rust/kernel/alloc/box_ext.rs deleted +0 -89

89 lines not on this page · raw message

rust/kernel/init.rs +1 -45

75 lines not on this page · raw message

rust/kernel/lib.rs +0 -1
index b6395b4209d7..5bbaf6282265 100644
@@ -16,7 +16,6 @@
 #![feature(coerce_unsized)]
 #![feature(dispatch_from_dyn)]
 #![feature(lint_reasons)]
-#![feature(new_uninit)]
 #![feature(unsize)]
 
 // Ensure conditional compilation based on the kernel configuration works;
rust/kernel/prelude.rs +2 -2
index a9210634a8c3..c1f8e5c832e2 100644
@@ -14,10 +14,10 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
+pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
 
 #[doc(no_inline)]
-pub use alloc::{boxed::Box, vec::Vec};
+pub use alloc::vec::Vec;
 
 #[doc(no_inline)]
 pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable};
rust/kernel/types.rs +0 -50

67 lines not on this page · raw message

Signature · 1 line
2.48.1
maintainer Applied
#64 lore raw

Patch "rust: alloc: remove extension of std's `Box`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: remove extension of std's Box

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-remove-extension-of-std-s-box.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:15 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:39 +0100
Subject: rust: alloc: remove extension of std's Box
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit e8c6ccdbcaaf31f26c0fffd4073edd0b0147cdc6 upstream.

Now that all existing Box users were moved to the kernel Box type, remove the BoxExt extension and all other related extensions.

---
 rust/kernel/alloc.rs         |    1 
 rust/kernel/alloc/box_ext.rs |   89 -------------------------------------------
 rust/kernel/init.rs          |   46 ----------------------
 rust/kernel/lib.rs           |    1 
 rust/kernel/prelude.rs       |    4 -
 rust/kernel/types.rs         |   50 ------------------------
 6 files changed, 3 insertions(+), 188 deletions(-)
 delete mode 100644 rust/kernel/alloc/box_ext.rs
rust/kernel/alloc.rs +0 -1
@@ -4,7 +4,6 @@
 
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
-pub mod box_ext;
 pub mod kbox;
 pub mod vec_ext;
 
rust/kernel/alloc/box_ext.rs deleted +0 -89

89 lines not on this page · raw message

rust/kernel/init.rs +1 -45

75 lines not on this page · raw message

rust/kernel/lib.rs +0 -1
@@ -16,7 +16,6 @@
 #![feature(coerce_unsized)]
 #![feature(dispatch_from_dyn)]
 #![feature(lint_reasons)]
-#![feature(new_uninit)]
 #![feature(unsize)]
 
 // Ensure conditional compilation based on the kernel configuration works;
rust/kernel/prelude.rs +2 -2
@@ -14,10 +14,10 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
+pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
 
 #[doc(no_inline)]
-pub use alloc::{boxed::Box, vec::Vec};
+pub use alloc::vec::Vec;
 
 #[doc(no_inline)]
 pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable};
rust/kernel/types.rs +0 -50

67 lines not on this page · raw message

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#65 lore raw

PATCH 33/60 rust: alloc: add `Box` to prelude

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit e1044c2238f54ae5bd902cac6d12e48835df418b upstream.

Now that we removed BoxExt and the corresponding includes in prelude.rs, add the new kernel Box type instead.

---
 rust/kernel/prelude.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/prelude.rs +1 -1
index c1f8e5c832e2..d5f2fe42d093 100644
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
+pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox};
 
 #[doc(no_inline)]
 pub use alloc::vec::Vec;
Signature · 1 line
2.48.1
maintainer Applied
#66 lore raw

Patch "rust: alloc: add `Box` to prelude" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: add Box to prelude

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-add-box-to-prelude.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:17 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:40 +0100
Subject: rust: alloc: add Box to prelude
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit e1044c2238f54ae5bd902cac6d12e48835df418b upstream.

Now that we removed BoxExt and the corresponding includes in prelude.rs, add the new kernel Box type instead.

---
 rust/kernel/prelude.rs |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/prelude.rs +1 -1
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox};
+pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox};
 
 #[doc(no_inline)]
 pub use alloc::vec::Vec;

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#67 lore raw

PATCH 34/60 rust: alloc: introduce `ArrayLayout`

In reply to Miguel Ojeda

From: Benno Lossin <[email protected]>

commit 9e7bbfa182767f638ba61dba3518ff78da9f31ff upstream.

When allocating memory for arrays using allocators, the Layout::array function is typically used. It returns a result, since the given size might be too big. However, Vec and its iterators store their allocated capacity and thus they already did check that the size is not too big.

The ArrayLayout type provides this exact behavior, as it can be infallibly converted into a Layout. Instead of a usize capacity, Vec and other similar array-storing types can use ArrayLayout instead.

---
 rust/kernel/alloc.rs        |  1 +
 rust/kernel/alloc/layout.rs | 91 +++++++++++++++++++++++++++++++++++++
 2 files changed, 92 insertions(+)
 create mode 100644 rust/kernel/alloc/layout.rs
rust/kernel/alloc.rs +1 -0
index 94f4de5e0cdc..c679d93b0523 100644
@@ -5,6 +5,7 @@
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod kbox;
+pub mod layout;
 pub mod vec_ext;
 
 #[cfg(any(test, testlib))]
rust/kernel/alloc/layout.rs new file +91 -0

91 lines not on this page · raw message

Signature · 1 line
2.48.1
maintainer Applied
#68 lore raw

Patch "rust: alloc: introduce `ArrayLayout`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: introduce ArrayLayout

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-introduce-arraylayout.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:14 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:41 +0100
Subject: rust: alloc: introduce ArrayLayout
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Benno Lossin <[email protected]>

commit 9e7bbfa182767f638ba61dba3518ff78da9f31ff upstream.

When allocating memory for arrays using allocators, the Layout::array function is typically used. It returns a result, since the given size might be too big. However, Vec and its iterators store their allocated capacity and thus they already did check that the size is not too big.

The ArrayLayout type provides this exact behavior, as it can be infallibly converted into a Layout. Instead of a usize capacity, Vec and other similar array-storing types can use ArrayLayout instead.

---
 rust/kernel/alloc.rs        |    1 
 rust/kernel/alloc/layout.rs |   91 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 92 insertions(+)
 create mode 100644 rust/kernel/alloc/layout.rs
rust/kernel/alloc.rs +1 -0
@@ -5,6 +5,7 @@
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod kbox;
+pub mod layout;
 pub mod vec_ext;
 
 #[cfg(any(test, testlib))]
rust/kernel/alloc/layout.rs new file +91 -0

91 lines not on this page · raw message

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#69 lore raw

PATCH 35/60 rust: alloc: implement kernel `Vec` type

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 2aac4cd7dae3d7bb0e0ddec2561b2ee4cbe6c8f6 upstream.

Vec provides a contiguous growable array type with contents allocated with the kernel's allocators (e.g. Kmalloc, Vmalloc or KVmalloc).

In contrast to Rust's stdlib Vec type, the kernel Vec type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through Result<_, AllocError> and remains independent from unstable features.

[ This patch starts using a new unstable feature, inline_const, but
it was stabilized in Rust 1.79.0, i.e. the next version after the minimum one, thus it will not be an issue. - Miguel ]

[ Cleaned rustdoc unescaped backtick warning, added a couple more
backticks elsewhere, fixed typos, sorted features, rewrapped documentation lines. - Miguel ]

---
 rust/kernel/alloc.rs      |   6 +
 rust/kernel/alloc/kvec.rs | 648 ++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs        |   1 +
 rust/kernel/prelude.rs    |   2 +-
 4 files changed, 656 insertions(+), 1 deletion(-)
 create mode 100644 rust/kernel/alloc/kvec.rs
rust/kernel/alloc.rs +6 -0
index c679d93b0523..7f654b214ec2 100644
@@ -5,6 +5,7 @@
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod kbox;
+pub mod kvec;
 pub mod layout;
 pub mod vec_ext;
 
@@ -19,6 +20,11 @@
 pub use self::kbox::KVBox;
 pub use self::kbox::VBox;
 
+pub use self::kvec::KVVec;
+pub use self::kvec::KVec;
+pub use self::kvec::VVec;
+pub use self::kvec::Vec;
+
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
rust/kernel/alloc/kvec.rs new file +648 -0

648 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
index 5bbaf6282265..40c903515586 100644
@@ -15,6 +15,7 @@
 #![feature(arbitrary_self_types)]
 #![feature(coerce_unsized)]
 #![feature(dispatch_from_dyn)]
+#![feature(inline_const)]
 #![feature(lint_reasons)]
 #![feature(unsize)]
 
rust/kernel/prelude.rs +1 -1
index d5f2fe42d093..80223cdaa485 100644
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox};
+pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
 
 #[doc(no_inline)]
 pub use alloc::vec::Vec;
Signature · 1 line
2.48.1
maintainer Applied
#70 lore raw

Patch "rust: alloc: implement kernel `Vec` type" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement kernel Vec type

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-kernel-vec-type.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:17 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:42 +0100
Subject: rust: alloc: implement kernel Vec type
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 2aac4cd7dae3d7bb0e0ddec2561b2ee4cbe6c8f6 upstream.

Vec provides a contiguous growable array type with contents allocated with the kernel's allocators (e.g. Kmalloc, Vmalloc or KVmalloc).

In contrast to Rust's stdlib Vec type, the kernel Vec type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through Result<_, AllocError> and remains independent from unstable features.

[ This patch starts using a new unstable feature, inline_const, but
it was stabilized in Rust 1.79.0, i.e. the next version after the minimum one, thus it will not be an issue. - Miguel ]

[ Cleaned rustdoc unescaped backtick warning, added a couple more
backticks elsewhere, fixed typos, sorted features, rewrapped documentation lines. - Miguel ]

---
 rust/kernel/alloc.rs      |    6 
 rust/kernel/alloc/kvec.rs |  648 ++++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs        |    1 
 rust/kernel/prelude.rs    |    2 
 4 files changed, 656 insertions(+), 1 deletion(-)
 create mode 100644 rust/kernel/alloc/kvec.rs
rust/kernel/alloc.rs +6 -0
@@ -5,6 +5,7 @@
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
 pub mod kbox;
+pub mod kvec;
 pub mod layout;
 pub mod vec_ext;
 
@@ -19,6 +20,11 @@ pub use self::kbox::KBox;
 pub use self::kbox::KVBox;
 pub use self::kbox::VBox;
 
+pub use self::kvec::KVVec;
+pub use self::kvec::KVec;
+pub use self::kvec::VVec;
+pub use self::kvec::Vec;
+
 /// Indicates an allocation error.
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct AllocError;
rust/kernel/alloc/kvec.rs new file +648 -0

648 lines not on this page · raw message

rust/kernel/lib.rs +1 -0
@@ -15,6 +15,7 @@
 #![feature(arbitrary_self_types)]
 #![feature(coerce_unsized)]
 #![feature(dispatch_from_dyn)]
+#![feature(inline_const)]
 #![feature(lint_reasons)]
 #![feature(unsize)]
 
rust/kernel/prelude.rs +1 -1
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox};
+pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
 
 #[doc(no_inline)]
 pub use alloc::vec::Vec;

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#71 lore raw

PATCH 36/60 rust: alloc: implement `IntoIterator` for `Vec`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 1d1d223aa3b37c34271aefc2706340d0843bfcb2 upstream.

Implement IntoIterator for Vec, Vec's IntoIter type, as well as Iterator for IntoIter.

Vec::into_iter disassembles the Vec into its raw parts; additionally, IntoIter keeps track of a separate pointer, which is incremented correspondingly as the iterator advances, while the length, or the count of elements, is decremented.

This also means that IntoIter takes the ownership of the backing buffer and is responsible to drop the remaining elements and free the backing buffer, if it's dropped.

---
 rust/kernel/alloc.rs      |   1 +
 rust/kernel/alloc/kvec.rs | 170 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 171 insertions(+)
rust/kernel/alloc.rs +1 -0
index 7f654b214ec2..86d2077a8e64 100644
@@ -20,6 +20,7 @@
 pub use self::kbox::KVBox;
 pub use self::kbox::VBox;
 
+pub use self::kvec::IntoIter;
 pub use self::kvec::KVVec;
 pub use self::kvec::KVec;
 pub use self::kvec::VVec;
rust/kernel/alloc/kvec.rs +170 -0

173 lines not on this page · raw message

Signature · 1 line
2.48.1
maintainer Applied
#72 lore raw

Patch "rust: alloc: implement `IntoIterator` for `Vec`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement IntoIterator for Vec

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-intoiterator-for-vec.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:19 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:43 +0100
Subject: rust: alloc: implement IntoIterator for Vec
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 1d1d223aa3b37c34271aefc2706340d0843bfcb2 upstream.

Implement IntoIterator for Vec, Vec's IntoIter type, as well as Iterator for IntoIter.

Vec::into_iter disassembles the Vec into its raw parts; additionally, IntoIter keeps track of a separate pointer, which is incremented correspondingly as the iterator advances, while the length, or the count of elements, is decremented.

This also means that IntoIter takes the ownership of the backing buffer and is responsible to drop the remaining elements and free the backing buffer, if it's dropped.

---
 rust/kernel/alloc.rs      |    1 
 rust/kernel/alloc/kvec.rs |  170 ++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 171 insertions(+)
rust/kernel/alloc.rs +1 -0
@@ -20,6 +20,7 @@ pub use self::kbox::KBox;
 pub use self::kbox::KVBox;
 pub use self::kbox::VBox;
 
+pub use self::kvec::IntoIter;
 pub use self::kvec::KVVec;
 pub use self::kvec::KVec;
 pub use self::kvec::VVec;
rust/kernel/alloc/kvec.rs +170 -0

173 lines not on this page · raw message

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#73 lore raw

PATCH 37/60 rust: alloc: implement `collect` for `IntoIter`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 93e602310f87b7b515b86a8f919cc0799387e5c3 upstream.

Currently, we can't implement FromIterator. There are a couple of issues with this trait in the kernel, namely:

- Rust's specialization feature is unstable. This prevents us to optimize for the special case where I::IntoIter equals Vec's IntoIter type.
- We also can't use I::IntoIter's type ID either to work around this, since FromIterator doesn't require this type to be 'static.
- FromIterator::from_iter does return Self instead of Result<Self, AllocError>, hence we can't properly handle allocation failures.
- Neither Iterator::collect nor FromIterator::from_iter can handle additional allocation flags.

Instead, provide IntoIter::collect, such that we can at least convert IntoIter into a Vec again.

[ Added newline in documentation, changed case of section to be
consistent with an existing one, fixed typo. - Miguel ]

---
 rust/kernel/alloc/kvec.rs | 95 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 95 insertions(+)
rust/kernel/alloc/kvec.rs +95 -0
index 4ddc2ca6cd32..ae9d072741ce 100644
@@ -692,6 +692,101 @@ pub struct IntoIter<T, A: Allocator> {
     _p: PhantomData<A>,
 }
 
+impl<T, A> IntoIter<T, A>
+where
+    A: Allocator,
+{
+    fn into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize) {
+        let me = ManuallyDrop::new(self);
+        let ptr = me.ptr;
+        let buf = me.buf;
+        let len = me.len;
+        let cap = me.layout.len();
+        (ptr, buf, len, cap)
+    }
+
+    /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let v = kernel::kvec![1, 2, 3]?;
+    /// let mut it = v.into_iter();
+    ///
+    /// assert_eq!(it.next(), Some(1));
+    ///
+    /// let v = it.collect(GFP_KERNEL);
+    /// assert_eq!(v, [2, 3]);
+    ///
+    /// # Ok::<(), Error>(())
+    /// ```
+    ///
+    /// # Implementation details
+    ///
+    /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait
+    /// in the kernel, namely:
+    ///
+    /// - Rust's specialization feature is unstable. This prevents us to optimize for the special
+    ///   case where `I::IntoIter` equals `Vec`'s `IntoIter` type.
+    /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator`
+    ///   doesn't require this type to be `'static`.
+    /// - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence
+    ///   we can't properly handle allocation failures.
+    /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation
+    ///   flags.
+    ///
+    /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a
+    /// `Vec` again.
+    ///
+    /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing
+    /// buffer. However, this backing buffer may be shrunk to the actual count of elements.
+    pub fn collect(self, flags: Flags) -> Vec<T, A> {
+        let old_layout = self.layout;
+        let (mut ptr, buf, len, mut cap) = self.into_raw_parts();
+        let has_advanced = ptr != buf.as_ptr();
+
+        if has_advanced {
+            // Copy the contents we have advanced to at the beginning of the buffer.
+            //
+            // SAFETY:
+            // - `ptr` is valid for reads of `len * size_of::<T>()` bytes,
+            // - `buf.as_ptr()` is valid for writes of `len * size_of::<T>()` bytes,
+            // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to
+            //   each other,
+            // - both `ptr` and `buf.ptr()` are properly aligned.
+            unsafe { ptr::copy(ptr, buf.as_ptr(), len) };
+            ptr = buf.as_ptr();
+
+            // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()`.
+            let layout = unsafe { ArrayLayout::<T>::new_unchecked(len) };
+
+            // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be
+            // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves
+            // it as it is.
+            ptr = match unsafe {
+                A::realloc(Some(buf.cast()), layout.into(), old_layout.into(), flags)
+            } {
+                // If we fail to shrink, which likely can't even happen, continue with the existing
+                // buffer.
+                Err(_) => ptr,
+                Ok(ptr) => {
+                    cap = len;
+                    ptr.as_ptr().cast()
+                }
+            };
+        }
+
+        // SAFETY: If the iterator has been advanced, the advanced elements have been copied to
+        // the beginning of the buffer and `len` has been adjusted accordingly.
+        //
+        // - `ptr` is guaranteed to point to the start of the backing buffer.
+        // - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`.
+        // - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original
+        //   `Vec`.
+        unsafe { Vec::from_raw_parts(ptr, len, cap) }
+    }
+}
+
 impl<T, A> Iterator for IntoIter<T, A>
 where
     A: Allocator,
Signature · 1 line
2.48.1
maintainer Applied
#74 lore raw

Patch "rust: alloc: implement `collect` for `IntoIter`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement collect for IntoIter

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-collect-for-intoiter.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:20 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:44 +0100
Subject: rust: alloc: implement collect for IntoIter
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 93e602310f87b7b515b86a8f919cc0799387e5c3 upstream.

Currently, we can't implement FromIterator. There are a couple of issues with this trait in the kernel, namely:

- Rust's specialization feature is unstable. This prevents us to optimize for the special case where I::IntoIter equals Vec's IntoIter type.
- We also can't use I::IntoIter's type ID either to work around this, since FromIterator doesn't require this type to be 'static.
- FromIterator::from_iter does return Self instead of Result<Self, AllocError>, hence we can't properly handle allocation failures.
- Neither Iterator::collect nor FromIterator::from_iter can handle additional allocation flags.

Instead, provide IntoIter::collect, such that we can at least convert IntoIter into a Vec again.

[ Added newline in documentation, changed case of section to be
consistent with an existing one, fixed typo. - Miguel ]

---
 rust/kernel/alloc/kvec.rs |   95 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 95 insertions(+)
rust/kernel/alloc/kvec.rs +95 -0
@@ -692,6 +692,101 @@ pub struct IntoIter<T, A: Allocator> {
     _p: PhantomData<A>,
 }
 
+impl<T, A> IntoIter<T, A>
+where
+    A: Allocator,
+{
+    fn into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize) {
+        let me = ManuallyDrop::new(self);
+        let ptr = me.ptr;
+        let buf = me.buf;
+        let len = me.len;
+        let cap = me.layout.len();
+        (ptr, buf, len, cap)
+    }
+
+    /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let v = kernel::kvec![1, 2, 3]?;
+    /// let mut it = v.into_iter();
+    ///
+    /// assert_eq!(it.next(), Some(1));
+    ///
+    /// let v = it.collect(GFP_KERNEL);
+    /// assert_eq!(v, [2, 3]);
+    ///
+    /// # Ok::<(), Error>(())
+    /// ```
+    ///
+    /// # Implementation details
+    ///
+    /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait
+    /// in the kernel, namely:
+    ///
+    /// - Rust's specialization feature is unstable. This prevents us to optimize for the special
+    ///   case where `I::IntoIter` equals `Vec`'s `IntoIter` type.
+    /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator`
+    ///   doesn't require this type to be `'static`.
+    /// - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence
+    ///   we can't properly handle allocation failures.
+    /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation
+    ///   flags.
+    ///
+    /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a
+    /// `Vec` again.
+    ///
+    /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing
+    /// buffer. However, this backing buffer may be shrunk to the actual count of elements.
+    pub fn collect(self, flags: Flags) -> Vec<T, A> {
+        let old_layout = self.layout;
+        let (mut ptr, buf, len, mut cap) = self.into_raw_parts();
+        let has_advanced = ptr != buf.as_ptr();
+
+        if has_advanced {
+            // Copy the contents we have advanced to at the beginning of the buffer.
+            //
+            // SAFETY:
+            // - `ptr` is valid for reads of `len * size_of::<T>()` bytes,
+            // - `buf.as_ptr()` is valid for writes of `len * size_of::<T>()` bytes,
+            // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to
+            //   each other,
+            // - both `ptr` and `buf.ptr()` are properly aligned.
+            unsafe { ptr::copy(ptr, buf.as_ptr(), len) };
+            ptr = buf.as_ptr();
+
+            // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()`.
+            let layout = unsafe { ArrayLayout::<T>::new_unchecked(len) };
+
+            // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be
+            // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves
+            // it as it is.
+            ptr = match unsafe {
+                A::realloc(Some(buf.cast()), layout.into(), old_layout.into(), flags)
+            } {
+                // If we fail to shrink, which likely can't even happen, continue with the existing
+                // buffer.
+                Err(_) => ptr,
+                Ok(ptr) => {
+                    cap = len;
+                    ptr.as_ptr().cast()
+                }
+            };
+        }
+
+        // SAFETY: If the iterator has been advanced, the advanced elements have been copied to
+        // the beginning of the buffer and `len` has been adjusted accordingly.
+        //
+        // - `ptr` is guaranteed to point to the start of the backing buffer.
+        // - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`.
+        // - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original
+        //   `Vec`.
+        unsafe { Vec::from_raw_parts(ptr, len, cap) }
+    }
+}
+
 impl<T, A> Iterator for IntoIter<T, A>
 where
     A: Allocator,

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#75 lore raw

PATCH 38/60 rust: treewide: switch to the kernel `Vec` type

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 58eff8e872bd04ccb3adcf99aec7334ffad06cfd upstream.

Now that we got the kernel Vec in place, convert all existing Vec users to make use of it.

---
 mm/kasan/kasan_test_rust.rs   |  2 +-
 rust/kernel/str.rs            | 12 +++++-------
 rust/kernel/sync/locked_by.rs |  2 +-
 rust/kernel/types.rs          |  2 +-
 rust/kernel/uaccess.rs        | 17 +++++++----------
 rust/macros/lib.rs            |  6 +++---
 samples/rust/rust_minimal.rs  |  4 ++--
 7 files changed, 20 insertions(+), 25 deletions(-)
mm/kasan/kasan_test_rust.rs +1 -1
index 47bcf033dd4f..5b34edf30e72 100644
@@ -11,7 +11,7 @@
 /// drop the vector, and touch it.
 #[no_mangle]
 pub extern "C" fn kasan_test_rust_uaf() -> u8 {
-    let mut v: Vec<u8> = Vec::new();
+    let mut v: KVec<u8> = KVec::new();
     for _ in 0..4096 {
         v.push(0x42, GFP_KERNEL).unwrap();
     }
rust/kernel/str.rs +5 -7
index 66d4527f6c6f..6053bc7a98d1 100644
@@ -2,8 +2,7 @@
 
 //! String representations.
 
-use crate::alloc::{flags::*, vec_ext::VecExt, AllocError};
-use alloc::vec::Vec;
+use crate::alloc::{flags::*, AllocError, KVec};
 use core::fmt::{self, Write};
 use core::ops::{self, Deref, DerefMut, Index};
 
@@ -791,7 +790,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
 /// assert_eq!(s.is_ok(), false);
 /// ```
 pub struct CString {
-    buf: Vec<u8>,
+    buf: KVec<u8>,
 }
 
 impl CString {
@@ -804,7 +803,7 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
         let size = f.bytes_written();
 
         // Allocate a vector with the required number of bytes, and write to it.
-        let mut buf = <Vec<_> as VecExt<_>>::with_capacity(size, GFP_KERNEL)?;
+        let mut buf = KVec::with_capacity(size, GFP_KERNEL)?;
         // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes.
         let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
         f.write_fmt(args)?;
@@ -851,10 +850,9 @@ impl<'a> TryFrom<&'a CStr> for CString {
     type Error = AllocError;
 
     fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
-        let mut buf = Vec::new();
+        let mut buf = KVec::new();
 
-        <Vec<_> as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KERNEL)
-            .map_err(|_| AllocError)?;
+        buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?;
 
         // INVARIANT: The `CStr` and `CString` types have the same invariants for
         // the string data, and we copied it over without changes.
rust/kernel/sync/locked_by.rs +1 -1
index ce2ee8d87865..a7b244675c2b 100644
@@ -43,7 +43,7 @@
 /// struct InnerDirectory {
 ///     /// The sum of the bytes used by all files.
 ///     bytes_used: u64,
-///     _files: Vec<File>,
+///     _files: KVec<File>,
 /// }
 ///
 /// struct Directory {
rust/kernel/types.rs +1 -1
index c426c36a4db7..22b1faac874c 100644
@@ -135,7 +135,7 @@ unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {}
 /// # use kernel::types::ScopeGuard;
 /// fn example3(arg: bool) -> Result {
 ///     let mut vec =
-///         ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
+///         ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
 ///
 ///     vec.push(10u8, GFP_KERNEL)?;
 ///     if arg {
rust/kernel/uaccess.rs +7 -10
index e9347cff99ab..bc011061de45 100644
@@ -11,7 +11,6 @@
     prelude::*,
     types::{AsBytes, FromBytes},
 };
-use alloc::vec::Vec;
 use core::ffi::{c_ulong, c_void};
 use core::mem::{size_of, MaybeUninit};
 
@@ -46,7 +45,6 @@
 /// every byte in the region.
 ///
 /// ```no_run
-/// use alloc::vec::Vec;
 /// use core::ffi::c_void;
 /// use kernel::error::Result;
 /// use kernel::uaccess::{UserPtr, UserSlice};
@@ -54,7 +52,7 @@
 /// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> {
 ///     let (read, mut write) = UserSlice::new(uptr, len).reader_writer();
 ///
-///     let mut buf = Vec::new();
+///     let mut buf = KVec::new();
 ///     read.read_all(&mut buf, GFP_KERNEL)?;
 ///
 ///     for b in &mut buf {
@@ -69,7 +67,6 @@
 /// Example illustrating a TOCTOU (time-of-check to time-of-use) bug.
 ///
 /// ```no_run
-/// use alloc::vec::Vec;
 /// use core::ffi::c_void;
 /// use kernel::error::{code::EINVAL, Result};
 /// use kernel::uaccess::{UserPtr, UserSlice};
@@ -78,21 +75,21 @@
 /// fn is_valid(uptr: UserPtr, len: usize) -> Result<bool> {
 ///     let read = UserSlice::new(uptr, len).reader();
 ///
-///     let mut buf = Vec::new();
+///     let mut buf = KVec::new();
 ///     read.read_all(&mut buf, GFP_KERNEL)?;
 ///
 ///     todo!()
 /// }
 ///
 /// /// Returns the bytes behind this user pointer if they are valid.
-/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result<Vec<u8>> {
+/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result<KVec<u8>> {
 ///     if !is_valid(uptr, len)? {
 ///         return Err(EINVAL);
 ///     }
 ///
 ///     let read = UserSlice::new(uptr, len).reader();
 ///
-///     let mut buf = Vec::new();
+///     let mut buf = KVec::new();
 ///     read.read_all(&mut buf, GFP_KERNEL)?;
 ///
 ///     // THIS IS A BUG! The bytes could have changed since we checked them.
@@ -130,7 +127,7 @@ pub fn new(ptr: UserPtr, length: usize) -> Self {
     /// Reads the entirety of the user slice, appending it to the end of the provided buffer.
     ///
     /// Fails with [`EFAULT`] if the read happens on a bad address.
-    pub fn read_all(self, buf: &mut Vec<u8>, flags: Flags) -> Result {
+    pub fn read_all(self, buf: &mut KVec<u8>, flags: Flags) -> Result {
         self.reader().read_all(buf, flags)
     }
 
@@ -291,9 +288,9 @@ pub fn read<T: FromBytes>(&mut self) -> Result<T> {
     /// Reads the entirety of the user slice, appending it to the end of the provided buffer.
     ///
     /// Fails with [`EFAULT`] if the read happens on a bad address.
-    pub fn read_all(mut self, buf: &mut Vec<u8>, flags: Flags) -> Result {
+    pub fn read_all(mut self, buf: &mut KVec<u8>, flags: Flags) -> Result {
         let len = self.length;
-        VecExt::<u8>::reserve(buf, len, flags)?;
+        buf.reserve(len, flags)?;
 
         // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes
         // long.
rust/macros/lib.rs +3 -3
index 1f1d3a28032c..939ae00b723a 100644
@@ -242,7 +242,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream {
 /// #[pin_data]
 /// struct DriverData {
 ///     #[pin]
-///     queue: Mutex<Vec<Command>>,
+///     queue: Mutex<KVec<Command>>,
 ///     buf: KBox<[u8; 1024 * 1024]>,
 /// }
 /// ```
@@ -251,7 +251,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream {
 /// #[pin_data(PinnedDrop)]
 /// struct DriverData {
 ///     #[pin]
-///     queue: Mutex<Vec<Command>>,
+///     queue: Mutex<KVec<Command>>,
 ///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
@@ -281,7 +281,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream {
 /// #[pin_data(PinnedDrop)]
 /// struct DriverData {
 ///     #[pin]
-///     queue: Mutex<Vec<Command>>,
+///     queue: Mutex<KVec<Command>>,
 ///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
samples/rust/rust_minimal.rs +2 -2
index 2a9eaab62d1c..4aaf117bf8e3 100644
@@ -13,7 +13,7 @@
 }
 
 struct RustMinimal {
-    numbers: Vec<i32>,
+    numbers: KVec<i32>,
 }
 
 impl kernel::Module for RustMinimal {
@@ -21,7 +21,7 @@ fn init(_module: &'static ThisModule) -> Result<Self> {
         pr_info!("Rust minimal sample (init)\n");
         pr_info!("Am I built-in? {}\n", !cfg!(MODULE));
 
-        let mut numbers = Vec::new();
+        let mut numbers = KVec::new();
         numbers.push(72, GFP_KERNEL)?;
         numbers.push(108, GFP_KERNEL)?;
         numbers.push(200, GFP_KERNEL)?;
Signature · 1 line
2.48.1
maintainer Applied
#76 lore raw

Patch "rust: treewide: switch to the kernel `Vec` type" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: treewide: switch to the kernel Vec type

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-treewide-switch-to-the-kernel-vec-type.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:26 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:45 +0100
Subject: rust: treewide: switch to the kernel Vec type
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 58eff8e872bd04ccb3adcf99aec7334ffad06cfd upstream.

Now that we got the kernel Vec in place, convert all existing Vec users to make use of it.

---
 mm/kasan/kasan_test_rust.rs   |    2 +-
 rust/kernel/str.rs            |   12 +++++-------
 rust/kernel/sync/locked_by.rs |    2 +-
 rust/kernel/types.rs          |    2 +-
 rust/kernel/uaccess.rs        |   17 +++++++----------
 rust/macros/lib.rs            |    6 +++---
 samples/rust/rust_minimal.rs  |    4 ++--
 7 files changed, 20 insertions(+), 25 deletions(-)
mm/kasan/kasan_test_rust.rs +1 -1
@@ -11,7 +11,7 @@ use kernel::prelude::*;
 /// drop the vector, and touch it.
 #[no_mangle]
 pub extern "C" fn kasan_test_rust_uaf() -> u8 {
-    let mut v: Vec<u8> = Vec::new();
+    let mut v: KVec<u8> = KVec::new();
     for _ in 0..4096 {
         v.push(0x42, GFP_KERNEL).unwrap();
     }
rust/kernel/str.rs +5 -7
@@ -2,8 +2,7 @@
 
 //! String representations.
 
-use crate::alloc::{flags::*, vec_ext::VecExt, AllocError};
-use alloc::vec::Vec;
+use crate::alloc::{flags::*, AllocError, KVec};
 use core::fmt::{self, Write};
 use core::ops::{self, Deref, DerefMut, Index};
 
@@ -791,7 +790,7 @@ impl fmt::Write for Formatter {
 /// assert_eq!(s.is_ok(), false);
 /// ```
 pub struct CString {
-    buf: Vec<u8>,
+    buf: KVec<u8>,
 }
 
 impl CString {
@@ -804,7 +803,7 @@ impl CString {
         let size = f.bytes_written();
 
         // Allocate a vector with the required number of bytes, and write to it.
-        let mut buf = <Vec<_> as VecExt<_>>::with_capacity(size, GFP_KERNEL)?;
+        let mut buf = KVec::with_capacity(size, GFP_KERNEL)?;
         // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes.
         let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
         f.write_fmt(args)?;
@@ -851,10 +850,9 @@ impl<'a> TryFrom<&'a CStr> for CString {
     type Error = AllocError;
 
     fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
-        let mut buf = Vec::new();
+        let mut buf = KVec::new();
 
-        <Vec<_> as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KERNEL)
-            .map_err(|_| AllocError)?;
+        buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?;
 
         // INVARIANT: The `CStr` and `CString` types have the same invariants for
         // the string data, and we copied it over without changes.
rust/kernel/sync/locked_by.rs +1 -1
@@ -43,7 +43,7 @@ use core::{cell::UnsafeCell, mem::size_o
 /// struct InnerDirectory {
 ///     /// The sum of the bytes used by all files.
 ///     bytes_used: u64,
-///     _files: Vec<File>,
+///     _files: KVec<File>,
 /// }
 ///
 /// struct Directory {
rust/kernel/types.rs +1 -1
@@ -135,7 +135,7 @@ impl ForeignOwnable for () {
 /// # use kernel::types::ScopeGuard;
 /// fn example3(arg: bool) -> Result {
 ///     let mut vec =
-///         ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
+///         ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len()));
 ///
 ///     vec.push(10u8, GFP_KERNEL)?;
 ///     if arg {
rust/kernel/uaccess.rs +7 -10
@@ -11,7 +11,6 @@ use crate::{
     prelude::*,
     types::{AsBytes, FromBytes},
 };
-use alloc::vec::Vec;
 use core::ffi::{c_ulong, c_void};
 use core::mem::{size_of, MaybeUninit};
 
@@ -46,7 +45,6 @@ pub type UserPtr = usize;
 /// every byte in the region.
 ///
 /// ```no_run
-/// use alloc::vec::Vec;
 /// use core::ffi::c_void;
 /// use kernel::error::Result;
 /// use kernel::uaccess::{UserPtr, UserSlice};
@@ -54,7 +52,7 @@ pub type UserPtr = usize;
 /// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> {
 ///     let (read, mut write) = UserSlice::new(uptr, len).reader_writer();
 ///
-///     let mut buf = Vec::new();
+///     let mut buf = KVec::new();
 ///     read.read_all(&mut buf, GFP_KERNEL)?;
 ///
 ///     for b in &mut buf {
@@ -69,7 +67,6 @@ pub type UserPtr = usize;
 /// Example illustrating a TOCTOU (time-of-check to time-of-use) bug.
 ///
 /// ```no_run
-/// use alloc::vec::Vec;
 /// use core::ffi::c_void;
 /// use kernel::error::{code::EINVAL, Result};
 /// use kernel::uaccess::{UserPtr, UserSlice};
@@ -78,21 +75,21 @@ pub type UserPtr = usize;
 /// fn is_valid(uptr: UserPtr, len: usize) -> Result<bool> {
 ///     let read = UserSlice::new(uptr, len).reader();
 ///
-///     let mut buf = Vec::new();
+///     let mut buf = KVec::new();
 ///     read.read_all(&mut buf, GFP_KERNEL)?;
 ///
 ///     todo!()
 /// }
 ///
 /// /// Returns the bytes behind this user pointer if they are valid.
-/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result<Vec<u8>> {
+/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result<KVec<u8>> {
 ///     if !is_valid(uptr, len)? {
 ///         return Err(EINVAL);
 ///     }
 ///
 ///     let read = UserSlice::new(uptr, len).reader();
 ///
-///     let mut buf = Vec::new();
+///     let mut buf = KVec::new();
 ///     read.read_all(&mut buf, GFP_KERNEL)?;
 ///
 ///     // THIS IS A BUG! The bytes could have changed since we checked them.
@@ -130,7 +127,7 @@ impl UserSlice {
     /// Reads the entirety of the user slice, appending it to the end of the provided buffer.
     ///
     /// Fails with [`EFAULT`] if the read happens on a bad address.
-    pub fn read_all(self, buf: &mut Vec<u8>, flags: Flags) -> Result {
+    pub fn read_all(self, buf: &mut KVec<u8>, flags: Flags) -> Result {
         self.reader().read_all(buf, flags)
     }
 
@@ -291,9 +288,9 @@ impl UserSliceReader {
     /// Reads the entirety of the user slice, appending it to the end of the provided buffer.
     ///
     /// Fails with [`EFAULT`] if the read happens on a bad address.
-    pub fn read_all(mut self, buf: &mut Vec<u8>, flags: Flags) -> Result {
+    pub fn read_all(mut self, buf: &mut KVec<u8>, flags: Flags) -> Result {
         let len = self.length;
-        VecExt::<u8>::reserve(buf, len, flags)?;
+        buf.reserve(len, flags)?;
 
         // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes
         // long.
rust/macros/lib.rs +3 -3
@@ -242,7 +242,7 @@ pub fn concat_idents(ts: TokenStream) ->
 /// #[pin_data]
 /// struct DriverData {
 ///     #[pin]
-///     queue: Mutex<Vec<Command>>,
+///     queue: Mutex<KVec<Command>>,
 ///     buf: KBox<[u8; 1024 * 1024]>,
 /// }
 /// ```
@@ -251,7 +251,7 @@ pub fn concat_idents(ts: TokenStream) ->
 /// #[pin_data(PinnedDrop)]
 /// struct DriverData {
 ///     #[pin]
-///     queue: Mutex<Vec<Command>>,
+///     queue: Mutex<KVec<Command>>,
 ///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
@@ -281,7 +281,7 @@ pub fn pin_data(inner: TokenStream, item
 /// #[pin_data(PinnedDrop)]
 /// struct DriverData {
 ///     #[pin]
-///     queue: Mutex<Vec<Command>>,
+///     queue: Mutex<KVec<Command>>,
 ///     buf: KBox<[u8; 1024 * 1024]>,
 ///     raw_info: *mut Info,
 /// }
samples/rust/rust_minimal.rs +2 -2
@@ -13,7 +13,7 @@ module! {
 }
 
 struct RustMinimal {
-    numbers: Vec<i32>,
+    numbers: KVec<i32>,
 }
 
 impl kernel::Module for RustMinimal {
@@ -21,7 +21,7 @@ impl kernel::Module for RustMinimal {
         pr_info!("Rust minimal sample (init)\n");
         pr_info!("Am I built-in? {}\n", !cfg!(MODULE));
 
-        let mut numbers = Vec::new();
+        let mut numbers = KVec::new();
         numbers.push(72, GFP_KERNEL)?;
         numbers.push(108, GFP_KERNEL)?;
         numbers.push(200, GFP_KERNEL)?;

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#77 lore raw

PATCH 39/60 rust: alloc: remove `VecExt` extension

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 405966efc789888c3e1a53cd09d2c2b338064438 upstream.

Now that all existing Vec users were moved to the kernel Vec type, remove the VecExt extension.

---
 rust/kernel/alloc.rs         |   1 -
 rust/kernel/alloc/vec_ext.rs | 185 -----------------------------------
 rust/kernel/prelude.rs       |   5 +-
 3 files changed, 1 insertion(+), 190 deletions(-)
 delete mode 100644 rust/kernel/alloc/vec_ext.rs
rust/kernel/alloc.rs +0 -1
index 86d2077a8e64..7fc2e404e594 100644
@@ -7,7 +7,6 @@
 pub mod kbox;
 pub mod kvec;
 pub mod layout;
-pub mod vec_ext;
 
 #[cfg(any(test, testlib))]
 pub mod allocator_test;
rust/kernel/alloc/vec_ext.rs deleted +0 -185

185 lines not on this page · raw message

rust/kernel/prelude.rs +1 -4
index 80223cdaa485..07daccf6ca8e 100644
@@ -14,10 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
-
-#[doc(no_inline)]
-pub use alloc::vec::Vec;
+pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
 
 #[doc(no_inline)]
 pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable};
Signature · 1 line
2.48.1
maintainer Applied
#78 lore raw

Patch "rust: alloc: remove `VecExt` extension" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: remove VecExt extension

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-remove-vecext-extension.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:46 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:46 +0100
Subject: rust: alloc: remove VecExt extension
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 405966efc789888c3e1a53cd09d2c2b338064438 upstream.

Now that all existing Vec users were moved to the kernel Vec type, remove the VecExt extension.

---
 rust/kernel/alloc.rs         |    1 
 rust/kernel/alloc/vec_ext.rs |  185 -------------------------------------------
 rust/kernel/prelude.rs       |    5 -
 3 files changed, 1 insertion(+), 190 deletions(-)
 delete mode 100644 rust/kernel/alloc/vec_ext.rs
rust/kernel/alloc.rs +0 -1
@@ -7,7 +7,6 @@ pub mod allocator;
 pub mod kbox;
 pub mod kvec;
 pub mod layout;
-pub mod vec_ext;
 
 #[cfg(any(test, testlib))]
 pub mod allocator_test;
rust/kernel/alloc/vec_ext.rs deleted +0 -185

185 lines not on this page · raw message

rust/kernel/prelude.rs +1 -4
@@ -14,10 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
-
-#[doc(no_inline)]
-pub use alloc::vec::Vec;
+pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
 
 #[doc(no_inline)]
 pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable};

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#79 lore raw

PATCH 40/60 rust: alloc: add `Vec` to prelude

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 3145dc91c3c0ad945f06354385a6eb89d22becdb upstream.

Now that we removed VecExt and the corresponding includes in prelude.rs, add the new kernel Vec type instead.

---
 rust/kernel/prelude.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/prelude.rs +1 -1
index 07daccf6ca8e..8bdab9aa0d16 100644
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
+pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec};
 
 #[doc(no_inline)]
 pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable};
Signature · 1 line
2.48.1
maintainer Applied
#80 lore raw

Patch "rust: alloc: add `Vec` to prelude" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: add Vec to prelude

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-add-vec-to-prelude.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:37 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:47 +0100
Subject: rust: alloc: add Vec to prelude
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 3145dc91c3c0ad945f06354385a6eb89d22becdb upstream.

Now that we removed VecExt and the corresponding includes in prelude.rs, add the new kernel Vec type instead.

---
 rust/kernel/prelude.rs |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/prelude.rs +1 -1
@@ -14,7 +14,7 @@
 #[doc(no_inline)]
 pub use core::pin::Pin;
 
-pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec};
+pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec};
 
 #[doc(no_inline)]
 pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable};

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#81 lore raw

PATCH 41/60 rust: error: use `core::alloc::LayoutError`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 29a48d25ff53c183482dc88a99133a0fb5aa541a upstream.

Use core::alloc::LayoutError instead of alloc::alloc::LayoutError in preparation to get rid of Rust's alloc crate.

---
 rust/kernel/error.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/error.rs +1 -1
index be6509d5f4a4..aced2fe68b86 100644
@@ -6,7 +6,7 @@
 
 use crate::{alloc::AllocError, str::CStr};
 
-use alloc::alloc::LayoutError;
+use core::alloc::LayoutError;
 
 use core::fmt;
 use core::num::NonZeroI32;
Signature · 1 line
2.48.1
maintainer Applied
#82 lore raw

Patch "rust: error: use `core::alloc::LayoutError`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: error: use core::alloc::LayoutError

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-error-use-core-alloc-layouterror.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:38 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:48 +0100
Subject: rust: error: use core::alloc::LayoutError
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 29a48d25ff53c183482dc88a99133a0fb5aa541a upstream.

Use core::alloc::LayoutError instead of alloc::alloc::LayoutError in preparation to get rid of Rust's alloc crate.

---
 rust/kernel/error.rs |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/error.rs +1 -1
@@ -6,7 +6,7 @@
 
 use crate::{alloc::AllocError, str::CStr};
 
-use alloc::alloc::LayoutError;
+use core::alloc::LayoutError;
 
 use core::fmt;
 use core::num::NonZeroI32;

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#83 lore raw

PATCH 42/60 rust: error: check for config `test` in `Error::name`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 4a28ab469ff01855eb819dfd94754d1792f03f2a upstream.

Additional to testlib also check for test in Error::name. This is required by a subsequent patch that (indirectly) uses Error in test cases.

---
 rust/kernel/error.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/error.rs +2 -2
index aced2fe68b86..7cd3bbab52f2 100644
@@ -161,7 +161,7 @@ pub fn to_ptr<T>(self) -> *mut T {
     }
 
     /// Returns a string representing the error, if one exists.
-    #[cfg(not(testlib))]
+    #[cfg(not(any(test, testlib)))]
     pub fn name(&self) -> Option<&'static CStr> {
         // SAFETY: Just an FFI call, there are no extra safety requirements.
         let ptr = unsafe { bindings::errname(-self.0.get()) };
@@ -178,7 +178,7 @@ pub fn name(&self) -> Option<&'static CStr> {
     /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
     /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
     /// run in userspace.
-    #[cfg(testlib)]
+    #[cfg(any(test, testlib))]
     pub fn name(&self) -> Option<&'static CStr> {
         None
     }
Signature · 1 line
2.48.1
maintainer Applied
#84 lore raw

Patch "rust: error: check for config `test` in `Error::name`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: error: check for config test in Error::name

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-error-check-for-config-test-in-error-name.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:54 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:49 +0100
Subject: rust: error: check for config test in Error::name
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 4a28ab469ff01855eb819dfd94754d1792f03f2a upstream.

Additional to testlib also check for test in Error::name. This is required by a subsequent patch that (indirectly) uses Error in test cases.

---
 rust/kernel/error.rs |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/error.rs +2 -2
@@ -161,7 +161,7 @@ impl Error {
     }
 
     /// Returns a string representing the error, if one exists.
-    #[cfg(not(testlib))]
+    #[cfg(not(any(test, testlib)))]
     pub fn name(&self) -> Option<&'static CStr> {
         // SAFETY: Just an FFI call, there are no extra safety requirements.
         let ptr = unsafe { bindings::errname(-self.0.get()) };
@@ -178,7 +178,7 @@ impl Error {
     /// When `testlib` is configured, this always returns `None` to avoid the dependency on a
     /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still
     /// run in userspace.
-    #[cfg(testlib)]
+    #[cfg(any(test, testlib))]
     pub fn name(&self) -> Option<&'static CStr> {
         None
     }

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#85 lore raw

PATCH 43/60 rust: alloc: implement `contains` for `Flags`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 909037ce0369bc3f4fd31743fd2d8d7096f06002 upstream.

Provide a simple helper function to check whether given flags do contain one or multiple other flags.

This is used by a subsequent patch implementing the Cmalloc Allocator to check for __GFP_ZERO.

---
 rust/kernel/alloc.rs | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
rust/kernel/alloc.rs +6 -1
index 7fc2e404e594..049fca7a514d 100644
@@ -35,7 +35,7 @@
 /// They can be combined with the operators `|`, `&`, and `!`.
 ///
 /// Values can be used from the [`flags`] module.
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, PartialEq)]
 pub struct Flags(u32);
 
 impl Flags {
@@ -43,6 +43,11 @@ impl Flags {
     pub(crate) fn as_raw(self) -> u32 {
         self.0
     }
+
+    /// Check whether `flags` is contained in `self`.
+    pub fn contains(self, flags: Flags) -> bool {
+        (self & flags) == flags
+    }
 }
 
 impl core::ops::BitOr for Flags {
Signature · 1 line
2.48.1
maintainer Applied
#86 lore raw

Patch "rust: alloc: implement `contains` for `Flags`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement contains for Flags

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-contains-for-flags.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:55 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:50 +0100
Subject: rust: alloc: implement contains for Flags
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 909037ce0369bc3f4fd31743fd2d8d7096f06002 upstream.

Provide a simple helper function to check whether given flags do contain one or multiple other flags.

This is used by a subsequent patch implementing the Cmalloc Allocator to check for __GFP_ZERO.

---
 rust/kernel/alloc.rs |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
rust/kernel/alloc.rs +6 -1
@@ -35,7 +35,7 @@ use core::{alloc::Layout, ptr::NonNull};
 /// They can be combined with the operators `|`, `&`, and `!`.
 ///
 /// Values can be used from the [`flags`] module.
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, PartialEq)]
 pub struct Flags(u32);
 
 impl Flags {
@@ -43,6 +43,11 @@ impl Flags {
     pub(crate) fn as_raw(self) -> u32 {
         self.0
     }
+
+    /// Check whether `flags` is contained in `self`.
+    pub fn contains(self, flags: Flags) -> bool {
+        (self & flags) == flags
+    }
 }
 
 impl core::ops::BitOr for Flags {

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#87 lore raw

PATCH 44/60 rust: alloc: implement `Cmalloc` in module allocator_test

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit dd09538fb4093176a818fcecd45114430cc5840f upstream.

So far the kernel's Box and Vec types can't be used by userspace test cases, since all users of those types (e.g. CString) use kernel allocators for instantiation.

In order to allow userspace test cases to make use of such types as well, implement the Cmalloc allocator within the allocator_test module and type alias all kernel allocators to Cmalloc. The Cmalloc allocator uses libc's realloc() function as allocator backend.

[ Removed the temporary allow(dead_code) as discussed in the list and
fixed typo, added backticks. - Miguel ]

---
 rust/kernel/alloc.rs                |  1 -
 rust/kernel/alloc/allocator_test.rs | 89 ++++++++++++++++++++++++++---
 2 files changed, 81 insertions(+), 9 deletions(-)
rust/kernel/alloc.rs +0 -1
index 049fca7a514d..c6024afa3739 100644
@@ -215,7 +215,6 @@ unsafe fn free(ptr: NonNull<u8>, layout: Layout) {
     }
 }
 
-#[allow(dead_code)]
 /// Returns a properly aligned dangling pointer from the given `layout`.
 pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> {
     let ptr = layout.align() as *mut u8;
rust/kernel/alloc/allocator_test.rs +81 -8

103 lines not on this page · raw message

Signature · 1 line
2.48.1
maintainer Applied
#88 lore raw

Patch "rust: alloc: implement `Cmalloc` in module allocator_test" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: implement Cmalloc in module allocator_test

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-implement-cmalloc-in-module-allocator_test.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:44 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:51 +0100
Subject: rust: alloc: implement Cmalloc in module allocator_test
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit dd09538fb4093176a818fcecd45114430cc5840f upstream.

So far the kernel's Box and Vec types can't be used by userspace test cases, since all users of those types (e.g. CString) use kernel allocators for instantiation.

In order to allow userspace test cases to make use of such types as well, implement the Cmalloc allocator within the allocator_test module and type alias all kernel allocators to Cmalloc. The Cmalloc allocator uses libc's realloc() function as allocator backend.

[ Removed the temporary allow(dead_code) as discussed in the list and
fixed typo, added backticks. - Miguel ]

---
 rust/kernel/alloc.rs                |    1 
 rust/kernel/alloc/allocator_test.rs |   89 ++++++++++++++++++++++++++++++++----
 2 files changed, 81 insertions(+), 9 deletions(-)
rust/kernel/alloc.rs +0 -1
@@ -215,7 +215,6 @@ pub unsafe trait Allocator {
     }
 }
 
-#[allow(dead_code)]
 /// Returns a properly aligned dangling pointer from the given `layout`.
 pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull<u8> {
     let ptr = layout.align() as *mut u8;
rust/kernel/alloc/allocator_test.rs +81 -8

103 lines not on this page · raw message

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#89 lore raw

PATCH 45/60 rust: str: test: replace `alloc::format`

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit eb6f92cd3f755c179204ea1f933b07cf992892fd upstream.

The current implementation of tests in str.rs use format! to format strings for comparison, which, internally, creates a new String.

In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement format! for CString.

Note that for userspace tests, Kmalloc, which is backing CString's memory, is just a type alias to Cmalloc.

---
 rust/kernel/str.rs | 23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)
rust/kernel/str.rs +22 -1
index 6053bc7a98d1..aff6baa521d4 100644
@@ -524,7 +524,28 @@ macro_rules! c_str {
 #[cfg(test)]
 mod tests {
     use super::*;
-    use alloc::format;
+
+    struct String(CString);
+
+    impl String {
+        fn from_fmt(args: fmt::Arguments<'_>) -> Self {
+            String(CString::try_from_fmt(args).unwrap())
+        }
+    }
+
+    impl Deref for String {
+        type Target = str;
+
+        fn deref(&self) -> &str {
+            self.0.to_str().unwrap()
+        }
+    }
+
+    macro_rules! format {
+        ($($f:tt)*) => ({
+            &*String::from_fmt(kernel::fmt!($($f)*))
+        })
+    }
 
     const ALL_ASCII_CHARS: &'static str =
         "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\
Signature · 1 line
2.48.1
maintainer Applied
#90 lore raw

Patch "rust: str: test: replace `alloc::format`" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: str: test: replace alloc::format

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-str-test-replace-alloc-format.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:58 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:52 +0100
Subject: rust: str: test: replace alloc::format
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit eb6f92cd3f755c179204ea1f933b07cf992892fd upstream.

The current implementation of tests in str.rs use format! to format strings for comparison, which, internally, creates a new String.

In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement format! for CString.

Note that for userspace tests, Kmalloc, which is backing CString's memory, is just a type alias to Cmalloc.

---
 rust/kernel/str.rs |   23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)
rust/kernel/str.rs +22 -1
@@ -524,7 +524,28 @@ macro_rules! c_str {
 #[cfg(test)]
 mod tests {
     use super::*;
-    use alloc::format;
+
+    struct String(CString);
+
+    impl String {
+        fn from_fmt(args: fmt::Arguments<'_>) -> Self {
+            String(CString::try_from_fmt(args).unwrap())
+        }
+    }
+
+    impl Deref for String {
+        type Target = str;
+
+        fn deref(&self) -> &str {
+            self.0.to_str().unwrap()
+        }
+    }
+
+    macro_rules! format {
+        ($($f:tt)*) => ({
+            &*String::from_fmt(kernel::fmt!($($f)*))
+        })
+    }
 
     const ALL_ASCII_CHARS: &'static str =
         "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch

author maintainer
#91 lore raw

PATCH 46/60 rust: alloc: update module comment of alloc.rs

In reply to Miguel Ojeda

From: Danilo Krummrich <[email protected]>

commit 8ae740c3917ff92108df17236b3cf1b9a74bd359 upstream.

Before we remove Rust's alloc crate, rewrite the module comment in alloc.rs to avoid a rustdoc warning.

Besides that, the module comment in alloc.rs isn't correct anymore, we're no longer extending Rust's alloc crate.

---
 rust/kernel/alloc.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/alloc.rs +1 -1
index c6024afa3739..f2f7f3a53d29 100644
@@ -1,6 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 
-//! Extensions to the [`alloc`] crate.
+//! Implementation of the kernel's memory allocation infrastructure.
 
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;
Signature · 1 line
2.48.1
maintainer Applied
#92 lore raw

Patch "rust: alloc: update module comment of alloc.rs" has been added to the 6.12-stable tree

This is a note to let you know that I've just added the patch titled

rust: alloc: update module comment of alloc.rs

to the 6.12-stable tree which can be found at:
http://www.kernel.org/git/?p=linux/kernel/git/stable/stable-queue.git;a=summary

The filename of the patch is:
rust-alloc-update-module-comment-of-alloc.rs.patch
and it can be found in the queue-6.12 subdirectory.

If you, or anyone else, feels it should not be added to the stable tree, please let <[email protected]> know about it.

From [email protected] Fri Mar 7 23:52:59 2025
From: Miguel Ojeda <[email protected]>
Date: Fri, 7 Mar 2025 23:49:53 +0100
Subject: rust: alloc: update module comment of alloc.rs
To: Greg Kroah-Hartman <[email protected]>, Sasha Levin <[email protected]>, [email protected]
Cc: Danilo Krummrich <[email protected]>, Alice Ryhl <[email protected]>, Alyssa Ross <[email protected]>, NoisyCoil <[email protected]>, [email protected], Miguel Ojeda <[email protected]>
Message-ID: <[email protected]>

From: Danilo Krummrich <[email protected]>

commit 8ae740c3917ff92108df17236b3cf1b9a74bd359 upstream.

Before we remove Rust's alloc crate, rewrite the module comment in alloc.rs to avoid a rustdoc warning.

Besides that, the module comment in alloc.rs isn't correct anymore, we're no longer extending Rust's alloc crate.

---
 rust/kernel/alloc.rs |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/alloc.rs +1 -1
@@ -1,6 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 
-//! Extensions to the [`alloc`] crate.
+//! Implementation of the kernel's memory allocation infrastructure.
 
 #[cfg(not(any(test, testlib)))]
 pub mod allocator;

Patches currently in stable-queue which might be from [email protected] are

queue-6.12/drm-panic-avoid-reimplementing-iterator-find.patch queue-6.12/documentation-rust-add-coding-guidelines-on-lints.patch queue-6.12/rust-provide-proper-code-documentation-titles.patch queue-6.12/rust-alloc-make-allocator-module-public.patch queue-6.12/rust-alloc-remove-vecext-extension.patch queue-6.12/rust-alloc-implement-reallocfunc.patch queue-6.12/rust-alloc-separate-aligned_size-from-krealloc_aligned.patch queue-6.12/rust-enable-clippy-unnecessary_safety_comment-lint.patch queue-6.12/rust-alloc-update-module-comment-of-alloc.rs.patch queue-6.12/rust-kbuild-expand-rusttest-target-for-macros.patch queue-6.12/rust-error-use-core-alloc-layouterror.patch queue-6.12/rust-str-test-replace-alloc-format.patch queue-6.12/loongarch-use-asm_reachable.patch queue-6.12/rust-alloc-implement-allocator-for-kmalloc.patch queue-6.12/rust-alloc-implement-collect-for-intoiter.patch queue-6.12/rust-alloc-introduce-arraylayout.patch queue-6.12/rust-alloc-implement-vmalloc-allocator.patch queue-6.12/documentation-rust-discuss-in-the-guidelines.patch queue-6.12/rust-error-check-for-config-test-in-error-name.patch queue-6.12/rust-enable-clippy-ignored_unit_patterns-lint.patch queue-6.12/rust-enable-clippy-unnecessary_safety_doc-lint.patch queue-6.12/rust-alloc-add-box-to-prelude.patch queue-6.12/kbuild-rust-remove-the-alloc-crate-and-globalalloc.patch queue-6.12/rust-alloc-add-allocator-trait.patch queue-6.12/rust-treewide-switch-to-our-kernel-box-type.patch queue-6.12/rust-introduce-.clippy.toml.patch queue-6.12/rust-alloc-rename-kernelallocator-to-kmalloc.patch queue-6.12/rust-alloc-implement-cmalloc-in-module-allocator_test.patch queue-6.12/drm-panic-allow-verbose-version-check.patch queue-6.12/rust-map-__kernel_size_t-and-friends-also-to-usize-isize.patch queue-6.12/rust-alloc-add-module-allocator_test.patch queue-6.12/rust-replace-clippy-dbg_macro-with-disallowed_macros.patch queue-6.12/rust-alloc-add-__gfp_nowarn-to-flags.patch queue-6.12/rust-enable-clippy-s-check-private-items.patch queue-6.12/rust-error-make-conversion-functions-public.patch queue-6.12/rust-sort-global-rust-flags.patch queue-6.12/rust-alloc-implement-contains-for-flags.patch queue-6.12/rust-init-remove-unneeded.patch queue-6.12/rust-use-custom-ffi-integer-types.patch queue-6.12/rust-sync-remove-unneeded.patch queue-6.12/rust-treewide-switch-to-the-kernel-vec-type.patch queue-6.12/rust-alloc-implement-kvmalloc-allocator.patch queue-6.12/drm-panic-correctly-indent-continuation-of-line-in-list-item.patch queue-6.12/rust-alloc-implement-kernel-vec-type.patch queue-6.12/rust-workqueue-remove-unneeded.patch queue-6.12/rust-error-optimize-error-type-to-use-nonzero.patch queue-6.12/drm-panic-remove-unnecessary-borrow-in-alignment_pattern.patch queue-6.12/rust-alloc-remove-extension-of-std-s-box.patch queue-6.12/rust-block-fix-formatting-in-gendisk-doc.patch queue-6.12/rust-enable-rustdoc-unescaped_backticks-lint.patch queue-6.12/rust-fix-size_t-in-bindgen-prototypes-of-c-builtins.patch queue-6.12/rust-enable-clippy-undocumented_unsafe_blocks-lint.patch queue-6.12/rust-alloc-add-vec-to-prelude.patch queue-6.12/rust-alloc-implement-intoiterator-for-vec.patch queue-6.12/rust-alloc-implement-kernel-box.patch queue-6.12/drm-panic-remove-redundant-field-when-assigning-value.patch queue-6.12/rust-types-avoid-repetition-in-as-from-bytes-impls.patch queue-6.12/rust-start-using-the-attribute.patch queue-6.12/drm-panic-allow-verbose-boolean-for-clarity.patch queue-6.12/maintainers-add-entry-for-the-rust-alloc-module.patch queue-6.12/rust-alloc-fix-arraylayout-allocations.patch queue-6.12/drm-panic-prefer-eliding-lifetimes.patch