Commit Graph

1295553 Commits

Author SHA1 Message Date
Wedson Almeida Filho
a3df991d3d
rust: cred: add Rust abstraction for struct cred
Add a wrapper around `struct cred` called `Credential`, and provide
functionality to get the `Credential` associated with a `File`.

Rust Binder must check the credentials of processes when they attempt to
perform various operations, and these checks usually take a
`&Credential` as parameter. The security_binder_set_context_mgr function
would be one example. This patch is necessary to access these security_*
methods from Rust.

This Rust abstraction makes the following assumptions about the C side:
* `struct cred` is refcounted with `get_cred`/`put_cred`.
* It's okay to transfer a `struct cred` across threads, that is, you do
  not need to call `put_cred` on the same thread as where you called
  `get_cred`.
* The `euid` field of a `struct cred` never changes after
  initialization.
* The `f_cred` field of a `struct file` never changes after
  initialization.

Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240915-alice-file-v10-4-88484f7a3dcf@google.com
Reviewed-by: Kees Cook <kees@kernel.org>
Reviewed-by: Paul Moore <paul@paul-moore.com>
Signed-off-by: Christian Brauner <brauner@kernel.org>
2024-09-30 13:02:28 +02:00
Wedson Almeida Filho
851849824b
rust: file: add Rust abstraction for struct file
This abstraction makes it possible to manipulate the open files for a
process. The new `File` struct wraps the C `struct file`. When accessing
it using the smart pointer `ARef<File>`, the pointer will own a
reference count to the file. When accessing it as `&File`, then the
reference does not own a refcount, but the borrow checker will ensure
that the reference count does not hit zero while the `&File` is live.

Since this is intended to manipulate the open files of a process, we
introduce an `fget` constructor that corresponds to the C `fget`
method. In future patches, it will become possible to create a new fd in
a process and bind it to a `File`. Rust Binder will use these to send
fds from one process to another.

We also provide a method for accessing the file's flags. Rust Binder
will use this to access the flags of the Binder fd to check whether the
non-blocking flag is set, which affects what the Binder ioctl does.

This introduces a struct for the EBADF error type, rather than just
using the Error type directly. This has two advantages:
* `File::fget` returns a `Result<ARef<File>, BadFdError>`, which the
  compiler will represent as a single pointer, with null being an error.
  This is possible because the compiler understands that `BadFdError`
  has only one possible value, and it also understands that the
  `ARef<File>` smart pointer is guaranteed non-null.
* Additionally, we promise to users of the method that the method can
  only fail with EBADF, which means that they can rely on this promise
  without having to inspect its implementation.
That said, there are also two disadvantages:
* Defining additional error types involves boilerplate.
* The question mark operator will only utilize the `From` trait once,
  which prevents you from using the question mark operator on
  `BadFdError` in methods that return some third error type that the
  kernel `Error` is convertible into. (However, it works fine in methods
  that return `Error`.)

Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Co-developed-by: Daniel Xu <dxu@dxuuu.xyz>
Signed-off-by: Daniel Xu <dxu@dxuuu.xyz>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240915-alice-file-v10-3-88484f7a3dcf@google.com
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Christian Brauner <brauner@kernel.org>
2024-09-30 13:02:28 +02:00
Alice Ryhl
913f8cf4f3
rust: task: add Task::current_raw
Introduces a safe function for getting a raw pointer to the current
task.

When writing bindings that need to access the current task, it is often
more convenient to call a method that directly returns a raw pointer
than to use the existing `Task::current` method. However, the only way
to do that is `bindings::get_current()` which is unsafe since it calls
into C. By introducing `Task::current_raw()`, it becomes possible to
obtain a pointer to the current task without using unsafe.

Link: https://lore.kernel.org/all/CAH5fLgjT48X-zYtidv31mox3C4_Ogoo_2cBOCmX0Ang3tAgGHA@mail.gmail.com/
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240915-alice-file-v10-2-88484f7a3dcf@google.com
Signed-off-by: Christian Brauner <brauner@kernel.org>
2024-09-30 13:02:28 +02:00
Alice Ryhl
e7572e5dea
rust: types: add NotThreadSafe
This introduces a new marker type for types that shouldn't be thread
safe. By adding a field of this type to a struct, it becomes non-Send
and non-Sync, which means that it cannot be accessed in any way from
threads other than the one it was created on.

This is useful for APIs that require globals such as `current` to remain
constant while the value exists.

We update two existing users in the Kernel to use this helper:

 * `Task::current()` - moving the return type of this value to a
   different thread would not be safe as you can no longer be guaranteed
   that the `current` pointer remains valid.
 * Lock guards. Mutexes and spinlocks should be unlocked on the same
   thread as where they were locked, so we enforce this using the Send
   trait.

There are also additional users in later patches of this patchset. See
[1] and [2] for the discussion that led to the introduction of this
patch.

Link: https://lore.kernel.org/all/nFDPJFnzE9Q5cqY7FwSMByRH2OAn_BpI4H53NQfWIlN6I2qfmAqnkp2wRqn0XjMO65OyZY4h6P4K2nAGKJpAOSzksYXaiAK_FoH_8QbgBI4=@proton.me/ [1]
Link: https://lore.kernel.org/all/nFDPJFnzE9Q5cqY7FwSMByRH2OAn_BpI4H53NQfWIlN6I2qfmAqnkp2wRqn0XjMO65OyZY4h6P4K2nAGKJpAOSzksYXaiAK_FoH_8QbgBI4=@proton.me/ [2]
Suggested-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
Reviewed-by: Björn Roy Baron <bjorn3_gh@protonmail.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240915-alice-file-v10-1-88484f7a3dcf@google.com
Signed-off-by: Christian Brauner <brauner@kernel.org>
2024-09-30 13:02:27 +02:00
Alice Ryhl
d077242d68 rust: support for shadow call stack sanitizer
Add all of the flags that are needed to support the shadow call stack
(SCS) sanitizer with Rust, and updates Kconfig to allow only
configurations that work.

The -Zfixed-x18 flag is required to use SCS on arm64, and requires rustc
version 1.80.0 or greater. This restriction is reflected in Kconfig.

