Commit graph

25 commits

Author SHA1 Message Date
Miguel Ojeda
8ecb65b7b6 Alloc & DMA changes for v6.17
Box:
   - Implement Borrow / BorrowMut for Box<T, A>.
 
 Vec:
   - Implement Default for Vec<T, A>.
 
   - Implement Borrow / BorrowMut for Vec<T, A>.
 
 DMA:
   - Clarify wording and be consistent in 'coherent' nomenclature.
 
   - Convert the read!() / write!() macros to return a Result.
 
   - Add as_slice() / write() methods in CoherentAllocation.
 
   - Fix doc-comment of dma_handle().
 
   - Expose count() and size() in CoherentAllocation and add the
     corresponding type invariants.
 
   - Implement CoherentAllocation::dma_handle_with_offset().
 
   - Require mutable reference for as_slice_mut() and write().
 
 - Add Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki and Lorenzo Stoakes
   as reviewers (thanks everyone).
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCaHZWlAAKCRBFlHeO1qrK
 LgBrAQDgp1+5ocMJKJDgBtCXpRCe2F9OBz9L7CY1EzSRz2JHTAD/YZ5D1DeSi1l8
 U+tqG9+5i8twB3PR/TC4d7+GaBfTcQQ=
 =LaOk
 -----END PGP SIGNATURE-----

Merge tag 'alloc-next-v6.17-2025-07-15' of https://github.com/Rust-for-Linux/linux into rust-next

Pull alloc and DMA updates from Danilo Krummrich:

  Box:
   - Implement Borrow / BorrowMut for Box<T, A>.

  Vec:
   - Implement Default for Vec<T, A>.

   - Implement Borrow / BorrowMut for Vec<T, A>.

  DMA:
   - Clarify wording and be consistent in 'coherent' nomenclature.

   - Convert the read!() / write!() macros to return a Result.

   - Add as_slice() / write() methods in CoherentAllocation.

   - Fix doc-comment of dma_handle().

   - Expose count() and size() in CoherentAllocation and add the
     corresponding type invariants.

   - Implement CoherentAllocation::dma_handle_with_offset().

   - Require mutable reference for as_slice_mut() and write().

  MAINTAINERS:
   - Add Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki and Lorenzo
     Stoakes as reviewers (thanks everyone).

* tag 'alloc-next-v6.17-2025-07-15' of https://github.com/Rust-for-Linux/linux:
  MAINTAINERS: add mm folks as reviewers to rust alloc
  rust: dma: require mutable reference for as_slice_mut() and write()
  rust: dma: add dma_handle_with_offset method to CoherentAllocation
  rust: dma: expose the count and size of CoherentAllocation
  rust: dma: fix doc-comment of dma_handle()
  rust: dma: add as_slice/write functions for CoherentAllocation
  rust: dma: convert the read/write macros to return Result
  rust: dma: clarify wording and be consistent in `coherent` nomenclature
  rust: alloc: implement `Borrow` and `BorrowMut` for `KBox`
  rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
  rust: vec: impl Default for Vec with any allocator
2025-07-15 23:42:55 +02:00
Tamir Duberstein
fcad9bbf9e rust: enable clippy::ptr_as_ptr lint
In Rust 1.51.0, Clippy introduced the `ptr_as_ptr` lint [1]:

> Though `as` casts between raw pointers are not terrible,
> `pointer::cast` is safer because it cannot accidentally change the
> pointer's mutability, nor cast the pointer to other types like `usize`.

There are a few classes of changes required:
- Modules generated by bindgen are marked
  `#[allow(clippy::ptr_as_ptr)]`.
- Inferred casts (` as _`) are replaced with `.cast()`.
- Ascribed casts (` as *... T`) are replaced with `.cast::<T>()`.
- Multistep casts from references (` as *const _ as *const T`) are
  replaced with `core::ptr::from_ref(&x).cast()` with or without `::<T>`
  according to the previous rules. The `core::ptr::from_ref` call is
  required because `(x as *const _).cast::<T>()` results in inference
  failure.
