Commit graph

833 commits

Author SHA1 Message Date
Miguel Ojeda
897d1df653 rust: add kunit_tests to the prelude
It is convenient to have certain things in the `kernel` prelude, and
means kernel developers will find it even easier to start writing tests.

And, anyway, nobody should need to use this identifier for anything else.

Thus add it to the prelude.

Reviewed-by: David Gow <davidgow@google.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250502215133.1923676-4-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-27 20:09:59 +02:00
Miguel Ojeda
950b306c29 rust: kunit: support checked -> Results in KUnit #[test]s
Currently, return values of KUnit `#[test]` functions are ignored.

Thus introduce support for `-> Result` functions by checking their
returned values.

At the same time, require that test functions return `()` or `Result<T,
E>`, which should avoid mistakes, especially with non-`#[must_use]`
types. Other types can be supported in the future if needed.

With this, a failing test like:

    #[test]
    fn my_test() -> Result {
        f()?;
        Ok(())
    }

will output:

    [    3.744214]     KTAP version 1
    [    3.744287]     # Subtest: my_test_suite
    [    3.744378]     # speed: normal
    [    3.744399]     1..1
    [    3.745817]     # my_test: ASSERTION FAILED at rust/kernel/lib.rs:321
    [    3.745817]     Expected is_test_result_ok(my_test()) to be true, but is false
    [    3.747152]     # my_test.speed: normal
    [    3.747199]     not ok 1 my_test
    [    3.747345] not ok 4 my_test_suite