When CONFIG_DYNAMIC_SCS is enabled, the build will be configured to
include unwind tables in the build artifacts. Dynamic SCS uses the
unwind tables at boot to find all places that need to be patched. The
-Cforce-unwind-tables=y flag ensures that unwind tables are available
for Rust code.

In non-dynamic mode, the -Zsanitizer=shadow-call-stack flag is what
enables the SCS sanitizer. Using this flag requires rustc version 1.82.0
or greater on the targets used by Rust in the kernel. This restriction
is reflected in Kconfig.

It is possible to avoid the requirement of rustc 1.80.0 by using
-Ctarget-feature=+reserve-x18 instead of -Zfixed-x18. However, this flag
emits a warning during the build, so this patch does not add support for
using it and instead requires 1.80.0 or greater.

The dependency is placed on `select HAVE_RUST` to avoid a situation
where enabling Rust silently turns off the sanitizer. Instead, turning
on the sanitizer results in Rust being disabled. We generally do not
want changes to CONFIG_RUST to result in any mitigations being changed
or turned off.

At the time of writing, rustc 1.82.0 only exists via the nightly release
channel. There is a chance that the -Zsanitizer=shadow-call-stack flag
will end up needing 1.83.0 instead, but I think it is small.

Reviewed-by: Sami Tolvanen <samitolvanen@google.com>
Reviewed-by: Ard Biesheuvel <ardb@kernel.org>
Reviewed-by: Kees Cook <kees@kernel.org>
Acked-by: Will Deacon <will@kernel.org>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240829-shadow-call-stack-v7-1-2f62a4432abf@google.com
[ Fixed indentation using spaces. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-13 00:03:14 +02:00
Miguel Ojeda
93dc3be194 docs: rust: include other expressions in conditional compilation section
Expand the conditional compilation section to explain how to support
other expressions, such as testing whether `RUSTC_VERSION` is at least
a given version, which requires a numerical comparison that Rust's `cfg`
predicates do not support (yet?).

Reviewed-by: Nicolas Schier <nicolas@fjasle.eu>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Masahiro Yamada <masahiroy@kernel.org>
Link: https://lore.kernel.org/r/20240902165535.1101978-7-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-05 22:45:01 +02:00
Miguel Ojeda
aeb0e24abb kbuild: rust: replace proc macros dependency on core.o with the version text
With the `RUSTC_VERSION_TEXT` rebuild support in place, now proc macros
can depend on that instead of `core.o`.

This means that both the `core` and `macros` crates can be built in
parallel, and that touching `core.o` does not trigger a rebuild of the
proc macros.

This could be accomplished using the same approach as for `core`
(i.e. depending directly on `include/config/RUSTC_VERSION_TEXT`). However,
that is considered an implementation detail [1], and thus it is best
to avoid it. Instead, let fixdep find a string that we explicitly
write down in the source code for this purpose (like it is done for
`include/linux/compiler-version.h`), which we can easily do (unlike for
`core`) since this is our own source code.

Suggested-by: Masahiro Yamada <masahiroy@kernel.org>
Link: https://lore.kernel.org/rust-for-linux/CAK7LNAQBG0nDupXSgAAk-6nOqeqGVkr3H1RjYaqRJ1OxmLm6xA@mail.gmail.com/ [1]
Reviewed-by: Nicolas Schier <nicolas@fjasle.eu>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Masahiro Yamada <masahiroy@kernel.org>
Link: https://lore.kernel.org/r/20240902165535.1101978-5-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-05 22:44:51 +02:00
Miguel Ojeda
ac3e972629 kbuild: rust: rebuild if the version text changes
Now that `RUSTC_VERSION_TEXT` exists, use it to rebuild `core` when the
version text changes (which in turn will trigger a rebuild of all the
kernel Rust code).

This also applies to proc macros (which only work with the `rustc` that
compiled them), via the already existing dependency on `core.o`. That
is cleaned up in the next commit.

However, this does not cover host programs written in Rust, which is
the same case in the C side.

This is accomplished by referencing directly the generated file, instead
of using the `fixdep` header trick, since we cannot change the Rust
standard library sources. This is not too much of a burden, since it
only needs to be done for `core`.

Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Nicolas Schier <nicolas@fjasle.eu>
Acked-by: Masahiro Yamada <masahiroy@kernel.org>
Link: https://lore.kernel.org/r/20240902165535.1101978-4-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-05 22:44:41 +02:00
Miguel Ojeda
5134a335cf kbuild: rust: re-run Kconfig if the version text changes
Re-run Kconfig if we detect the Rust compiler has changed via the version
text, like it is done for C.

Unlike C, and unlike `RUSTC_VERSION`, the `RUSTC_VERSION_TEXT` is kept
under `depends on RUST`, since it should not be needed unless `RUST`
is enabled.

Reviewed-by: Nicolas Schier <nicolas@fjasle.eu>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Masahiro Yamada <masahiroy@kernel.org>
Link: https://lore.kernel.org/r/20240902165535.1101978-3-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-05 22:44:34 +02:00
Miguel Ojeda
6e74c6b5a4 kbuild: rust: add CONFIG_RUSTC_VERSION
Now that we support several Rust versions, introduce
`CONFIG_RUSTC_VERSION` so that it can be used in Kconfig to enable and
disable configuration options based on the `rustc` version.

The approach taken resembles `pahole`'s -- see commit 613fe16923
("kbuild: Add CONFIG_PAHOLE_VERSION"), i.e. a simple version parsing
without trying to identify several kinds of compilers, since so far
there is only one (`rustc`).

However, unlike `pahole`'s, we also print a zero if executing failed for
any reason, rather than checking if the command is found and executable
(which still leaves things like a file that exists and is executable,
but e.g. is built for another platform [1]). An equivalent approach to
the one here was also submitted for `pahole` [2].

Link: https://lore.kernel.org/rust-for-linux/CANiq72=4vX_tJMJLE6e+bg7ZECHkS-AQpm8GBzuK75G1EB7+Nw@mail.gmail.com/ [1]
Link: https://lore.kernel.org/linux-kbuild/20240728125527.690726-1-ojeda@kernel.org/ [2]
Reviewed-by: Nicolas Schier <nicolas@fjasle.eu>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Masahiro Yamada <masahiroy@kernel.org>
Link: https://lore.kernel.org/r/20240902165535.1101978-2-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-05 22:44:18 +02:00
Miguel Ojeda
ab309b6e08 rust: avoid box_uninit_write feature
Like commit 0903b9e2a4 ("rust: alloc: eschew
`Box<MaybeUninit<T>>::write`"), but for the new `rbtree` and `alloc` code.

That is, `feature(new_uninit)` [1] got partially stabilized [2]
for Rust 1.82.0 (expected to be released on 2024-10-17), but it
did not include `Box<MaybeUninit<T>>::write`, which got split into
`feature(box_uninit_write)` [3].

To avoid relying on a new unstable feature, rewrite the `write` +
`assume_init` pair manually.

Link: https://github.com/rust-lang/rust/issues/63291 [1]
Link: https://github.com/rust-lang/rust/pull/129401 [2]
Link: https://github.com/rust-lang/rust/issues/129397 [3]
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Matt Gilbride <mattgilbride@google.com>
Link: https://lore.kernel.org/r/20240904144229.18592-1-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-04 23:11:31 +02:00
Miguel Ojeda
68d3b6aa08 MAINTAINERS: add Trevor Gross as Rust reviewer
Trevor has been involved with the Rust for Linux project for more than
a year now. He has been active reviewing Rust code in the mailing list,
and he already is a formal reviewer of the Rust PHY library and the two
PHY drivers.

In addition, he is also part of several upstream Rust teams:
compiler-contributors team (contributors to the Rust compiler on a regular
basis), libs-contributors (contributors to the Rust standard library on a
regular basis), crate-maintainers (maintainers of official Rust crates),
the binary size working group and the Rust for Linux ping group.

His expertise with the language will be very useful to have around in
the future if Rust keeps growing within the kernel, thus add him to the
`RUST` entry as a reviewer.

Acked-by: Boqun Feng <boqun.feng@gmail.com>
Acked-by: Trevor Gross <tmgross@umich.edu>
Link: https://lore.kernel.org/r/20240902173255.1105340-1-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-09-03 23:53:58 +02:00
Alice Ryhl
a335e95914 rust: rbtree: add RBTree::entry
This mirrors the entry API [1] from the Rust standard library on
`RBTree`. This API can be used to access the entry at a specific key and
make modifications depending on whether the key is vacant or occupied.
This API is useful because it can often be used to avoid traversing the
tree multiple times.

This is used by binder to look up and conditionally access or insert a
value, depending on whether it is there or not [2].

Link: https://doc.rust-lang.org/stable/std/collections/btree_map/enum.Entry.html [1]
Link: https://android-review.googlesource.com/c/kernel/common/+/2849906 [2]
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Matt Gilbride <mattgilbride@google.com>
Link: https://lore.kernel.org/r/20240822-b4-rbtree-v12-5-014561758a57@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-31 17:36:20 +02:00
Matt Gilbride
98c14e40e0 rust: rbtree: add cursor
Add a cursor interface to `RBTree`, supporting the following use cases:
- Inspect the current node pointed to by the cursor, inspect/move to
  it's neighbors in sort order (bidirectionally).
- Mutate the tree itself by removing the current node pointed to by the
  cursor, or one of its neighbors.

Add functions to obtain a cursor to the tree by key:
- The node with the smallest key
- The node with the largest key
- The node matching the given key, or the one with the next larger key

The cursor abstraction is needed by the binder driver to efficiently
search for nodes and (conditionally) modify them, as well as their
neighbors [1].

Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-6-08ba9197f637@google.com/ [1]
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Matt Gilbride <mattgilbride@google.com>
Link: https://lore.kernel.org/r/20240822-b4-rbtree-v12-4-014561758a57@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-31 17:36:20 +02:00
Wedson Almeida Filho
cf5397d177 rust: rbtree: add mutable iterator
Add mutable Iterator implementation for `RBTree`,
allowing iteration over (key, value) pairs in key order. Only values are
mutable, as mutating keys implies modifying a node's position in the tree.

Mutable iteration is used by the binder driver during shutdown to
clean up the tree maintained by the "range allocator" [1].

Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-6-08ba9197f637@google.com/ [1]
Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Matt Gilbride <mattgilbride@google.com>
Link: https://lore.kernel.org/r/20240822-b4-rbtree-v12-3-014561758a57@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-31 17:36:19 +02:00
Wedson Almeida Filho
e601f1bb8e rust: rbtree: add iterator
- Add Iterator implementation for `RBTree`, allowing
  iteration over (key, value) pairs in key order.
- Add individual `keys()` and `values()` functions to iterate over keys
  or values alone.
- Update doctests to use iteration instead of explicitly getting items.

Iteration is needed by the binder driver to enumerate all values in a
tree for oneway spam detection [1].

Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-17-08ba9197f637@google.com/ [1]
Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Signed-off-by: Matt Gilbride <mattgilbride@google.com>
Link: https://lore.kernel.org/r/20240822-b4-rbtree-v12-2-014561758a57@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-31 17:36:19 +02:00
Wedson Almeida Filho
a0d13aac70 rust: rbtree: add red-black tree implementation backed by the C version
The rust rbtree exposes a map-like interface over keys and values,
backed by the kernel red-black tree implementation. Values can be
inserted, deleted, and retrieved from a `RBTree` by key.

This base abstraction is used by binder to store key/value
pairs and perform lookups, for example the patch
"[PATCH RFC 03/20] rust_binder: add threading support"
in the binder RFC [1].

Link: https://lore.kernel.org/rust-for-linux/20231101-rust-binder-v1-3-08ba9197f637@google.com/ [1]
Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Matt Gilbride <mattgilbride@google.com>
Link: https://lore.kernel.org/r/20240822-b4-rbtree-v12-1-014561758a57@google.com
[ Updated link to docs.kernel.org. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-31 17:35:08 +02:00
Miguel Ojeda
6e6efc5fef rust: enable rustdoc's --generate-link-to-definition
In Rust 1.56.0 [1], rustdoc introduced the "jump to definition"
feature [2], i.e. the unstable flag `--generate-link-to-definition`.
It adds links to the source view of the documentation.

For instance, in the source view of `rust/kernel/sync.rs`, for this code:

    impl Default for LockClassKey {
        fn default() -> Self {
            Self::new()
        }
    }

It will add three hyperlinks:

  - `Default` points to the rendered "Trait `core::default::Default`"
    page (not the source view, since it goes to another crate, though
    this may change).

  - `LockClassKey` points to the `pub struct LockClassKey(...);` line
    in the same page, highlighting the line number.

  - `Self::new()` points to the `pub const fn new() -> Self { ... }`
    associated function, highlighting its line numbers (i.e. for the
    full function).

This makes the source view more useful and a bit closer to the experience
in e.g. the Elixir Cross Referencer [3].

I have provisionally enabled it for rust.docs.kernel.org [4] -- one can
take a look at the source view there for an example of how it looks like.

Thus enable it.

Cc: Guillaume Gomez <guillaume1.gomez@gmail.com>
Link: https://github.com/rust-lang/rust/pull/84176 [1]
Link: https://github.com/rust-lang/rust/issues/89095 [2]
Link: https://elixir.bootlin.com [3]
Link: https://rust.docs.kernel.org [4]
Reviewed-by: Gary Guo <gary@garyguo.net>
Link: https://lore.kernel.org/r/20240818141249.387166-1-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-25 18:37:40 +02:00
Miguel Ojeda
b2bf463ed9 docs: rust: improve main page introducing a "Code documentation" section
Clean the "Rust" main page by introducing a 'Code documentation" section
to separate it from the rest of the text above.

In addition, introduce the "Rust code documentation" term, which may be
clearer than referring to a potentially unknown tool.

Furthermore, for the HTML case, homogenize both `rustdoc` and
non-`rustdoc` cases and use the term introduced above instead.

Then, always generate the pregenerated version part, since now there
is a section that is always generated and thus makes sense to do so.

Finally, finish the new section with a link to more details about the
Rust code documentation.

The intention is that:

  - The non-HTML case mentions the code documentation too, making it
    more prominent for readers of non-HTML docs.

  - Both HTML cases read more naturally.

  - The pregenerated version is always mentioned, since it is likely
    useful for readers of non-HTML docs.

Link: https://lore.kernel.org/r/20240818141200.386899-2-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-25 18:37:40 +02:00
Miguel Ojeda
0eef6ec5a8 docs: rust: link to https://rust.docs.kernel.org
The Rust code documentation (i.e. `rustdoc`-generated docs) is now
available at:

    https://rust.docs.kernel.org

Thus document it and remove the `TODO` line.

The generation uses a particular kernel configuration, based on x86_64,
which may get tweaked over time. Older tags, and how they are generated,
may also change in the future. We may consider freezing them at some
point, but for the moment, the content should not be considered immutable.

Thanks Konstantin for the support setting it up!

Cc: Konstantin Ryabitsev <konstantin@linuxfoundation.org>
Acked-by: Konstantin Ryabitsev <konstantin@linuxfoundation.org>
Link: https://lore.kernel.org/r/20240818141200.386899-1-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-25 18:37:40 +02:00
Kartik Prajapati
96fff2dc29 rust: types: add ARef::into_raw
Add a method for `ARef` that is analogous to `Arc::into_raw`. It is the
inverse operation of `ARef::from_raw`, and allows you to convert the
`ARef` back into a raw pointer while retaining ownership of the
refcount.

This new function will be used by [1] for converting the type in an
`ARef` using `ARef::from_raw(ARef::into_raw(me).cast())`. Alice has
also needed the same function for other use-cases in the past, but [1]
is the first to go upstream.

This was implemented independently by Kartik and Alice. The two versions
were merged by Alice, so all mistakes are Alice's.

Link: https://lore.kernel.org/r/20240801-vma-v3-1-db6c1c0afda9@google.com [1]
Link: https://github.com/Rust-for-Linux/linux/issues/1044
Signed-off-by: Kartik Prajapati <kartikprajapati987@gmail.com>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
[ Reworded to correct the author reference and changed tag to Link
  since it is not a bug. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-25 14:44:39 +02:00
Michael Vetter
c73051168e rust: kernel: use docs.kernel.org links in code documentation
Use links to docs.kernel.org instead of www.kernel.org/doc/html/latest
in the code documentation. The links are shorter and cleaner.

Link: https://github.com/Rust-for-Linux/linux/issues/1101
Signed-off-by: Michael Vetter <jubalh@iodoru.org>
[ Reworded slightly. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-25 14:44:34 +02:00
Miguel Ojeda
f363930484 docs: rust: quick-start: add Debian Testing
Debian Testing is now also providing recent Rust releases (outside of
the freeze period), like Debian Unstable (Sid).

Thus add it to the list.

Cc: Fabian Grünbichler <debian@fabian.gruenbichler.email>
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-24 19:44:24 +02:00
Alice Ryhl
b204bbc53f rust: list: add ListArcField
One way to explain what `ListArc` does is that it controls exclusive
access to the prev/next pointer field in a refcounted object. The
feature of having a special reference to a refcounted object with
exclusive access to specific fields is useful for other things, so
provide a general utility for that.

This is used by Rust Binder to keep track of which processes have a
reference to a given node. This involves an object for each process/node
pair, that is referenced by both the process and the node. For some
fields in this object, only the process's reference needs to access
them (and it needs mutable access), so Binder uses a ListArc to give the
process's reference exclusive access.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-10-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
2003c04b05 rust: list: support heterogeneous lists
Support linked lists that can hold many different structs at once. This
is generally done using trait objects. The main challenge is figuring
what the struct is given only a pointer to the ListLinks.

We do this by storing a pointer to the struct next to the ListLinks
field. The container_of operation will then just read that pointer. When
the type is a trait object, that pointer will be a fat pointer whose
metadata is a vtable that tells you what kind of struct it is.

Heterogeneous lists are heavily used by Rust Binder. There are a lot of
so-called todo lists containing various events that need to be delivered
to userspace next time userspace calls into the driver. And there are
quite a few different todo item types: incoming transaction, changes to
refcounts, death notifications, and more.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-9-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
9078a4f956 rust: list: add cursor
The cursor is very similar to the list iterator, but it has one
important feature that the iterator doesn't: it can be used to remove
items from the linked list.

This feature cannot be added to the iterator because the references you
get from the iterator are considered borrows of the original list,
rather than borrows of the iterator. This means that there's no way to
prevent code like this:

let item = iter.next();
iter.remove();
use(item);

If `iter` was a cursor instead of an iterator, then `item` will be
considered a borrow of `iter`. Since `remove` destroys `iter`, this
means that the borrow-checker will prevent uses of `item` after the call
to `remove`.

So there is a trade-off between supporting use in traditional for loops,
and supporting removal of elements as you iterate. Iterators and cursors
represents two different choices on that spectrum.

Rust Binder needs cursors for the list of death notifications that a
process is currently handling. When userspace tells Binder that it has
finished processing the death notification, Binder will iterate the list
to search for the relevant item and remove it.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-8-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
deeecc9c1b rust: list: add iterators
Rust Binder has lists containing stuff such as all contexts or all
processes, and sometimes needs to iterate over them. This patch enables
Rust Binder to do that using a normal for loop.

The iterator returns the ArcBorrow type, so it is possible to grab a
refcount to values while iterating.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-7-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
db841866ec rust: list: add List
Add the actual linked list itself.

The linked list uses the following design: The List type itself just has
a single pointer to the first element of the list. And the actual list
items then form a cycle. So the last item is `first->prev`.

This is slightly different from the usual kernel linked list. Matching
that exactly would amount to giving List two pointers, and having it be
part of the cycle of items. This alternate design has the advantage that
the cycle is never completely empty, which can reduce the number of
branches in some cases. However, it also has the disadvantage that List
must be pinned, which this design is trying to avoid.

Having the list items form a cycle rather than having null pointers at
the beginning/end is convenient for several reasons. For one, it lets us
store only one pointer in List, and it simplifies the implementation of
several functions.

Unfortunately, the `remove` function that removes an arbitrary element
from the list has to be unsafe. This is needed because there is no way
to handle the case where you pass an element from the wrong list. For
example, if it is the first element of some other list, then that other
list's `first` pointer would not be updated. Similarly, it could be a
data race if you try to remove it from two different lists in parallel.
(There's no problem with passing `remove` an item that's not in any
list. Additionally, other removal methods such as `pop_front` need not
be unsafe, as they can't be used to remove items from another list.)

A future patch in this series will introduce support for cursors that
can be used to remove arbitrary items without unsafe code.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-6-f5f5e8075da0@google.com
[ Fixed a few typos. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
40c5329459 rust: list: add macro for implementing ListItem
Adds a macro for safely implementing the ListItem trait. As part of the
implementation of the macro, we also provide a HasListLinks trait
similar to the workqueue's HasWorkItem trait.

The HasListLinks trait is only necessary if you are implementing
ListItem using the impl_list_item macro.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-5-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
14176295fe rust: list: add struct with prev/next pointers
Define the ListLinks struct, which wraps the prev/next pointers that
will be used to insert values into a List in a future patch. Also
define the ListItem trait, which is implemented by structs that have a
ListLinks field.

The ListItem trait provides four different methods that are all
essentially container_of or the reverse of container_of. Two of them are
used before inserting/after removing an item from the list, and the two
others are used when looking at a value without changing whether it is
in a list. This distinction is introduced because it is needed for the
patch that adds support for heterogeneous lists, which are implemented
by adding a third pointer field with a fat pointer to the full struct.
When inserting into the heterogeneous list, the pointer-to-self is
updated to have the right vtable, and the container_of operation is
implemented by just returning that pointer instead of using the real
container_of operation.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-4-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
a48026315c rust: list: add tracking for ListArc
Add the ability to track whether a ListArc exists for a given value,
allowing for the creation of ListArcs without going through UniqueArc.

The `impl_list_arc_safe!` macro is extended with a `tracked_by` strategy
that defers the tracking of ListArcs to a field of the struct.
Additionally, the AtomicListArcTracker type is introduced, which can
track whether a ListArc exists using an atomic. By deferring the
tracking to a field of type AtomicListArcTracker, structs gain the
ability to create ListArcs without going through a UniqueArc.

Rust Binder uses this for some objects where we want to be able to
insert them into a linked list at any time. Using the
AtomicListArcTracker, we are able to check whether an item is already in
the list, and if not, we can create a `ListArc` and push it.

The macro has the ability to defer the tracking of ListArcs to a field,
using whatever strategy that field has. Since we don't add any
strategies other than AtomicListArcTracker, another similar option would
be to hard-code that the field should be an AtomicListArcTracker.
However, Rust Binder has a case where the AtomicListArcTracker is not
stored directly in the struct, but in a sub-struct. Furthermore, the
outer struct is generic:

struct Wrapper<T: ?Sized> {
    links: ListLinks,
    inner: T,
}

Here, the Wrapper struct implements ListArcSafe with `tracked_by inner`,
and then the various types used with `inner` also uses the macro to
implement ListArcSafe. Some of them use the untracked strategy, and some
of them use tracked_by with an AtomicListArcTracker. This way, Wrapper
just inherits whichever choice `inner` has made.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-3-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Alice Ryhl
6cd3417155 rust: list: add ListArc
The `ListArc` type can be thought of as a special reference to a
refcounted object that owns the permission to manipulate the
`next`/`prev` pointers stored in the refcounted object. By ensuring that
each object has only one `ListArc` reference, the owner of that
reference is assured exclusive access to the `next`/`prev` pointers.
When a `ListArc` is inserted into a `List`, the `List` takes ownership
of the `ListArc` reference.

There are various strategies for ensuring that a value has only one
`ListArc` reference. The simplest is to convert a `UniqueArc` into a
`ListArc`. However, the refcounted object could also keep track of
whether a `ListArc` exists using a boolean, which could allow for the
creation of new `ListArc` references from an `Arc` reference. Whatever
strategy is used, the relevant tracking is referred to as "the tracking
inside `T`", and the `ListArcSafe` trait (and its subtraits) are used to
update the tracking when a `ListArc` is created or destroyed.

Note that we allow the case where the tracking inside `T` thinks that a
`ListArc` exists, but actually, there isn't a `ListArc`. However, we do
not allow the opposite situation where a `ListArc` exists, but the
tracking thinks it doesn't. This is because the former can at most
result in us failing to create a `ListArc` when the operation could
succeed, whereas the latter can result in the creation of two `ListArc`
references. Only the latter situation can lead to memory safety issues.

This patch introduces the `impl_list_arc_safe!` macro that allows you to
implement `ListArcSafe` for types using the strategy where a `ListArc`
can only be created from a `UniqueArc`. Other strategies are introduced
in later patches.

This is part of the linked list that Rust Binder will use for many
different things. The strategy where a `ListArc` can only be created
from a `UniqueArc` is actually sufficient for most of the objects that
Rust Binder needs to insert into linked lists. Usually, these are todo
items that are created and then immediately inserted into a queue.

The const generic ID allows objects to have several prev/next pointer
pairs so that the same object can be inserted into several different
lists. You are able to have several `ListArc` references as long as they
correspond to different pointer pairs. The ID itself is purely a
compile-time concept and will not be present in the final binary. Both
the `List` and the `ListArc` will need to agree on the ID for them to
work together. Rust Binder uses this in a few places (e.g. death
recipients) where the same object can be inserted into both generic todo
lists and some other lists for tracking the status of the object.

The ID is a const generic rather than a type parameter because the
`pair_from_unique` method needs to be able to assert that the two ids
are different. There's no easy way to assert that when using types
instead of integers.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-2-f5f5e8075da0@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:26:57 +02:00
Benno Lossin
0528ca0a4f rust: init: add assert_pinned macro
Add a macro to statically check if a field of a struct is marked with
`#[pin]` ie that it is structurally pinned. This can be used when
`unsafe` code needs to rely on fields being structurally pinned.

The macro has a special "inline" mode for the case where the type
depends on generic parameters from the surrounding scope.

Signed-off-by: Benno Lossin <benno.lossin@proton.me>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240814-linked-list-v5-1-f5f5e8075da0@google.com
[ Replaced `compile_fail` with `ignore` and a TODO note. Removed
  `pub` from example to clean `unreachable_pub` lint. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:25:59 +02:00
Matthew Maurer
c6945acad7 rust: support arrays in target JSON
Some configuration options such as the supported sanitizer list are
arrays. To support using Rust with sanitizers on x86, we must update the
target.json generator to support this case.

The Push trait is removed in favor of the From trait because the Push
trait doesn't work well in the nested case where you are not really
pushing values to a TargetSpec.

Signed-off-by: Matthew Maurer <mmaurer@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Tested-by: Gatlin Newhouse <gatlin.newhouse@gmail.com>
Link: https://lore.kernel.org/r/20240730-target-json-arrays-v1-1-2b376fd0ecf4@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-23 06:25:59 +02:00
Benno Lossin
6d1c22d0ac rust: init: add write_[pin_]init functions
Sometimes it is necessary to split allocation and initialization into
two steps. One such situation is when reusing existing allocations
obtained via `Box::drop_contents`. See [1] for an example.

In order to support this use case add `write_[pin_]init` functions to the
pin-init API. These functions operate on already allocated smart
pointers that wrap `MaybeUninit<T>`.

Link: https://lore.kernel.org/rust-for-linux/f026532f-8594-4f18-9aa5-57ad3f5bc592@proton.me/ [1]
Signed-off-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Link: https://lore.kernel.org/r/20240819112415.99810-2-benno.lossin@proton.me
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-22 00:16:16 +02:00
Benno Lossin
01db99b272 rust: kernel: add drop_contents to BoxExt
Sometimes (see [1]) it is necessary to drop the value inside of a
`Box<T>`, but retain the allocation. For example to reuse the allocation
in the future.

Introduce a new function `drop_contents` that turns a `Box<T>` into
`Box<MaybeUninit<T>>` by dropping the value.

Link: https://lore.kernel.org/rust-for-linux/20240418-b4-rbtree-v3-5-323e134390ce@google.com/ [1]
Signed-off-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240819112415.99810-1-benno.lossin@proton.me
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-22 00:16:06 +02:00
Miguel Ojeda
76501d19c6 rust: enable bindgen's --enable-function-attribute-detection flag
`bindgen` is able to detect certain function attributes and annotate
functions correspondingly in its output for the Rust side, when the
`--enable-function-attribute-detection` is passed.

In particular, it is currently able to use `__must_check` in C
(`#[must_use]` in Rust), which give us a bunch of annotations that are
nice to have to prevent possible issues in Rust abstractions, e.g.:

     extern "C" {
    +    #[must_use]
         pub fn kobject_add(
             kobj: *mut kobject,
             parent: *mut kobject,
             fmt: *const core::ffi::c_char,
             ...
         ) -> core::ffi::c_int;
     }

Apparently, there are edge cases where this can make generation very slow,
which is why it is behind a flag [1], but it does not seem to affect us
in any major way at the moment.

Thus enable it.

Link: https://github.com/rust-lang/rust-bindgen/issues/1465 [1]
Link: https://lore.kernel.org/rust-for-linux/CANiq72=u5Nrz_NW3U3_VqywJkD8pECA07q2pFDd1wjtXOWdkAQ@mail.gmail.com/
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20240814163722.1550064-1-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-21 00:37:02 +02:00
Alice Ryhl
1d15880378 rust: sort blk includes in bindings_helper.h
The headers in this file are sorted alphabetically, which makes it
easy to quickly resolve conflicts by selecting all of the headers and
invoking :'<,'>sort to sort them. To keep this technique to resolve
conflicts working, also apply sorting to symbols that are not letters.

This file is very prone to merge conflicts, so I think keeping conflict
resolution really easy is more important than not messing with git blame
history.

These includes were originally introduced in commit 3253aba340 ("rust:
block: introduce `kernel::block::mq` module").

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20240809132835.274603-1-aliceryhl@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-21 00:37:02 +02:00
Gary Guo
e26fa54604 rust: kbuild: auto generate helper exports
This removes the need to explicitly export all symbols.

Generate helper exports similarly to what's currently done for Rust
crates. These helpers are exclusively called from within Rust code and
therefore can be treated similar as other Rust symbols.

Signed-off-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Tested-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20240817165302.3852499-1-gary@garyguo.net
[ Fixed dependency path, reworded slightly, edited comment a bit and
  rebased on top of the changes made when applying Andreas' patch
  (e.g. no `README.md` anymore, so moved the edits).  - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-19 11:09:02 +02:00
Miguel Ojeda
c4d7f546dd objtool/kbuild/rust: enable objtool for Rust
Now that we should be `objtool`-warning free, enable `objtool` for
Rust too.

Before this patch series, we were already getting warnings under e.g. IBT
builds, since those would see Rust code via `vmlinux.o`.

Tested-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Gary Guo <gary@garyguo.net>
Link: https://lore.kernel.org/r/20240725183325.122827-7-ojeda@kernel.org
[ Solved trivial conflict. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:34:37 +02:00
Miguel Ojeda
56d680dd23 objtool/rust: list noreturn Rust functions
Rust functions may be `noreturn` (i.e. diverging) by returning the
"never" type, `!`, e.g.

    fn f() -> ! {
        loop {}
    }

Thus list the known `noreturn` functions to avoid such warnings.

Without this, `objtool` would complain if enabled for Rust, e.g.:

    rust/core.o: warning: objtool:
    _R...9panic_fmt() falls through to next function _R...18panic_nounwind_fmt()

    rust/alloc.o: warning: objtool:
    .text: unexpected end of section

In order to do so, we cannot match symbols' names exactly, for two
reasons:

  - Rust mangling scheme [1] contains disambiguators [2] which we
    cannot predict (e.g. they may vary depending on the compiler version).

    One possibility to solve this would be to parse v0 and ignore/zero
    those before comparison.

  - Some of the diverging functions come from `core`, i.e. the Rust
    standard library, which may change with each compiler version
    since they are implementation details (e.g. `panic_internals`).

Thus, to workaround both issues, only part of the symbols are matched,
instead of using the `NORETURN` macro in `noreturns.h`.

Ideally, just like for the C side, we should have a better solution. For
instance, the compiler could give us the list via something like:

    $ rustc --emit=noreturns ...

[ Kees agrees this should be automated and Peter says:

    So it would be fairly simple to make objtool consume a magic section
    emitted by the compiler.. I think we've asked the compiler folks
    for that at some point even, but I don't have clear recollections.

  We will ask upstream Rust about it. And if they agree, then perhaps
  we can get Clang/GCC to implement something similar too -- for this
  sort of thing we can take advantage of the shorter cycles of `rustc`
  as well as their unstable features concept to experiment.

  Gary proposed using DWARF (though it would need to be available), and
  wrote a proof of concept script using the `object` and `gimli` crates:
  https://gist.github.com/nbdd0121/449692570622c2f46a29ad9f47c3379a

    - Miguel ]

Link: https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html [1]
Link: https://doc.rust-lang.org/rustc/symbol-mangling/v0.html#disambiguator [2]
Acked-by: Peter Zijlstra (Intel) <peterz@infradead.org>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Kees Cook <kees@kernel.org>
Tested-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20240725183325.122827-6-ojeda@kernel.org
[ Added `len_mismatch_fail` symbol for new `kernel` crate code merged
  since then as well as 3 more `core::panicking` symbols that appear
  in `RUST_DEBUG_ASSERTIONS=y` builds.  - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:34:37 +02:00
Miguel Ojeda
fc582dfc1f x86/rust: support MITIGATION_SLS
Support `MITIGATION_SLS` by enabling the target features that Clang does.

Without this, `objtool` would complain if enabled for Rust, e.g.:

    rust/core.o: warning: objtool:
    _R...next_up+0x44: missing int3 after ret

These should be eventually enabled via `-Ctarget-feature` when `rustc`
starts recognizing them (or via a new dedicated flag) [1].

Link: https://github.com/rust-lang/rust/issues/116851 [1]
Reviewed-by: Gary Guo <gary@garyguo.net>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20240725183325.122827-5-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:34:37 +02:00
Miguel Ojeda
d7868550d5 x86/rust: support MITIGATION_RETHUNK
The Rust compiler added support for `-Zfunction-return=thunk-extern` [1]
in 1.76.0 [2], i.e. the equivalent of `-mfunction-return=thunk-extern`.
Thus add support for `MITIGATION_RETHUNK`.

Without this, `objtool` would warn if enabled for Rust and already warns
under IBT builds, e.g.:

    samples/rust/rust_print.o: warning: objtool:
    _R...init+0xa5c: 'naked' return found in RETHUNK build

Link: https://github.com/rust-lang/rust/issues/116853 [1]
Link: https://github.com/rust-lang/rust/pull/116892 [2]
Reviewed-by: Gary Guo <gary@garyguo.net>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Thomas Gleixner <tglx@linutronix.de>
Link: https://github.com/Rust-for-Linux/linux/issues/945
Link: https://lore.kernel.org/r/20240725183325.122827-4-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:34:37 +02:00
Miguel Ojeda
284a3ac4a9 x86/rust: support MITIGATION_RETPOLINE
Support `MITIGATION_RETPOLINE` by enabling the target features that
Clang does.

The existing target feature being enabled was a leftover from
our old `rust` branch, and it is not enough: the target feature
`retpoline-external-thunk` only implies `retpoline-indirect-calls`, but
not `retpoline-indirect-branches` (see LLVM's `X86.td`), unlike Clang's
flag of the same name `-mretpoline-external-thunk` which does imply both
(see Clang's `lib/Driver/ToolChains/Arch/X86.cpp`).

Without this, `objtool` would complain if enabled for Rust, e.g.:

    rust/core.o: warning: objtool:
    _R...escape_default+0x13: indirect jump found in RETPOLINE build

In addition, change the comment to note that LLVM is the one disabling
jump tables when retpoline is enabled, thus we do not need to use
`-Zno-jump-tables` for Rust here -- see commit c58f2166ab39 ("Introduce
the "retpoline" x86 mitigation technique ...") [1]:

    The goal is simple: avoid generating code which contains an indirect
    branch that could have its prediction poisoned by an attacker. In
    many cases, the compiler can simply use directed conditional
    branches and a small search tree. LLVM already has support for
    lowering switches in this way and the first step of this patch is
    to disable jump-table lowering of switches and introduce a pass to
    rewrite explicit indirectbr sequences into a switch over integers.

As well as a live example at [2].

These should be eventually enabled via `-Ctarget-feature` when `rustc`
starts recognizing them (or via a new dedicated flag) [3].

Cc: Daniel Borkmann <daniel@iogearbox.net>
Link: c58f2166ab [1]
Link: https://godbolt.org/z/G4YPr58qG [2]
Link: https://github.com/rust-lang/rust/issues/116852 [3]
Reviewed-by: Gary Guo <gary@garyguo.net>
Tested-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Benno Lossin <benno.lossin@proton.me>
Link: https://github.com/Rust-for-Linux/linux/issues/945
Link: https://lore.kernel.org/r/20240725183325.122827-3-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:34:37 +02:00
Miguel Ojeda
289088d546 rust: module: add static pointer to {init,cleanup}_module()
Add the equivalent of the `___ADDRESSABLE()` annotation in the
`module_{init,exit}` macros to the Rust `module!` macro.

Without this, `objtool` would complain if enabled for Rust (under IBT
builds), e.g.:

    samples/rust/rust_print.o: warning: objtool: cleanup_module(): not an indirect call target
    samples/rust/rust_print.o: warning: objtool: init_module(): not an indirect call target

Tested-by: Alice Ryhl <aliceryhl@google.com>
Tested-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Gary Guo <gary@garyguo.net>
Link: https://lore.kernel.org/r/20240725183325.122827-2-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:34:37 +02:00
Andreas Hindborg
876346536c rust: kbuild: split up helpers.c
This patch splits up the rust helpers C file. When rebasing patch sets on
upstream linux, merge conflicts in helpers.c is common and time consuming
[1]. Thus, split the file so that each kernel component can live in a
separate file.

This patch lists helper files explicitly and thus conflicts in the file
list is still likely. However, they should be more simple to resolve than
the conflicts usually seen in helpers.c.

[ Removed `README.md` and undeleted the original comment since now,
  in v3 of the series, we have a `helpers.c` again; which also allows
  us to keep the "Sorted alphabetically" line and makes the diff easier.

  In addition, updated the Documentation/ mentions of the file, reworded
  title and removed blank lines at the end of `page.c`.  - Miguel ]

Link: https://rust-for-linux.zulipchat.com/#narrow/stream/288089-General/topic/Splitting.20up.20helpers.2Ec/near/426694012 [1]
Signed-off-by: Andreas Hindborg <a.hindborg@samsung.com>
Reviewed-by: Gary Guo <gary@garyguo.net>
Acked-by: Dirk Behme <dirk.behme@de.bosch.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20240815103016.2771842-1-nmi@metaspace.dk
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:34:26 +02:00
Neal Gompa
f1385dc670 init/Kconfig: Only block on RANDSTRUCT for RUST
When enabling Rust in the kernel, we only need to block on the
RANDSTRUCT feature and GCC plugin. The rest of the GCC plugins
are reasonably safe to enable.

[ Originally (years ago) we only had this restriction, but we ended up
  restricting also the rest of the GCC plugins 1) to be on the safe side,
  2) since compiler plugin support could be going away in the kernel and
  3) since mixed builds are best effort so far; so I asked Neal about
  his experience enabling the other plugins -- Neal says:

    When I originally wrote this patch two years ago to get things
    working, Fedora used all the GCC plugins, so I was trying to get GCC +
    Rust to work while minimizing the delta on build differences. This was
    the combination that worked. We've been carrying this patch in the
    Asahi tree for a year now. And while Fedora does not currently have
    GCC plugins enabled because it caused issues with some third-party
    modules (I think it was the NVIDIA driver, but I'm not sure), it was
    around long enough for me to know with some confidence that it was
    fine this way.

  - Miguel ]

Signed-off-by: Neal Gompa <neal@gompa.dev>
Link: https://lore.kernel.org/r/20240731125615.3368813-1-neal@gompa.dev
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:10:53 +02:00
Miguel Ojeda
7bc186731e rust: error: allow useless_conversion for 32-bit builds
For the new Rust support for 32-bit arm [1], Clippy warns:

    error: useless conversion to the same type: `i32`
       --> rust/kernel/error.rs:139:36
        |
    139 |         unsafe { bindings::ERR_PTR(self.0.into()) as *mut _ }
        |                                    ^^^^^^^^^^^^^ help: consider removing `.into()`: `self.0`
        |
        = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#useless_conversion
        = note: `-D clippy::useless-conversion` implied by `-D warnings`
        = help: to override `-D warnings` add `#[allow(clippy::useless_conversion)]`

The `self.0.into()` converts an `c_int` into `ERR_PTR`'s parameter
which is a `c_long`. Thus, both types are `i32` in 32-bit. Therefore,
allow it for those architectures.

Link: https://lore.kernel.org/rust-for-linux/2dbd1491-149d-443c-9802-75786a6a3b73@gmail.com/ [1]
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Christian Schrefl <chrisi.schrefl@gmail.com>
Link: https://lore.kernel.org/r/20240730155702.1110144-1-ojeda@kernel.org
[ Fixed typo in tag. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:10:53 +02:00
Benno Lossin
7adcdd5722 rust: types: improve ForeignOwnable documentation
There are no guarantees for the pointer returned by `into_foreign`.
This is simply because there is no safety documentation stating any
guarantees. Therefore dereferencing and all other operations for that
pointer are not allowed in a general context (i.e. when the concrete
type implementing the trait is not known).
This might be confusing, therefore add normal documentation to state
that there are no guarantees given for the pointer.

Signed-off-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20240730182251.1466684-1-benno.lossin@proton.me
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:10:53 +02:00
Alice Ryhl
6c2d0ad53b rust: implement ForeignOwnable for Pin<Box<T>>
We already implement ForeignOwnable for Box<T>, but it may be useful to
store pinned data in a ForeignOwnable container. This patch makes that
possible.

This will be used together with upcoming miscdev abstractions, which
Binder will use when binderfs is disabled.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20240730-foreign-ownable-pin-box-v1-1-b1d70cdae541@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-08-18 23:10:53 +02:00