- Native literal C strings are replaced with `c_str!().as_char_ptr()`.
- `*mut *mut T as _` is replaced with `let *mut *const T = (*mut *mut
  T)`.cast();` since pointer to pointer can be confusing.

Apply these changes and enable the lint -- no functional change
intended.

Link: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr [1]
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Acked-by: Viresh Kumar <viresh.kumar@linaro.org>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: Tejun Heo <tj@kernel.org>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250615-ptr-as-ptr-v12-1-f43b024581e8@gmail.com
[ Added `.cast()` for `opp`. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-22 23:08:42 +02:00
Alexandre Courbot
c09a8ac1cd rust: alloc: implement Borrow and BorrowMut for Vec
Implement `Borrow<[T]>` and `BorrowMut<[T]>` for `Vec<T>`. This allows
`Vec<T>` to be used in generic APIs asking for types implementing those
traits. `[T; N]` and `&mut [T]` also implement those traits allowing
users to use either owned, borrowed and heap-owned values.

The implementation leverages `as_slice` and `as_mut_slice`.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250616-borrow_impls-v4-1-36f9beb3fe6a@nvidia.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-18 23:09:21 +02:00
Alice Ryhl
47d8101924 rust: vec: impl Default for Vec with any allocator
The implementation of Default is restricted to only work with kmalloc
vectors for no good reason. This means I have to use

	mem::replace(&mut my_vec, KVVec::new())

in Rust Binder instead of `mem::take(&mut my_vec)`. Thus, expand the
impl of Default to work with any allocator including kvmalloc.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250610-vec-default-v1-1-7bb2c97d75a0@google.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-11 16:35:10 +02:00
Miguel Ojeda
bb941ea789 rust: remove unneeded Rust 1.87.0 allow(clippy::ptr_eq)
For the Rust 1.87.0 release, Clippy was expected to warn with:

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

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

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

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

Link: https://github.com/rust-lang/rust/pull/140859 [1]
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250520182125.806758-1-ojeda@kernel.org
[ Reworded for clarity. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-22 11:46:50 +02:00
Miguel Ojeda
22c3335c5d Alloc changes for v6.16
Box:
   - support for type coercion, e.g. `Box<T>` to `Box<dyn U>` if T
     implements U
 
 Vec:
   - implement new methods (prerequisites for nova-core and binder)
     - Vec::truncate()
     - Vec::resize()
     - Vec::clear()
     - Vec::pop()
     - Vec::push_within_capacity()
       - new error type: PushError
     - Vec::drain_all()
     - Vec::retain()
     - Vec::remove()
       - new error type: RemoveError
     - Vec::insert_within_capacity
       - new error type: InsertError
   - simplify Vec::push() using Vec::spare_capacity_mut()
   - split Vec::set_len() into Vec::inc_len() and Vec::dec_len()
     - add type invariant Vec::len() <= Vec::capacity
     - simplify Vec::truncate() using Vec::dec_len()
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCaCMRLAAKCRBFlHeO1qrK
 LsN3AP4jqS886xuFT6+Ibh1rinGu3RX5ffK0b2/tm47+BP2ysAD/UZ5M1DHhP1z4
 SIQ+Ad9hSQoV6kQngRBKo0SdsZw8jgk=
 =T22w
 -----END PGP SIGNATURE-----

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

Pull alloc updates from Danilo Krummrich:
 "Box:

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

  Vec:

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

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

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

* tag 'alloc-next-v6.16-2025-05-13' of https://github.com/Rust-for-Linux/linux:
  rust: alloc: add Vec::insert_within_capacity
  rust: alloc: add Vec::remove
  rust: alloc: add Vec::retain
  rust: alloc: add Vec::drain_all
  rust: alloc: add Vec::push_within_capacity
  rust: alloc: add Vec::pop
  rust: alloc: add Vec::clear
  rust: alloc: replace `Vec::set_len` with `inc_len`
  rust: alloc: refactor `Vec::truncate` using `dec_len`
  rust: alloc: add `Vec::dec_len`
  rust: alloc: add Vec::len() <= Vec::capacity invariant
  rust: alloc: allow coercion from `Box<T>` to `Box<dyn U>` if T implements U
  rust: alloc: use `spare_capacity_mut` to reduce unsafe
  rust: alloc: add Vec::resize method
  rust: alloc: add Vec::truncate method
  rust: alloc: add missing invariant in Vec::set_len()
2025-05-18 20:56:03 +02:00
Alice Ryhl
771c5a7d98 rust: alloc: add Vec::insert_within_capacity
This adds a variant of Vec::insert that does not allocate memory. This
makes it safe to use this function while holding a spinlock. Rust Binder
uses it for the range allocator fast path.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-7-06d20ad9366f@google.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:40:45 +02:00
Alice Ryhl
294a7ecbdf rust: alloc: add Vec::remove
This is needed by Rust Binder in the range allocator, and by upcoming
GPU drivers during firmware initialization.

Panics in the kernel are best avoided when possible, so an error is
returned if the index is out of bounds. An error type is used rather
than just returning Option<T> to let callers handle errors with ?.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-6-06d20ad9366f@google.com
[ Remove `# Panics` section; `Vec::remove() handles the error properly.`
  - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:40:02 +02:00
