summaryrefslogtreecommitdiff
AgeCommit message (Collapse)Author
2024-09-10mm: krealloc: clarify valid usage of __GFP_ZEROmm/kreallocDanilo Krummrich
Properly document that if __GFP_ZERO logic is requested, callers must ensure that, starting with the initial memory allocation, every subsequent call to this API for the same memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that __GFP_ZERO is not fully honored by this API. Link: https://lkml.kernel.org/r/20240812223707.32049-2-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org> Acked-by: David Rientjes <rientjes@google.com> Cc: Christoph Lameter <cl@linux.com> Cc: Hyeonggon Yoo <42.hyeyoo@gmail.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com> Cc: Pekka Enberg <penberg@kernel.org> Cc: Roman Gushchin <roman.gushchin@linux.dev> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2024-09-10mm: krealloc: consider spare memory for __GFP_ZERODanilo Krummrich
As long as krealloc() is called with __GFP_ZERO consistently, starting with the initial memory allocation, __GFP_ZERO should be fully honored. However, if for an existing allocation krealloc() is called with a decreased size, it is not ensured that the spare portion the allocation is zeroed. Thus, if krealloc() is subsequently called with a larger size again, __GFP_ZERO can't be fully honored, since we don't know the previous size, but only the bucket size. Example: buf = kzalloc(64, GFP_KERNEL); memset(buf, 0xff, 64); buf = krealloc(buf, 48, GFP_KERNEL | __GFP_ZERO); /* After this call the last 16 bytes are still 0xff. */ buf = krealloc(buf, 64, GFP_KERNEL | __GFP_ZERO); Fix this, by explicitly setting spare memory to zero, when shrinking an allocation with __GFP_ZERO flag set or init_on_alloc enabled. Link: https://lkml.kernel.org/r/20240812223707.32049-1-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org> Acked-by: Vlastimil Babka <vbabka@suse.cz> Acked-by: David Rientjes <rientjes@google.com> Cc: Christoph Lameter <cl@linux.com> Cc: Hyeonggon Yoo <42.hyeyoo@gmail.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com> Cc: Pekka Enberg <penberg@kernel.org> Cc: Roman Gushchin <roman.gushchin@linux.dev> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2024-09-10mm: kvmalloc: align kvrealloc() with krealloc()Danilo Krummrich
Besides the obvious (and desired) difference between krealloc() and kvrealloc(), there is some inconsistency in their function signatures and behavior: - krealloc() frees the memory when the requested size is zero, whereas kvrealloc() simply returns a pointer to the existing allocation. - krealloc() behaves like kmalloc() if a NULL pointer is passed, whereas kvrealloc() does not accept a NULL pointer at all and, if passed, would fault instead. - krealloc() is self-contained, whereas kvrealloc() relies on the caller to provide the size of the previous allocation. Inconsistent behavior throughout allocation APIs is error prone, hence make kvrealloc() behave like krealloc(), which seems superior in all mentioned aspects. Besides that, implementing kvrealloc() by making use of krealloc() and vrealloc() provides oppertunities to grow (and shrink) allocations more efficiently. For instance, vrealloc() can be optimized to allocate and map additional pages to grow the allocation or unmap and free unused pages to shrink the allocation. [dakr@kernel.org: document concurrency restrictions] Link: https://lkml.kernel.org/r/20240725125442.4957-1-dakr@kernel.org [dakr@kernel.org: disable KASAN when switching to vmalloc] Link: https://lkml.kernel.org/r/20240730185049.6244-2-dakr@kernel.org [dakr@kernel.org: properly document __GFP_ZERO behavior] Link: https://lkml.kernel.org/r/20240730185049.6244-5-dakr@kernel.org Link: https://lkml.kernel.org/r/20240722163111.4766-3-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org> Acked-by: Michal Hocko <mhocko@suse.com> Acked-by: Vlastimil Babka <vbabka@suse.cz> Cc: Chandan Babu R <chandan.babu@oracle.com> Cc: Christian König <christian.koenig@amd.com> Cc: Christoph Hellwig <hch@infradead.org> Cc: Christoph Lameter <cl@linux.com> Cc: David Rientjes <rientjes@google.com> Cc: Hyeonggon Yoo <42.hyeyoo@gmail.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com> Cc: Kees Cook <kees@kernel.org> Cc: Marc Zyngier <maz@kernel.org> Cc: Michael Ellerman <mpe@ellerman.id.au> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Oliver Upton <oliver.upton@linux.dev> Cc: Pekka Enberg <penberg@kernel.org> Cc: Roman Gushchin <roman.gushchin@linux.dev> Cc: Uladzislau Rezki <urezki@gmail.com> Cc: Wedson Almeida Filho <wedsonaf@gmail.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2024-09-10mm: vmalloc: implement vrealloc()Danilo Krummrich
Patch series "Align kvrealloc() with krealloc()", v2. Besides the obvious (and desired) difference between krealloc() and kvrealloc(), there is some inconsistency in their function signatures and behavior: - krealloc() frees the memory when the requested size is zero, whereas kvrealloc() simply returns a pointer to the existing allocation. - krealloc() behaves like kmalloc() if a NULL pointer is passed, whereas kvrealloc() does not accept a NULL pointer at all and, if passed, would fault instead. - krealloc() is self-contained, whereas kvrealloc() relies on the caller to provide the size of the previous allocation. Inconsistent behavior throughout allocation APIs is error prone, hence make kvrealloc() behave like krealloc(), which seems superior in all mentioned aspects. In order to be able to get rid of kvrealloc()'s oldsize parameter, introduce vrealloc() and make use of it in kvrealloc(). Making use of vrealloc() in kvrealloc() also provides oppertunities to grow (and shrink) allocations more efficiently. For instance, vrealloc() can be optimized to allocate and map additional pages to grow the allocation or unmap and free unused pages to shrink the allocation. Besides the above, those functions are required by Rust's allocator abstractons [1] (rework based on this series in [2]). With `Vec` or `KVec` respectively, potentially growing (and shrinking) data structures are rather common. [1] https://lore.kernel.org/lkml/20240704170738.3621-1-dakr@redhat.com/ [2] https://git.kernel.org/pub/scm/linux/kernel/git/dakr/linux.git/log/?h=rust/mm This patch (of 2): Implement vrealloc() analogous to krealloc(). Currently, krealloc() requires the caller to pass the size of the previous memory allocation, which, instead, should be self-contained. We attempt to fix this in a subsequent patch which, in order to do so, requires vrealloc(). Besides that, we need realloc() functions for kernel allocators in Rust too. With `Vec` or `KVec` respectively, potentially growing (and shrinking) data structures are rather common. [dakr@kernel.org: fix missing nommu implementation] Link: https://lkml.kernel.org/r/20240725141227.13954-1-dakr@kernel.org [dakr@kernel.org: document concurrency restrictions] Link: https://lkml.kernel.org/r/20240725125442.4957-1-dakr@kernel.org [dakr@kernel.org: consider spare memory for __GFP_ZERO] Link: https://lkml.kernel.org/r/20240730185049.6244-3-dakr@kernel.org [dakr@kernel.org: properly document __GFP_ZERO behavior] Link: https://lkml.kernel.org/r/20240730185049.6244-4-dakr@kernel.org Link: https://lkml.kernel.org/r/20240722163111.4766-1-dakr@kernel.org Link: https://lkml.kernel.org/r/20240722163111.4766-2-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org> Acked-by: Michal Hocko <mhocko@suse.com> Acked-by: Vlastimil Babka <vbabka@suse.cz> Cc: Chandan Babu R <chandan.babu@oracle.com> Cc: Christian König <christian.koenig@amd.com> Cc: Christoph Hellwig <hch@infradead.org> Cc: Christoph Lameter <cl@linux.com> Cc: David Rientjes <rientjes@google.com> Cc: Hyeonggon Yoo <42.hyeyoo@gmail.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com> Cc: Kees Cook <kees@kernel.org> Cc: Marc Zyngier <maz@kernel.org> Cc: Michael Ellerman <mpe@ellerman.id.au> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Oliver Upton <oliver.upton@linux.dev> Cc: Pekka Enberg <penberg@kernel.org> Cc: Roman Gushchin <roman.gushchin@linux.dev> Cc: Uladzislau Rezki <urezki@gmail.com> Cc: Wedson Almeida Filho <wedsonaf@gmail.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2024-09-05docs: rust: include other expressions in conditional compilation sectionMiguel Ojeda
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-05kbuild: rust: replace proc macros dependency on `core.o` with the version textMiguel Ojeda
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-05kbuild: rust: rebuild if the version text changesMiguel Ojeda
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-05kbuild: rust: re-run Kconfig if the version text changesMiguel Ojeda
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-05kbuild: rust: add `CONFIG_RUSTC_VERSION`Miguel Ojeda
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 613fe1692377 ("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-04rust: avoid `box_uninit_write` featureMiguel Ojeda
Like commit 0903b9e2a46c ("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-03MAINTAINERS: add Trevor Gross as Rust reviewerMiguel Ojeda
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-08-31rust: rbtree: add `RBTree::entry`Alice Ryhl
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-31rust: rbtree: add cursorMatt Gilbride
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-31rust: rbtree: add mutable iteratorWedson Almeida Filho
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-31rust: rbtree: add iteratorWedson Almeida Filho
- 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-31rust: rbtree: add red-black tree implementation backed by the C versionWedson Almeida Filho
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-25rust: enable rustdoc's `--generate-link-to-definition`Miguel Ojeda
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-25docs: rust: improve main page introducing a "Code documentation" sectionMiguel Ojeda
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-25docs: rust: link to https://rust.docs.kernel.orgMiguel Ojeda
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-25rust: types: add `ARef::into_raw`Kartik Prajapati
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-25rust: kernel: use docs.kernel.org links in code documentationMichael Vetter
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-24docs: rust: quick-start: add Debian TestingMiguel Ojeda
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-23rust: list: add ListArcFieldAlice Ryhl
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-23rust: list: support heterogeneous listsAlice Ryhl
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-23rust: list: add cursorAlice Ryhl
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-23rust: list: add iteratorsAlice Ryhl
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-23rust: list: add ListAlice Ryhl
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-23rust: list: add macro for implementing ListItemAlice Ryhl
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-23rust: list: add struct with prev/next pointersAlice Ryhl
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-23rust: list: add tracking for ListArcAlice Ryhl
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-23rust: list: add ListArcAlice Ryhl
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-23rust: init: add `assert_pinned` macroBenno Lossin
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-23rust: support arrays in target JSONMatthew Maurer
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-22rust: init: add `write_[pin_]init` functionsBenno Lossin
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-22rust: kernel: add `drop_contents` to `BoxExt`Benno Lossin
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-21rust: enable bindgen's `--enable-function-attribute-detection` flagMiguel Ojeda
`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-21rust: sort blk includes in bindings_helper.hAlice Ryhl
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 3253aba3408a ("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-19rust: kbuild: auto generate helper exportsGary Guo
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-18objtool/kbuild/rust: enable objtool for RustMiguel Ojeda
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-18objtool/rust: list `noreturn` Rust functionsMiguel Ojeda
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-18x86/rust: support MITIGATION_SLSMiguel Ojeda
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-18x86/rust: support MITIGATION_RETHUNKMiguel Ojeda
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-18x86/rust: support MITIGATION_RETPOLINEMiguel Ojeda
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: https://github.com/llvm/llvm-project/commit/c58f2166ab3987f37cb0d7815b561bff5a20a69a [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-18rust: module: add static pointer to `{init,cleanup}_module()`Miguel Ojeda
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-18rust: kbuild: split up helpers.cAndreas Hindborg
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-18init/Kconfig: Only block on RANDSTRUCT for RUSTNeal Gompa
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-18rust: error: allow `useless_conversion` for 32-bit buildsMiguel Ojeda
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-18rust: types: improve `ForeignOwnable` documentationBenno Lossin
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-18rust: implement ForeignOwnable for Pin<Box<T>>Alice Ryhl
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-18rust: Implement the smart pointer `InPlaceInit` for `Arc`Alex Mantel
For pinned and unpinned initialization of structs, a trait named `InPlaceInit` exists for uniform access. `Arc` did not implement `InPlaceInit` yet, although the functions already existed. The main reason for that, was that the trait itself returned a `Pin<Self>`. The `Arc` implementation of the kernel is already implicitly pinned. To enable `Arc` to implement `InPlaceInit` and to have uniform access, for in-place and pinned in-place initialization, an associated type is introduced for `InPlaceInit`. The new implementation of `InPlaceInit` for `Arc` sets `Arc` as the associated type. Older implementations use an explicit `Pin<T>` as the associated type. The implemented methods for `Arc` are mostly moved from a direct implementation on `Arc`. There should be no user impact. The implementation for `ListArc` is omitted, because it is not merged yet. Link: https://github.com/Rust-for-Linux/linux/issues/1079 Signed-off-by: Alex Mantel <alexmantel93@mailbox.org> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20240727042442.682109-1-alexmantel93@mailbox.org [ Removed "Rusts" (Benno). - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>