Reviewed-by: David Gow <davidgow@google.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250502215133.1923676-3-ojeda@kernel.org
[ Used `::kernel` for paths. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-27 20:09:59 +02:00
Miguel Ojeda
36174d16f3 rust: kunit: support KUnit-mapped assert! macros in #[test]s
The KUnit `#[test]` support that landed recently is very basic and does
not map the `assert*!` macros into KUnit like the doctests do, so they
panic at the moment.

Thus implement the custom mapping in a similar way to doctests, reusing
the infrastructure there.

In Rust 1.88.0, the `file()` method in `Span` may be stable [1]. However,
it was changed recently (from `SourceFile`), so we need to do something
different in previous versions. Thus create a helper for it and use it
to get the path.

With this, a failing test suite like:

    #[kunit_tests(my_test_suite)]
    mod tests {
        use super::*;

        #[test]
        fn my_first_test() {
            assert_eq!(42, 43);
        }

        #[test]
        fn my_second_test() {
            assert!(42 >= 43);
        }
    }

will properly map back to KUnit, printing something like:

    [    1.924325]     KTAP version 1
    [    1.924421]     # Subtest: my_test_suite
    [    1.924506]     # speed: normal
    [    1.924525]     1..2
    [    1.926385]     # my_first_test: ASSERTION FAILED at rust/kernel/lib.rs:251
    [    1.926385]     Expected 42 == 43 to be true, but is false
    [    1.928026]     # my_first_test.speed: normal
    [    1.928075]     not ok 1 my_first_test
    [    1.928723]     # my_second_test: ASSERTION FAILED at rust/kernel/lib.rs:256
    [    1.928723]     Expected 42 >= 43 to be true, but is false
    [    1.929834]     # my_second_test.speed: normal
    [    1.929868]     not ok 2 my_second_test
    [    1.930032] # my_test_suite: pass:0 fail:2 skip:0 total:2
    [    1.930153] # Totals: pass:0 fail:2 skip:0 total

Link: https://github.com/rust-lang/rust/pull/140514 [1]
Reviewed-by: David Gow <davidgow@google.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250502215133.1923676-2-ojeda@kernel.org
[ Required `KUNIT=y` like for doctests. Used the `cfg_attr` from the
  TODO comment and clarified its comment now that the stabilization is
  in beta and thus quite likely stable in Rust 1.88.0. Simplified the
  `new_body` code by introducing a new variable. Added
  `#[allow(clippy::incompatible_msrv)]`. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-27 20:07:09 +02:00
Viresh Kumar
15bc5c00d1 rust: opp: Move cfg(CONFIG_OF) attribute to the top of doc test
Move the `#[cfg(CONFIG_OF)]` attribute to the top of the documentation test
block and hide it. This applies the condition to the entire test and improves
readability.

Placing configuration flags like `CONFIG_OF` at the top serves as a clear
indicator of the conditions under which the example is valid, effectively
acting like configuration metadata for the example itself.

Suggested-by: Miguel Ojeda <miguel.ojeda.sandonis@gmail.com>
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
Link: https://patch.msgid.link/9d93c783cc4419f16dd8942a4359d74bc0149203.1748323971.git.viresh.kumar@linaro.org
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
2025-05-27 15:29:17 +02:00
Linus Torvalds
07046958f6 RCU pull request for v6.16
Summary of changes:
 - Removed swake_up_one_online() workaround
 - Reverted an incorrect rcuog wake-up fix from offline softirq
 - Rust RCU Guard methods marked as inline
 - Updated MAINTAINERS with Joel’s and Zqiang's new email address
 - Replaced magic constant in rcu_seq_done_exact() with named constant
 - Added warning mechanism to validate rcu_seq_done_exact()
 - Switched SRCU polling API to use rcu_seq_done_exact()
 - Commented on redundant delta check in rcu_seq_done_exact()
 - Made ->gpwrap tests in rcutorture more frequent
 - Fixed reuse of ARM64 images in rcutorture
 - rcutorture improved to check Kconfig and reader conflict handling
 - Extracted logic from rcu_torture_one_read() for clarity
 - Updated LWN RCU API documentation links
 - Enabled --do-rt in torture.sh for CONFIG_PREEMPT_RT
 - Added tests for SRCU up/down reader primitives
 - Added comments and delays checks in rcutorture
 - Deprecated srcu_read_lock_lite() and srcu_read_unlock_lite() via checkpatch
 - Added --do-normal and --do-no-normal to torture.sh
 - Added RCU Rust binding tests to torture.sh
 - Reduced CPU overcommit and removed MAXSMP/CPUMASK_OFFSTACK in TREE01
 - Replaced kmalloc() with kcalloc() in rcuscale
 - Refined listRCU example code for stale data elimination
 - Fixed hardirq count bug for x86 in cpu_stall_cputime
 - Added safety checks in rcu/nocb for offloaded rdp access
 - Other miscellaneous changes
 -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEcoCIrlGe4gjE06JJqA4nf2o45hAFAmgoF5oACgkQqA4nf2o4
 5hDvVw//TNsJ/g0HTMu02uXMmtFIrgvpTnH7OEGJ+2p/KErrmWYsBJQw41ueLAQL
 Drtq3q9888UFF5LLA43HC88DFmT9uV8V8TmmURH+pZWdmJY1Ekn8UBSBhDPGGpC5
 sGIO2jJKjHN8G7fyJKoPtL9jxKSulHF/XQTIL2pP23jopAIwosoCHVAwGvnGVvBC
 smXfMSu+bd3IifNFroodsqjVXgnNQwWUNboOkz0KfkiiosgZsWWW8DaM3NGjdp+C
 tUHLs1zfC6sgJUjdpokTE3TcNudlMgVlB2Quj5jhh1YvsvedgIJXl4wpR6JVutyN
 F9awKt1AZkyZ+cTp+JpohaWaN9aKfNNG7jZ+rxQ0VcuRh35wmBJtiWNjEtJ38R82
 kTC1RI7MEus+6OZRt92jv5TNSa9t3wHbi5fBjNRiQ8PYq5cibZy7Lyrj2JOK7Zqs
 pgmdUnhQH2Uhf52b+clG5hWO55gEtACY8pin6kNewClcRtz04Jew7gkiYDGka4F4
 EXbuDHSWi25eSb3FzT2BqR72OZcJ0kv747OTp+2yTv2TaBA5p+OD8hvL/WbWC2Ok
 DK1YQ4RgEerTSZ4PbgPtWkNnlf6xjdWBaYNwmo+G/DgfjPoTOy1Jp73Z4b1AqSB5
 IPEQy1d/799QgGTYkbrvRtvWHg8yfOMz3ByZoHg31rafr0AsrXM=
 =6mun
 -----END PGP SIGNATURE-----

Merge tag 'next.2025.05.17a' of git://git.kernel.org/pub/scm/linux/kernel/git/rcu/linux

Pull RCU updates from Joel Fernandes:
 - Removed swake_up_one_online() workaround
 - Reverted an incorrect rcuog wake-up fix from offline softirq
 - Rust RCU Guard methods marked as inline
 - Updated MAINTAINERS with Joel’s and Zqiang's new email address
 - Replaced magic constant in rcu_seq_done_exact() with named constant
 - Added warning mechanism to validate rcu_seq_done_exact()
 - Switched SRCU polling API to use rcu_seq_done_exact()
 - Commented on redundant delta check in rcu_seq_done_exact()
 - Made ->gpwrap tests in rcutorture more frequent
 - Fixed reuse of ARM64 images in rcutorture
 - rcutorture improved to check Kconfig and reader conflict handling
 - Extracted logic from rcu_torture_one_read() for clarity
 - Updated LWN RCU API documentation links
 - Enabled --do-rt in torture.sh for CONFIG_PREEMPT_RT
 - Added tests for SRCU up/down reader primitives
 - Added comments and delays checks in rcutorture
 - Deprecated srcu_read_lock_lite() and srcu_read_unlock_lite() via checkpatch
 - Added --do-normal and --do-no-normal to torture.sh
 - Added RCU Rust binding tests to torture.sh
 - Reduced CPU overcommit and removed MAXSMP/CPUMASK_OFFSTACK in TREE01
 - Replaced kmalloc() with kcalloc() in rcuscale
 - Refined listRCU example code for stale data elimination
 - Fixed hardirq count bug for x86 in cpu_stall_cputime
 - Added safety checks in rcu/nocb for offloaded rdp access
 - Other miscellaneous changes

* tag 'next.2025.05.17a' of git://git.kernel.org/pub/scm/linux/kernel/git/rcu/linux: (27 commits)
  rcutorture: Fix issue with re-using old images on ARM64
  rcutorture: Remove MAXSMP and CPUMASK_OFFSTACK from TREE01
  rcutorture: Reduce TREE01 CPU overcommit
  torture: Check for "Call trace:" as well as "Call Trace:"
  rcutorture: Perform more frequent testing of ->gpwrap
  torture: Add testing of RCU's Rust bindings to torture.sh
  torture: Add --do-{,no-}normal to torture.sh
  checkpatch: Deprecate srcu_read_lock_lite() and srcu_read_unlock_lite()
  rcutorture: Comment invocations of tick_dep_set_task()
  rcu/nocb: Add Safe checks for access offloaded rdp
  rcuscale: using kcalloc() to relpace kmalloc()
  doc/RCU/listRCU: refine example code for eliminating stale data
  doc: Update LWN RCU API links in whatisRCU.rst
  Revert "rcu/nocb: Fix rcuog wake-up from offline softirq"
  rust: sync: rcu: Mark Guard methods as inline
  rcu/cpu_stall_cputime: fix the hardirq count for x86 architecture
  rcu: Remove swake_up_one_online() bandaid
  MAINTAINERS: Update Zqiang's email address
  rcutorture: Make torture.sh --do-rt use CONFIG_PREEMPT_RT
  srcu: Use rcu_seq_done_exact() for polling API
  ...
2025-05-26 14:20:50 -07:00
Linus Torvalds
a56d3133bd configfs-for-v6.16
-----BEGIN PGP SIGNATURE-----
 
 iQJKBAABCAA0FiEEEsH5R1a/fCoV1sAS4bgaPnkoY3cFAmgm4zAWHGEuaGluZGJv
 cmdAa2VybmVsLm9yZwAKCRDhuBo+eShjd8+nD/4xLZRdP5/Sq8boG/ZjPwja8ATv
 MjSrakeOHFPJx+ac/QNmhkWmVQrpazA72YU9NN5VL9UdM+eFHJ4EmFIUQFcKsYhU
 edj5Fyegc2/CzY4wPcJQcY4ck9n6xoWqR//75uEtHRfMVAwJguQ7/qg7XR+Skhy7
 RSuJ96qi2uf6ktrZUGVilkF+tjhg0j9eoiJUnU+2d5khT/vqlezv/x6xC1Vxr5WK
 JgsIhg9NzEc3BjZotmurZ7WaAIFey83ta8r7fwQM+SfSqMbLbdXu3XNQ5v9MBbBO
 YDsxl2LD2ukCzucbY5h6/h1TjQ+IBUSx9ExEq0ATG46HzMGBc7EFMYb3Q2klaSX2
 lfK5YKvZVFPZUp1Yr94+YIvyhU6g0dtDELOBVB5lj1FHv7wqDOUY9wofh+tLgyMT
 PTp/sYHc7UUvPghFMNhrkbGaIrUI2fRZviTgAJGOp2zE2gvV2lz4Jg9UvBkbpezc
 q8X6xx+3r1dj5MhlrjeLifLWiXaZhumT2D5TEwYl3LjKLzekFKCMoqJ5eqFPSty9
 vvp5uBk7siErAlAi3xq19HWmrGoacMg0tPqe9QElkA2jzBzNBcEdo7NQAAOzjkg+
 NA58fKyrcmKrI7Y1NQmHTmx1RIUOWPXyW7ddZS8CGgsDzlVH35gIBPFqmj235tSq
 67Rtb/Iev7KtPL0z8w==
 =d1MQ
 -----END PGP SIGNATURE-----

Merge tag 'configfs-for-v6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/a.hindborg/linux

Pull configfs updates from Andreas Hindborg:

 - Allow creation of rw files with custom permissions. This allows
   drivers to better protect secrets written through configfs

 - Fix a bug where an error condition did not cause an early return
   while populating attributes

 - Report ENOMEM rather than EFAULT when kvasprintf() fails in
   config_item_set_name()

 - Add a Rust API for configfs. This allows Rust drivers to use configfs
   through a memory safe interface

* tag 'configfs-for-v6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/a.hindborg/linux:
  MAINTAINERS: add configfs Rust abstractions
  rust: configfs: add a sample demonstrating configfs usage
  rust: configfs: introduce rust support for configfs
  configfs: Correct error value returned by API config_item_set_name()
  configfs: Do not override creating attribute file failure in populate_attrs()
  configfs: Delete semicolon from macro type_print() definition
  configfs: Add CONFIGFS_ATTR_PERM helper
2025-05-26 12:28:55 -07:00
Patrick Miller
4bf7b97eb3 rust: make section names plural
Clean Rust documentation section headers to use plural names.

Suggested-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://github.com/Rust-for-Linux/linux/issues/1110
Signed-off-by: Patrick Miller <paddymills@proton.me>
Link: https://lore.kernel.org/r/20241002022749.390836-1-paddymills@proton.me
[ Removed the `init` one that doesn't apply anymore and
  reworded slightly. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-26 18:03:09 +02:00
Benno Lossin
eb71feaaca rust: list: fix path of assert_pinned!
Commit dbd5058ba6 ("rust: make pin-init its own crate") moved all
items from pin-init into the pin-init crate, including the
`assert_pinned!` macro.

Thus fix the path of the sole user of the `assert_pinned!` macro.

This occurrence was missed in the commit above, since it is in a macro
rule that has no current users (although binder is a future user).

Cc: stable@kernel.org
Fixes: dbd5058ba6 ("rust: make pin-init its own crate")
Signed-off-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250525173450.853413-1-lossin@kernel.org
[ Reworded slightly as discussed in the list. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-26 17:43:53 +02:00
Viresh Kumar
21d8a6857b rust: opp: Make the doctest example depend on CONFIG_OF
The doctest example uses a function only available for CONFIG_OF and so
the build with doc tests fails when it isn't enabled.

  error[E0599]: no function or associated item named `from_of_cpumask`
  found for struct `rust_doctest_kernel_alloc_kbox_rs_4::kernel::opp::Table`
  in the current scope

Fix this by making the doctest depend on CONFIG_OF.

Reported-by: kernel test robot <lkp@intel.com>
Closes: https://lore.kernel.org/oe-kbuild-all/202505260856.ZQWHW2xT-lkp@intel.com/
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
Link: https://patch.msgid.link/a80bfedcb4d94531dc27d3b48062db5042078e88.1748237646.git.viresh.kumar@linaro.org
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
2025-05-26 13:07:23 +02:00
Miguel Ojeda
df523db15a rust: dma: add missing Markdown code span
Add missing Markdown code span.

This was found using the Clippy `doc_markdown` lint, which we may want
to enable.

Fixes: ad2907b4e3 ("rust: add dma coherent allocator abstraction")
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250324210359.1199574-6-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-25 22:58:36 +02:00
Miguel Ojeda
f54c750333 rust: task: add missing Markdown code spans and intra-doc links
Add missing Markdown code spans and also convert them into intra-doc
links.

This was found using the Clippy `doc_markdown` lint, which we may want
to enable.

Fixes: e0020ba6cb ("rust: add PidNamespace")
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20250324210359.1199574-10-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-25 22:58:35 +02:00
Miguel Ojeda
1dbaf8b1ba rust: pci: fix docs related to missing Markdown code spans
In particular:

  - Add missing Markdown code spans.

  - Improve title for `DeviceId`, adding a link to the struct in the
    C side, rather than referring to `bindings::`.

  - Convert `TODO` from documentation to a normal comment, and put code
    in block.

This was found using the Clippy `doc_markdown` lint, which we may want
to enable.

Fixes: 1bd8b6b2c5 ("rust: pci: add basic PCI device / driver abstractions")
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250324210359.1199574-8-ojeda@kernel.org
[ Prefixed link text with `struct`. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-25 22:58:35 +02:00
Miguel Ojeda
abd21a163d rust: alloc: add missing Markdown code span
Add missing Markdown code span.

This was found using the Clippy `doc_markdown` lint, which we may want
to enable.

Fixes: dd09538fb4 ("rust: alloc: implement `Cmalloc` in module allocator_test")
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250324210359.1199574-5-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-25 22:58:35 +02:00
Miguel Ojeda
673ec360cf rust: alloc: add missing Markdown code spans
Add missing Markdown code spans.

This was found using the Clippy `doc_markdown` lint, which we may want
to enable.

Fixes: b6a006e21b ("rust: alloc: introduce allocation flags")
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250324210359.1199574-4-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-25 22:58:35 +02:00
Miguel Ojeda
9f04763683 rust: platform: fix docs related to missing Markdown code spans
Convert `TODO` from documentation to a normal comment, and put code in
block.

This was found using the Clippy `doc_markdown` lint, which we may want
to enable.

Fixes: 683a63befc ("rust: platform: add basic platform device / driver abstractions")
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: https://lore.kernel.org/r/20250324210359.1199574-9-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-25 22:58:35 +02:00
Miguel Ojeda
3d5bef5d47 rust: add C FFI types to the prelude
Rust kernel code is supposed to use the custom mapping of C FFI types,
i.e. those from the `ffi` crate, rather than the ones coming from `core`.

Thus, to minimize mistakes and to simplify the code everywhere, just
provide them in the `kernel` prelude and ask in the Coding Guidelines
to use them directly, i.e. as a single segment path.

After this lands, we can start cleaning up the existing users.

Ideally, we would use something like Clippy's `disallowed-types` to
prevent the use of the `core` ones, but that one sees through aliases.

Link: https://lore.kernel.org/rust-for-linux/CANiq72kc4gzfieD-FjuWfELRDXXD2vLgPv4wqk3nt4pjdPQ=qg@mail.gmail.com/
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250413005650.1745894-1-ojeda@kernel.org
[ Reworded content of the documentation to focus on how to use the
  aliases first. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-23 16:31:43 +02:00
Igor Korotin
de7cd3e4d6 rust: use absolute paths in macros referencing core and kernel
Macros and auto-generated code should use absolute paths, `::core::...`
and `::kernel::...`, for core and kernel references.

This prevents issues where user-defined modules named `core` or `kernel`
could be picked up instead of the `core` or `kernel` crates.

Thus clean some references up.

Suggested-by: Benno Lossin <benno.lossin@proton.me>
Closes: https://github.com/Rust-for-Linux/linux/issues/1150
Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: https://lore.kernel.org/r/20250519164615.3310844-1-igor.korotin.linux@gmail.com
[ Applied `rustfmt`. Reworded slightly. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-23 00:12:14 +02:00
Miguel Ojeda
8cbc95f983 rust: workaround bindgen issue with forward references to enum types
`bindgen` currently generates the wrong type for an `enum` when there
is a forward reference to it. For instance:

    enum E;
    enum E { A };

generates:

    pub const E_A: E = 0;
    pub type E = i32;

instead of the expected:

    pub const E_A: E = 0;
    pub type E = ffi::c_uint;

The issue was reported to upstream `bindgen` [1].

Now, both GCC and Clang support silently these forward references to
`enum` types, unless `-Wpedantic` is passed, and it turns out that some
headers in the kernel depend on them.

Thus, depending on how the headers are included, which in turn may depend
on the kernel configuration or the architecture, we may get a different
type on the Rust side for a given C `enum`.

That can be quite confusing, to say the least, especially since
developers may only notice issues when building for other architectures
like in [2]. In particular, they may end up forcing a cast and adding
an `#[allow(clippy::unnecessary_cast)]` like it was done in commit
94e05a66ea ("rust: hrtimer: allow timer restart from timer handler"),
which isn't great.

Instead, let's have a section at the top of our `bindings_helper.h` that
`#include`s the headers with the affected types -- hopefully there are
not many cases and there is a single ordering that covers all cases.

This allows us to remove the cast and the `#[allow]`, thus keeping the
correct code in the source files. When the issue gets resolved in upstream
`bindgen` (and we update our minimum `bindgen` version), we can easily
remove this section at the top.

Link: https://github.com/rust-lang/rust-bindgen/issues/3179 [1]
Link: https://lore.kernel.org/rust-for-linux/87tt7md1s6.fsf@kernel.org/ [2]
Acked-by: Andreas Hindborg <a.hindborg@kernel.org>
Link: https://lore.kernel.org/r/20250325184309.97170-1-ojeda@kernel.org
[ Added extra paragraph on the comment to clarify that the workaround may
  not be possible in some cases. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-22 15:39:16 +02:00
I Hsin Cheng
195746046c rust: list: Add examples for linked list
Add basic examples for the structure "List", which also serve as unit
tests for basic list methods. It includes the following manipulations:
* List creation
* List emptiness check
* List insertion through push_front(), push_back()
* List item removal through pop_front(), pop_back()
* Push one list to another through push_all_back()

The method "remove()" doesn't have an example here because insertion
with push_front() or push_back() will take the ownership of the item,
which means we can't keep any valid reference to the node we want to
remove, unless Cursor is used. The "remove" example through Cursor is
already demonstrated with commit 52ae96f518 ("rust: list: make the
cursor point between elements").

Link: https://github.com/Rust-for-Linux/linux/issues/1121
Signed-off-by: I Hsin Cheng <richard120310@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250311133357.90322-1-richard120310@gmail.com
[ Removed prelude import and spurious newlines. Formatted comments
  with the usual style. Reworded slightly. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-22 12:00:52 +02:00
I Hsin Cheng
28669b2f37 rust: list: Use "List::is_empty()" to perform checking when possible
"List::is_empty()" provides a straight forward convention to check
whether a given "List" is empty or not. There're numerous places in the
current implementation still use "self.first.is_null()" to perform the
equivalent check, replace them with "List::is_empty()".

Signed-off-by: I Hsin Cheng <richard120310@gmail.com>
Link: https://lore.kernel.org/r/20250310073853.427954-1-richard120310@gmail.com
Reviewed-by: Benno Lossin <lossin@kernel.org>
[ Rebased dropping the cases that do not apply anymore. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-22 12:00:37 +02:00
Miguel Ojeda
bb941ea789 rust: remove unneeded Rust 1.87.0 allow(clippy::ptr_eq)
For the Rust 1.87.0 release, Clippy was expected to warn with:

    error: use `core::ptr::eq` when comparing raw pointers
       --> rust/kernel/list.rs:438:12
        |
    438 |         if self.first == item {
        |            ^^^^^^^^^^^^^^^^^^ help: try: `core::ptr::eq(self.first, item)`
        |
        = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_eq
        = note: `-D clippy::ptr-eq` implied by `-D warnings`
        = help: to override `-D warnings` add `#[allow(clippy::ptr_eq)]`

However, a backport to relax a bit the `clippy::ptr_eq` finally landed,
and thus Clippy did not warn by the time the release happened.

Thus remove the `allow`s added back then, which were added just in case
the backport did not land in time.

See commit a39f308709 ("rust: allow Rust 1.87.0's `clippy::ptr_eq`
lint") for details.

Link: https://github.com/rust-lang/rust/pull/140859 [1]
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250520182125.806758-1-ojeda@kernel.org
[ Reworded for clarity. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-22 11:46:50 +02:00
Christian Marangi
31afd6bc55 net: phy: pass PHY driver to .match_phy_device OP
Pass PHY driver pointer to .match_phy_device OP in addition to phydev.
Having access to the PHY driver struct might be useful to check the
PHY ID of the driver is being matched for in case the PHY ID scanned in
the phydev is not consistent.

A scenario for this is a PHY that change PHY ID after a firmware is
loaded, in such case, the PHY ID stored in PHY device struct is not
valid anymore and PHY will manually scan the ID in the match_phy_device
function.

Having the PHY driver info is also useful for those PHY driver that
implement multiple simple .match_phy_device OP to match specific MMD PHY
ID. With this extra info if the parsing logic is the same, the matching
function can be generalized by using the phy_id in the PHY driver
instead of hardcoding.

Rust wrapper callback is updated to align to the new match_phy_device
arguments.

Suggested-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk>
Reviewed-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk>
Signed-off-by: Christian Marangi <ansuelsmth@gmail.com>
Reviewed-by: Benno Lossin <lossin@kernel.org> # for Rust
Reviewed-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://patch.msgid.link/20250517201353.5137-2-ansuelsmth@gmail.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
2025-05-21 15:56:09 -07:00
Rafael J. Wysocki
0c905cadf3 CPUFreq updates for 6.16
- Rust abstractions for CPUFreq framework (Viresh Kumar).
 
 - Rust abstractions for OPP framework (Viresh Kumar).
 
 - Basic Rust abstractions for Clk and Cpumask frameworks (Viresh Kumar).
 
 - Minor cleanup to the SCMI cpufreq driver (Mike Tipton).
 -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEx73Crsp7f6M6scA70rkcPK6BEhwFAmgsHJEACgkQ0rkcPK6B
 EhwzURAAp1T46sM970xrUKAbm542LYw2Rff6nYzNl9khU+tMo60ypdjtSh/RVQAZ
 fcEKyaaXOEgHE6ahWOLaOIaMHYiah0DqIf8eVbZsJa3jTZ4nVNTd4Em1TQprWYer
 0KfDT9UXqiz5sE6h3RvFRid0T8t93XOHZ0y48CDLnVnIzIMogB4dkWYM3O/KoAmh
 MSVKYOvJXhj97AjHrFnJ6JzYlwX6gqq5UvRi6tzgm6B3kxHZG9dxCB25fCkRU+gP
 0oVL1JHixYE36Os3oC0BnjXpAyvJa3gjv7XCNilVHnoqWpIccspBp/7uUI3eex/4
 4uamldNalTA1bmP84JJzYt5qc9rBHME2nDvDlD6VbnmjjT/WFAF9/RAMeaE443Eo
 0v/XiLcQuM+xDUGqUh6HheAfguIvfYASLM2Nkzi6yq13xYO2jK1NC+Ijwim2RJnC
 lvYHrQTuvAbPyH2oFqPWvXM6/2HbDva6wxD3LI879Bpf7cJi/FfLDIGisDkx80WU
 q8Ys2q8wXm0BkzWpaEbl2tZW43pMAS9TaYVUjoU3WZKbLsIWfmL/BofPS6Yjd6X7
 dKCzREn3lw10Rk23SKUvJP6TYqBHW3ohkyGUtjoMbY0IGFrKv+XEZw7wDmj0GBWt
 sA62Kf+s0bFmo0jy+x4uaEdf0ZNG9VqhcB2sYHaJpfk+votl2ic=
 =Zx0u
 -----END PGP SIGNATURE-----

Merge tag 'cpufreq-arm-updates-6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/vireshk/pm

Merge ARM CPUFreq updates for 6.16 from Viresh Kumar:

"- Rust abstractions for CPUFreq framework (Viresh Kumar).

 - Rust abstractions for OPP framework (Viresh Kumar).

 - Basic Rust abstractions for Clk and Cpumask frameworks (Viresh Kumar).

 - Minor cleanup to the SCMI cpufreq driver (Mike Tipton)."

* tag 'cpufreq-arm-updates-6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/vireshk/pm: (24 commits)
  cpufreq: scmi: Skip SCMI devices that aren't used by the CPUs
  cpufreq: Add Rust-based cpufreq-dt driver
  rust: opp: Extend OPP abstractions with cpufreq support
  rust: cpufreq: Extend abstractions for driver registration
  rust: cpufreq: Extend abstractions for policy and driver ops
  rust: cpufreq: Add initial abstractions for cpufreq framework
  rust: opp: Add abstractions for the configuration options
  rust: opp: Add abstractions for the OPP table
  rust: opp: Add initial abstractions for OPP framework
  rust: cpu: Add from_cpu()
  rust: macros: enable use of hyphens in module names
  rust: clk: Add initial abstractions
  rust: clk: Add helpers for Rust code
  MAINTAINERS: Add entry for Rust cpumask API
  rust: cpumask: Add initial abstractions
  rust: cpumask: Add few more helpers
  rust: devres: require a bound device
  rust: pci: move iomap_region() to impl Device<Bound>
  rust: device: implement Bound device context
  rust: pci: preserve device context in AsRef
  ...
2025-05-21 22:49:34 +02:00
Christian Schrefl
81e9edc1a8 rust: miscdevice: fix typo in MiscDevice::ioctl documentation
Fixes one small typo (`utilties` to `utilities`) in the documentation of
`MiscDevice::ioctl`.

Fixes: f893691e74 ("rust: miscdevice: add base miscdevice abstraction")
Signed-off-by: Christian Schrefl <chrisi.schrefl@gmail.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250517-rust_miscdevice_fix_typo-v1-1-8c30a6237ba9@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-05-21 14:03:20 +02:00
Jihed Chaibi
ae8b3a83fb rust: str: fix typo in comment
Fix a typo ("then" to "than") in a comment.

Signed-off-by: Jihed Chaibi <jihed.chaibi.dev@gmail.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Fixes: fffed679ee ("rust: str: add `Formatter` type")
Link: https://lore.kernel.org/r/20250517002604.603223-1-jihed.chaibi.dev@gmail.com
[ Reworded. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-20 22:57:27 +02:00
Dave Airlie
c4f8ac095f Nova changes for v6.16
auxiliary:
   - bus abstractions
   - implementation for driver registration
   - add sample driver
 
 drm:
   - implement __drm_dev_alloc()
   - DRM core infrastructure Rust abstractions
     - device, driver and registration
     - DRM IOCTL
     - DRM File
     - GEM object
   - IntoGEMObject rework
     - generically implement AlwaysRefCounted through IntoGEMObject
     - refactor unsound from_gem_obj() into as_ref()
     - refactor into_gem_obj() into as_raw()
 
 driver-core:
   - merge topic/device-context-2025-04-17 from driver-core tree
   - implement Devres::access()
     - fix: doctest build under `!CONFIG_PCI`
   - accessor for Device::parent()
     - fix: conditionally expect `dead_code` for `parent()`
   - impl TryFrom<&Device> bus devices (PCI, platform)
 
 nova-core:
   - remove completed Vec extentions from task list
   - register auxiliary device for nova-drm
   - derive useful traits for Chipset
   - add missing GA100 chipset
   - take &Device<Bound> in Gpu::new()
   - infrastructure to generate register definitions
   - fix register layout of NV_PMC_BOOT_0
   - move Firmware into own (Rust) module
   - fix: select AUXILIARY_BUS
 
 nova-drm:
   - initial driver skeleton (depends on drm and auxiliary bus
     abstractions)
   - fix: select AUXILIARY_BUS
 
 Rust (dependencies):
   - implement Opaque::zeroed()
   - implement Revocable::try_access_with()
   - implement Revocable::access()
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCaCw8MQAKCRBFlHeO1qrK
 LjWvAP9kg3wJuJtO5KT7RsEk/fsPXoHy0QuB45v/R7yWdehsrwEA7WPoR/3TfDqN
 Ydq1JMMHw9lrDqaSNcMMw5K8zYs4oQQ=
 =FRbl
 -----END PGP SIGNATURE-----

Merge tag 'nova-next-v6.16-2025-05-20' of https://gitlab.freedesktop.org/drm/nova into drm-next

Nova changes for v6.16

auxiliary:
  - bus abstractions
  - implementation for driver registration
  - add sample driver

drm:
  - implement __drm_dev_alloc()
  - DRM core infrastructure Rust abstractions
    - device, driver and registration
    - DRM IOCTL
    - DRM File
    - GEM object
  - IntoGEMObject rework
    - generically implement AlwaysRefCounted through IntoGEMObject
    - refactor unsound from_gem_obj() into as_ref()
    - refactor into_gem_obj() into as_raw()

driver-core:
  - merge topic/device-context-2025-04-17 from driver-core tree
  - implement Devres::access()
    - fix: doctest build under `!CONFIG_PCI`
  - accessor for Device::parent()
    - fix: conditionally expect `dead_code` for `parent()`
  - impl TryFrom<&Device> bus devices (PCI, platform)

nova-core:
  - remove completed Vec extentions from task list
  - register auxiliary device for nova-drm
  - derive useful traits for Chipset
  - add missing GA100 chipset
  - take &Device<Bound> in Gpu::new()
  - infrastructure to generate register definitions
  - fix register layout of NV_PMC_BOOT_0
  - move Firmware into own (Rust) module
  - fix: select AUXILIARY_BUS

nova-drm:
  - initial driver skeleton (depends on drm and auxiliary bus
    abstractions)
  - fix: select AUXILIARY_BUS

Rust (dependencies):
  - implement Opaque::zeroed()
  - implement Revocable::try_access_with()
  - implement Revocable::access()

From: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/aCxAf3RqQAXLDhAj@cassiopeiae
2025-05-21 05:49:31 +10:00
Viresh Kumar
14f47156cf rust: opp: Extend OPP abstractions with cpufreq support
Extend the OPP abstractions to include support for interacting with the
cpufreq core, including the ability to retrieve frequency tables from
OPP table.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 11:21:11 +05:30
Viresh Kumar
c6af9a1191 rust: cpufreq: Extend abstractions for driver registration
Extend the cpufreq abstractions to support driver registration from
Rust.

Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 11:21:10 +05:30
Viresh Kumar
6ebdd7c931 rust: cpufreq: Extend abstractions for policy and driver ops
Extend the cpufreq abstractions to include support for policy handling
and driver operations.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 11:21:10 +05:30
Viresh Kumar
2207856ff0 rust: cpufreq: Add initial abstractions for cpufreq framework
Introduce initial Rust abstractions for the cpufreq core. This includes
basic representations for cpufreq flags, relation types, and the cpufreq
table.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 11:21:10 +05:30
Viresh Kumar
ce32e2d47c rust: opp: Add abstractions for the configuration options
Introduce Rust abstractions for the OPP core configuration options,
enabling safe access to various configurable aspects of the OPP
framework.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 10:11:14 +05:30
Viresh Kumar
d52c7e868f rust: opp: Add abstractions for the OPP table
Introduce Rust abstractions for `struct opp_table`, enabling access to
OPP tables from Rust.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 10:10:53 +05:30
Viresh Kumar
8f835497b3 rust: opp: Add initial abstractions for OPP framework
Introduce initial Rust abstractions for the Operating Performance Points
(OPP) framework. This includes bindings for `struct dev_pm_opp` and
`struct dev_pm_opp_data`, laying the groundwork for further OPP
integration.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 10:04:06 +05:30
Viresh Kumar
3accb57d56 rust: cpu: Add from_cpu()
This implements cpu::from_cpu(), which returns a reference to
Device for a CPU. The C struct is created at initialization time for
CPUs and is never freed and so ARef isn't returned from this function.

The new helper will be used by Rust based cpufreq drivers.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20 10:04:06 +05:30
Viresh Kumar
d01d702056 rust: clk: Add initial abstractions
Add initial abstractions for the clk APIs. These provide the minimal
functionality needed for common use cases, making them straightforward
to introduce in the first iteration.

These will be used by Rust based cpufreq / OPP layers to begin with.

Tested-by: Daniel Almeida <daniel.almeida@collabora.com>
Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com>
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-19 12:55:40 +05:30
Viresh Kumar
8961b8cb30 rust: cpumask: Add initial abstractions
Add initial Rust abstractions for struct cpumask, covering a subset of
its APIs. Additional APIs can be added as needed.

These abstractions will be used in upcoming Rust support for cpufreq and
OPP frameworks.

Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
Reviewed-by: Yury Norov [NVIDIA] <yury.norov@gmail.com>
2025-05-19 12:55:40 +05:30
Miguel Ojeda
22c3335c5d Alloc changes for v6.16
Box:
   - support for type coercion, e.g. `Box<T>` to `Box<dyn U>` if T
     implements U
 
 Vec:
   - implement new methods (prerequisites for nova-core and binder)
     - Vec::truncate()
     - Vec::resize()
     - Vec::clear()
     - Vec::pop()
     - Vec::push_within_capacity()
       - new error type: PushError
     - Vec::drain_all()
     - Vec::retain()
     - Vec::remove()
       - new error type: RemoveError
     - Vec::insert_within_capacity
       - new error type: InsertError
   - simplify Vec::push() using Vec::spare_capacity_mut()
   - split Vec::set_len() into Vec::inc_len() and Vec::dec_len()
     - add type invariant Vec::len() <= Vec::capacity
     - simplify Vec::truncate() using Vec::dec_len()
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCaCMRLAAKCRBFlHeO1qrK
 LsN3AP4jqS886xuFT6+Ibh1rinGu3RX5ffK0b2/tm47+BP2ysAD/UZ5M1DHhP1z4
 SIQ+Ad9hSQoV6kQngRBKo0SdsZw8jgk=
 =T22w
 -----END PGP SIGNATURE-----

Merge tag 'alloc-next-v6.16-2025-05-13' of https://github.com/Rust-for-Linux/linux into rust-next

Pull alloc updates from Danilo Krummrich:
 "Box:

   - Support for type coercion, e.g. 'Box<T>' to 'Box<dyn U>' if T
     implements U

  Vec:

   - Implement new methods (prerequisites for nova-core and binder)
      - Vec::truncate()
      - Vec::resize()
      - Vec::clear()
      - Vec::pop()
      - Vec::push_within_capacity()
         - New error type: PushError
      - Vec::drain_all()
      - Vec::retain()
      - Vec::remove()
         - New error type: RemoveError
      - Vec::insert_within_capacity
         - New error type: InsertError

   - Simplify Vec::push() using Vec::spare_capacity_mut()

   - Split Vec::set_len() into Vec::inc_len() and Vec::dec_len()
      - Add type invariant Vec::len() <= Vec::capacity
      - Simplify Vec::truncate() using Vec::dec_len()"

* tag 'alloc-next-v6.16-2025-05-13' of https://github.com/Rust-for-Linux/linux:
  rust: alloc: add Vec::insert_within_capacity
  rust: alloc: add Vec::remove
  rust: alloc: add Vec::retain
  rust: alloc: add Vec::drain_all
  rust: alloc: add Vec::push_within_capacity
  rust: alloc: add Vec::pop
  rust: alloc: add Vec::clear
  rust: alloc: replace `Vec::set_len` with `inc_len`
  rust: alloc: refactor `Vec::truncate` using `dec_len`
  rust: alloc: add `Vec::dec_len`
  rust: alloc: add Vec::len() <= Vec::capacity invariant
  rust: alloc: allow coercion from `Box<T>` to `Box<dyn U>` if T implements U
  rust: alloc: use `spare_capacity_mut` to reduce unsafe
  rust: alloc: add Vec::resize method
  rust: alloc: add Vec::truncate method
  rust: alloc: add missing invariant in Vec::set_len()
2025-05-18 20:56:03 +02:00
Miguel Ojeda
06ff274f25 Rust xarray API for v6.16
Introduce Rust support for the `xarray` data structure:
 
  - Add a rust abstraction for the `xarray` data structure. This abstraction
    allows rust code to leverage the `xarray` to store types that implement
    `ForeignOwnable`. This support is a dependency for memory backing feature of
    the rust null block driver, which is waiting to be merged.
 
  - Set up an entry in MAINTAINERS for the xarray rust support. Patches will go
    to the new rust xarray tree and then via the rust subsystem tree for now.
 
 `kernel` crate:
 
  - Allow `ForeignOwnable` to carry information about the pointed-to type. This
    helps asserting alignment requirements for the pointer passed to the foreign
    language.
 -----BEGIN PGP SIGNATURE-----
 
 iQJKBAABCAA0FiEEEsH5R1a/fCoV1sAS4bgaPnkoY3cFAmgZ6fgWHGEuaGluZGJv
 cmdAa2VybmVsLm9yZwAKCRDhuBo+eShjdxXVD/44Pko7d9oVLhLGG0nndMbWFjkk
 /pCTdtw0+0NkulbJ8hKoIC5vYg47P2lE/nx6MsKJSbFdwts2fWd3nKHbxAQq8ox/
 cWVLlzPESe719YmAUhLZhRPIOzRVyShWfbAIjyRDQZ0pc3txYbmiRHcBv9teu4In
 bKCaV+OTqZFZSwZomyqFCz41uDPHdQxxb1O4vV8Kwh2vwD2x5/bcYvG2veU/Bzil
 w1sSjhGvLAa0M3r/lP+72S4y5IbnA8HOsT9eBJMBVkdgWdw7avS9UfkuYeR1FcHg
 7/osUZK4qvGKs9WDU2jkzt7imj0Zegis2/etlwblpzhR+GtSsTr0TZRGuuFL0HSr
 bWb/2qbSDwKR28J3k4yfM7ksg3+PIztBA5MfTcffpMI4yjqaVQXkIzWGlFOoiGrx
 tF+sZYqTqFBOgsKgir1pTAcK2/IZh7Y39HXYG7Wr4EO6GCXGkNxM68uzVR4WEbeT
 PoxoxMzkjHaZe/sNyNYhhOfTjuhkikd9MazM+Ss8cpA8cFsWIcyDj/T5uyIuhE0+
 BxzN/NTTwIM37ixAbtb9ZWT5F4hV9iwzXtvp+OqC0HUKcZH8vpXn/VFr0jKh4NKT
 HpG3mwSYZt/eTSxvrGooVLYt36yvAKuP47jqqE8UaPzLtYEULwHuVDGJTfXNnErk
 lV7grpE36dgXaSaErg==
 =Ig1t
 -----END PGP SIGNATURE-----

Merge tag 'rust-xarray-for-v6.16' of https://github.com/Rust-for-Linux/linux into rust-next

Pull XArray updates from Andreas Hindborg:
 "Introduce Rust support for the 'xarray' data structure:

   - Add a Rust abstraction for the 'xarray' data structure. This
     abstraction allows Rust code to leverage the 'xarray' to store
     types that implement 'ForeignOwnable'. This support is a dependency
     for memory backing feature of the Rust null block driver, which is
     waiting to be merged.

   - Set up an entry in MAINTAINERS for the XArray Rust support. Patches
     will go to the new Rust XArray tree and then via the Rust subsystem
     tree for now.

  'kernel' crate:

   - Allow 'ForeignOwnable' to carry information about the pointed-to
     type. This helps asserting alignment requirements for the pointer
     passed to the foreign language."

* tag 'rust-xarray-for-v6.16' of https://github.com/Rust-for-Linux/linux:
  MAINTAINERS: add entry for Rust XArray API
  rust: xarray: Add an abstraction for XArray
  rust: types: add `ForeignOwnable::PointedTo`
2025-05-18 20:36:56 +02:00
Miguel Ojeda
373827fce2 Rust timekeeping changes for v6.16
- Morph the rust hrtimer subsystem into the rust timekeeping subsystem,
    covering delay, sleep, timekeeping, timers. This new subsystem has all the
    relevant timekeeping C maintainers listed in the entry.
 
  - Replace `Ktime` with `Delta` and `Instant` types to represent a duration of
    time and a point in time.
 
  - Temporarily add `Ktime` to `hrtimer` module to allow `hrtimer` to delay
    converting to `Instant` and `Delta`.
 -----BEGIN PGP SIGNATURE-----
 
 iQJKBAABCAA0FiEEEsH5R1a/fCoV1sAS4bgaPnkoY3cFAmgZ1+8WHGEuaGluZGJv
 cmdAa2VybmVsLm9yZwAKCRDhuBo+eShjd8MTD/9di4KXLhRpWaqVcNDbmNIPDaCL
 e241wbiOkganrrel2ZtNg5ZVnxvHv7sNXcq1QrARNQE+/hb0LuXK/NHXINaovN2Y
 bL29UyZGeL8rVW7sw4EKR/q8WE4dxUqCGBL6cF0/8aRQHGPteUuWm3Le5T4p4fej
 tM0++NT9JzbNe0RFDYK5S5stl1S8VJiFeVLniTB85WhtpBdSvBGJ4P4d0GMUOwnZ
 4Nbis56CXFtR32G2B6N+ztiBpMHidqCJ3LkavnXkff/tD6ja5bScsbgeZerwLOrR
 Rkxz6n1IDFkx+tYLS7U54XWFnWGM0TeGtyGsxdHwPVn3g8O3sak5UN6mT+imeLXY
 3KAsMqXEMMYoONnYtxS3k2Th9KtWs79SCi5lMou6YekqMZBDQxvQmBP0M7vnNGeL
 wtGQ1ZUz3OsNwepjtH0Pjg13MmAK5Do+e+SEWGDwXiftDhnOmvRFFChqDO7kE/Jp
 sqq6y0IZBBoZEiNsfvF22NunGXvx0MePUq8bppEtf3v8j8KCK3pW9jXMa/9eECTO
 IBbIqG+uPvIGiTR6FnlEMBn8TUc1RBGSKuQ6qOKX/4YQ0uayTTQjO0ugNiMpODvB
 2w9HiPymq7Mk5iZ3Dmeeo1Je5AJEN1VsWiOAs5URABXAYeSopOdrsaBLG1vgK+yW
 0+xkDsf6VNiGcWdhbg==
 =M1o/
 -----END PGP SIGNATURE-----

Merge tag 'rust-timekeeping-for-v6.16-v2' of https://github.com/Rust-for-Linux/linux into rust-next

Pull timekeeping updates from Andreas Hindborg:

 - Morph the Rust hrtimer subsystem into the Rust timekeeping subsystem,
   covering delay, sleep, timekeeping, timers. This new subsystem has
   all the relevant timekeeping C maintainers listed in the entry.

 - Replace 'Ktime' with 'Delta' and 'Instant' types to represent a
   duration of time and a point in time.

 - Temporarily add 'Ktime' to 'hrtimer' module to allow 'hrtimer' to
   delay converting to 'Instant' and 'Delta'.

* tag 'rust-timekeeping-for-v6.16-v2' of https://github.com/Rust-for-Linux/linux:
  MAINTAINERS: rust: Add a new section for all of the time stuff
  rust: time: Introduce Instant type
  rust: time: Introduce Delta type
  rust: time: Add PartialEq/Eq/PartialOrd/Ord trait to Ktime
  rust: hrtimer: Add Ktime temporarily
2025-05-18 20:34:02 +02:00
I Hsin Cheng
9520371e3d rust: sync: rcu: Mark Guard methods as inline
Currently the implementation of "Guard" methods are basically wrappers
around rcu's function within kernel. Building the kernel with llvm
18.1.8 on x86_64 machine will generate the following symbols:

$ nm vmlinux | grep ' _R'.*Guard | rustfilt
ffffffff817b6c90 T <kernel::sync::rcu::Guard>::new
ffffffff817b6cb0 T <kernel::sync::rcu::Guard>::unlock
ffffffff817b6cd0 T <kernel::sync::rcu::Guard as core::ops::drop::Drop>::drop
ffffffff817b6c90 T <kernel::sync::rcu::Guard as core::default::Default>::default

These Rust symbols are basically wrappers around functions
"rcu_read_lock" and "rcu_read_unlock". Marking them as inline can
reduce the generation of these symbols, and saves the size of code
generation for 132 bytes.

$ ./scripts/bloat-o-meter vmlinux_old vmlinux_new
(Output is demangled for readability)

add/remove: 0/10 grow/shrink: 0/1 up/down: 0/-132 (-132)
Function                                     old     new   delta
rust_driver_pci::SampleDriver::probe        1041    1034      -7
kernel::sync::rcu::Guard::default             9       -      -9
kernel::sync::rcu::Guard::drop                9       -      -9
kernel::sync::rcu::read_lock                  9       -      -9
kernel::sync::rcu::Guard::unlock              9       -      -9
kernel::sync::rcu::Guard::new                 9       -      -9
__pfx__kernel::sync::rcu::Guard::default     16       -     -16
__pfx__kernel::sync::rcu::Guard::drop        16       -     -16
__pfx__kernel::sync::rcu::read_lock          16       -     -16
__pfx__kernel::sync::rcu::Guard::unlock      16       -     -16
__pfx__kernel::sync::rcu::Guard::new         16       -     -16
Total: Before=23365955, After=23365823, chg -0.00%

Link: https://github.com/Rust-for-Linux/linux/issues/1145
Signed-off-by: I Hsin Cheng <richard120310@gmail.com>
Reviewed-by: Joel Fernandes <joelagnelf@nvidia.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Charalampos Mitrodimas <charmitro@posteo.net>
Acked-by: Miguel Ojeda <ojeda@kernel.org>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
2025-05-16 09:00:54 -04:00
Lyude Paul
38cb08c3fc rust: drm: gem: Implement AlwaysRefCounted for all gem objects automatically
Currently we are requiring AlwaysRefCounted in most trait bounds for gem
objects, and implementing it by hand for our only current type of gem
object. However, all gem objects use the same functions for reference
counting - and all gem objects support reference counting.

We're planning on adding support for shmem gem objects, let's move this
around a bit by instead making IntoGEMObject require AlwaysRefCounted as a
trait bound, and then provide a blanket AlwaysRefCounted implementation for
any object that implements IntoGEMObject so all gem object types can use
the same AlwaysRefCounted implementation. This also makes things less
verbose by making the AlwaysRefCounted trait bound implicit for any
IntoGEMObject bound.

Signed-off-by: Lyude Paul <lyude@redhat.com>
Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com>
Link: https://lore.kernel.org/r/20250513221046.903358-5-lyude@redhat.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-14 00:37:16 +02:00
Lyude Paul
b36ff40b4a rust: drm: gem: s/into_gem_obj()/as_raw()/
There's a few changes here:
* The rename, of course (this should also let us drop the clippy annotation
  here)
* Return *mut bindings::drm_gem_object instead of
  &Opaque<bindings::drm_gem_object> - the latter doesn't really have any
  benefit and just results in conversion from the rust type to the C type
  having to be more verbose than necessary.

Signed-off-by: Lyude Paul <lyude@redhat.com>
Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com>
Link: https://lore.kernel.org/r/20250513221046.903358-4-lyude@redhat.com
[ Fixup s/into_gem_obj()/as_raw()/ in safety comment. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-14 00:35:58 +02:00
Lyude Paul
36b1ccbfa0 rust: drm: gem: Refactor IntoGEMObject::from_gem_obj() to as_ref()
There's a few issues with this function, mainly:

* This function -probably- should have been unsafe from the start. Pointers
  are not always necessarily valid, but you want a function that does
  field-projection for a pointer that can travel outside of the original
  struct to be unsafe, at least if I understand properly.
* *mut Self is not terribly useful in this context, the majority of uses of
  from_gem_obj() grab a *mut Self and then immediately convert it into a
  &'a Self. It also goes against the ffi conventions we've set in the rest
  of the kernel thus far.
* from_gem_obj() also doesn't follow the naming conventions in the rest of
  the DRM bindings at the moment, as_ref() would be a better name.

So, let's:

* Make from_gem_obj() unsafe
* Convert it to return &'a Self
* Rename it to as_ref()
* Update all call locations

Signed-off-by: Lyude Paul <lyude@redhat.com>
Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com>
Link: https://lore.kernel.org/r/20250513221046.903358-3-lyude@redhat.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-14 00:26:16 +02:00
Lyude Paul
6ee48aee8c rust: drm: gem: Use NonNull for Object::dev
There is usually not much of a reason to use a raw pointer in a data
struct, so move this to NonNull instead.

Signed-off-by: Lyude Paul <lyude@redhat.com>
Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com>
Link: https://lore.kernel.org/r/20250513221046.903358-2-lyude@redhat.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-14 00:26:08 +02:00
Andreas Hindborg
446cafc295 rust: configfs: introduce rust support for configfs
Add a Rust API for configfs, thus allowing Rust modules to use configfs for
configuration. Make the implementation a shim on top of the C configfs
implementation, allowing safe use of the C infrastructure from Rust.

Link: https://lore.kernel.org/r/20250508-configfs-v8-1-8ebde6180edc@kernel.org
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-05-12 11:05:07 +02:00
Miguel Ojeda
42055939a3 rust: devres: fix doctest build under !CONFIG_PCI
The doctest requires `CONFIG_PCI`:

    error[E0432]: unresolved import `kernel::pci`
        --> rust/doctests_kernel_generated.rs:2689:44
         |
    2689 | use kernel::{device::Core, devres::Devres, pci};
         |                                            ^^^ no `pci` in the root
         |
    note: found an item that was configured out
        --> rust/kernel/lib.rs:96:9
    note: the item is gated here
        --> rust/kernel/lib.rs:95:1

Thus conditionally compile it (which still checks the syntax).

Fixes: f301cb978c ("rust: devres: implement Devres::access()")
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://lore.kernel.org/r/20250511182533.1016163-1-ojeda@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-12 09:35:44 +02:00
Alice Ryhl
6acb75ad7b task: rust: rework how current is accessed
Introduce a new type called `CurrentTask` that lets you perform various
operations that are only safe on the `current` task.  Use the new type to
provide a way to access the current mm without incrementing its refcount.

With this change, you can write stuff such as

	let vma = current!().mm().lock_vma_under_rcu(addr);

without incrementing any refcounts.

This replaces the existing abstractions for accessing the current pid
namespace.  With the old approach, every field access to current involves
both a macro and a unsafe helper function.  The new approach simplifies
that to a single safe function on the `CurrentTask` type.  This makes it
less heavy-weight to add additional current accessors in the future.

That said, creating a `CurrentTask` type like the one in this patch
requires that we are careful to ensure that it cannot escape the current
task or otherwise access things after they are freed.  To do this, I
declared that it cannot escape the current "task context" where I defined
a "task context" as essentially the region in which `current` remains
unchanged.  So e.g., release_task() or begin_new_exec() would leave the
task context.

If a userspace thread returns to userspace and later makes another
syscall, then I consider the two syscalls to be different task contexts. 
This allows values stored in that task to be modified between syscalls,
even if they're guaranteed to be immutable during a syscall.

Ensuring correctness of `CurrentTask` is slightly tricky if we also want
the ability to have a safe `kthread_use_mm()` implementation in Rust.  To
support that safely, there are two patterns we need to ensure are safe:

	// Case 1: current!() called inside the scope.
	let mm;
	kthread_use_mm(some_mm, || {
	    mm = current!().mm();
	});
	drop(some_mm);
	mm.do_something(); // UAF

and:

	// Case 2: current!() called before the scope.
	let mm;
	let task = current!();
	kthread_use_mm(some_mm, || {
	    mm = task.mm();
	});
	drop(some_mm);
	mm.do_something(); // UAF

The existing `current!()` abstraction already natively prevents the first
case: The `&CurrentTask` would be tied to the inner scope, so the
borrow-checker ensures that no reference derived from it can escape the
scope.

Fixing the second case is a bit more tricky.  The solution is to
essentially pretend that the contents of the scope execute on an different
thread, which means that only thread-safe types can cross the boundary. 
Since `CurrentTask` is marked `NotThreadSafe`, attempts to move it to
another thread will fail, and this includes our fake pretend thread
boundary.

This has the disadvantage that other types that aren't thread-safe for
reasons unrelated to `current` also cannot be moved across the
`kthread_use_mm()` boundary.  I consider this an acceptable tradeoff.

Link: https://lkml.kernel.org/r/20250408-vma-v16-8-d8b446e885d9@google.com
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: Gary Guo <gary@garyguo.net>
Cc: Alex Gaynor <alex.gaynor@gmail.com>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Benno Lossin <benno.lossin@proton.me>
Cc: Björn Roy Baron <bjorn3_gh@protonmail.com>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Jann Horn <jannh@google.com>
Cc: John Hubbard <jhubbard@nvidia.com>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Cc: Miguel Ojeda <ojeda@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Trevor Gross <tmgross@umich.edu>
Cc: Vlastimil Babka <vbabka@suse.cz>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11 17:48:25 -07:00
Alice Ryhl
f8c7819881 rust: miscdevice: add mmap support
Add the ability to write a file_operations->mmap hook in Rust when using
the miscdevice abstraction.  The `vma` argument to the `mmap` hook uses
the `VmaNew` type from the previous commit; this type provides the correct
set of operations for a file_operations->mmap hook.

Link: https://lkml.kernel.org/r/20250408-vma-v16-7-d8b446e885d9@google.com
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: Gary Guo <gary@garyguo.net>
Cc: Alex Gaynor <alex.gaynor@gmail.com>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Benno Lossin <benno.lossin@proton.me>
Cc: Björn Roy Baron <bjorn3_gh@protonmail.com>
Cc: Boqun Feng <boqun.feng@gmail.com>
Cc: Jann Horn <jannh@google.com>
Cc: John Hubbard <jhubbard@nvidia.com>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Cc: Miguel Ojeda <ojeda@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Trevor Gross <tmgross@umich.edu>
Cc: Vlastimil Babka <vbabka@suse.cz>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11 17:48:25 -07:00
Alice Ryhl
dcb81aeab4 mm: rust: add VmaNew for f_ops->mmap()
This type will be used when setting up a new vma in an f_ops->mmap() hook.
Using a separate type from VmaRef allows us to have a separate set of
operations that you are only able to use during the mmap() hook.  For
example, the VM_MIXEDMAP flag must not be changed after the initial setup
that happens during the f_ops->mmap() hook.

To avoid setting invalid flag values, the methods for clearing VM_MAYWRITE
and similar involve a check of VM_WRITE, and return an error if VM_WRITE
is set.  Trying to use `try_clear_maywrite` without checking the return
value results in a compilation error because the `Result` type is marked
#[must_use].

For now, there's only a method for VM_MIXEDMAP and not VM_PFNMAP.  When we
add a VM_PFNMAP method, we will need some way to prevent you from setting
both VM_MIXEDMAP and VM_PFNMAP on the same vma.

Link: https://lkml.kernel.org/r/20250408-vma-v16-6-d8b446e885d9@google.com
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com>
Reviewed-by: Jann Horn <jannh@google.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Cc: Alex Gaynor <alex.gaynor@gmail.com>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Benno Lossin <benno.lossin@proton.me>
Cc: Björn Roy Baron <bjorn3_gh@protonmail.com>
Cc: Boqun Feng <boqun.feng@gmail.com>
Cc: Gary Guo <gary@garyguo.net>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: John Hubbard <jhubbard@nvidia.com>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Cc: Miguel Ojeda <ojeda@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Trevor Gross <tmgross@umich.edu>
Cc: Vlastimil Babka <vbabka@suse.cz>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11 17:48:25 -07:00
Alice Ryhl
114ba9b9e8 mm: rust: add mmput_async support
Adds an MmWithUserAsync type that uses mmput_async when dropped but is
otherwise identical to MmWithUser.  This has to be done using a separate
type because the thing we are changing is the destructor.

Rust Binder needs this to avoid a certain deadlock.  See commit
9a9ab0d963 ("binder: fix race between mmput() and do_exit()") for
details.  It's also needed in the shrinker to avoid cleaning up the mm in
the shrinker's context.

Link: https://lkml.kernel.org/r/20250408-vma-v16-5-d8b446e885d9@google.com
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: Gary Guo <gary@garyguo.net>
Cc: Alex Gaynor <alex.gaynor@gmail.com>
Cc: Arnd Bergmann <arnd@arndb.de>
Cc: Balbir Singh <balbirs@nvidia.com>
Cc: Benno Lossin <benno.lossin@proton.me>
Cc: Björn Roy Baron <bjorn3_gh@protonmail.com>
Cc: Boqun Feng <boqun.feng@gmail.com>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Jann Horn <jannh@google.com>
Cc: John Hubbard <jhubbard@nvidia.com>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Cc: Miguel Ojeda <ojeda@kernel.org>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Trevor Gross <tmgross@umich.edu>
Cc: Vlastimil Babka <vbabka@suse.cz>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11 17:48:24 -07:00