Alice Ryhl
9f140894e7 rust: alloc: add Vec::retain
This adds a common Vec method called `retain` that removes all elements
that don't match a certain condition. Rust Binder uses it to find all
processes that match a given pid.

The stdlib retain method takes &T rather than &mut T and has a separate
retain_mut for the &mut T case. However, this is considered an API
mistake that can't be fixed now due to backwards compatibility. There's
no reason for us to repeat that mistake.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-5-06d20ad9366f@google.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:39:39 +02:00
Alice Ryhl
088bf14a88 rust: alloc: add Vec::drain_all
This is like the stdlib method drain, except that it's hard-coded to use
the entire vector's range. Rust Binder uses it in the range allocator to
take ownership of everything in a vector in a case where reusing the
vector is desirable.

Implementing `DrainAll` in terms of `slice::IterMut` lets us reuse some
nice optimizations in core for the case where T is a ZST.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-4-06d20ad9366f@google.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:39:22 +02:00
Alice Ryhl
9def0d0a2a rust: alloc: add Vec::push_within_capacity
This introduces a new method called `push_within_capacity` for appending
to a vector without attempting to allocate if the capacity is full. Rust
Binder will use this in various places to safely push to a vector while
holding a spinlock.

The implementation is moved to a push_within_capacity_unchecked method.
This is preferred over having push() call push_within_capacity()
followed by an unwrap_unchecked() for simpler unsafe.

Panics in the kernel are best avoided when possible, so an error is
returned if the vector does not have sufficient capacity. An error type
is used rather than just returning Result<(),T> to make it more
convenient for callers (i.e. they can use ? or unwrap).

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-3-06d20ad9366f@google.com
[ Remove public visibility from `Vec::push_within_capacity_unchecked()`.
  - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:39:01 +02:00
Alice Ryhl
f2b4dd7093 rust: alloc: add Vec::pop
This introduces a basic method that our custom Vec is missing. I expect
that it will be used in many places, but at the time of writing, Rust
Binder has six calls to Vec::pop.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-2-06d20ad9366f@google.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:38:24 +02:00
Alice Ryhl
a1e4d5c9d7 rust: alloc: add Vec::clear
Our custom Vec type is missing the stdlib method `clear`, thus add it.
It will be used in the miscdevice sample.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Tamir Duberstein <tamird@gmail.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: https://lore.kernel.org/r/20250502-vec-methods-v5-1-06d20ad9366f@google.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07 18:36:59 +02:00
Miguel Ojeda
a39f308709 rust: allow Rust 1.87.0's clippy::ptr_eq lint
Starting with Rust 1.87.0 (expected 2025-05-15) [1], Clippy may expand
the `ptr_eq` lint, e.g.:

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

It is expected that a PR to relax the lint will be backported [2] by
the time Rust 1.87.0 releases, since the lint was considered too eager
(at least by default) [3].

Thus allow the lint temporarily just in case.

Cc: stable@vger.kernel.org # Needed in 6.12.y and later (Rust is pinned in older LTSs).
Link: https://github.com/rust-lang/rust-clippy/pull/14339 [1]
Link: https://github.com/rust-lang/rust-clippy/pull/14526 [2]
Link: https://github.com/rust-lang/rust-clippy/issues/14525 [3]
Link: https://lore.kernel.org/r/20250502140237.1659624-3-ojeda@kernel.org
[ Converted to `allow`s since backport was confirmed. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-07 00:11:02 +02:00
Tamir Duberstein
88d5d6a38d rust: alloc: replace Vec::set_len with inc_len
Rename `set_len` to `inc_len` and simplify its safety contract.

Note that the usage in `CString::try_from_fmt` remains correct as the
receiver is known to have `len == 0`.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20250416-vec-set-len-v4-4-112b222604cd@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-23 12:05:23 +02:00
Tamir Duberstein
1b04b466c8 rust: alloc: refactor Vec::truncate using dec_len
Use `checked_sub` to satisfy the safety requirements of `dec_len` and
replace nearly the whole body of `truncate` with a call to `dec_len`.

Reviewed-by: Andrew Ballance <andrewjballance@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20250416-vec-set-len-v4-3-112b222604cd@gmail.com
[ Remove #[expect(unused)] from dec_len(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-23 12:05:22 +02:00
Tamir Duberstein
dbb0b840a0 rust: alloc: add Vec::dec_len
Add `Vec::dec_len` that reduces the length of the receiver. This method
is intended to be used from methods that remove elements from `Vec` such
as `truncate`, `pop`, `remove`, and others. This method is intentionally
not `pub`.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20250416-vec-set-len-v4-2-112b222604cd@gmail.com
[ Add #[expect(unused)] to dec_len(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-23 12:05:22 +02:00
Tamir Duberstein
47a17a63f9 rust: alloc: add Vec::len() <= Vec::capacity invariant
Document the invariant that the vector's length is always less than or
equal to its capacity. This is already implied by these other
invariants:

- `self.len` always represents the exact number of elements stored in
  the vector.
- `self.layout` represents the absolute number of elements that can be
  stored within the vector without re-allocation.

but it doesn't hurt to spell it out. Note that the language references
`self.capacity` rather than `self.layout.len` as the latter is zero for
a vector of ZSTs.

Update a safety comment touched by this patch to correctly reference
`realloc` rather than `alloc` and replace "leaves" with "leave" to
improve grammar.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20250416-vec-set-len-v4-1-112b222604cd@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-23 12:05:15 +02:00
Tamir Duberstein
c3152988c0 rust: alloc: use spare_capacity_mut to reduce unsafe
Use `spare_capacity_mut` in the implementation of `push` to reduce the
use of `unsafe`. Both methods were added in commit 2aac4cd7da ("rust:
alloc: implement kernel `Vec` type").

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/r/20250318-vec-push-use-spare-v3-1-68741671d1af@gmail.com
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-07 16:59:06 +02:00
Andrew Ballance
1679b71593 rust: alloc: add Vec::resize method
Implement the equivalent of the rust std's Vec::resize on the kernel's
Vec type.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20250316111644.154602-3-andrewjballance@gmail.com
Signed-off-by: Andrew Ballance <andrewjballance@gmail.com>
[ Use checked_sub(), as suggested by Tamir. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-07 14:41:10 +02:00
Andrew Ballance
81e1c4dab5 rust: alloc: add Vec::truncate method
Implement the equivalent to the std's Vec::truncate on the kernel's Vec
type.

Link: https://lore.kernel.org/r/20250316111644.154602-2-andrewjballance@gmail.com
Signed-off-by: Andrew Ballance <andrewjballance@gmail.com>
[ Rewrote safety comment of set_len(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-07 14:38:02 +02:00
Danilo Krummrich
fb1bf1067d rust: alloc: add missing invariant in Vec::set_len()
When setting a new length, we have to justify that the set length
represents the exact number of elements stored in the vector.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reported-by: Alice Ryhl <aliceryhl@google.com>
Closes: https://lore.kernel.org/rust-for-linux/20250311-iov-iter-v1-4-f6c9134ea824@google.com
Fixes: 2aac4cd7da ("rust: alloc: implement kernel `Vec` type")
Link: https://lore.kernel.org/r/20250315154436.65065-2-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-07 14:02:56 +02:00
Danilo Krummrich
93e602310f rust: alloc: implement collect for IntoIter
Currently, we can't implement `FromIterator`. There are a couple of
issues with this trait in the kernel, namely:

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

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

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20241004154149.93856-19-dakr@kernel.org
[ Added newline in documentation, changed case of section to be
  consistent with an existing one, fixed typo. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-10-15 23:10:32 +02:00
Danilo Krummrich
1d1d223aa3 rust: alloc: implement IntoIterator for Vec
Implement `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as
`Iterator` for `IntoIter`.

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

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

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20241004154149.93856-18-dakr@kernel.org
[ Fixed typos. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-10-15 23:10:32 +02:00
Danilo Krummrich
2aac4cd7da rust: alloc: implement kernel Vec type
`Vec` provides a contiguous growable array type with contents allocated
with the kernel's allocators (e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`).

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

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

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20241004154149.93856-17-dakr@kernel.org
[ Cleaned `rustdoc` unescaped backtick warning, added a couple more
  backticks elsewhere, fixed typos, sorted `feature`s, rewrapped
  documentation lines. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2024-10-15 23:10:32 +02:00