From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B3DE3149002; Wed, 11 Sep 2024 22:55:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095306; cv=none; b=q7x8CfLpe6+6fLeMk73LS7JDG3Rg5FFAs3ajnWUuZ/nN1DinOJKsPngOTXy3ZECz1qbpG/Y5Jp4xyUnXaq9+NH+AHijJc1s8AFCXHbRExIGzTdBn2gqhtC8s9RYNHUUhc47SsTF+CldhH7mQwBjcnjEyt33YnMonPoF314jcTRE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095306; c=relaxed/simple; bh=YJ+3Hmuf4lg4RSyjGhOmEDyEN9eOYFpIUvOB6gUqpsA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=pWBoRaJDU/uzcOx2WjDo2fNoxkoXUlVVCmvx5VvqThlCeIyx44Vj8FuUkXVtAqGLqEn1iXiPqbtiU1K9qbcdnyNNEDSWx0I33u/RyVBAjuP2PPytwLMQ/5iz4EkWCTys4k0JtN4fl84ObnAkb6iaj6Xnz3cQIxvVRCcOt+BzzQQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=PP0oko47; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="PP0oko47" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 65187C4CECD; Wed, 11 Sep 2024 22:55:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095306; bh=YJ+3Hmuf4lg4RSyjGhOmEDyEN9eOYFpIUvOB6gUqpsA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=PP0oko47af8i3c5/Hy4kVN84YWSFkT4p5u/bF6oMUDUOZRQfFG0aMXubN+SNpeYQl cctwMTAnRRXh1rDSCnD52PpqzOTQ8w3HGFwhoqSWbCCXY6aeRmN1FhE64VK72pQ2j5 ydR9BBdGMz8nUgJnI5R/AVyqMLrm1FRRz3vPpsyXc0byHV2UD41PKjPn/A5YR59pLq JZlF/t+zbfPr1eW0CAOx1/tMzOxJl1uF5rGQM7OdGcNzE19DB/60OCTs4r65NJkf87 KT1UlGA/9BV/3iuLjtUoQTHY49o5fI3MBDBfB5Mt+5RXpSYXbJKaq6fMc7wKLgnoAm 9dA6oIh6GatmA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 01/26] rust: alloc: add `Allocator` trait Date: Thu, 12 Sep 2024 00:52:37 +0200 Message-ID: <20240911225449.152928-2-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add a kernel specific `Allocator` trait, that in contrast to the one in Rust's core library doesn't require unstable features and supports GFP flags. Subsequent patches add the following trait implementors: `Kmalloc`, `Vmalloc` and `KVmalloc`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 112 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..6c21bd2edad9 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -11,6 +11,7 @@ /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; +use core::{alloc::Layout, ptr::NonNull}; =20 /// Flags to be used when allocating memory. /// @@ -86,3 +87,114 @@ pub mod flags { /// small allocations. pub const GFP_NOWAIT: Flags =3D Flags(bindings::GFP_NOWAIT); } + +/// The kernel's [`Allocator`] trait. +/// +/// An implementation of [`Allocator`] can allocate, re-allocate and free = memory buffers described +/// via [`Layout`]. +/// +/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] fu= nctions do not operate on +/// an object instance. +/// +/// In order to be able to support `#[derive(SmartPointer)]` later on, we = need to avoid a design +/// that requires an `Allocator` to be instantiated, hence its functions m= ust not contain any kind +/// of `self` parameter. +/// +/// # Safety +/// +/// - A memory allocation returned from an allocator must remain valid unt= il it is explicitly freed. +/// +/// - Any pointer to a valid memory allocation must be valid to be passed = to any other [`Allocator`] +/// function of the same type. +/// +/// - Implementers must ensure that all trait functions abide by the guara= ntees documented in the +/// `# Guarantees` sections. +// +// Note that `Allocator::{realloc,free}` don't have an `old_layout` argume= nt (like stdlib's +// corresponding `Allocator` trait functions have), since the implemented = (kernel) allocators +// neither need nor honor such an argument. Thus, it would be misleading t= o make this API require it +// anyways. +// +// More generally, this trait isn't intended for implementers to encode a = lot of semantics, but +// rather provide a thin generalization layer for the kernel's allocators. +// +// Depending on future requirements, the requirements for this trait may c= hange as well and +// implementing allocators that need to encode more semantics may become d= esirable. +pub unsafe trait Allocator { + /// Allocate memory based on `layout` and `flags`. + /// + /// On success, returns a buffer represented as `NonNull<[u8]>` that s= atisfies the layout + /// constraints (i.e. minimum size and alignment as specified by `layo= ut`). + /// + /// This function is equivalent to `realloc` when called with `None`. + /// + /// # Guarantees + /// + /// When the return value is `Ok(ptr)`, then `ptr` is + /// - valid for reads and writes for `layout.size()` bytes, until it i= s passed to + /// [`Allocator::free`] or [`Allocator::realloc`], + /// - aligned to `layout.align()`, + /// + /// Additionally, `Flags` are honored as documented in + /// . + fn alloc(layout: Layout, flags: Flags) -> Result, AllocE= rror> { + // SAFETY: Passing `None` to `realloc` is valid by it's safety req= uirements and asks for a + // new memory allocation. + unsafe { Self::realloc(None, layout, flags) } + } + + /// Re-allocate an existing memory allocation to satisfy the requested= `layout`. + /// + /// If the requested size is zero, `realloc` behaves equivalent to `fr= ee`. + /// + /// If the requested size is larger than the size of the existing allo= cation, a successful call + /// to `realloc` guarantees that the new or grown buffer has at least = `Layout::size` bytes, but + /// may also be larger. + /// + /// If the requested size is smaller than the size of the existing all= ocation, `realloc` may or + /// may not shrink the buffer; this is implementation specific to the = allocator. + /// + /// On allocation failure, the existing buffer, if any, remains valid. + /// + /// The buffer is represented as `NonNull<[u8]>`. + /// + /// # Safety + /// + /// If `ptr =3D=3D Some(p)`, then `p` must point to an existing and va= lid memory allocation created + /// by this allocator. The alignment encoded in `layout` must be small= er than or equal to the + /// alignment requested in the previous `alloc` or `realloc` call of t= he same allocation. + /// + /// Additionally, `ptr` is allowed to be `None`; in this case a new me= mory allocation is + /// created. + /// + /// # Guarantees + /// + /// This function has the same guarantees as [`Allocator::alloc`]. Whe= n `ptr =3D=3D Some(p)`, then + /// it additionally guarantees that: + /// - the contents of the memory pointed to by `p` are preserved up to= the lesser of the new + /// and old size, + /// and old size, i.e. + /// `ret_ptr[0..min(layout.size(), old_size)] =3D=3D p[0..min(layout= .size(), old_size)]`, where + /// `old_size` is the size of the allocation that `p` points at. + /// - when the return value is `Err(AllocError)`, then `p` is still va= lid. + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError>; + + /// Free an existing memory allocation. + /// + /// # Safety + /// + /// `ptr` must point to an existing and valid memory allocation create= d by this `Allocator` and + /// must not be a dangling pointer. + /// + /// The memory allocation at `ptr` must never again be read from or wr= itten to. + unsafe fn free(ptr: NonNull) { + // SAFETY: The caller guarantees that `ptr` points at a valid allo= cation created by this + // allocator. We are passing a `Layout` with the smallest possible= alignment, so it is + // smaller than or equal to the alignment previously used with thi= s allocation. + let _ =3D unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), F= lags(0)) }; + } +} --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1A56E1AED49; Wed, 11 Sep 2024 22:55:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095312; cv=none; b=HPAUZjy91fK3IQPX97SfWWkB1HEmgbFVZGChSbZMQ5AAkqTqlKqeRRTeBV6JrtFZe8/Y1GxE5xqIsboZsJZSUooDKSG3JhCiHbimTS55Kzv0U0UPUE8cl64OYGULIbMx3Pg6sieovGQCaqAFNH8weF+sb22zytCPxLgFyGjzLLE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095312; c=relaxed/simple; bh=KguwORfCY7YFKN8ylS2gRnroFHbMzQZYk2Q9X4DUkvo=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=BGbW9TII+TXAeKOEHe+8QkbYVVlocw40QpwrnfjpbDJzClIAQHN/DLFtjwf2qyFUh3RlNjGgS0AEeadPEXpZwmfzODTwk/ERU0iZZi+2st4znolgjCogc81rAOiLuNiPuJ3pFbXQZGlaGD0hUfLNWyw61Ip/yzRIuAih6magvMg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=D/WgSl3S; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="D/WgSl3S" Received: by smtp.kernel.org (Postfix) with ESMTPSA id B5D95C4CECF; Wed, 11 Sep 2024 22:55:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095311; bh=KguwORfCY7YFKN8ylS2gRnroFHbMzQZYk2Q9X4DUkvo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=D/WgSl3S/dVR8lPldARNWqtzBxXX0S7eYokMIzvH+tUsNddrFOKgY8H7hg3IL8v7J 5v3sEjSAvsQtbpDLlySeaWqNttFjmU7ML31CGvfUsC/plF1j/aqfY37ymrpz7dLwr4 m8SN45KADpIY+l8OIBaofroxoa8zToBc0GZpMJXQ/2HCUq50F82aulAVsB08GbMIFM FNi8Phjw2JIHJl0FBTLH8aa4ZAiEFoRbkkVQJyW3tWl7BSKy9ThyabCKX9zCaNhquT vId+Sd/uYzs29X0EN8pG29Xhh5iduiyOOXP7EIzE8u8Tqx/zcgaocb/94BA3Zze16h aGi5EIDGU9qFQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 02/26] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Thu, 12 Sep 2024 00:52:38 +0200 Message-ID: <20240911225449.152928-3-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Separate `aligned_size` from `krealloc_aligned`. Subsequent patches implement `Allocator` derivates, such as `Kmalloc`, that require `aligned_size` and replace the original `krealloc_aligned`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..c83b6dff896d 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,6 +8,17 @@ =20 struct KernelAllocator; =20 +/// Returns a proper size to alloc a new object aligned to `new_layout`'s = alignment. +fn aligned_size(new_layout: Layout) -> usize { + // Customized layouts from `Layout::from_size_align()` can have size <= align, so pad first. + let layout =3D new_layout.pad_to_align(); + + // Note that `layout.size()` (after padding) is guaranteed to be a mul= tiple of `layout.align()` + // which together with the slab guarantees means the `krealloc` will r= eturn a properly aligned + // object (see comments in `kmalloc()` for more information). + layout.size() +} + /// Calls `krealloc` with a proper size to alloc a new object aligned to `= new_layout`'s alignment. /// /// # Safety @@ -15,13 +26,7 @@ /// - `ptr` can be either null or a pointer which has been allocated by th= is allocator. /// - `new_layout` must have a non-zero size. pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, fl= ags: Flags) -> *mut u8 { - // Customized layouts from `Layout::from_size_align()` can have size <= align, so pad first. - let layout =3D new_layout.pad_to_align(); - - // Note that `layout.size()` (after padding) is guaranteed to be a mul= tiple of `layout.align()` - // which together with the slab guarantees means the `krealloc` will r= eturn a properly aligned - // object (see comments in `kmalloc()` for more information). - let size =3D layout.size(); + let size =3D aligned_size(new_layout); =20 // SAFETY: // - `ptr` is either null or a pointer returned from a previous `k{re}= alloc()` by the --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 530831BA276; Wed, 11 Sep 2024 22:55:17 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095317; cv=none; b=YeYsSCX2DWUDbB0DTcquKHKX1KVqrZPtR9pmp2XySk7IWxT4TnX2tDlHo7fTSdNN9eae2aA0VMMQLIY8g14WIpSOdRzJfTWsLLmk8/avVShAuTXFjJWV8GugeMb7htV1eLUN65DlK0USCifxKSIx0P3F0OW7b0YTBWXTv+yTIC0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095317; c=relaxed/simple; bh=Ul5b1CTJ9tob+sYMI0uOwgqpbhRR4cA87hpBjRrp3KM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=oGfVH1q9/RJf6QMSziZ9GmB4vVSQM81hLylJ0neojSTH+lu2gIOOR6IabNO2VpQvpSgHETlw93hjXCdE4Ujio6TLGWASylGZeATfOEylykAkDcJO65KBYR/NwdvxEfSEoibMPqA1AFVHh7i/EsQ3ET0YeiEikcbtz+F+7cKeJIc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=KCGcTqnl; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="KCGcTqnl" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1039CC4CECE; Wed, 11 Sep 2024 22:55:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095316; bh=Ul5b1CTJ9tob+sYMI0uOwgqpbhRR4cA87hpBjRrp3KM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KCGcTqnlJVTcLOAmbSEUKqOazK/xR4SmyhHf6E6yLxfNTUBqg888J/jQNW3zoXMsW BI7/fwKW0MKhxs3jEBmYWCiX4BhCu3aKf0fLOGyIKRsM56Bnyr3XrrFXy62AfbCpLW 8UF1PfSA3yeN2oduAomH1dIhBJa9dBiM9jJu8L/NJ+IvW3gY6y7K6YmVvjs0Wkm3Da 7EZiR7QheKaarwwp8Fxdn7RjH/jtPFM9neQDEJW/KBl4n37/fZAZM94WAfK9n0Ka8B 0vTcbjzPGHt2Hv76tpvxptGeMIwheH2dMcELkpMpl4R7rMMGQd0pYO6WbbhSgsk/34 zCnCFGDSpWd7w== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 03/26] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Thu, 12 Sep 2024 00:52:39 +0200 Message-ID: <20240911225449.152928-4-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Subsequent patches implement `Vmalloc` and `KVmalloc` allocators, hence align `KernelAllocator` to this naming scheme. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index c83b6dff896d..e32182f91167 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -6,7 +6,7 @@ use core::alloc::{GlobalAlloc, Layout}; use core::ptr; =20 -struct KernelAllocator; +struct Kmalloc; =20 /// Returns a proper size to alloc a new object aligned to `new_layout`'s = alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -36,7 +36,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_l= ayout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, fla= gs.0) as *mut u8 } } =20 -unsafe impl GlobalAlloc for KernelAllocator { +unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero s= ize by the function safety // requirement. @@ -72,7 +72,7 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } =20 #[global_allocator] -static ALLOCATOR: KernelAllocator =3D KernelAllocator; +static ALLOCATOR: Kmalloc =3D Kmalloc; =20 // See . #[no_mangle] --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 58F821BC9F1; Wed, 11 Sep 2024 22:55:22 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095322; cv=none; b=MET0s65W3hh8VVmaLUjlsYOTamjYdEg6mH22l9Vp0RM2U28px3qkDdcTYHUNOOboZn2X+tHUtIy1CWNe67lSrRHgau/VWWAbMyntCqncn1vuH+DM9RtJv1KZfF4fknb37h+nGS/5ZQH5f3K5pVGhJVIwYnkq723B3rAehfxXZlg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095322; c=relaxed/simple; bh=lbiLQnErRGDrQbj4pxfkEOD42vZ0I0vTG1uGJ1op8G0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=qqK9dAxqdw+qgcIAnxoJRE8a+TrHgxqOScrNxqdonD0QZKbKY9GyM70DQhpxa3AYWw4N7K9U5DNikQOzKYkzoEAoave3D4utG4PbGjatnQtDnnYQGqrSz9Db6lLxHMUZM6fDgD9DKonR/TbppW/ug/t39pJ6OhQvCW3dUQdlpmA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=g/+6QwRq; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="g/+6QwRq" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5E35FC4CEC5; Wed, 11 Sep 2024 22:55:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095322; bh=lbiLQnErRGDrQbj4pxfkEOD42vZ0I0vTG1uGJ1op8G0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=g/+6QwRqD1gJeXD0nTRAi39kPwchUeku9kzbofccjkCxU8yKJ5xJQ9NbBWGzIY1J7 9bJDgYS9aUM5Kt1EmpIupw1BwMb8FinYpT9XninnRN7iEZEWbNW2TysnpXm+OukEZx ZuZ/IbeVMnIEZXNXgxVoCjP1tM91eAhZrdpDSq0CRNFAv/gKPqJs/6WbtW0xrFEJOs pr8NENuo8oo+1kjNBNQeVnArUGCnEjf4wxB+KRDyGNa17RP0LqHvduThVsdqPJMDLT x9NQtar2HyN8X5z4mqq6zfCPrH6DElkh9WCtMtjG8kcWiEEs/UhfpS/gCeJYmZxwoK Q2wE3EZLWULFA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 04/26] rust: alloc: implement `Allocator` for `Kmalloc` Date: Thu, 12 Sep 2024 00:52:40 +0200 Message-ID: <20240911225449.152928-5-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Implement `Allocator` for `Kmalloc`, the kernel's default allocator, typically used for objects smaller than page size. All memory allocations made with `Kmalloc` end up in `krealloc()`. It serves as allocator for the subsequently introduced types `KBox` and `KVec`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 89 +++++++++++++++++++++++++++++++++- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 6c21bd2edad9..535ed1527034 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -4,7 +4,7 @@ =20 #[cfg(not(test))] #[cfg(not(testlib))] -mod allocator; +pub mod allocator; pub mod box_ext; pub mod vec_ext; =20 diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e32182f91167..7a93442187a1 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -1,12 +1,28 @@ // SPDX-License-Identifier: GPL-2.0 =20 //! Allocator support. +//! +//! Documentation for the kernel's memory allocators can found in the "Mem= ory Allocation Guide" +//! linked below. For instance, this includes the concept of "get free pag= e" (GFP) flags and the +//! typical application of the different kernel allocators. +//! +//! Reference: =20 use super::{flags::*, Flags}; use core::alloc::{GlobalAlloc, Layout}; use core::ptr; +use core::ptr::NonNull; =20 -struct Kmalloc; +use crate::alloc::{AllocError, Allocator}; +use crate::bindings; + +/// The contiguous kernel allocator. +/// +/// `Kmalloc` is typically used for physically contiguous allocations up t= o page size, but also +/// supports larger allocations up to `bindings::KMALLOC_MAX_SIZE`, which = is hardware specific. +/// +/// For more details see [self]. +pub struct Kmalloc; =20 /// Returns a proper size to alloc a new object aligned to `new_layout`'s = alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -36,6 +52,77 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_= layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, fla= gs.0) as *mut u8 } } =20 +/// # Invariants +/// +/// One of the following `krealloc`, `vrealloc`, `kvrealloc`. +struct ReallocFunc( + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut cor= e::ffi::c_void, +); + +impl ReallocFunc { + // INVARIANT: `krealloc` satisfies the type invariants. + const KREALLOC: Self =3D Self(bindings::krealloc); + + /// # Safety + /// + /// This method has the same safety requirements as [`Allocator::reall= oc`]. + /// + /// # Guarantees + /// + /// This method has the same guarantees as `Allocator::realloc`. Addit= ionally + /// - it accepts any pointer to a valid memory allocation allocated by= this function. + /// - memory allocated by this function remains valid until it is pass= ed to this function. + unsafe fn call( + &self, + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let size =3D aligned_size(layout); + let ptr =3D match ptr { + Some(ptr) =3D> ptr.as_ptr(), + None =3D> ptr::null(), + }; + + // SAFETY: + // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc` and th= us only requires that + // `ptr` is NULL or valid. + // - `ptr` is either NULL or valid by the safety requirements of t= his function. + // + // GUARANTEE: + // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc`. + // - Those functions provide the guarantees of this function. + let raw_ptr =3D unsafe { + // If `size =3D=3D 0` and `ptr !=3D NULL` the memory behind th= e pointer is freed. + self.0(ptr.cast(), size, flags.0).cast() + }; + + let ptr =3D if size =3D=3D 0 { + NonNull::dangling() + } else { + NonNull::new(raw_ptr).ok_or(AllocError)? + }; + + Ok(NonNull::slice_from_raw_parts(ptr, size)) + } +} + +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees th= at +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the= same. +unsafe impl Allocator for Kmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // SAFETY: `ReallocFunc::call` has the same safety requirements as= `Allocator::realloc`. + unsafe { ReallocFunc::KREALLOC.call(ptr, layout, flags) } + } +} + unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero s= ize by the function safety --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AAF39187334; Wed, 11 Sep 2024 22:55:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095327; cv=none; b=Iue9R3EnyVNGZWTiSk7m4LfUEYEo0h6P3YXwSjUh65GIQwJfaeslUq6AVl5cvxClRGSv+UYoxb5n59CfrTSimwuwKmpL5ylOvzf0B1OZThqFyJKgG7XnWQDCg9jvvmNtQsEm5H13sL7RVsU4Et80Mrhz3AgNHFzWLYvBGxaZlDA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095327; c=relaxed/simple; bh=6UhtPHghMdWoDtF9TGoHZC9u3Z5IdMcvwYnLuoTa2qc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=nKpn3sNDJ62fLzIDbAFYd8MW4vN5Di1e3PLyLjLtt4lj948f4JK9dB9s5nQr4PF/4qbDSl8ZuOjH5f7P6NmEh1pvj3YIScATZ+bUr63Dbi06BNi2PFPUkLb/9Y0cxRkG5pfOKXD0w8vxK7tQiOMNzwmoXz0eHUGolZFCYof5vyc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=RXwms/Q1; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="RXwms/Q1" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A98B6C4CED0; Wed, 11 Sep 2024 22:55:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095327; bh=6UhtPHghMdWoDtF9TGoHZC9u3Z5IdMcvwYnLuoTa2qc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RXwms/Q1IYeTrOVyS8N6rmwVkuedlR7RrzOdigur1Nqg3fVvLpdjdpt87ycrYgBak UL4Us49SUfm6lzmfl286zvwwQQ6+fZJvTwTCQOoT+Rmc98EoIWGzN9YVgQd9GRJQj7 PjiLKvK5hZ8yXT4bPvuwFG/9I7iyeWLqE5RN8Ij81osBIQ9csfmWVxmb5HyMvzjAvB Y+MhH4C9XSnTyz48Ul81QJ092J0832DhYYkhm29zar+vQO3eVBU9nHURmuXisch9zy bb4hNzvrwTD+0uwAH36Id9zHlpN3/ayuyyHlhEvLDHQogD8XYcVbHi96wwOaChS528 frujahViF8gvQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 05/26] rust: alloc: add module `allocator_test` Date: Thu, 12 Sep 2024 00:52:41 +0200 Message-ID: <20240911225449.152928-6-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" `Allocator`s, such as `Kmalloc`, will be used by e.g. `Box` and `Vec` in subsequent patches, and hence this dependency propagates throughout the whole kernel. Add the `allocator_test` module that provides an empty implementation for all `Allocator`s in the kernel, such that we don't break the `rusttest` make target in subsequent patches. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 9 +++++++-- rust/kernel/alloc/allocator_test.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/allocator_test.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 535ed1527034..da025faf07f8 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -2,12 +2,17 @@ =20 //! Extensions to the [`alloc`] crate. =20 -#[cfg(not(test))] -#[cfg(not(testlib))] +#[cfg(not(any(test, testlib)))] pub mod allocator; pub mod box_ext; pub mod vec_ext; =20 +#[cfg(any(test, testlib))] +pub mod allocator_test; + +#[cfg(any(test, testlib))] +pub use self::allocator_test as allocator; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/alloca= tor_test.rs new file mode 100644 index 000000000000..4785efc474a7 --- /dev/null +++ b/rust/kernel/alloc/allocator_test.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0 + +#![allow(missing_docs)] + +use super::{AllocError, Allocator, Flags}; +use core::alloc::Layout; +use core::ptr::NonNull; + +pub struct Kmalloc; + +unsafe impl Allocator for Kmalloc { + unsafe fn realloc( + _ptr: Option>, + _layout: Layout, + _flags: Flags, + ) -> Result, AllocError> { + panic!(); + } +} --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 05C1C187334; Wed, 11 Sep 2024 22:55:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095333; cv=none; b=EFXzr7OpsehD+iVgpw85Uf4iNo0f34KowGbOSZChp1XR7YN4HlBIAV4PissKJxfuWlLBr2c+WPQ9N3ajhwvFEJePTsLxno1JH2YE6TRFpBryitMU7fGtOeYV0z0WToldaLAi0ZG27EJCibWHIWLgzvBmxMcyVGOqZPdR9wPueCg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095333; c=relaxed/simple; bh=kZOIx3Co/Hq0ECAauxmLflkd+d0Tj2aHN+O0afOlvOc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=PHmkhLFoekzPVhuxv9lbSXjX+x0WsZSue8IJMFMERhJcl5R/gKbVitnbwFzD+o3JQwnw6pT4wGiQxz8kXilpGp0XXsj0tyc8wsieo4jW5OxAWbqUHU86nkTMqPQAQvTEqFvx5gmgCLhSyAdjuRNixwgqBVmLCCCWJ1jCtBH/rpg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Trml8k+n; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Trml8k+n" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0846BC4CEC0; Wed, 11 Sep 2024 22:55:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095332; bh=kZOIx3Co/Hq0ECAauxmLflkd+d0Tj2aHN+O0afOlvOc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Trml8k+nqKDeTUNPT+Q0B0wvV+B+DWgxGKE7UnVOvVcv9HfLKATNF6fhsj47h9iXV nrywaauzGj4lgxa7f7xhiOeXOhOa4jhrhk0aJbt2WS6uE25MeEEb7ECReBtdm3z5V+ Ghk+wMz+UjV+GGyGsr2rDdhFuUsui+3bn6x0M3o5H/hSH0WPiIh7e1qQJuC1D7eLkZ NtvqlCiNNBLhQsJxc5teRL1Zt83GIbrLUF67Cp2BFree4q129nsPVzUKeBg55kn5zH Hv2jMnY9qjlGlbH4yr5yCJJreEwShKO/DEWm2xC+eWRG4VjsvB5JBP7aOayJ0bq+ZT zfV95Op4i3MLg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 06/26] rust: alloc: implement `Vmalloc` allocator Date: Thu, 12 Sep 2024 00:52:42 +0200 Message-ID: <20240911225449.152928-7-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Implement `Allocator` for `Vmalloc`, the kernel's virtually contiguous allocator, typically used for larger objects, (much) larger than page size. All memory allocations made with `Vmalloc` end up in `vrealloc()`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/helpers/helpers.c | 1 + rust/helpers/vmalloc.c | 9 ++++++++ rust/kernel/alloc/allocator.rs | 36 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 4 files changed, 47 insertions(+) create mode 100644 rust/helpers/vmalloc.c diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 30f40149f3a9..20a0c69d5cc7 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -22,5 +22,6 @@ #include "spinlock.c" #include "task.c" #include "uaccess.c" +#include "vmalloc.c" #include "wait.c" #include "workqueue.c" diff --git a/rust/helpers/vmalloc.c b/rust/helpers/vmalloc.c new file mode 100644 index 000000000000..80d34501bbc0 --- /dev/null +++ b/rust/helpers/vmalloc.c @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +void * __must_check __realloc_size(2) +rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) +{ + return vrealloc(p, size, flags); +} diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 7a93442187a1..0f2bc702e8e4 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -15,6 +15,7 @@ =20 use crate::alloc::{AllocError, Allocator}; use crate::bindings; +use crate::pr_warn; =20 /// The contiguous kernel allocator. /// @@ -24,6 +25,15 @@ /// For more details see [self]. pub struct Kmalloc; =20 +/// The virtually contiguous kernel allocator. +/// +/// `Vmalloc` allocates pages from the page level allocator and maps them = into the contiguous kernel +/// virtual space. It is typically used for large allocations. The memory = allocated with this +/// allocator is not physically contiguous. +/// +/// For more details see [self]. +pub struct Vmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s = alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size <= align, so pad first. @@ -63,6 +73,9 @@ impl ReallocFunc { // INVARIANT: `krealloc` satisfies the type invariants. const KREALLOC: Self =3D Self(bindings::krealloc); =20 + // INVARIANT: `vrealloc` satisfies the type invariants. + const VREALLOC: Self =3D Self(bindings::vrealloc); + /// # Safety /// /// This method has the same safety requirements as [`Allocator::reall= oc`]. @@ -158,6 +171,29 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut = u8 { } } =20 +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees th= at +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the= same. +unsafe impl Allocator for Vmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("Vmalloc does not support alignments larger than PAGE= _SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid me= mory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::VREALLOC.call(ptr, layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc =3D Kmalloc; =20 diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/alloca= tor_test.rs index 4785efc474a7..e7bf2982f68f 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -7,6 +7,7 @@ use core::ptr::NonNull; =20 pub struct Kmalloc; +pub type Vmalloc =3D Kmalloc; =20 unsafe impl Allocator for Kmalloc { unsafe fn realloc( --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A11071A3047; Wed, 11 Sep 2024 22:55:38 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095338; cv=none; b=Yr40C07Bew9OK9sUgl09mAvpt+IEUs2TMHK8OwA42t2LZX1uCz9W7O6sftQcnHRHtSlVyOW05xBR2OeZBgaO6EMCMVBYRCHH0tesUGYqN3xATSDwbTR4XZQQSP9WG0YzYqlCjO10FeC6CySsN6IYX1zWkQ55ygta63i90ITGvYE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095338; c=relaxed/simple; bh=7ud9iFBT5EcUDGEvKd041Y+gvEKEu7RxRlS2eA0UCRA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=qSi1pUX/QrcNjeauKfe6Ag6m+Q9/v8kidULDAGMfXEI0LxYUMwdphc7vhM+QOnuf5WdLlJSJBL1N0b2Y6CmEVQCUQDOaIpxqdh2gD3seoSk6qlAVxkXfXVpU23UUHC2yRE0oi/fpOkDyLdRspEcq2sXhEevaL/6KCEpaXbezVug= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=sh382Oa/; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="sh382Oa/" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5A1C7C4CEC5; Wed, 11 Sep 2024 22:55:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095338; bh=7ud9iFBT5EcUDGEvKd041Y+gvEKEu7RxRlS2eA0UCRA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=sh382Oa/l5uE2UTx21wKubJ27EmXt/WljM5TDLCvic0zWfZUvcq0zujcO0gwtq8UN frSY8H4qkNT32280yR8hCKXi+tJGkeGY5mHW8l5aOYU7V8gfphjJJ6SzFh3O7D/j4d UEgK+aCBsDu+hr6gEL8aTYlWF8nBFRgQaAsgPEnw2kJaHBgWUB+fyqREO+OOM0I+jY mV50Hr2ANdJESRoToUkBIfUIggcAVBckovKxkAdC4hTFOLLzCn75rA54hGe/eF7wxp H6JsuRM16TZWPBhgK0nnGbrkA087+fbnAGT9hNcDPE2UU1L7Y3IY/+sfiWnwIIUTdx 86+gU0pe6L42g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 07/26] rust: alloc: implement `KVmalloc` allocator Date: Thu, 12 Sep 2024 00:52:43 +0200 Message-ID: <20240911225449.152928-8-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Implement `Allocator` for `KVmalloc`, an `Allocator` that tries to allocate memory wth `kmalloc` first and, on failure, falls back to `vmalloc`. All memory allocations made with `KVmalloc` end up in `kvrealloc_noprof()`; all frees in `kvfree()`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/helpers/slab.c | 6 +++++ rust/kernel/alloc/allocator.rs | 35 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 42 insertions(+) diff --git a/rust/helpers/slab.c b/rust/helpers/slab.c index f043e087f9d6..a842bfbddcba 100644 --- a/rust/helpers/slab.c +++ b/rust/helpers/slab.c @@ -7,3 +7,9 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp= _t flags) { return krealloc(objp, new_size, flags); } + +void * __must_check __realloc_size(2) +rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags) +{ + return kvrealloc(p, size, flags); +} diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 0f2bc702e8e4..a5d7e66a68db 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -34,6 +34,15 @@ /// For more details see [self]. pub struct Vmalloc; =20 +/// The kvmalloc kernel allocator. +/// +/// `KVmalloc` attempts to allocate memory with `Kmalloc` first, but falls= back to `Vmalloc` upon +/// failure. This allocator is typically used when the size for the reques= ted allocation is not +/// known and may exceed the capabilities of `Kmalloc`. +/// +/// For more details see [self]. +pub struct KVmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s = alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size <= align, so pad first. @@ -76,6 +85,9 @@ impl ReallocFunc { // INVARIANT: `vrealloc` satisfies the type invariants. const VREALLOC: Self =3D Self(bindings::vrealloc); =20 + // INVARIANT: `kvrealloc` satisfies the type invariants. + const KVREALLOC: Self =3D Self(bindings::kvrealloc); + /// # Safety /// /// This method has the same safety requirements as [`Allocator::reall= oc`]. @@ -194,6 +206,29 @@ unsafe fn realloc( } } =20 +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees th= at +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the= same. +unsafe impl Allocator for KVmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("KVmalloc does not support alignments larger than PAG= E_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid me= mory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc =3D Kmalloc; =20 diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/alloca= tor_test.rs index e7bf2982f68f..1b2642c547ec 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -8,6 +8,7 @@ =20 pub struct Kmalloc; pub type Vmalloc =3D Kmalloc; +pub type KVmalloc =3D Kmalloc; =20 unsafe impl Allocator for Kmalloc { unsafe fn realloc( --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 16A9B1BC065; Wed, 11 Sep 2024 22:55:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095344; cv=none; b=SfdjO01GTlz5wHcxSPn3qS2tYDgZiacishBlayb1Nz0H2PTvMCRL+iFEvMfcMOjd0ErDpluOkRgdgVJBvulNividuLcWDlqY0665umyqd+bpD12CBPofnjRy9Q5OqVdM6JiRbBC2l0m1cahmQq1zOGDHJKyzgtY2X8GwTBUhoNE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095344; c=relaxed/simple; bh=cw4d7ozoaPZp9ThW0IiXPabVi14FeEz+TkCXge43sLA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=FBN1WfpRBljlzE5tVyWqXs6G2gmB0mSKXfY2CWwy1vsyZzYBM9TY9tu0ohqVnRoxPx1ADE8ZVsPahmAHTOOlePA9p0NBzMTSlR6PV2jN1a6awrFs0CTVAZQJNizo3kB2Vbnk2scy3qpvjYxMs0p6kEQhXLuBbahJo35HJ/4cNhw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=QPvCMXFp; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="QPvCMXFp" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A63D1C4CEC0; Wed, 11 Sep 2024 22:55:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095343; bh=cw4d7ozoaPZp9ThW0IiXPabVi14FeEz+TkCXge43sLA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QPvCMXFpIwzfoZbpxM2gjuVdmtZUL2+Yc6GhKLt//9t7CDDcaB8AgbIiSKcHmTb0C x3EGE9ZzTqaLvqTvzVZYjvTAg13F3eEJnh3cJJEWio3yD+JN8s3DsYCmcMLD9Yc97W A/GUrN62DQFaaEosXHom6aUqb6ujSOgzzIhn+XhM/km6w65C3We22AI9nBIBuXuu/5 L4MD9j0pviw9fbRrP/07HmRhI3G5Zllhkjf4P9q9vlqmXaWmXUuzLzM1PyTb8m68c9 3xPHmt7Mu/gEjvkGoVc4YPmFE+GRhsiPEmyJRhGJ6rKl7lsXMWukOy0DuYZ/aXCFf6 o5h4yzR932z0Q== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 08/26] rust: alloc: add __GFP_NOWARN to `Flags` Date: Thu, 12 Sep 2024 00:52:44 +0200 Message-ID: <20240911225449.152928-9-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Some test cases in subsequent patches provoke allocation failures. Add `__GFP_NOWARN` to enable test cases to silence unpleasant warnings. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/bindings/bindings_helper.h | 1 + rust/kernel/alloc.rs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index ae82e9c941af..a80783fcbe04 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -31,4 +31,5 @@ const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT =3D GFP_= KERNEL_ACCOUNT; const gfp_t RUST_CONST_HELPER_GFP_NOWAIT =3D GFP_NOWAIT; const gfp_t RUST_CONST_HELPER___GFP_ZERO =3D __GFP_ZERO; const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM =3D ___GFP_HIGHMEM; +const gfp_t RUST_CONST_HELPER___GFP_NOWARN =3D ___GFP_NOWARN; const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL =3D BLK_FEAT_RO= TATIONAL; diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index da025faf07f8..7a405d6f3034 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -91,6 +91,11 @@ pub mod flags { /// use any filesystem callback. It is very likely to fail to allocat= e memory, even for very /// small allocations. pub const GFP_NOWAIT: Flags =3D Flags(bindings::GFP_NOWAIT); + + /// Suppresses allocation failure reports. + /// + /// This is normally or'd with other flags. + pub const __GFP_NOWARN: Flags =3D Flags(bindings::__GFP_NOWARN); } =20 /// The kernel's [`Allocator`] trait. --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 216DD1BC070; Wed, 11 Sep 2024 22:55:48 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095349; cv=none; b=SXC1gsCW9TxOUCnFI0V87jQFrzqEjB/yVWHq66o3aRXtrDnXhPAbfSxvZ++OUl1SdJXT+T26V8EnpVm5IJ5sWc4QFBdYG+TwSY1WCw1mjlb66G6fxhc22T7umiHHoZjeUW8apxR+OH8jjfZgHtvQctHLxLHht386onhmYZczE38= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095349; c=relaxed/simple; bh=ONKVPueTm7R2PEVvV8+tCD9cNcEk3jCly02IRQlQKQg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=TSBuR39qXb0sCjZqZkkMHnIHftTnHByi+2ES5DzPyFwa8/hGnS+htQzw9ZK7MwGaaP22xq0Yiu05j3tzZ4khK5/+OovInBA20PqQhBCS4FuA8WmE81sUpaGWRWV+qarEa4PsTi9c+dcUeuynYP9ywlxylrBWfTaO8Ak2xVLrD2o= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=eUiJEiIQ; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="eUiJEiIQ" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 00C2EC4CECF; Wed, 11 Sep 2024 22:55:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095348; bh=ONKVPueTm7R2PEVvV8+tCD9cNcEk3jCly02IRQlQKQg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eUiJEiIQGC8VjeuVStZGt08/gecMgGbA6/Fo846oN4XZsN1GacSC0O/e2hdwKqY4I V/cQVDeymgAllj1Ey5mMJHQl1F/GC7GV5Yt6Q1WeU4iNzkMzP+exjY7BAlreNrqbUd MWGJRxchhyh+qHR5c1CfTeuEUPL7RisF07YbyWGuaf8Ts0N+wzLm6Elp7VP/BNdyxf VykicW0iKU8O1umLdSKlIc8xTXa3wMnlJcDo37urOPv/YBpi5lcq0oyK5wK6Jca5Sj MiWZz7aL5NKXkn6LUXRrA2xKpGHMG3t/s9RmYdje9xUVzoo3EomMT39Xfa064Lmy0K CcQPMS1RGnEUQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 09/26] rust: alloc: implement kernel `Box` Date: Thu, 12 Sep 2024 00:52:45 +0200 Message-ID: <20240911225449.152928-10-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" `Box` provides the simplest way to allocate memory for a generic type with one of the kernel's allocators, e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`. In contrast to Rust's `Box` type, the kernel `Box` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 465 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 472 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 7a405d6f3034..b1f28334b27a 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -5,6 +5,7 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; pub mod box_ext; +pub mod kbox; pub mod vec_ext; =20 #[cfg(any(test, testlib))] @@ -13,6 +14,11 @@ #[cfg(any(test, testlib))] pub use self::allocator_test as allocator; =20 +pub use self::kbox::Box; +pub use self::kbox::KBox; +pub use self::kbox::KVBox; +pub use self::kbox::VBox; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs new file mode 100644 index 000000000000..6188494f040d --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,465 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +#[allow(unused_imports)] // Used in doc comments. +use super::allocator::{KVmalloc, Kmalloc, Vmalloc}; +use super::{AllocError, Allocator, Flags}; +use core::fmt; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::pin::Pin; +use core::ptr::NonNull; +use core::result::Result; + +use crate::init::{InPlaceInit, InPlaceWrite, Init, PinInit}; +use crate::types::ForeignOwnable; + +/// The kernel's [`Box`] type -- a heap allocation for a single value of t= ype `T`. +/// +/// This is the kernel's version of the Rust stdlib's `Box`. There are sev= eral of differences, +/// for example no `noalias` attribute is emitted and partially moving out= of a `Box` is not +/// supported. There are also several API differences, e.g. `Box` always r= equires an [`Allocator`] +/// implementation to be passed as generic, page [`Flags`] when allocating= memory and all functions +/// that may allocate memory are fallible. +/// +/// `Box` works with any of the kernel's allocators, e.g. [`Kmalloc`], [`V= malloc`] or [`KVmalloc`]. +/// There are aliases for `Box` with these allocators ([`KBox`], [`VBox`],= [`KVBox`]). +/// +/// When dropping a [`Box`], the value is also dropped and the heap memory= is automatically freed. +/// +/// # Examples +/// +/// ``` +/// let b =3D KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// const SIZE: usize =3D bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KBox::::new_uninit(GFP_KERNEL | __GFP_NOWARN).is_err()); +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// const SIZE: usize =3D bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KVBox::::new_uninit(GFP_KERNEL).is_ok()); +/// ``` +/// +/// # Invariants +/// +/// `self.0` is always properly aligned and either points to memory alloca= ted with `A` or, for +/// zero-sized types, is a dangling, well aligned pointer. +#[repr(transparent)] +pub struct Box(NonNull, PhantomData); + +/// Type alias for [`Box`] with a [`Kmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b =3D KBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type KBox =3D Box; + +/// Type alias for [`Box`] with a [`Vmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b =3D VBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type VBox =3D Box; + +/// Type alias for [`Box`] with a [`KVmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b =3D KVBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type KVBox =3D Box; + +// SAFETY: `Box` is `Send` if `T` is `Send` because the `Box` owns a `T`. +unsafe impl Send for Box +where + T: Send + ?Sized, + A: Allocator, +{ +} + +// SAFETY: `Box` is `Sync` if `T` is `Sync` because the `Box` owns a `T`. +unsafe impl Sync for Box +where + T: Sync + ?Sized, + A: Allocator, +{ +} + +impl Box +where + T: ?Sized, + A: Allocator, +{ + /// Creates a new `Box` from a raw pointer. + /// + /// # Safety + /// + /// For non-ZSTs, `raw` must point at an allocation allocated with `A`= that is sufficiently + /// aligned for and holds a valid `T`. The caller passes ownership of = the allocation to the + /// `Box`. + /// + /// For ZSTs, `raw` must be a dangling, well aligned pointer. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // INVARIANT: Validity of `raw` is guaranteed by the safety precon= ditions of this function. + // SAFETY: By the safety preconditions of this function, `raw` is = not a NULL pointer. + Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData::) + } + + /// Consumes the `Box` and returns a raw pointer. + /// + /// This will not run the destructor of `T` and for non-ZSTs the alloc= ation will stay alive + /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop t= he value and free the + /// allocation, if any. + /// + /// # Examples + /// + /// ``` + /// let x =3D KBox::new(24, GFP_KERNEL)?; + /// let ptr =3D KBox::into_raw(x); + /// let x =3D unsafe { KBox::from_raw(ptr) }; + /// + /// assert_eq!(*x, 24); + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + pub fn into_raw(b: Self) -> *mut T { + let b =3D ManuallyDrop::new(b); + + b.0.as_ptr() + } + + /// Consumes and leaks the `Box` and returns a mutable reference. + /// + /// See [Box::into_raw] for more details. + #[inline] + pub fn leak<'a>(b: Self) -> &'a mut T { + // SAFETY: `Box::into_raw` always returns a properly aligned and d= ereferenceable pointer + // which points to an initialized instance of `T`. + unsafe { &mut *Box::into_raw(b) } + } +} + +impl Box, A> +where + A: Allocator, +{ + /// Converts a `Box, A>` to a `Box`. + /// + /// It is undefined behavior to call this function while the value ins= ide of `b` is not yet + /// fully initialized. + /// + /// # Safety + /// + /// Callers must ensure that the value inside of `b` is in an initiali= zed state. + pub unsafe fn assume_init(b: Self) -> Box { + let raw =3D Self::into_raw(b); + + // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By= the safety requirements + // of this function, the value inside the `Box` is in an initializ= ed state. Hence, it is + // safe to reconstruct the `Box` as `Box`. + unsafe { Box::from_raw(raw.cast()) } + } + + /// Writes the value and converts to `Box`. + pub fn write(mut b: Self, value: T) -> Box { + (*b).write(value); + // SAFETY: We've just initialized `b`'s value. + unsafe { Self::assume_init(b) } + } +} + +impl Box +where + A: Allocator, +{ + fn is_zst() -> bool { + core::mem::size_of::() =3D=3D 0 + } + + /// Creates a new `Box` and initializes its contents with `x`. + /// + /// New memory is allocated with `A`. The allocation may fail, in whic= h case an error is + /// returned. For ZSTs no memory is allocated. + pub fn new(x: T, flags: Flags) -> Result { + let b =3D Self::new_uninit(flags)?; + Ok(Box::write(b, x)) + } + + /// Creates a new `Box` with uninitialized contents. + /// + /// New memory is allocated with `A`. The allocation may fail, in whic= h case an error is + /// returned. For ZSTs no memory is allocated. + /// + /// # Examples + /// + /// ``` + /// let b =3D KBox::::new_uninit(GFP_KERNEL)?; + /// let b =3D KBox::write(b, 24); + /// + /// assert_eq!(*b, 24_u64); + /// # Ok::<(), Error>(()) + /// ``` + pub fn new_uninit(flags: Flags) -> Result, A>, Allo= cError> { + let ptr =3D if Self::is_zst() { + NonNull::dangling() + } else { + let layout =3D core::alloc::Layout::new::>(); + let ptr =3D A::alloc(layout, flags)?; + + ptr.cast() + }; + + // INVARIANT: `ptr` is either a dangling pointer or points to memo= ry allocated with `A`, + // which is sufficient in size and alignment for storing a `T`. + Ok(Box(ptr, PhantomData::)) + } + + /// Constructs a new `Pin>`. If `T` does not implement [`Unp= in`], then `x` will be + /// pinned in memory and can't be moved. + #[inline] + pub fn pin(x: T, flags: Flags) -> Result>, AllocError> + where + A: 'static, + { + Ok(Self::new(x, flags)?.into()) + } + + /// Forgets the contents (does not run the destructor), but keeps the = allocation. + fn forget_contents(this: Self) -> Box, A> { + let ptr =3D Self::into_raw(this); + + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { Box::from_raw(ptr.cast()) } + } + + /// Drops the contents, but keeps the allocation. + /// + /// # Examples + /// + /// ``` + /// let value =3D KBox::new([0; 32], GFP_KERNEL)?; + /// assert_eq!(*value, [0; 32]); + /// let value =3D KBox::drop_contents(value); + /// // Now we can re-use `value`: + /// let value =3D KBox::write(value, [1; 32]); + /// assert_eq!(*value, [1; 32]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn drop_contents(this: Self) -> Box, A> { + let ptr =3D this.0.as_ptr(); + + // SAFETY: `ptr` is valid, because it came from `this`. After this= call we never access the + // value stored in `this` again. + unsafe { core::ptr::drop_in_place(ptr) }; + + Self::forget_contents(this) + } + + /// Moves the `Box`' value out of the `Box` and consumes the `Box`. + pub fn into_inner(b: Self) -> T { + // SAFETY: By the type invariant `&*b` is valid for `read`. + let value =3D unsafe { core::ptr::read(&*b) }; + let _ =3D Self::forget_contents(b); + value + } +} + +impl From> for Pin> +where + T: ?Sized, + A: Allocator, +{ + /// Converts a `Box` into a `Pin>`. If `T` does not im= plement [`Unpin`], then + /// `*b` will be pinned in memory and can't be moved. + /// + /// This moves `b` into `Pin` without moving `*b` or allocating and co= pying any memory. + fn from(b: Box) -> Self { + // SAFETY: The value wrapped inside a `Pin>` cannot be m= oved or replaced as long + // as `T` does not implement `Unpin`. + unsafe { Pin::new_unchecked(b) } + } +} + +impl InPlaceWrite for Box, A> +where + A: Allocator + 'static, +{ + type Initialized =3D Box; + + fn write_init(mut self, init: impl Init) -> Result { + let slot =3D self.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but = not dropped, + // slot is valid. + unsafe { init.__init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(self) }) + } + + fn write_pin_init(mut self, init: impl PinInit) -> Result, E> { + let slot =3D self.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but = not dropped, + // slot is valid and will not be moved, because we pin it later. + unsafe { init.__pinned_init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(self) }.into()) + } +} + +impl InPlaceInit for Box +where + A: Allocator + 'static, +{ + type PinnedSelf =3D Pin; + + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + Box::<_, A>::new_uninit(flags)?.write_pin_init(init) + } + + #[inline] + fn try_init(init: impl Init, flags: Flags) -> Result + where + E: From, + { + Box::<_, A>::new_uninit(flags)?.write_init(init) + } +} + +impl ForeignOwnable for Box +where + A: Allocator, +{ + type Borrowed<'a> =3D &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + Box::into_raw(self) as _ + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Box::from_raw(ptr as _) } + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { + // SAFETY: The safety requirements of this method ensure that the = object remains alive and + // immutable for the duration of 'a. + unsafe { &*ptr.cast() } + } +} + +impl ForeignOwnable for Pin> +where + A: Allocator, +{ + type Borrowed<'a> =3D Pin<&'a T>; + + fn into_foreign(self) -> *const core::ffi::c_void { + // SAFETY: We are still treating the box as pinned. + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { + // SAFETY: The safety requirements for this function ensure that t= he object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the = object remains alive for + // the lifetime of the returned value. + let r =3D unsafe { &*ptr.cast() }; + + // SAFETY: This pointer originates from a `Pin>`. + unsafe { Pin::new_unchecked(r) } + } +} + +impl Deref for Box +where + T: ?Sized, + A: Allocator, +{ + type Target =3D T; + + fn deref(&self) -> &T { + // SAFETY: `self.0` is always properly aligned, dereferenceable an= d points to an initialized + // instance of `T`. + unsafe { self.0.as_ref() } + } +} + +impl DerefMut for Box +where + T: ?Sized, + A: Allocator, +{ + fn deref_mut(&mut self) -> &mut T { + // SAFETY: `self.0` is always properly aligned, dereferenceable an= d points to an initialized + // instance of `T`. + unsafe { self.0.as_mut() } + } +} + +impl fmt::Debug for Box +where + T: ?Sized + fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Drop for Box +where + T: ?Sized, + A: Allocator, +{ + fn drop(&mut self) { + let size =3D core::mem::size_of_val::(self); + + // SAFETY: The pointer in `self.0` is guaranteed to be valid by th= e type invariant. + unsafe { core::ptr::drop_in_place::(self.deref_mut()) }; + + if size !=3D 0 { + // SAFETY: As `size` is not zero, `self.0` was previously allo= cated with `A`. + unsafe { A::free(self.0.cast()) }; + } + } +} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 4571daec0961..a9210634a8c3 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; =20 -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt}; +pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, K= VBox, VBox}; =20 #[doc(no_inline)] pub use alloc::{boxed::Box, vec::Vec}; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 24A5E1BDA96; Wed, 11 Sep 2024 22:55:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095354; cv=none; b=jVRLpTGErgQmESMLwPWkw2EbN/2K8PYnLJXgqtqhDf9wX1JI+rQZdNXxfMBmtwhn4YOJ3HXKdBjseOG++OC8nJAAu+ol1OSMDCRYmTkQUPRSb6czhwt5OzKpoGtN7xeBmq96IIfyAnO3LnbRMK4fDRhNoiL7CxTzzcyWPvE42f4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095354; c=relaxed/simple; bh=HeNALPSOjE0/n20+LWU+GT6yCUL8iOTLWac/bFqoeV0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=M/qSsWFbwz+k/0QGHbzzkLYb4RW2W5z4dkuNa0acrNdWtBkTgwWxjq4rZgA3KIbe2DEKGLAJc8aMlJ49OHWpPZlIZ9vuOdO9VwMPUtUcacT3cMM3sOlWpIHXTevJH3PSw+WaAEEf0KA2Cm5n13LwmQg2EU0D4yxfLH630VjD5oM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Qmmsw43W; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Qmmsw43W" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2539AC4CEC5; Wed, 11 Sep 2024 22:55:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095354; bh=HeNALPSOjE0/n20+LWU+GT6yCUL8iOTLWac/bFqoeV0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Qmmsw43Wnal8FJjiGoJbRtDfBnn+XXk9RxQCjiU1kb+2Kj7ZpJ1pkKck1wI7NS7GF s5jREs6+svc8czMLdyk0FQlAJNa7vytaWS4bB/TuP2zeGRSJHePnI54F3GEttJRbFw YeN6TBLLvtlNIyc8+mBPovBljl9dpI/r8X3mEWflpT5CBUNvIt6KQuXdXnaoEx34/i O+jsL2mWEhLLOUpVlZjHa9dGCwN5gWEVfHRPdRIyFBFaNE87TYZ0s8RIQryEEBi4mV DJ+nDFg+YMlJeG7B/4kbnMX+pXB+AoNhyp630lI34XcMey25irWQoT3vtd5w6CFiw7 pyenSvRj6Qk3g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 10/26] rust: treewide: switch to our kernel `Box` type Date: Thu, 12 Sep 2024 00:52:46 +0200 Message-ID: <20240911225449.152928-11-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that we got the kernel `Box` type in place, convert all existing `Box` users to make use of it. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- drivers/block/rnull.rs | 4 +-- rust/kernel/init.rs | 51 ++++++++++++++++--------------- rust/kernel/init/__internal.rs | 2 +- rust/kernel/rbtree.rs | 49 ++++++++++++++++------------- rust/kernel/sync/arc.rs | 17 +++++------ rust/kernel/sync/condvar.rs | 4 +-- rust/kernel/sync/lock/mutex.rs | 2 +- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/workqueue.rs | 20 ++++++------ rust/macros/lib.rs | 6 ++-- 10 files changed, 81 insertions(+), 76 deletions(-) diff --git a/drivers/block/rnull.rs b/drivers/block/rnull.rs index b0227cf9ddd3..5de7223beb4d 100644 --- a/drivers/block/rnull.rs +++ b/drivers/block/rnull.rs @@ -32,7 +32,7 @@ } =20 struct NullBlkModule { - _disk: Pin>>>, + _disk: Pin>>>, } =20 impl kernel::Module for NullBlkModule { @@ -47,7 +47,7 @@ fn init(_module: &'static ThisModule) -> Result { .rotational(false) .build(format_args!("rnullb{}", 0), tagset)?; =20 - let disk =3D Box::pin_init(new_mutex!(disk, "nullb:disk"), flags::= GFP_KERNEL)?; + let disk =3D KBox::pin_init(new_mutex!(disk, "nullb:disk"), flags:= :GFP_KERNEL)?; =20 Ok(Self { _disk: disk }) } diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index a17ac8762d8f..e057b374f255 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -13,7 +13,7 @@ //! To initialize a `struct` with an in-place constructor you will need tw= o things: //! - an in-place constructor, //! - a memory location that can hold your `struct` (this can be the [stac= k], an [`Arc`], -//! [`UniqueArc`], [`Box`] or any other smart pointer that impleme= nts [`InPlaceInit`]). +//! [`UniqueArc`], [`KBox`] or any other smart pointer that implem= ents [`InPlaceInit`]). //! //! To get an in-place constructor there are generally three options: //! - directly creating an in-place constructor using the [`pin_init!`] ma= cro, @@ -68,7 +68,7 @@ //! # a <- new_mutex!(42, "Foo::a"), //! # b: 24, //! # }); -//! let foo: Result>> =3D Box::pin_init(foo, GFP_KERNEL); +//! let foo: Result>> =3D KBox::pin_init(foo, GFP_KERNEL); //! ``` //! //! For more information see the [`pin_init!`] macro. @@ -93,14 +93,14 @@ //! struct DriverData { //! #[pin] //! status: Mutex, -//! buffer: Box<[u8; 1_000_000]>, +//! buffer: KBox<[u8; 1_000_000]>, //! } //! //! impl DriverData { //! fn new() -> impl PinInit { //! try_pin_init!(Self { //! status <- new_mutex!(0, "DriverData::status"), -//! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?, +//! buffer: KBox::init(kernel::init::zeroed(), GFP_KERNEL)?, //! }) //! } //! } @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! =20 use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, error::{self, Error}, sync::Arc, sync::UniqueArc, @@ -298,7 +298,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -307,7 +307,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Result, AllocError> =3D pin= _init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -324,7 +324,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -333,7 +333,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Pin<&mut Foo> =3D? pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -392,7 +392,7 @@ macro_rules! stack_try_pin_init { /// }, /// }); /// # initializer } -/// # Box::pin_init(demo(), GFP_KERNEL).unwrap(); +/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap(); /// ``` /// /// Arbitrary Rust expressions can be used to set the value of a variable. @@ -462,7 +462,7 @@ macro_rules! stack_try_pin_init { /// # }) /// # } /// # } -/// let foo =3D Box::pin_init(Foo::new(), GFP_KERNEL); +/// let foo =3D KBox::pin_init(Foo::new(), GFP_KERNEL); /// ``` /// /// They can also easily embed it into their own `struct`s: @@ -594,7 +594,7 @@ macro_rules! pin_init { /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// ptr: *mut u8, /// } @@ -602,7 +602,7 @@ macro_rules! pin_init { /// impl BigBuf { /// fn new() -> impl PinInit { /// try_pin_init!(Self { -/// big: Box::init(init::zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init::zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) @@ -694,16 +694,16 @@ macro_rules! init { /// # Examples /// /// ```rust -/// use kernel::{init::{PinInit, zeroed}, error::Error}; +/// use kernel::{alloc::KBox, init::{PinInit, zeroed}, error::Error}; /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// } /// /// impl BigBuf { /// fn new() -> impl Init { /// try_init!(Self { -/// big: Box::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// }? Error) /// } @@ -814,8 +814,8 @@ macro_rules! assert_pinned { /// A pin-initializer for the type `T`. /// /// To use this initializer, you will need a suitable memory location that= can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`s= tack_pin_init!`]). Use the -/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] = on this. +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`= stack_pin_init!`]). Use +/// the [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. /// /// Also see the [module description](self). /// @@ -894,7 +894,7 @@ fn pin_chain(self, f: F) -> ChainPinInit } =20 /// An initializer returned by [`PinInit::pin_chain`]. -pub struct ChainPinInit(I, F, __internal::Invariant<(E= , Box)>); +pub struct ChainPinInit(I, F, __internal::Invariant<(E= , KBox)>); =20 // SAFETY: The `__pinned_init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -920,8 +920,8 @@ unsafe fn __pinned_init(self, slot: *mut T) -> Result<(= ), E> { /// An initializer for `T`. /// /// To use this initializer, you will need a suitable memory location that= can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`s= tack_pin_init!`]). Use the -/// [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on t= his. Because +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`= stack_pin_init!`]). Use +/// the [`InPlaceInit::init`] function of a smart pointer like [`Arc`] = on this. Because /// [`PinInit`] is a super trait, you can use every function that ta= kes it as well. /// /// Also see the [module description](self). @@ -993,7 +993,7 @@ fn chain(self, f: F) -> ChainInit } =20 /// An initializer returned by [`Init::chain`]. -pub struct ChainInit(I, F, __internal::Invariant<(E, B= ox)>); +pub struct ChainInit(I, F, __internal::Invariant<(E, K= Box)>); =20 // SAFETY: The `__init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -1077,8 +1077,9 @@ pub fn uninit() -> impl Init, E>= { /// # Examples /// /// ```rust -/// use kernel::{error::Error, init::init_array_from_fn}; -/// let array: Box<[usize; 1_000]> =3D Box::init::(init_array_from_= fn(|i| i), GFP_KERNEL).unwrap(); +/// use kernel::{alloc::KBox, error::Error, init::init_array_from_fn}; +/// let array: KBox<[usize; 1_000]> =3D +/// KBox::init::(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(= ); /// assert_eq!(array.len(), 1_000); /// ``` pub fn init_array_from_fn( @@ -1451,7 +1452,7 @@ macro_rules! impl_zeroable { // // In this case we are allowed to use `T: ?Sized`, since all zeros is = the `None` variant. {} Option>, - {} Option>, + {} Option>, =20 // SAFETY: `null` pointer is valid. // diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.rs index 13cefd37512f..b31f498f4f8e 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -102,7 +102,7 @@ fn make_closure(self, f: F) -> F } } =20 -pub struct AllData(PhantomData) -> Box>); +pub struct AllData(PhantomData) -> KBox>); =20 impl Clone for AllData { fn clone(&self) -> Self { diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index 25eb36fd1cdc..a63d4b0fe485 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -7,7 +7,6 @@ //! Reference: =20 use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::= *}; -use alloc::boxed::Box; use core::{ cmp::{Ord, Ordering}, marker::PhantomData, @@ -497,7 +496,7 @@ fn drop(&mut self) { // but it is not observable. The loop invariant is still maint= ained. =20 // SAFETY: `this` is valid per the loop invariant. - unsafe { drop(Box::from_raw(this.cast_mut())) }; + unsafe { drop(KBox::from_raw(this.cast_mut())) }; } } } @@ -764,7 +763,7 @@ pub fn remove_current(self) -> (Option, RBTreeNod= e) { // point to the links field of `Node` objects. let this =3D unsafe { container_of!(self.current.as_ptr(), Node, links) }.cast_mut(); // SAFETY: `this` is valid by the type invariants as described abo= ve. - let node =3D unsafe { Box::from_raw(this) }; + let node =3D unsafe { KBox::from_raw(this) }; let node =3D RBTreeNode { node }; // SAFETY: The reference to the tree used to create the cursor out= lives the cursor, so // the tree cannot change. By the tree invariant, all nodes are va= lid. @@ -809,7 +808,7 @@ fn remove_neighbor(&mut self, direction: Direction) -> = Option> // point to the links field of `Node` objects. let this =3D unsafe { container_of!(neighbor, Node, link= s) }.cast_mut(); // SAFETY: `this` is valid by the type invariants as described= above. - let node =3D unsafe { Box::from_raw(this) }; + let node =3D unsafe { KBox::from_raw(this) }; return Some(RBTreeNode { node }); } None @@ -1035,7 +1034,7 @@ fn next(&mut self) -> Option { /// It contains the memory needed to hold a node that can be inserted into= a red-black tree. One /// can be obtained by directly allocating it ([`RBTreeNodeReservation::ne= w`]). pub struct RBTreeNodeReservation { - node: Box>>, + node: KBox>>, } =20 impl RBTreeNodeReservation { @@ -1043,7 +1042,7 @@ impl RBTreeNodeReservation { /// call to [`RBTree::insert`]. pub fn new(flags: Flags) -> Result> { Ok(RBTreeNodeReservation { - node: as BoxExt<_>>::new_uninit(flags)?, + node: KBox::new_uninit(flags)?, }) } } @@ -1059,14 +1058,15 @@ impl RBTreeNodeReservation { /// Initialises a node reservation. /// /// It then becomes an [`RBTreeNode`] that can be inserted into a tree. - pub fn into_node(mut self, key: K, value: V) -> RBTreeNode { - self.node.write(Node { - key, - value, - links: bindings::rb_node::default(), - }); - // SAFETY: We just wrote to it. - let node =3D unsafe { self.node.assume_init() }; + pub fn into_node(self, key: K, value: V) -> RBTreeNode { + let node =3D KBox::write( + self.node, + Node { + key, + value, + links: bindings::rb_node::default(), + }, + ); RBTreeNode { node } } } @@ -1076,7 +1076,7 @@ pub fn into_node(mut self, key: K, value: V) -> RBTre= eNode { /// The node is fully initialised (with key and value) and can be inserted= into a tree without any /// extra allocations or failure paths. pub struct RBTreeNode { - node: Box>, + node: KBox>, } =20 impl RBTreeNode { @@ -1088,7 +1088,9 @@ pub fn new(key: K, value: V, flags: Flags) -> Result<= RBTreeNode> { =20 /// Get the key and value from inside the node. pub fn to_key_value(self) -> (K, V) { - (self.node.key, self.node.value) + let node =3D KBox::into_inner(self.node); + + (node.key, node.value) } } =20 @@ -1110,7 +1112,7 @@ impl RBTreeNode { /// may be freed (but only for the key/value; memory for the node itse= lf is kept for reuse). pub fn into_reservation(self) -> RBTreeNodeReservation { RBTreeNodeReservation { - node: Box::drop_contents(self.node), + node: KBox::drop_contents(self.node), } } } @@ -1161,7 +1163,7 @@ impl<'a, K, V> RawVacantEntry<'a, K, V> { /// The `node` must have a key such that inserting it here does not br= eak the ordering of this /// [`RBTree`]. fn insert(self, node: RBTreeNode) -> &'a mut V { - let node =3D Box::into_raw(node.node); + let node =3D KBox::into_raw(node.node); =20 // SAFETY: `node` is valid at least until we call `Box::from_raw`,= which only happens when // the node is removed or replaced. @@ -1235,21 +1237,24 @@ pub fn remove_node(self) -> RBTreeNode { // SAFETY: The node was a node in the tree, but we removed it,= so we can convert it // back into a box. node: unsafe { - Box::from_raw(container_of!(self.node_links, Node, l= inks).cast_mut()) + KBox::from_raw(container_of!(self.node_links, Node, = links).cast_mut()) }, } } =20 /// Takes the value of the entry out of the map, and returns it. pub fn remove(self) -> V { - self.remove_node().node.value + let rb_node =3D self.remove_node(); + let node =3D KBox::into_inner(rb_node.node); + + node.value } =20 /// Swap the current node for the provided node. /// /// The key of both nodes must be equal. fn replace(self, node: RBTreeNode) -> RBTreeNode { - let node =3D Box::into_raw(node.node); + let node =3D KBox::into_raw(node.node); =20 // SAFETY: `node` is valid at least until we call `Box::from_raw`,= which only happens when // the node is removed or replaced. @@ -1265,7 +1270,7 @@ fn replace(self, node: RBTreeNode) -> RBTreeNod= e { // - `self.node_ptr` produces a valid pointer to a node in the tre= e. // - Now that we removed this entry from the tree, we can convert = the node to a box. let old_node =3D - unsafe { Box::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }; + unsafe { KBox::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }; =20 RBTreeNode { node: old_node } } diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 3021f30fd822..d7adbad7d3b4 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -17,13 +17,12 @@ //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html =20 use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{AllocError, Flags, KBox}, bindings, init::{self, InPlaceInit, Init, PinInit}, try_init, types::{ForeignOwnable, Opaque}, }; -use alloc::boxed::Box; use core::{ alloc::Layout, fmt, @@ -204,11 +203,11 @@ pub fn new(contents: T, flags: Flags) -> Result { data: contents, }; =20 - let inner =3D as BoxExt<_>>::new(value, flags)?; + let inner =3D KBox::new(value, flags)?; =20 // SAFETY: We just created `inner` with a reference count of 1, wh= ich is owned by the new // `Arc` object. - Ok(unsafe { Self::from_inner(Box::leak(inner).into()) }) + Ok(unsafe { Self::from_inner(KBox::leak(inner).into()) }) } } =20 @@ -401,8 +400,8 @@ fn drop(&mut self) { if is_zero { // The count reached zero, we must free the memory. // - // SAFETY: The pointer was initialised from the result of `Box= ::leak`. - unsafe { drop(Box::from_raw(self.ptr.as_ptr())) }; + // SAFETY: The pointer was initialised from the result of `KBo= x::leak`. + unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) }; } } } @@ -647,7 +646,7 @@ pub fn new(value: T, flags: Flags) -> Result { /// Tries to allocate a new [`UniqueArc`] instance whose contents are = not initialised yet. pub fn new_uninit(flags: Flags) -> Result>, A= llocError> { // INVARIANT: The refcount is initialised to a non-zero value. - let inner =3D Box::try_init::( + let inner =3D KBox::try_init::( try_init!(ArcInner { // SAFETY: There are no safety requirements for this FFI c= all. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) = }), @@ -657,8 +656,8 @@ pub fn new_uninit(flags: Flags) -> Result>, AllocError> )?; Ok(UniqueArc { // INVARIANT: The newly-created object has a refcount of 1. - // SAFETY: The pointer from the `Box` is valid. - inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, + // SAFETY: The pointer from the `KBox` is valid. + inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) }, }) } } diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs index 2b306afbe56d..2081932bb4b9 100644 --- a/rust/kernel/sync/condvar.rs +++ b/rust/kernel/sync/condvar.rs @@ -70,8 +70,8 @@ macro_rules! new_condvar { /// } /// /// /// Allocates a new boxed `Example`. -/// fn new_example() -> Result>> { -/// Box::pin_init(pin_init!(Example { +/// fn new_example() -> Result>> { +/// KBox::pin_init(pin_init!(Example { /// value <- new_mutex!(0), /// value_changed <- new_condvar!(), /// }), GFP_KERNEL) diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index 30632070ee67..f8f6d530db7d 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -58,7 +58,7 @@ macro_rules! new_mutex { /// } /// /// // Allocate a boxed `Example`. -/// let e =3D Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e =3D KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spin= lock.rs index ea5c5bc1ce12..a9096a4dc42a 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -56,7 +56,7 @@ macro_rules! new_spinlock { /// } /// /// // Allocate a boxed `Example`. -/// let e =3D Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e =3D KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 553a5cba2adc..94318472507f 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -216,7 +216,7 @@ pub fn try_spawn( func: Some(func), }); =20 - self.enqueue(Box::pin_init(init, flags).map_err(|_| AllocError)?); + self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?); Ok(()) } } @@ -239,9 +239,9 @@ fn project(self: Pin<&mut Self>) -> &mut Option { } =20 impl WorkItem for ClosureWork { - type Pointer =3D Pin>; + type Pointer =3D Pin>; =20 - fn run(mut this: Pin>) { + fn run(mut this: Pin>) { if let Some(func) =3D this.as_mut().project().take() { (func)() } @@ -297,7 +297,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self:= :EnqueueOutput =20 /// Defines the method that should be called directly when a work item is = executed. /// -/// This trait is implemented by `Pin>` and [`Arc`], and is main= ly intended to be +/// This trait is implemented by `Pin>` and [`Arc`], and is mai= nly intended to be /// implemented for smart pointer types. For your own structs, you would i= mplement [`WorkItem`] /// instead. The [`run`] method on this trait will usually just perform th= e appropriate /// `container_of` translation and then call into the [`run`][WorkItem::ru= n] method from the @@ -329,7 +329,7 @@ pub unsafe trait WorkItemPointer: RawWor= kItem { /// This trait is used when the `work_struct` field is defined using the [= `Work`] helper. pub trait WorkItem { /// The pointer type that this struct is wrapped in. This will typical= ly be `Arc` or - /// `Pin>`. + /// `Pin>`. type Pointer: WorkItemPointer; =20 /// The method that should be called when this work item is executed. @@ -565,7 +565,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self:= :EnqueueOutput } } =20 -unsafe impl WorkItemPointer for Pin> +unsafe impl WorkItemPointer for Pin> where T: WorkItem, T: HasWork, @@ -576,7 +576,7 @@ unsafe impl WorkItemPointer for P= in> // SAFETY: This computes the pointer that `__enqueue` got from `Ar= c::into_raw`. let ptr =3D unsafe { T::work_container_of(ptr) }; // SAFETY: This pointer comes from `Arc::into_raw` and we've been = given back ownership. - let boxed =3D unsafe { Box::from_raw(ptr) }; + let boxed =3D unsafe { KBox::from_raw(ptr) }; // SAFETY: The box was already pinned when it was enqueued. let pinned =3D unsafe { Pin::new_unchecked(boxed) }; =20 @@ -584,7 +584,7 @@ unsafe impl WorkItemPointer for P= in> } } =20 -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -598,9 +598,9 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self:= :EnqueueOutput // SAFETY: We're not going to move `self` or any of its fields, so= its okay to temporarily // remove the `Pin` wrapper. let boxed =3D unsafe { Pin::into_inner_unchecked(self) }; - let ptr =3D Box::into_raw(boxed); + let ptr =3D KBox::into_raw(boxed); =20 - // SAFETY: Pointers into a `Box` point at a valid value. + // SAFETY: Pointers into a `KBox` point at a valid value. let work_ptr =3D unsafe { T::raw_get_work(ptr) }; // SAFETY: `raw_get_work` returns a pointer to a valid value. let work_ptr =3D unsafe { Work::raw_get(work_ptr) }; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index a626b1145e5c..ab93111a048c 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -243,7 +243,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` /// @@ -252,7 +252,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// @@ -282,7 +282,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) = -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id BDA1E1BDAB6; Wed, 11 Sep 2024 22:55:59 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095359; cv=none; b=Y/l9MR5t1mDZAB5nfFJVKBaNRaD6m29tof7869Ge529RVfxNPRzKOkPWdZr/hUIUjyyEOFtikwhj6CGF4XOLeKxIFp0jhvhZ1QYYbh0BR3n7nc9wuZq8aruQ+ymefgyEsJzXPoNsDVJaXes3YPCBNPtrNjtkPhbrDNA89yWbl/o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095359; c=relaxed/simple; bh=bmBk92HB3W03D2BfbbW7zaJgdP/ajBEnHftULDObyCA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=qloqRYjW5pinnJzIKe4lkDZn8fXXS0gO5zzOtYnvD8wuoX9yT4pL2uoZVnyb2yNl5S0S8Kc0ilCjIebt7MJW1iKhdPWwjw+qK/mIroGY2J8i5geIqFtC+HcscKzm7rifc5qO2idqEah+4/rCb/ZBP2Z2gRaXiu8iXrWScraPyHc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=iepKWa5w; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="iepKWa5w" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 73E08C4CECF; Wed, 11 Sep 2024 22:55:54 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095359; bh=bmBk92HB3W03D2BfbbW7zaJgdP/ajBEnHftULDObyCA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=iepKWa5wL+zjAHwn6N6ep2yRpx+Zw5Ctq/woW3R5wGUhjZzx+SQDdSg2o8dfIzFt+ 32g34oKYqB4yFGI/VtPCV7JntljTb+jT86Fa8wlNZq8LUt8x0tPgxQ6OXTfCMXQBBT xYh82wtRgOVRcgc98HG0I0aBK8AXnJ7F6oLXb/tBvegoXiqkM0dUTQBCYk34iGzdHg h6c/r7HnYxpvN9fdXGHdCJ+7PVS7ixUHC8d4oOPQjV8ITKUPrv3Bx+O44p5jFbz7mL jkbsGqG3Uspl/oMAIlboYdmOccZRmsHiiGchGYYTXItjxZqycSz9QgchbyPdCyyyh/ 0s1nfxn7/Dkrg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 11/26] rust: alloc: remove extension of std's `Box` Date: Thu, 12 Sep 2024 00:52:47 +0200 Message-ID: <20240911225449.152928-12-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that all existing `Box` users were moved to the kernel `Box` type, remove the `BoxExt` extension and all other related extensions. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 87 ------------------------------------ rust/kernel/init.rs | 46 +------------------ rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +- rust/kernel/types.rs | 50 --------------------- 6 files changed, 3 insertions(+), 186 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index b1f28334b27a..1d0cb6f12af9 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -4,7 +4,6 @@ =20 #[cfg(not(any(test, testlib)))] pub mod allocator; -pub mod box_ext; pub mod kbox; pub mod vec_ext; =20 diff --git a/rust/kernel/alloc/box_ext.rs b/rust/kernel/alloc/box_ext.rs deleted file mode 100644 index 5b1550d620fd..000000000000 --- a/rust/kernel/alloc/box_ext.rs +++ /dev/null @@ -1,87 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Box`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::boxed::Box; -use core::{mem::MaybeUninit, ptr, result::Result}; - -/// Extensions to [`Box`]. -pub trait BoxExt: Sized { - /// Allocates a new box. - /// - /// The allocation may fail, in which case an error is returned. - fn new(x: T, flags: Flags) -> Result; - - /// Allocates a new uninitialised box. - /// - /// The allocation may fail, in which case an error is returned. - fn new_uninit(flags: Flags) -> Result>, AllocError>; - - /// Drops the contents, but keeps the allocation. - /// - /// # Examples - /// - /// ``` - /// use kernel::alloc::{flags, box_ext::BoxExt}; - /// let value =3D Box::new([0; 32], flags::GFP_KERNEL)?; - /// assert_eq!(*value, [0; 32]); - /// let mut value =3D Box::drop_contents(value); - /// // Now we can re-use `value`: - /// value.write([1; 32]); - /// // SAFETY: We just wrote to it. - /// let value =3D unsafe { value.assume_init() }; - /// assert_eq!(*value, [1; 32]); - /// # Ok::<(), Error>(()) - /// ``` - fn drop_contents(this: Self) -> Box>; -} - -impl BoxExt for Box { - fn new(x: T, flags: Flags) -> Result { - let b =3D >::new_uninit(flags)?; - Ok(Box::write(b, x)) - } - - #[cfg(any(test, testlib))] - fn new_uninit(_flags: Flags) -> Result>, AllocError= > { - Ok(Box::new_uninit()) - } - - #[cfg(not(any(test, testlib)))] - fn new_uninit(flags: Flags) -> Result>, AllocError>= { - let ptr =3D if core::mem::size_of::>() =3D=3D 0 { - core::ptr::NonNull::<_>::dangling().as_ptr() - } else { - let layout =3D core::alloc::Layout::new::>(); - - // SAFETY: Memory is being allocated (first arg is null). The = only other source of - // safety issues is sleeping on atomic context, which is addre= ssed by klint. Lastly, - // the type is not a SZT (checked above). - let ptr =3D - unsafe { super::allocator::krealloc_aligned(core::ptr::nul= l_mut(), layout, flags) }; - if ptr.is_null() { - return Err(AllocError); - } - - ptr.cast::>() - }; - - // SAFETY: For non-zero-sized types, we allocate above using the g= lobal allocator. For - // zero-sized types, we use `NonNull::dangling`. - Ok(unsafe { Box::from_raw(ptr) }) - } - - fn drop_contents(this: Self) -> Box> { - let ptr =3D Box::into_raw(this); - // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. - unsafe { ptr::drop_in_place(ptr) }; - - // CAST: `MaybeUninit` is a transparent wrapper of `T`. - let ptr =3D ptr.cast::>(); - - // SAFETY: `ptr` is valid for writes, because it came from `Box::i= nto_raw` and it is valid for - // reads, since the pointer came from `Box::into_raw` and the type= is `MaybeUninit`. - unsafe { Box::from_raw(ptr) } - } -} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index e057b374f255..2f562642e9a4 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,13 +211,12 @@ //! [`pin_init!`]: crate::pin_init! =20 use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, + alloc::{AllocError, Flags, KBox}, error::{self, Error}, sync::Arc, sync::UniqueArc, types::{Opaque, ScopeGuard}, }; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, convert::Infallible, @@ -590,7 +589,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1244,26 +1242,6 @@ fn try_init(init: impl Init, flags: Flags) = -> Result } } =20 -impl InPlaceInit for Box { - type PinnedSelf =3D Pin; - - #[inline] - fn try_pin_init(init: impl PinInit, flags: Flags) -> Result - where - E: From, - { - as BoxExt<_>>::new_uninit(flags)?.write_pin_init(init) - } - - #[inline] - fn try_init(init: impl Init, flags: Flags) -> Result - where - E: From, - { - as BoxExt<_>>::new_uninit(flags)?.write_init(init) - } -} - impl InPlaceInit for UniqueArc { type PinnedSelf =3D Pin; =20 @@ -1300,28 +1278,6 @@ pub trait InPlaceWrite { fn write_pin_init(self, init: impl PinInit) -> Result, E>; } =20 -impl InPlaceWrite for Box> { - type Initialized =3D Box; - - fn write_init(mut self, init: impl Init) -> Result { - let slot =3D self.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but = not dropped, - // slot is valid. - unsafe { init.__init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { self.assume_init() }) - } - - fn write_pin_init(mut self, init: impl PinInit) -> Result, E> { - let slot =3D self.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but = not dropped, - // slot is valid and will not be moved, because we pin it later. - unsafe { init.__pinned_init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { self.assume_init() }.into()) - } -} - impl InPlaceWrite for UniqueArc> { type Initialized =3D UniqueArc; =20 diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index f10b06a78b9d..eb5c593acfc0 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -14,7 +14,6 @@ #![no_std] #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] -#![feature(new_uninit)] #![feature(receiver_trait)] #![feature(unsize)] =20 diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index a9210634a8c3..c1f8e5c832e2 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,10 @@ #[doc(no_inline)] pub use core::pin::Pin; =20 -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, K= VBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; =20 #[doc(no_inline)] -pub use alloc::{boxed::Box, vec::Vec}; +pub use alloc::vec::Vec; =20 #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 9e7ca066355c..53d3ddc0b98c 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -3,13 +3,11 @@ //! Kernel types. =20 use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, mem::{ManuallyDrop, MaybeUninit}, ops::{Deref, DerefMut}, - pin::Pin, ptr::NonNull, }; =20 @@ -71,54 +69,6 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void= ) -> Option { } } =20 -impl ForeignOwnable for Box { - type Borrowed<'a> =3D &'a T; - - fn into_foreign(self) -> *const core::ffi::c_void { - Box::into_raw(self) as _ - } - - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { - // SAFETY: The safety requirements for this function ensure that t= he object is still alive, - // so it is safe to dereference the raw pointer. - // The safety requirements of `from_foreign` also ensure that the = object remains alive for - // the lifetime of the returned value. - unsafe { &*ptr.cast() } - } - - unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { - // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr as _) } - } -} - -impl ForeignOwnable for Pin> { - type Borrowed<'a> =3D Pin<&'a T>; - - fn into_foreign(self) -> *const core::ffi::c_void { - // SAFETY: We are still treating the box as pinned. - Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ - } - - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { - // SAFETY: The safety requirements for this function ensure that t= he object is still alive, - // so it is safe to dereference the raw pointer. - // The safety requirements of `from_foreign` also ensure that the = object remains alive for - // the lifetime of the returned value. - let r =3D unsafe { &*ptr.cast() }; - - // SAFETY: This pointer originates from a `Pin>`. - unsafe { Pin::new_unchecked(r) } - } - - unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { - // SAFETY: The safety requirements of this function ensure that `p= tr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } - } -} - impl ForeignOwnable for () { type Borrowed<'a> =3D (); =20 --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 35C4C1BC9E9; Wed, 11 Sep 2024 22:56:04 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095365; cv=none; b=a5jS4u6aVAxpeB7Vgz9P55J7SQssLPvjvmAnrN/0Pjjnt1oxJmt2VhNNZ8AMRv/bRoMgs3QntyBi5gv54QxMMAA1KCDsR9ynTjUxZeFE4s0/8MTC6xRPO8C92JSztAm3hiKYhCMaZiqD2HjSMg9MA8qe5zShi9u6HEmV7yi4lIk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095365; c=relaxed/simple; bh=cG7LgUDIz4/c/n6Pe+TTApJnhkzb0osvgtaCA8JUOxc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=DqU2NKVRjQy/4ucwP2D+JPCNk1GxGe+sGIe0hHjbI815jw9YSjfc8AHLd8Bf+1MiO2K575pjL/zVCSK51VOneisVKAv19dd++ZRXdR8cr7J8XiOJDX+14ImWW6jfX5eebVVKfVJA462OFw+0jAF5TmQFWkMJS3xJC8HDmATJ0s8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=dpmfrHai; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="dpmfrHai" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C7454C4CEC0; Wed, 11 Sep 2024 22:55:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095364; bh=cG7LgUDIz4/c/n6Pe+TTApJnhkzb0osvgtaCA8JUOxc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dpmfrHairLbF/WFnDc9mCRxFc4TWwJtNuuEBCQGTkA5kZgRbz9m1xhG6wVnWSHl7n 2uKwNsknq2qHLD42rJOMTTaEIAO4x4rTO5oyVA/GB0PKQA7f5Rsk7c0YVYOJaAIWkB cNR2TzQoSm7yK/KzjDPPgoCJNab3xr7ixisMOEfwCP6E6Vm5IQV23FzTWf8u5R+xcR BGxhGzckFXGnU/hNP/qIfREYZDRN9Nf0+LB12qJmQ8WZcQe+CpIbljlzgG+fB0x3W4 /ffi5ETohcuJd+MD8CdRhsRo4bjM0doJtGkEWioO5TnDqqf9r4piOpub9UcrlZofuH pvuLLxS+bnJmg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 12/26] rust: alloc: add `Box` to prelude Date: Thu, 12 Sep 2024 00:52:48 +0200 Message-ID: <20240911225449.152928-13-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that we removed `BoxExt` and the corresponding includes in prelude.rs, add the new kernel `Box` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index c1f8e5c832e2..d5f2fe42d093 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; =20 -pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox}; =20 #[doc(no_inline)] pub use alloc::vec::Vec; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 807471BC9F7; Wed, 11 Sep 2024 22:56:10 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095370; cv=none; b=OtgEjcrd1oLuNMfDQguY0ffDRv/ohji8tP0h7fDWaymmmmDiWJtULgRk+MuX314TLcbJTuA9nvBs6OR570kozcT8sBWsOIvqkx5FBD6c2IrqXfs5acnOofSEs7NQp7cZcuvYYEbmWPAeePl/PEedhHiOIgxfnluiLRvpHQy005c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095370; c=relaxed/simple; bh=KwoehbhzPcxrEmOIZIyHuxsvPUIruBJfFaLK+8sOSio=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=cDVZuSUyzdAJKssWDwbVDjeXPJwusN3Lr1i9ipkn2N1hYAhmMdJ1+R8tB74Y6e7N+t8YHQ//ET4ihVM3jsMjKwciMu/nbxkSfQd9l60JjQOfHEJZ09SoKYiVTSnH7bzr+viK3MJpAoae4gglLqOwLZFDgDzXxOqeIFU9xjxzSgM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=RP7N2kn8; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="RP7N2kn8" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2C10EC4CEC5; Wed, 11 Sep 2024 22:56:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095370; bh=KwoehbhzPcxrEmOIZIyHuxsvPUIruBJfFaLK+8sOSio=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RP7N2kn8A7twihnr9wgeDk6Qtz3Ze8f5dhG9oP9w057T3zPImZU68n533d86lDYMO gdcbpvzAFN3g/nLWetza/mcUDV6PsR7xsCxnPo3douEKp5wmZ+99iqwds+rvDQ3YWL VDKxgDtX6LSw2CVtLx1Z0cUW7f3rnvlj0AOu83IftlH2RuqtFHkdXCQ+vZOJcVOaye Pxk5IXrNCDQeVmo/I1imlQlSWhnDKgxANpNGkvbgzNU4N9wfLAf/WijkqsbP+d4r9F 0gnMr677kSFYFiru37n2xPtb5ujPEyvBfbIEsSE8C/IUBRhYh4aV79r++jZ9k+bI9O +MKeTydyduBPw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 13/26] rust: alloc: implement kernel `Vec` type Date: Thu, 12 Sep 2024 00:52:49 +0200 Message-ID: <20240911225449.152928-14-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" `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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kvec.rs | 638 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 645 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1d0cb6f12af9..4fb983b63d46 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -5,6 +5,7 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; pub mod kbox; +pub mod kvec; pub mod vec_ext; =20 #[cfg(any(test, testlib))] @@ -18,6 +19,11 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; =20 +pub use self::kvec::KVVec; +pub use self::kvec::KVec; +pub use self::kvec::VVec; +pub use self::kvec::Vec; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs new file mode 100644 index 000000000000..631a44e19f35 --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,638 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{ + allocator::{KVmalloc, Kmalloc, Vmalloc}, + AllocError, Allocator, Box, Flags, +}; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + ptr::NonNull, + slice, + slice::SliceIndex, +}; + +/// Create a [`Vec`] containing the arguments. +/// +/// # Examples +/// +/// ``` +/// let mut v =3D kernel::kvec![]; +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(v, [1]); +/// +/// let mut v =3D kernel::kvec![1; 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 1, 1, 4]); +/// +/// let mut v =3D kernel::kvec![1, 2, 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 2, 3, 4]); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[macro_export] +macro_rules! kvec { + () =3D> ( + $crate::alloc::KVec::new() + ); + ($elem:expr; $n:expr) =3D> ( + $crate::alloc::KVec::from_elem($elem, $n, GFP_KERNEL) + ); + ($($x:expr),+ $(,)?) =3D> ( + match $crate::alloc::KBox::new_uninit(GFP_KERNEL) { + Ok(b) =3D> Ok($crate::alloc::KVec::from($crate::alloc::KBox::w= rite(b, [$($x),+]))), + Err(e) =3D> Err(e), + } + ); +} + +/// The kernel's [`Vec`] type. +/// +/// A contiguous growable array type with contents allocated with the kern= el's allocators (e.g. +/// `Kmalloc`, `Vmalloc` or `KVmalloc`), written `Vec`. +/// +/// For non-zero-sized values, a [`Vec`] will use the given allocator `A` = for its allocation. For +/// the most common allocators the type aliases `KVec`, `VVec` and `KVVec`= exist. +/// +/// For zero-sized types the [`Vec`]'s pointer must be `dangling_mut::`= ; no memory is allocated. +/// +/// Generally, [`Vec`] consists of a pointer that represents the vector's = backing buffer, the +/// capacity of the vector (the number of elements that currently fit into= the vector), it's length +/// (the number of elements that are currently stored in the vector) and t= he `Allocator` type used +/// to allocate (and free) the backing buffer. +/// +/// A [`Vec`] can be deconstructed into and (re-)constructed from it's pre= viously named raw parts +/// and manually modified. +/// +/// [`Vec`]'s backing buffer gets, if required, automatically increased (r= e-allocated) when elements +/// are added to the vector. +/// +/// # Invariants +/// +/// - `self.ptr` is always properly aligned and either points to memory al= located with `A` or, for +/// zero-sized types, is a dangling, well aligned pointer. +/// +/// - `self.len` always represents the exact number of elements stored in = the vector. +/// +/// - `self.cap` represents the absolute number of elements that can be st= ored within the vector +/// without re-allocation. However, it is legal for the backing buffer t= o be larger than +/// `size_of` times the capacity. +/// +/// - The `Allocator` type `A` of the vector is the exact same `Allocator`= type the backing buffer +/// was allocated with (and must be freed with). +pub struct Vec { + ptr: NonNull, + /// Represents the actual buffer size as `cap` times `size_of::` by= tes. + /// + /// Note: This isn't quite the same as `Self::capacity`, which in cont= rast returns the number of + /// elements we can still store without reallocating. + /// + /// # Invariants + /// + /// `cap` must be in the `0..=3Disize::MAX` range. + cap: usize, + len: usize, + _p: PhantomData, +} + +/// Type alias for [`Vec`] with a [`Kmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v =3D KVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVec =3D Vec; + +/// Type alias for [`Vec`] with a [`Vmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v =3D VVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type VVec =3D Vec; + +/// Type alias for [`Vec`] with a [`KVmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v =3D KVVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVVec =3D Vec; + +// SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its element= s. +unsafe impl Send for Vec +where + T: Send, + A: Allocator, +{ +} + +// SAFETY: `Vec` is `Sync` if `T` is `Sync` because `Vec` owns its element= s. +unsafe impl Sync for Vec +where + T: Sync, + A: Allocator, +{ +} + +impl Vec +where + A: Allocator, +{ + #[inline] + fn is_zst() -> bool { + core::mem::size_of::() =3D=3D 0 + } + + /// Returns the number of elements that can be stored within the vecto= r without allocating + /// additional memory. + pub fn capacity(&self) -> usize { + if Self::is_zst() { + usize::MAX + } else { + self.cap + } + } + + /// Returns the number of elements stored within the vector. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forcefully sets `self.len` to `new_len`. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity`]. + /// - If `new_len` is greater than `self.len`, all elements within the= interval + /// [`self.len`,`new_len`) must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + debug_assert!(new_len <=3D self.capacity()); + self.len =3D new_len; + } + + /// Returns a slice of the entire vector. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Returns a mutable slice of the entire vector. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + /// Returns a mutable raw pointer to the vector's backing buffer, or, = if `T` is a ZST, a + /// dangling raw pointer. + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + self.ptr.as_ptr() + } + + /// Returns a raw pointer to the vector's backing buffer, or, if `T` i= s a ZST, a dangling raw + /// pointer. + #[inline] + pub fn as_ptr(&self) -> *const T { + self.ptr.as_ptr() + } + + /// Returns `true` if the vector contains no elements, `false` otherwi= se. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D KVec::new(); + /// assert!(v.is_empty()); + /// + /// v.push(1, GFP_KERNEL); + /// assert!(!v.is_empty()); + /// ``` + #[inline] + pub fn is_empty(&self) -> bool { + self.len() =3D=3D 0 + } + + /// Creates a new, empty Vec. + /// + /// This method does not allocate by itself. + #[inline] + pub const fn new() -> Self { + Self { + ptr: NonNull::dangling(), + cap: 0, + len: 0, + _p: PhantomData::, + } + } + + /// Returns a slice of `MaybeUninit` for the remaining spare capaci= ty of the vector. + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // SAFETY: + // - `self.len` is smaller than `self.capacity` and hence, the res= ulting pointer is + // guaranteed to be part of the same allocated object. + // - `self.len` can not overflow `isize`. + let ptr =3D unsafe { self.as_mut_ptr().add(self.len) } as *mut May= beUninit; + + // SAFETY: The memory between `self.len` and `self.capacity` is gu= aranteed to be allocated + // and valid, but uninitialized. + unsafe { slice::from_raw_parts_mut(ptr, self.capacity() - self.len= ) } + } + + /// Appends an element to the back of the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// assert_eq!(&v, &[1]); + /// + /// v.push(2, GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 2]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { + Vec::reserve(self, 1, flags)?; + + // SAFETY: + // - `self.len` is smaller than `self.capacity` and hence, the res= ulting pointer is + // guaranteed to be part of the same allocated object. + // - `self.len` can not overflow `isize`. + let ptr =3D unsafe { self.as_mut_ptr().add(self.len) }; + + // SAFETY: + // - `ptr` is properly aligned and valid for writes. + unsafe { core::ptr::write(ptr, v) }; + + // SAFETY: We just initialised the first spare entry, so it is saf= e to increase the length + // by 1. We also know that the new length is <=3D capacity because= of the previous call to + // `reserve` above. + unsafe { self.set_len(self.len() + 1) }; + Ok(()) + } + + /// Creates a new [`Vec`] instance with at least the given capacity. + /// + /// # Examples + /// + /// ``` + /// let v =3D KVec::::with_capacity(20, GFP_KERNEL)?; + /// + /// assert!(v.capacity() >=3D 20); + /// # Ok::<(), Error>(()) + /// ``` + pub fn with_capacity(capacity: usize, flags: Flags) -> Result { + let mut v =3D Vec::new(); + + Self::reserve(&mut v, capacity, flags)?; + + Ok(v) + } + + /// Pushes clones of the elements of slice into the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// + /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 20, 30, 40]); + /// + /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Resu= lt<(), AllocError> + where + T: Clone, + { + self.reserve(other.len(), flags)?; + for (slot, item) in core::iter::zip(self.spare_capacity_mut(), oth= er) { + slot.write(item.clone()); + } + + // SAFETY: + // - `other.len()` spare entries have just been initialized, so it= is safe to increase + // the length by the same number. + // - `self.len() + other.len() <=3D self.capacity()` is guaranteed= by the preceding `reserve` + // call. + unsafe { self.set_len(self.len() + other.len()) }; + Ok(()) + } + + /// Creates a Vec from a pointer, a length and a capacity using = the allocator `A`. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D kernel::kvec![1, 2, 3]?; + /// v.reserve(1, GFP_KERNEL)?; + /// + /// let (mut ptr, mut len, cap) =3D v.into_raw_parts(); + /// + /// // SAFETY: We've just reserved memory for another element. + /// unsafe { ptr.add(len).write(4) }; + /// len +=3D 1; + /// + /// // SAFETY: We only wrote an additional element at the end of the `= KVec`'s buffer and + /// // correspondingly increased the length of the `KVec` by one. Othe= rwise, we construct it + /// // from the exact same raw parts. + /// let v =3D unsafe { KVec::from_raw_parts(ptr, len, cap) }; + /// + /// assert_eq!(v, [1, 2, 3, 4]); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// # Safety + /// + /// If `T` is a ZST: + /// + /// - `ptr` must be a dangling, well aligned pointer. + /// + /// Otherwise: + /// + /// - `ptr` must have been allocated with the allocator `A`. + /// - `ptr` must satisfy or exceed the alignment requirements of `T`. + /// - `ptr` must point to memory with a size of at least `size_of::= () * capacity`. + /// bytes. + /// - The allocated size in bytes must not be larger than `isize::MAX`. + /// - `length` must be less than or equal to `capacity`. + /// - The first `length` elements must be initialized values of type `= T`. + /// + /// It is also valid to create an empty `Vec` passing a dangling point= er for `ptr` and zero for + /// `cap` and `len`. + pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usi= ze) -> Self { + let cap =3D if Self::is_zst() { 0 } else { capacity }; + + Self { + // SAFETY: By the safety requirements, `ptr` is either danglin= g or pointing to a valid + // memory allocation, allocated with `A`. + ptr: unsafe { NonNull::new_unchecked(ptr) }, + cap, + len: length, + _p: PhantomData::, + } + } + + /// Consumes the `Vec` and returns its raw components `pointer`,= `length` and `capacity`. + /// + /// This will not run the destructor of the contained elements and for= non-ZSTs the allocation + /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recov= er the [`Vec`], drop the + /// elements and free the allocation, if any. + pub fn into_raw_parts(self) -> (*mut T, usize, usize) { + let mut me =3D ManuallyDrop::new(self); + let len =3D me.len(); + let capacity =3D me.capacity(); + let ptr =3D me.as_mut_ptr(); + (ptr, len, capacity) + } + + /// Ensures that the capacity exceeds the length by at least `addition= al` + /// elements. + /// + /// # Examples + /// + /// ``` + /// let mut v =3D KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let cap =3D v.capacity(); + /// assert!(cap >=3D 10); + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let new_cap =3D v.capacity(); + /// assert_eq!(new_cap, cap); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(= ), AllocError> { + let len =3D self.len(); + let cap =3D self.capacity(); + + if cap - len >=3D additional { + return Ok(()); + } + + if Self::is_zst() { + // The capacity is already `usize::MAX` for ZSTs, we can't go = higher. + return Err(AllocError); + } + + // We know `cap` is <=3D `isize::MAX` because of the type invarian= ts of `Self`. So the + // multiplication by two won't overflow. + let new_cap =3D core::cmp::max(cap * 2, len.checked_add(additional= ).ok_or(AllocError)?); + let layout =3D core::alloc::Layout::array::(new_cap).map_err(|_= | AllocError)?; + + // We need to make sure that `ptr` is either NULL or comes from a = previous call to + // `realloc_flags`. A `Vec`'s `ptr` value is not guaranteed = to be NULL and might be + // dangling after being created with `Vec::new`. Instead, we can r= ely on `Vec`'s + // capacity to be zero if no memory has been allocated yet. + let ptr =3D if cap =3D=3D 0 { + None + } else { + Some(self.ptr.cast()) + }; + + // SAFETY: `ptr` is valid because it's either `None` or comes from= a previous call to + // `A::realloc`. We also verified that the type is not a ZST. + let ptr =3D unsafe { A::realloc(ptr, layout, flags)? }; + + self.ptr =3D ptr.cast(); + + // INVARIANT: `Layout::array` fails if the resulting byte size is = greater than `isize::MAX`. + self.cap =3D new_cap; + + Ok(()) + } +} + +impl Vec { + /// Extend the vector by `n` clones of `value`. + pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Res= ult<(), AllocError> { + if n =3D=3D 0 { + return Ok(()); + } + + self.reserve(n, flags)?; + + let spare =3D self.spare_capacity_mut(); + + for item in spare.iter_mut().take(n - 1) { + item.write(value.clone()); + } + + // We can write the last element directly without cloning needless= ly. + spare[n - 1].write(value); + + // SAFETY: + // - `self.len() + n < self.capacity()` due to the call to reserve= above, + // - the loop and the line above initialized the next `n` elements. + unsafe { self.set_len(self.len() + n) }; + + Ok(()) + } + + /// Create a new `Vec and extend it by `n` clones of `value`. + pub fn from_elem(value: T, n: usize, flags: Flags) -> Result { + let mut v =3D Self::with_capacity(n, flags)?; + + v.extend_with(n, value, flags)?; + + Ok(v) + } +} + +impl Drop for Vec +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: We need to drop the vector's elements in place, before = we free the backing + // memory. + unsafe { + core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( + self.as_mut_ptr(), + self.len, + )) + }; + + // If `cap =3D=3D 0` we never allocated any memory in the first pl= ace. + if self.cap !=3D 0 { + // SAFETY: `self.ptr` was previously allocated with `A`. + unsafe { A::free(self.ptr.cast()) }; + } + } +} + +impl From> for Vec +where + A: Allocator, +{ + fn from(b: Box<[T; N], A>) -> Vec { + let len =3D b.len(); + let ptr =3D Box::into_raw(b); + + // SAFETY: + // - `b` has been allocated with `A`, + // - `ptr` fulfills the alignment requirements for `T`, + // - `ptr` points to memory with at least a size of `size_of::(= ) * len`, + // - all elements within `b` are initialized values of `T`, + // - `len` does not exceed `isize::MAX`. + unsafe { Vec::from_raw_parts(ptr as _, len, len) } + } +} + +impl Default for KVec { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for Vec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Deref for Vec +where + A: Allocator, +{ + type Target =3D [T]; + + #[inline] + fn deref(&self) -> &[T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to cont= ain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } + } +} + +impl DerefMut for Vec +where + A: Allocator, +{ + #[inline] + fn deref_mut(&mut self) -> &mut [T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to cont= ain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } + } +} + +impl Eq for Vec where A: Allocator {} + +impl, A> Index for Vec +where + A: Allocator, +{ + type Output =3D I::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + Index::index(&**self, index) + } +} + +impl, A> IndexMut for Vec +where + A: Allocator, +{ + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + IndexMut::index_mut(&mut **self, index) + } +} + +macro_rules! impl_slice_eq { + ([$($vars:tt)*] $lhs:ty, $rhs:ty) =3D> { + impl PartialEq<$rhs> for $lhs + where + T: PartialEq, + { + #[inline] + fn eq(&self, other: &$rhs) -> bool { self[..] =3D=3D other[..]= } + } + } +} + +impl_slice_eq! { [A1: Allocator, A2: Allocator] Vec, Vec } +impl_slice_eq! { [A: Allocator] Vec, &[U] } +impl_slice_eq! { [A: Allocator] Vec, &mut [U] } +impl_slice_eq! { [A: Allocator] &[T], Vec } +impl_slice_eq! { [A: Allocator] &mut [T], Vec } +impl_slice_eq! { [A: Allocator] Vec, [U] } +impl_slice_eq! { [A: Allocator] [T], Vec } +impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } +impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index d5f2fe42d093..80223cdaa485 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; =20 -pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec,= KVec, VBox, VVec}; =20 #[doc(no_inline)] pub use alloc::vec::Vec; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CBA641BCA0A; Wed, 11 Sep 2024 22:56:15 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095375; cv=none; b=FA9A9v5bpZWxo7ZRlgmHDOnYQfpLQ/hMBTuHVexDD30Eii/74RDvzZHYfcI34AXy9S/3I9YrALqZPErkupt4Y2b/FNlwiLKOiPHJfX/SI1HVYyhQsOeW5I6c8MwV3OoU69C6lbGzxmEDYfq6AdaNatvMVeeA8lyInc9jFJnx0CE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095375; c=relaxed/simple; bh=aLDdES0o6RDAOJEjGLFT1eKKbvsH9kq1wWFmHyySuYc=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=JLySTBhyVBLISxGEyHnnn3CsEXQsH42wmAss19HiRuhWrqjJl+yLcPxd7YIQAvJVHdZLAmqg4LROCmmJRgtu+y2KjxqERFJ3shva98HhSry/AeSDBrTxySRVZ90kydTLAJfqvm0+FMgawKtmIeyMLqyTtFngm0lOVKuX+YQXXPU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=IRpiFgQp; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="IRpiFgQp" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7CB19C4CECC; Wed, 11 Sep 2024 22:56:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095375; bh=aLDdES0o6RDAOJEjGLFT1eKKbvsH9kq1wWFmHyySuYc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=IRpiFgQp9WwC2xCKc1aDcSeNN12nD+GShRbakKlDuGMWhi3GjwI+uXBKLL1jQIdbm QE2NbWO/lOI8KRM7Svf2gz/Z9mvaNRDH8/eEyVNvsinjSYS4k3cA2ac8ABB8Tnimfw w3XYcJeORuRs+NrHWD3UBYZhdYf7VAVg53hUr9bv1R82NYriI8OPKmq5gQfTpzEceL iVdQ85KiWl+VZHVWaMll71MQ32Zlv+nn1Khu6+jrIAURDNl/RDzgtlk3vzubC/Njk7 m4fr+jhaMvgefyfbBM/wKub+78OgiSGAEwLdN4jf6pM9TQPMbINCd0VluGuv6xQYZK MKwer9LnsErWA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 14/26] rust: alloc: implement `IntoIterator` for `Vec` Date: Thu, 12 Sep 2024 00:52:50 +0200 Message-ID: <20240911225449.152928-15-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 correspondingsly 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 181 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 4fb983b63d46..e8fbae2adadb 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -19,6 +19,7 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; =20 +pub use self::kvec::IntoIter; pub use self::kvec::KVVec; pub use self::kvec::KVec; pub use self::kvec::VVec; diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 631a44e19f35..e91761c5c52d 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -14,6 +14,7 @@ ops::DerefMut, ops::Index, ops::IndexMut, + ptr, ptr::NonNull, slice, slice::SliceIndex, @@ -636,3 +637,183 @@ fn eq(&self, other: &$rhs) -> bool { self[..] =3D=3D = other[..] } impl_slice_eq! { [A: Allocator] [T], Vec } impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } + +impl<'a, T, A> IntoIterator for &'a Vec +where + A: Allocator, +{ + type Item =3D &'a T; + type IntoIter =3D slice::Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec +where + A: Allocator, +{ + type Item =3D &'a mut T; + type IntoIter =3D slice::IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +/// An [`Iterator`] implementation for [`Vec`] that moves elements out of = a vector. +/// +/// This structure is created by the [`Vec::into_iter`] method on [`Vec`] = (provided by the +/// [`IntoIterator`] trait). +/// +/// # Examples +/// +/// ``` +/// let v =3D kernel::kvec![0, 1, 2]?; +/// let iter =3D v.into_iter(); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub struct IntoIter { + ptr: *mut T, + buf: NonNull, + len: usize, + cap: usize, + _p: PhantomData, +} + +impl IntoIter +where + A: Allocator, +{ + fn as_raw_mut_slice(&mut self) -> *mut [T] { + ptr::slice_from_raw_parts_mut(self.ptr, self.len) + } +} + +impl Iterator for IntoIter +where + A: Allocator, +{ + type Item =3D T; + + /// # Examples + /// + /// ``` + /// let v =3D kernel::kvec![1, 2, 3]?; + /// let mut it =3D v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// assert_eq!(it.next(), Some(2)); + /// assert_eq!(it.next(), Some(3)); + /// assert_eq!(it.next(), None); + /// + /// # Ok::<(), Error>(()) + /// ``` + fn next(&mut self) -> Option { + if self.len =3D=3D 0 { + return None; + } + + let current =3D self.ptr; + + // SAFETY: We can't overflow; decreasing `self.len` by one every t= ime we advance `self.ptr` + // by one guarantees that. + unsafe { self.ptr =3D self.ptr.add(1) }; + + self.len -=3D 1; + + // SAFETY: `current` is guaranteed to point at a valid element wit= hin the buffer. + Some(unsafe { current.read() }) + } + + /// # Examples + /// + /// ``` + /// let v: KVec =3D kernel::kvec![1, 2, 3]?; + /// let mut iter =3D v.into_iter(); + /// let size =3D iter.size_hint().0; + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 1); + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 2); + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 3); + /// + /// # Ok::<(), Error>(()) + /// ``` + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl Drop for IntoIter +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: The pointer in `self.0` is guaranteed to be valid by th= e type invariant. + unsafe { ptr::drop_in_place(self.as_raw_mut_slice()) }; + + // If `cap =3D=3D 0` we never allocated any memory in the first pl= ace. + if self.cap !=3D 0 { + // SAFETY: `self.buf` was previously allocated with `A`. + unsafe { A::free(self.buf.cast()) }; + } + } +} + +impl IntoIterator for Vec +where + A: Allocator, +{ + type Item =3D T; + type IntoIter =3D IntoIter; + + /// Consumes the `Vec` and creates an `Iterator`, which moves ea= ch value out of the + /// vector (from start to end). + /// + /// # Examples + /// + /// ``` + /// let v =3D kernel::kvec![1, 2]?; + /// let mut v_iter =3D v.into_iter(); + /// + /// let first_element: Option =3D v_iter.next(); + /// + /// assert_eq!(first_element, Some(1)); + /// assert_eq!(v_iter.next(), Some(2)); + /// assert_eq!(v_iter.next(), None); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// ``` + /// let v =3D kernel::kvec![]; + /// let mut v_iter =3D v.into_iter(); + /// + /// let first_element: Option =3D v_iter.next(); + /// + /// assert_eq!(first_element, None); + /// + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (ptr, len, cap) =3D self.into_raw_parts(); + + IntoIter { + ptr, + // SAFETY: `ptr` is either a dangling pointer or a pointer to = a valid memory + // allocation, allocated with `A`. + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +} --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C9D561BCA0F; Wed, 11 Sep 2024 22:56:20 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095380; cv=none; b=I8SXTQw4h7mUT2GzbRX9IenPg3st+FnJ2HBOUpVjrn6qP3USVdX/o8FtzX96nSltl0oLjEL/j1BWfffw2JP2F7z0/lvXIcxDU9w+5iPjIEmbcEFLbw5/twfVfMN3Hjdb5Tw3AArtWFbSlSgAB4ibTGRSVVGqiXkXQyxW6IHHsq0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095380; c=relaxed/simple; bh=d0GTO9ovdr9mLJZ1kH3EJFt21UVQxchmojeAlHWWgj8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=IvIBGzhixKX4lNCeqWcarwrN0pow+tIYiQkVmDNnY0+iy4T9s7/8MC9dXiceYC6ENu1pz3FwmxyT3tZHiQQFX9UDJ0RmzfjvRNqpWQb9cI0Cgh1/qIw93+dmS36CWw4axxVq43Cy9iA6Pe7fBDJF2AZSTDD3RM7XKCjdGglkxMA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=HNs5tm92; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="HNs5tm92" Received: by smtp.kernel.org (Postfix) with ESMTPSA id CD080C4CEC0; Wed, 11 Sep 2024 22:56:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095380; bh=d0GTO9ovdr9mLJZ1kH3EJFt21UVQxchmojeAlHWWgj8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HNs5tm92QKne4wWPulUe3fcINVeehDTsWYP7OKbBuDAFJioQkoDs4xtPbMxWiphQb PZ2Xb2cE86reASaruvlmCSipU1rMPqObS0eRNUwsW3pQIH8bTigMxzP0QNorxbtwi8 hKr2oRBWsQAcxalCvk4SXGAdIuxQQwKJ55ChGFBQ9wdJEpSw8/TByF2JJfW8LlU+vH CAmR/f1U71SlL4T+Om9uVQWQFDPHSwlZ/trHlxvTVa6bmYEB2DMK7/UVMEpjm0Vexc Svc8EMpnLgkW2ZbarbI+b/qasorJz8jaeNpZWcGpm/AUYy3l9X/e/y/DOhuqfGCJKZ t8uAn5K+Ub5pQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 15/26] rust: alloc: implement `collect` for `IntoIter` Date: Thu, 12 Sep 2024 00:52:51 +0200 Message-ID: <20240911225449.152928-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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 optimze 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`, 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/alloc/kvec.rs | 86 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index e91761c5c52d..686e969463f8 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -690,6 +690,92 @@ impl IntoIter fn as_raw_mut_slice(&mut self) -> *mut [T] { ptr::slice_from_raw_parts_mut(self.ptr, self.len) } + + fn into_raw_parts(self) -> (*mut T, NonNull, usize, usize) { + let me =3D ManuallyDrop::new(self); + let ptr =3D me.ptr; + let buf =3D me.buf; + let len =3D me.len; + let cap =3D me.cap; + (ptr, buf, len, cap) + } + + /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`. + /// + /// # Examples + /// + /// ``` + /// let v =3D kernel::kvec![1, 2, 3]?; + /// let mut it =3D v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// + /// let v =3D it.collect(GFP_KERNEL); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// # Implementation Details + /// + /// Currently, we can't implement `FromIterator`. There are a couple o= f issues with this trait + /// in the kernel, namely: + /// + /// - Rust's specialization feature is unstable. This prevents us to o= ptimze 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 ha= ndle additional allocation + /// flags. + /// + /// Instead, provide `IntoIter::collect`, such that we can at least co= nvert a `IntoIter` into a + /// `Vec` again. + /// + /// Note that `IntoIter::collect` doesn't require `Flags`, since it re= -uses the existing backing + /// buffer. However, this backing buffer may be shrunk to the actual c= ount of elements. + pub fn collect(self, flags: Flags) -> Vec { + let (mut ptr, buf, len, mut cap) =3D self.into_raw_parts(); + let has_advanced =3D ptr !=3D buf.as_ptr(); + + if has_advanced { + // Copy the contents we have advanced to at the beginning of t= he buffer. + // + // SAFETY: + // - `ptr` is valid for reads of `len * size_of::()` bytes, + // - `buf.as_ptr()` is valid for writes of `len * size_of::= ()` bytes, + // - `ptr` and `buf.as_ptr()` are not be subject to aliasing r= estrictions relative to + // each other, + // - both `ptr` and `buf.ptr()` are properly aligned. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr =3D buf.as_ptr(); + } + + // This can never fail, `len` is guaranteed to be smaller than `ca= p`. + let layout =3D core::alloc::Layout::array::(len).unwrap(); + + // SAFETY: `buf` points to the start of the backing buffer and `le= n` is guaranteed to be + // smaller than `cap`. Depending on `alloc` this operation may shr= ink the buffer or leaves + // it as it is. + ptr =3D match unsafe { A::realloc(Some(buf.cast()), layout, flags)= } { + // If we fail to shrink, which likely can't even happen, conti= nue with the existing + // buffer. + Err(_) =3D> ptr, + Ok(ptr) =3D> { + cap =3D len; + ptr.as_ptr().cast() + } + }; + + // SAFETY: If the iterator has been advanced, the advanced element= s have been copied to + // the beginning of the buffer and `len` has been adjusted accordi= ngly. + // + // - `ptr` is guaranteed to point to the start of the backing buff= er. + // - `cap` is either the original capacity or, after shrinking the= buffer, equal to `len`. + // - `alloc` is guaranteed to be unchanged since `into_iter` has b= een called on the original + // `Vec`. + unsafe { Vec::from_raw_parts(ptr, len, cap) } + } } =20 impl Iterator for IntoIter --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 702B41BB6AB; Wed, 11 Sep 2024 22:56:26 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095386; cv=none; b=uY6tRf3KeldX9P5k2a51jETEIxFHmKPHLQ1xq1vzfU5WslkzMZvOdWfB2yDhzBT4o3iTNZ6MXAfzZDinVpEqXt9Isy9qKjsSQpoaw4U186D3Ednd5v7P3nT9QJcBRif0/aUQ3kt7/DFiT3XNpSAx2k80jhZHK/qOBroMFGVLseQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095386; c=relaxed/simple; bh=kh3bW2oqiftIhCysHX0r3aVqtVie61GOoy8er6t2mxM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=imzQrLrxiP2eylshUH0UdKCyS1GHoutJQHt4c1yRV9Mxh7bW/K6ek9eX5NRUkHnnGGb7EVKK7P3TbxQbszAv3cYFUuynRcQKe6bCZUsTZ5GN2Ic21IkM9wp4FLR/t6uzP2inOoQ83VnkwG3z/U97MKjwtVUTQyujN1vMMG6kdGs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=MfPaagSK; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="MfPaagSK" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 286CCC4CECE; Wed, 11 Sep 2024 22:56:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095386; bh=kh3bW2oqiftIhCysHX0r3aVqtVie61GOoy8er6t2mxM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MfPaagSK3gG0avIvoa7NTT1obNqCvyu1MQUNPJ1yIpApc6/6hGDGyQ2whd+2QIDQz ryLdIIriYcECe39Cp22B80psQZJ3Zj4cWTLC7VZnkdjXMc0gvuExAFmuvZXB64rFof tHPByXCEX0kCWJ3KGNDXf/cShE5cJ6Om4a1ehEPqAmu4araOocZEKYj0X9wLWyvK8q d8VffI02SEIIZ205Bxor8Aq4QF4yQNwSjXMDTjlMvDT0U+0Umtc1loYSpLUMqh3PdP wNODrTDo0/Ww3yTU5sxNiTn2EPWwioQ8PuPW/QqX/NXSpVeGynQOESApvVKWY1GM0a pEWwq8VYIQduA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 16/26] rust: treewide: switch to the kernel `Vec` type Date: Thu, 12 Sep 2024 00:52:52 +0200 Message-ID: <20240911225449.152928-17-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that we got the kernel `Vec` in place, convert all existing `Vec` users to make use of it. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- rust/kernel/uaccess.rs | 17 +++++++---------- rust/macros/lib.rs | 6 +++--- samples/rust/rust_minimal.rs | 4 ++-- 6 files changed, 19 insertions(+), 24 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..209ad1bb1a49 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,8 +2,7 @@ =20 //! String representations. =20 -use crate::alloc::{flags::*, vec_ext::VecExt, AllocError}; -use alloc::vec::Vec; +use crate::alloc::{flags::*, AllocError, KVec}; use core::fmt::{self, Write}; use core::ops::{self, Deref, DerefMut, Index}; =20 @@ -790,7 +789,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result { /// assert_eq!(s.is_ok(), false); /// ``` pub struct CString { - buf: Vec, + buf: KVec, } =20 impl CString { @@ -803,7 +802,7 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result= { let size =3D f.bytes_written(); =20 // Allocate a vector with the required number of bytes, and write = to it. - let mut buf =3D as VecExt<_>>::with_capacity(size, GFP_KER= NEL)?; + let mut buf =3D KVec::with_capacity(size, GFP_KERNEL)?; // SAFETY: The buffer stored in `buf` is at least of size `size` a= nd is valid for writes. let mut f =3D unsafe { Formatter::from_buffer(buf.as_mut_ptr(), si= ze) }; f.write_fmt(args)?; @@ -850,10 +849,9 @@ impl<'a> TryFrom<&'a CStr> for CString { type Error =3D AllocError; =20 fn try_from(cstr: &'a CStr) -> Result { - let mut buf =3D Vec::new(); + let mut buf =3D KVec::new(); =20 - as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_w= ith_nul(), GFP_KERNEL) - .map_err(|_| AllocError)?; + buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?; =20 // INVARIANT: The `CStr` and `CString` types have the same invaria= nts for // the string data, and we copied it over without changes. diff --git a/rust/kernel/sync/locked_by.rs b/rust/kernel/sync/locked_by.rs index babc731bd5f6..b94517231fcc 100644 --- a/rust/kernel/sync/locked_by.rs +++ b/rust/kernel/sync/locked_by.rs @@ -43,7 +43,7 @@ /// struct InnerDirectory { /// /// The sum of the bytes used by all files. /// bytes_used: u64, -/// _files: Vec, +/// _files: KVec, /// } /// /// struct Directory { diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 53d3ddc0b98c..bf1a96d5e1f8 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -135,7 +135,7 @@ unsafe fn from_foreign(_: *const core::ffi::c_void) -> = Self {} /// # use kernel::types::ScopeGuard; /// fn example3(arg: bool) -> Result { /// let mut vec =3D -/// ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {}= elements\n", v.len())); +/// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {= } elements\n", v.len())); /// /// vec.push(10u8, GFP_KERNEL)?; /// if arg { diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index e9347cff99ab..bc011061de45 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -11,7 +11,6 @@ prelude::*, types::{AsBytes, FromBytes}, }; -use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; use core::mem::{size_of, MaybeUninit}; =20 @@ -46,7 +45,6 @@ /// every byte in the region. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::Result; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -54,7 +52,7 @@ /// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> { /// let (read, mut write) =3D UserSlice::new(uptr, len).reader_writer(= ); /// -/// let mut buf =3D Vec::new(); +/// let mut buf =3D KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// for b in &mut buf { @@ -69,7 +67,6 @@ /// Example illustrating a TOCTOU (time-of-check to time-of-use) bug. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::{code::EINVAL, Result}; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -78,21 +75,21 @@ /// fn is_valid(uptr: UserPtr, len: usize) -> Result { /// let read =3D UserSlice::new(uptr, len).reader(); /// -/// let mut buf =3D Vec::new(); +/// let mut buf =3D KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// todo!() /// } /// /// /// Returns the bytes behind this user pointer if they are valid. -/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { +/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { /// if !is_valid(uptr, len)? { /// return Err(EINVAL); /// } /// /// let read =3D UserSlice::new(uptr, len).reader(); /// -/// let mut buf =3D Vec::new(); +/// let mut buf =3D KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// // THIS IS A BUG! The bytes could have changed since we checked th= em. @@ -130,7 +127,7 @@ pub fn new(ptr: UserPtr, length: usize) -> Self { /// Reads the entirety of the user slice, appending it to the end of t= he provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(self, buf: &mut KVec, flags: Flags) -> Result { self.reader().read_all(buf, flags) } =20 @@ -291,9 +288,9 @@ pub fn read(&mut self) -> Result { /// Reads the entirety of the user slice, appending it to the end of t= he provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(mut self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(mut self, buf: &mut KVec, flags: Flags) -> Result { let len =3D self.length; - VecExt::::reserve(buf, len, flags)?; + buf.reserve(len, flags)?; =20 // The call to `try_reserve` was successful, so the spare capacity= is at least `len` bytes // long. diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index ab93111a048c..8d4ac914b48b 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -242,7 +242,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` @@ -251,7 +251,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } @@ -281,7 +281,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) = -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 2a9eaab62d1c..4aaf117bf8e3 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -13,7 +13,7 @@ } =20 struct RustMinimal { - numbers: Vec, + numbers: KVec, } =20 impl kernel::Module for RustMinimal { @@ -21,7 +21,7 @@ fn init(_module: &'static ThisModule) -> Result { pr_info!("Rust minimal sample (init)\n"); pr_info!("Am I built-in? {}\n", !cfg!(MODULE)); =20 - let mut numbers =3D Vec::new(); + let mut numbers =3D KVec::new(); numbers.push(72, GFP_KERNEL)?; numbers.push(108, GFP_KERNEL)?; numbers.push(200, GFP_KERNEL)?; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CDE6E1BB6BE; Wed, 11 Sep 2024 22:56:31 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095391; cv=none; b=cyGHvJmEhia7UYvzDxOv4Gd9bVFZt2zGaIf7GeuVTD6jmLv/GfaGo2c4BGhTvUmX3/nel9XhCKZcr1mWgpQGUfujjQAqPkuTnQjnOgznkJ+Q3JHsUk2lOoohT2vb7vLOD+iTIJbymDWn84pacwS3NhJS8ZZ3ddBO6dMvnOV1fA0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095391; c=relaxed/simple; bh=yPcuj3XtLEYkObWgOAn3jFjUUb0DA9DkDjwxMGFkw5M=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=NBNu6LGueKPYsxAxmTlPX0vL8tJao3W0a6t5+jMNn4sLyymjJZqVO1PTiOe5MhagM7IGvP7AbQp2Vtd0B0jOtWYpClcwX8uUqB29dso+LLIOGerQqE2Ez8NZjcBasB6Of7IyB4OWlINA/gLap0KNInyWhhXiLX4DNwRksQdk+6I= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=a1fzmL5S; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="a1fzmL5S" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7BECCC4CEC0; Wed, 11 Sep 2024 22:56:26 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095391; bh=yPcuj3XtLEYkObWgOAn3jFjUUb0DA9DkDjwxMGFkw5M=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=a1fzmL5S6iQ1G+qZ/fN386/6hhCpMJfzoO9SOlVZn5KWJLa2HfFxIt/w+Egnv8h3h HT9v6Q4SB7R+/+VZxqKo+/mJUS8O5xSciW0sg0UDKyqsRAG95oE8dVfrI651/vMT3R 0CTJ8r8yu3xWu87nlJqaryIV/oHJw8vbFyAtw8jtF96eULb3Ayho627G0dEbAmbv9t 4FhTcE4hv82Bg/AFGixyp5i9hY2KTtp817gsJ2zWDNEwj2GMR5yboGekSAbBRoTIHd m6sscVy1W6eWekGQhiBraXqn9lrX4GELtYvqB4lcb/36In7HZgYYidyW7dQRKLE/lC v1nbUA14OqFgw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 17/26] rust: alloc: remove `VecExt` extension Date: Thu, 12 Sep 2024 00:52:53 +0200 Message-ID: <20240911225449.152928-18-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that all existing `Vec` users were moved to the kernel `Vec` type, remove the `VecExt` extension. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/vec_ext.rs | 185 ----------------------------------- rust/kernel/prelude.rs | 5 +- 3 files changed, 1 insertion(+), 190 deletions(-) delete mode 100644 rust/kernel/alloc/vec_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index e8fbae2adadb..aabdf80e4f7b 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -6,7 +6,6 @@ pub mod allocator; pub mod kbox; pub mod kvec; -pub mod vec_ext; =20 #[cfg(any(test, testlib))] pub mod allocator_test; diff --git a/rust/kernel/alloc/vec_ext.rs b/rust/kernel/alloc/vec_ext.rs deleted file mode 100644 index 1297a4be32e8..000000000000 --- a/rust/kernel/alloc/vec_ext.rs +++ /dev/null @@ -1,185 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Vec`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::vec::Vec; - -/// Extensions to [`Vec`]. -pub trait VecExt: Sized { - /// Creates a new [`Vec`] instance with at least the given capacity. - /// - /// # Examples - /// - /// ``` - /// let v =3D Vec::::with_capacity(20, GFP_KERNEL)?; - /// - /// assert!(v.capacity() >=3D 20); - /// # Ok::<(), Error>(()) - /// ``` - fn with_capacity(capacity: usize, flags: Flags) -> Result; - - /// Appends an element to the back of the [`Vec`] instance. - /// - /// # Examples - /// - /// ``` - /// let mut v =3D Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// assert_eq!(&v, &[1]); - /// - /// v.push(2, GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 2]); - /// # Ok::<(), Error>(()) - /// ``` - fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError>; - - /// Pushes clones of the elements of slice into the [`Vec`] instance. - /// - /// # Examples - /// - /// ``` - /// let mut v =3D Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// - /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 20, 30, 40]); - /// - /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]); - /// # Ok::<(), Error>(()) - /// ``` - fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(= ), AllocError> - where - T: Clone; - - /// Ensures that the capacity exceeds the length by at least `addition= al` elements. - /// - /// # Examples - /// - /// ``` - /// let mut v =3D Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let cap =3D v.capacity(); - /// assert!(cap >=3D 10); - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let new_cap =3D v.capacity(); - /// assert_eq!(new_cap, cap); - /// - /// # Ok::<(), Error>(()) - /// ``` - fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), A= llocError>; -} - -impl VecExt for Vec { - fn with_capacity(capacity: usize, flags: Flags) -> Result { - let mut v =3D Vec::new(); - >::reserve(&mut v, capacity, flags)?; - Ok(v) - } - - fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { - >::reserve(self, 1, flags)?; - let s =3D self.spare_capacity_mut(); - s[0].write(v); - - // SAFETY: We just initialised the first spare entry, so it is saf= e to increase the length - // by 1. We also know that the new length is <=3D capacity because= of the previous call to - // `reserve` above. - unsafe { self.set_len(self.len() + 1) }; - Ok(()) - } - - fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(= ), AllocError> - where - T: Clone, - { - >::reserve(self, other.len(), flags)?; - for (slot, item) in core::iter::zip(self.spare_capacity_mut(), oth= er) { - slot.write(item.clone()); - } - - // SAFETY: We just initialised the `other.len()` spare entries, so= it is safe to increase - // the length by the same amount. We also know that the new length= is <=3D capacity because - // of the previous call to `reserve` above. - unsafe { self.set_len(self.len() + other.len()) }; - Ok(()) - } - - #[cfg(any(test, testlib))] - fn reserve(&mut self, additional: usize, _flags: Flags) -> Result<(), = AllocError> { - Vec::reserve(self, additional); - Ok(()) - } - - #[cfg(not(any(test, testlib)))] - fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), A= llocError> { - let len =3D self.len(); - let cap =3D self.capacity(); - - if cap - len >=3D additional { - return Ok(()); - } - - if core::mem::size_of::() =3D=3D 0 { - // The capacity is already `usize::MAX` for SZTs, we can't go = higher. - return Err(AllocError); - } - - // We know cap is <=3D `isize::MAX` because `Layout::array` fails = if the resulting byte size - // is greater than `isize::MAX`. So the multiplication by two won'= t overflow. - let new_cap =3D core::cmp::max(cap * 2, len.checked_add(additional= ).ok_or(AllocError)?); - let layout =3D core::alloc::Layout::array::(new_cap).map_err(|_= | AllocError)?; - - let (old_ptr, len, cap) =3D destructure(self); - - // We need to make sure that `ptr` is either NULL or comes from a = previous call to - // `krealloc_aligned`. A `Vec`'s `ptr` value is not guaranteed = to be NULL and might be - // dangling after being created with `Vec::new`. Instead, we can r= ely on `Vec`'s capacity - // to be zero if no memory has been allocated yet. - let ptr =3D if cap =3D=3D 0 { - core::ptr::null_mut() - } else { - old_ptr - }; - - // SAFETY: `ptr` is valid because it's either NULL or comes from a= previous call to - // `krealloc_aligned`. We also verified that the type is not a ZST. - let new_ptr =3D unsafe { super::allocator::krealloc_aligned(ptr.ca= st(), layout, flags) }; - if new_ptr.is_null() { - // SAFETY: We are just rebuilding the existing `Vec` with no c= hanges. - unsafe { rebuild(self, old_ptr, len, cap) }; - Err(AllocError) - } else { - // SAFETY: `ptr` has been reallocated with the layout for `new= _cap` elements. New cap - // is greater than `cap`, so it continues to be >=3D `len`. - unsafe { rebuild(self, new_ptr.cast::(), len, new_cap) }; - Ok(()) - } - } -} - -#[cfg(not(any(test, testlib)))] -fn destructure(v: &mut Vec) -> (*mut T, usize, usize) { - let mut tmp =3D Vec::new(); - core::mem::swap(&mut tmp, v); - let mut tmp =3D core::mem::ManuallyDrop::new(tmp); - let len =3D tmp.len(); - let cap =3D tmp.capacity(); - (tmp.as_mut_ptr(), len, cap) -} - -/// Rebuilds a `Vec` from a pointer, length, and capacity. -/// -/// # Safety -/// -/// The same as [`Vec::from_raw_parts`]. -#[cfg(not(any(test, testlib)))] -unsafe fn rebuild(v: &mut Vec, ptr: *mut T, len: usize, cap: usize) { - // SAFETY: The safety requirements from this function satisfy those of= `from_raw_parts`. - let mut tmp =3D unsafe { Vec::from_raw_parts(ptr, len, cap) }; - core::mem::swap(&mut tmp, v); -} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 80223cdaa485..07daccf6ca8e 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; =20 -pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec,= KVec, VBox, VVec}; - -#[doc(no_inline)] -pub use alloc::vec::Vec; +pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec= }; =20 #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C017C1BB6BE; Wed, 11 Sep 2024 22:56:36 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095396; cv=none; b=K1WWKVaUgLdu/dFXCTlf6EhNTKLCI5NquXUBEaz6e0U54ll8BsVeBPk7/eqw13v+bKEf7EMIgX1cjDhF6vhiUeP2mIoC5aJ2jX6TrIj5DFuXOttZE6/nPtYxCKom0R+ikTY3WMX8CZpbtnCKnvSn1xqraGF4Aies9FfjYbiHqXw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095396; c=relaxed/simple; bh=LpXBgctNj+tjXHis1qyn9ZWQx0pllgQA+Wvf8FmkV/A=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=JcDNtFUUE87+rzgMoO3vXt2yGiBArt5WVUs6EBONFS+zHExbabH/fkorHRWblI2vZKhdmy2OuO+ZWawyGW09YwmpNrYaBu1OISgJXbVKCOl2MIpIOtYE9yqnyccqNDPo5wUkjmS/OOz6FTp6jQjYEJhH/C26eugE/I7bvGkDyrA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=eXYbBBOq; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="eXYbBBOq" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C8FF2C4CEC5; Wed, 11 Sep 2024 22:56:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095396; bh=LpXBgctNj+tjXHis1qyn9ZWQx0pllgQA+Wvf8FmkV/A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eXYbBBOqTcZi/ck3nmSLuIo/cm3vH9ZCqqGY7cMR6byy9TvrFUZF9Ko0BLAU0XK5n IQcydTIGaCpDd1VdWShtJHNIhuSKbBiu8fZmbLNPk5V1FstGPSiHU4mlPiZoudj+Ar PQl5lIHYYx6DN9XopMPbbPArq5yaSmpw8e5IZ2fxZOyDV03qYVJXOkOnSQ34Apk2Yr hjSWUuaP4yKr8zeAshhWErn5eS5YnndvNZIaAYFOQQvXLhap2aMHNHVfcDtaJG21zB rXWNnxDqHjf/D33ZosFzBveNXrQC+Lla5IZg1w4nNUswcNQSYDii1X8IXBQYZjmjqo bqTnlXOfLpGWQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 18/26] rust: alloc: add `Vec` to prelude Date: Thu, 12 Sep 2024 00:52:54 +0200 Message-ID: <20240911225449.152928-19-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that we removed `VecExt` and the corresponding includes in prelude.rs, add the new kernel `Vec` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 07daccf6ca8e..8bdab9aa0d16 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; =20 -pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec= }; +pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec= , Vec}; =20 #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 751E11BBBD5; Wed, 11 Sep 2024 22:56:42 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095402; cv=none; b=u5cZNBVw+463oj0Qg/9iUBJpg6rtLDb1+Nwqv01vnFxept63BbZ3FZade1vi+6O8ilVwNoLMt9nUE5nQAwJMM2amoFV1ZTBqVvdWdh7Q3T4A6dXSxvwfpgXwEVVjuHLHEEiMIYhv7LBuTnzWwFmaCvL956q96arhQPa3+nYl6DA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095402; c=relaxed/simple; bh=XnmkIRl7JMA721xzQ642zkLKaoztfCsGi1LdCRFqGKk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=CSozeMr3VF9guvUtGCB2vg2dN10eVo7yEOs2kvKe0F1KIfXUKjxpJfQ7y82UUQVepDZztaDHIq7N+01lwAPS15HCwx3iCG0FA6RXDSJdhO4qtPYWaswzeKVeYbjtv4X8Ou0QKZy4c1h67Hp67IEt2PT8aCQrcqd1DCtJE6Srcl0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=bjxA++Nc; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="bjxA++Nc" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 21E5DC4CEC5; Wed, 11 Sep 2024 22:56:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095402; bh=XnmkIRl7JMA721xzQ642zkLKaoztfCsGi1LdCRFqGKk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bjxA++Nc5MWL3sYzSRC3CUdU6XlAZO+gTMbQlko/UFgVcABHnYcNL7X9oc9V8vXF1 16vDpXQcwuoVs8tLa8s8vS5OnpYaMML3OIuqzKOEHWtEL1G+Sz/KLpUwi3ga5c6bmP KtLlbSLmlGTCIRqd59l9O1xupERtI+YcthuBihC53gXR8dbNDUv5PKxeWeLvwGbsi5 NBtqMO8aZ0bWn9mVwCQYdiD5bjMTxIOGB6vsIdodaNMTVcFActNXTjqsEkDvO/i6Ls LsfPi8WwdizJlorAXL6qfea+gIBx1mk024CrhBQrnqxq9bADxq4Rqg7nSdlkMUtbkh 0bhjMNs4vhduQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 19/26] rust: error: use `core::alloc::LayoutError` Date: Thu, 12 Sep 2024 00:52:55 +0200 Message-ID: <20240911225449.152928-20-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Use `core::alloc::LayoutError` instead of `alloc::alloc::LayoutError` in preparation to get rid of Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 6f1587a2524e..81b4fc5cf21e 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -6,7 +6,7 @@ =20 use crate::{alloc::AllocError, str::CStr}; =20 -use alloc::alloc::LayoutError; +use core::alloc::LayoutError; =20 use core::fmt; use core::num::TryFromIntError; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6FFA01BBBD7; Wed, 11 Sep 2024 22:56:47 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095407; cv=none; b=hJ1EKKI8Axi6U5wDwDGjlAiH+83Dfs9d/dg0OL/RWROqhAAipKP2r/8FSPfOHgGqq8Nktm5dq98lYzNJ9XlrRzrqa4dQT4q/qgh4HAuP99CwgFdF3CXxDc47vD0KEX0lM2fpvGgtxYSCuTTjuTY5OXMBGeeKQtcz4xGM+8cv1MI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095407; c=relaxed/simple; bh=F2SiwlBtvDarApJOsx0M5Yh8m55DamKxmrKOHUpHf/A=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=KQSuMynM4uk+AHPW7uxkdk1hr/kluS9LvsIARyPOzQ8eIO+hTrW/mng6MCwJjCg9GWnYgeNwpbTpeFVDNu6UqZKOTzw34/7Hg2BVxiLG3R/PMMcIee43M0h/cljfSx0QK1J+kM3xGirP0v73QREm7fd//eNm9oS9yOaGr4iLftA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=Hlamu4iR; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="Hlamu4iR" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 77EDDC4CECD; Wed, 11 Sep 2024 22:56:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095407; bh=F2SiwlBtvDarApJOsx0M5Yh8m55DamKxmrKOHUpHf/A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Hlamu4iRv8xXSCkHAmar3KUNSPO3lkPYrPcPHu4IrAsbykCYVQpH0HcvRJJRZ0DHz XKpcM0mxEYFkl5S5WNATEcoL7Xs/iePmQhT1297x1nCybn3BwHGf9F8MwGHo1tF/re jyta5/E9VxSboNN95jYSIk5Krd7cpYjbyH+ePtE8st+cbUKNNS0G7EBY91R3VXZDou lt4MjcfAfxT2vFOVb5ZZaCHOvI5mp/oVMw5lME9XhehHaThcjPHWBshnWqF+FvwLUL zGZpYuNdVNupA6fpDQh6MD3xpcFe03UbJdkstToGDU7BpmtfXiTsnv2BjmKcVnv7f8 zi2EzgqaloJFA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 20/26] rust: error: check for config `test` in `Error::name` Date: Thu, 12 Sep 2024 00:52:56 +0200 Message-ID: <20240911225449.152928-21-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Additional to `testlib` also check for `test` in `Error::name`. This is required by a subsequent patch that (indirectly) uses `Error` in test cases. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/error.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 81b4fc5cf21e..b71fdd0f54c2 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -143,7 +143,7 @@ pub(crate) fn to_ptr(self) -> *mut T { } =20 /// Returns a string representing the error, if one exists. - #[cfg(not(testlib))] + #[cfg(not(any(test, testlib)))] pub fn name(&self) -> Option<&'static CStr> { // SAFETY: Just an FFI call, there are no extra safety requirement= s. let ptr =3D unsafe { bindings::errname(-self.0) }; @@ -160,7 +160,7 @@ pub fn name(&self) -> Option<&'static CStr> { /// When `testlib` is configured, this always returns `None` to avoid = the dependency on a /// kernel function so that tests that use this (e.g., by calling [`Re= sult::unwrap`]) can still /// run in userspace. - #[cfg(testlib)] + #[cfg(any(test, testlib))] pub fn name(&self) -> Option<&'static CStr> { None } --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C1F1B1B6551; Wed, 11 Sep 2024 22:56:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095412; cv=none; b=ae7SBfQNZuxQjwd7RwDwJqBajaojz775+Q/1scvDbDs7skXjgec1CqriZPxyNYzNEmWHBJC4DlMYnXg909ADsdbjhkJ9Lm+JauceSOMi6YV2QgpYLRxidp4AxJLQHvbQZetS+0C+z2t+HZURaU/GI5P0A5P5onvZElKHldbd0MA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095412; c=relaxed/simple; bh=BuRbAjKmy40vmT3N1pF21OHcKiAzSp8OEnKFLe420pQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=CvF7iRUM6QCeKri6x5sNHV2DTTyhPVoUwp1qYi5Ll/PdGaU4C6NqHrVNtvb+f1MEdNHMFIiEL4E9eL07T+FwuBEbpYNfw7kt/CjVYdpwDHbaqI+R39xGvgwWLVMM5o5tAbz3itpAyJ+ouKAVL+hjm1XJ6Kmmvr+hLJGER+0PW7I= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=pnKBHrnc; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="pnKBHrnc" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C4980C4CEC5; Wed, 11 Sep 2024 22:56:47 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095412; bh=BuRbAjKmy40vmT3N1pF21OHcKiAzSp8OEnKFLe420pQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=pnKBHrncLFslJd6q/nHuhtzqz1+1TBPq4XFiNkHyvx2teZQ09/rGvMq0rkZmjaUBQ Lbl4cpf4vZTYynneRL3vdFi1Bfzk//roOP+ergED0hIoIvTi45n+mq3kqjXJBmtOIE 2TUOfgMT/w6x7qTIrzC8BUSB0AsHIbayljpcYeLVt29Kz+Z5MdCntUZpOmeys+BJf/ +U0AYlUBKLQjbjODoG/ESll0BCXm0zsGtMDWqGWYJ0vhDiGDgL7bZP03DwWiqctj4+ qO7e62LiIaAdh3IGXN1jfezc0FpgcGxB/ZoBVQ43AZLRbGXi/3TLRnAl1HraDUiSRM p61kKYP/nDxBg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 21/26] rust: alloc: implement `contains` for `Flags` Date: Thu, 12 Sep 2024 00:52:57 +0200 Message-ID: <20240911225449.152928-22-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Provide a simple helper function to check whether given flags do contain one or multiple other flags. This is used by a subsequent patch implementing the Cmalloc `Allocator` to check for __GFP_ZERO. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index aabdf80e4f7b..caa0b9dfac87 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -34,7 +34,7 @@ /// They can be combined with the operators `|`, `&`, and `!`. /// /// Values can be used from the [`flags`] module. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq)] pub struct Flags(u32); =20 impl Flags { @@ -42,6 +42,11 @@ impl Flags { pub(crate) fn as_raw(self) -> u32 { self.0 } + + /// Check whether `flags` is contained in `self`. + pub fn contains(self, flags: Flags) -> bool { + (self & flags) =3D=3D flags + } } =20 impl core::ops::BitOr for Flags { --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1B46A1C1720; Wed, 11 Sep 2024 22:56:58 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095418; cv=none; b=hQ6t8Cb3OHjbj0bUdRiMQ6hando1Dj3oldAfeJuvjxTHLnoZULo0kPoud8eE5OX3BhPU+C1M8BUu/cm37NqWPsNatEqFruNzJ3zP0u6lAgadsx7RbT8o45y0zgWd74bq+dqE7CcWAfMnZtQma/VgN7X8Ez/Ju+O501d/tp5ParQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095418; c=relaxed/simple; bh=7DpUes9xKzKOnHl0l07t6QG5s3+EyWmOhpQ1qTWwvVs=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=NLcFCTEx7E1spSMp74fRtvg6blT+1c0XoLEsOKsCZCCkwCzJnRpbDpFVbyqMRR90b1abTfMU5meTBklqTHRrTlvGo8lL5ovV8AaVYAfec08R6LYj4EE1S9lsyWjF53hT4hdzkUsgy5M7og55i3/gRdTTucn4calxPpFzIjvp7u4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=f5op+dn3; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="f5op+dn3" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1FDB0C4CEC5; Wed, 11 Sep 2024 22:56:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095418; bh=7DpUes9xKzKOnHl0l07t6QG5s3+EyWmOhpQ1qTWwvVs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=f5op+dn3i4tC7w4m44y0/BVWrjnqhdMaDeiTdj7gMMWFcEsqpLZ3Pa6TPZPRaP4cY qmEmmQ1ePSh9njO9xpDSMFbyvIRJb6q9b45i/+HuA8Dxa2F5WviMheL0MPyuHnMyw9 wSuONwROY37HCYTJp4C/cYpRCBRt6Y1D7TDsQLB1vDIVbNW+Q4JHkSTOkjGudVFAbO VfM43r7k/JwMyD9a1raOjQYvKomK26B9yfqeWASlzFccAZzHCgf4Zqk/d10KSXznVY +RusIWr7OsxCpxHn85aWDpBqtMlcY9xvAgj5hl7N9WFo+q3/O6HKBiju9fCvKnxJQK GahYDWnm/rHiA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 22/26] rust: alloc: implement `Cmalloc` in module allocator_test Date: Thu, 12 Sep 2024 00:52:58 +0200 Message-ID: <20240911225449.152928-23-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users of those types (e.g. `CString`) use kernel allocators for instantiation. In order to allow userspace test cases to make use of such types as well, implement the `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as allocator backend. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator_test.rs | 193 +++++++++++++++++++++++++++- 1 file changed, 186 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/alloca= tor_test.rs index 1b2642c547ec..b5b30513c398 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -1,21 +1,200 @@ // SPDX-License-Identifier: GPL-2.0 =20 +//! So far the kernel's `Box` and `Vec` types can't be used by userspace t= est cases, since all users +//! of those types (e.g. `CString`) use kernel allocators for instantiatio= n. +//! +//! In order to allow userspace test cases to make use of such types as we= ll, implement the +//! `Cmalloc` allocator within the allocator_test module and type alias al= l kernel allocators to +//! `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as a= llocator backend. + #![allow(missing_docs)] =20 -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use core::alloc::Layout; +use core::cmp; +use core::mem; +use core::ptr; use core::ptr::NonNull; =20 -pub struct Kmalloc; +/// The userspace allocator based on libc. +pub struct Cmalloc; + +pub type Kmalloc =3D Cmalloc; pub type Vmalloc =3D Kmalloc; pub type KVmalloc =3D Kmalloc; =20 -unsafe impl Allocator for Kmalloc { +extern "C" { + #[link_name =3D "aligned_alloc"] + fn libc_aligned_alloc(align: usize, size: usize) -> *mut core::ffi::c_= void; + + #[link_name =3D "free"] + fn libc_free(ptr: *mut core::ffi::c_void); +} + +struct CmallocData { + // The actual size as requested through `Cmalloc::alloc` or `Cmalloc::= realloc`. + size: usize, + // The offset from the pointer returned to the caller of `Cmalloc::all= oc` or `Cmalloc::realloc` + // to the actual base address of the allocation. + offset: usize, +} + +impl Cmalloc { + /// Adjust the size and alignment such that we can additionally store = `CmallocData` right + /// before the actual data described by `layout`. + /// + /// Example: + /// + /// - For `CmallocData` assume an alignment of 8 and a size of 16. + /// - For `layout` assume and alignment of 16 and a size of 64. + /// + ///```text + /// 0 16 32 = 96 + /// |----------------|----------------|-------------------------------= -----------------| + /// empty CmallocData data + ///``` + /// + /// For this example the returned `Layout` has an alignment of 32 and = a size of 96. + fn layout_adjust(layout: Layout) -> Result { + let layout =3D layout.pad_to_align(); + + // Ensure that `CmallocData` fits into half the alignment. Additio= nally, this guarantees + // that advancing a pointer aligned to `align` by `align / 2` we s= till satisfy or exceed + // the alignment requested through `layout`. + let align =3D cmp::max( + layout.align(), + mem::size_of::().next_power_of_two(), + ) * 2; + + // Add the additional space required for `CmallocData`. + let size =3D layout.size() + mem::size_of::(); + + Ok(Layout::from_size_align(size, align) + .map_err(|_| AllocError)? + .pad_to_align()) + } + + fn alloc_store_data(layout: Layout) -> Result, AllocError>= { + let requested_size =3D layout.size(); + + let layout =3D Self::layout_adjust(layout)?; + let min_align =3D layout.align() / 2; + + // SAFETY: Returns either NULL or a pointer to a memory allocation= that satisfies or + // exceeds the given size and alignment requirements. + let raw_ptr =3D unsafe { libc_aligned_alloc(layout.align(), layout= .size()) } as *mut u8; + + let priv_ptr =3D NonNull::new(raw_ptr).ok_or(AllocError)?; + + // SAFETY: + // - By adding `min_align` the pointer remains within the allocate= d object and `min_align` + // can not exceed `isize`. + // + // GUARANTEE: + // - The adjustments from `Self::layout_adjust` ensure that after = this operation the + // original size and alignment requirements are still satisfied or= exceeded. + let ptr =3D unsafe { priv_ptr.as_ptr().add(min_align) }; + + // SAFETY: `min_align` is greater than or equal to the size of `Cm= allocData`, hence we + // don't exceed the allocation boundaries. + let data_ptr: *mut CmallocData =3D unsafe { ptr.sub(mem::size_of::= ()) }.cast(); + + let data =3D CmallocData { + size: requested_size, + offset: min_align, + }; + + // SAFETY: `data_ptr` is properly aligned and within the allocatio= n boundaries reserved for + // `CmallocData`. + unsafe { data_ptr.write(data) }; + + NonNull::new(ptr).ok_or(AllocError) + } + + /// # Safety + /// + /// - `ptr` must have been previously allocated with `Self::alloc_stor= e_data`. + unsafe fn data(ptr: NonNull) -> CmallocData { + // SAFETY: `Self::alloc_store_data` stores the `CmallocData` right= before the address + // returned to callers of `Self::alloc_store_data`. + let data_ptr: *mut CmallocData =3D + unsafe { ptr.as_ptr().sub(mem::size_of::()) }.cas= t(); + + // `CmallocData` has been previously stored at this offset with `S= elf::alloc_store_data`. + // + // SAFETY: + // - `data_ptr` points to a properly aligned and initialized value= of `CmallocData`. + unsafe { core::ptr::read(data_ptr) } + } + + /// # Safety + /// + /// This function must not be called more than once for the same alloc= ation. + /// + /// - `ptr` must have been previously allocated with `Self::alloc_stor= e_data`. + unsafe fn free_read_data(ptr: NonNull) { + // SAFETY: `ptr` has been created by `Self::alloc_store_data`. + let data =3D unsafe { Self::data(ptr) }; + + // SAFETY: `ptr` has been created by `Self::alloc_store_data`. + let priv_ptr =3D unsafe { ptr.as_ptr().sub(data.offset) }; + + // SAFETY: `priv_ptr` has previously been allocatored with this `A= llocator`. + unsafe { libc_free(priv_ptr.cast()) }; + } +} + +unsafe impl Allocator for Cmalloc { + fn alloc(layout: Layout, flags: Flags) -> Result, AllocE= rror> { + if layout.size() =3D=3D 0 { + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0= )); + } + + let ptr =3D Self::alloc_store_data(layout)?; + + if flags.contains(__GFP_ZERO) { + // SAFETY: `Self::alloc_store_data` guarantees that `ptr` poin= ts to memory of at least + // `layout.size()` bytes. + unsafe { ptr.as_ptr().write_bytes(0, layout.size()) }; + } + + Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) + } + unsafe fn realloc( - _ptr: Option>, - _layout: Layout, - _flags: Flags, + ptr: Option>, + layout: Layout, + flags: Flags, ) -> Result, AllocError> { - panic!(); + let Some(src) =3D ptr else { + return Self::alloc(layout, flags); + }; + + if layout.size() =3D=3D 0 { + // SAFETY: `src` has been created by `Self::alloc_store_data`. + unsafe { Self::free_read_data(src) }; + + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0= )); + } + + let dst =3D Self::alloc(layout, flags)?; + + // SAFETY: `src` has been created by `Self::alloc_store_data`. + let data =3D unsafe { Self::data(src) }; + + // SAFETY: `src` has previously been allocated with this `Allocato= r`; `dst` has just been + // newly allocated. Copy up to the smaller of both sizes. + unsafe { + ptr::copy_nonoverlapping( + src.as_ptr(), + dst.as_ptr().cast(), + cmp::min(layout.size(), data.size), + ) + }; + + // SAFETY: `src` has been created by `Self::alloc_store_data`. + unsafe { Self::free_read_data(src) }; + + Ok(dst) } } --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 68A171C1739; Wed, 11 Sep 2024 22:57:03 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095423; cv=none; b=dkiWACMIEGO4lW5bIWt/PLypuqjPcF4JPbfi/MezGRnjlmpzuO7gOrxDUNCpCbCqRQLf0MixY6RZjaF8TzDx/y8gAG3Xi6na0HlXw28UpIUZtQut4+FO2x2ki0xyKzIw1dx4+MoggU3ZjifHGl6mvoxuA2U55KUKavV4h7nDc2I= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095423; c=relaxed/simple; bh=fJujYBGRQtYZqIjs4LKUGmLmSm16nkPMSrJSclIruqE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=WFpy2V43cq2nIJ8h2TPKJ6bLHIiTRn7TkAn4tZtby/xSr9Pk99DWBSjPhWo5iiS/ryRfRjPQX7Wm4X1akLFsUQ07CtwF3ufmOGj9IZbyT6W7wecf62T2kHzefr8rKbVFrFp8LKUri9aWPsR+Op5jcShfPY+i+C6GybiLu4YHu0w= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=F2tMltIA; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="F2tMltIA" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6DA91C4CEC5; Wed, 11 Sep 2024 22:56:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095423; bh=fJujYBGRQtYZqIjs4LKUGmLmSm16nkPMSrJSclIruqE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=F2tMltIAnv/i/tJGJe7bNbkIVpUV0WYSuNcZNfxRBs0WykhZrbPUzjYzdq1yY34uH 1Tx1f0x7bXrf25FFCClhtCtxPjxtJodKtTeMP74jggPIzmW/Z/1VJE6bDVMXBtUCvg XkIo9Xxs8cYlTzpQVFzlR6GruyGgXDdHHxUw8xMdtQ8zupFvp5V7el7Qx/kcfhcV6F S8uHLX7f2feRP+Gm60bPlSTQHq8hx+Uef+zFzcViVZkn5GWlUJqbW3040EiuFZo9sg rXwez/Mly+0HlkBG7ZYvORIQfbENvQGSBM11EbHHo2c4mMzroKLodWB7u1U76CPay2 nU3m0kqSg8I5w== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 23/26] rust: str: test: replace `alloc::format` Date: Thu, 12 Sep 2024 00:52:59 +0200 Message-ID: <20240911225449.152928-24-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" The current implementation of tests in str.rs use `format!` to format strings for comparison, which, internally, creates a new `String`. In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement `format!` for `CString`. Note that for userspace tests, `Kmalloc`, which is backing `CString`'s memory, is just a type alias to `Cmalloc`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/str.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 209ad1bb1a49..726329530338 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,28 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; + + struct String(CString); + + impl String { + fn from_fmt(args: fmt::Arguments<'_>) -> Self { + String(CString::try_from_fmt(args).unwrap()) + } + } + + impl Deref for String { + type Target =3D str; + + fn deref(&self) -> &str { + self.0.to_str().unwrap() + } + } + + macro_rules! format { + ($($f:tt)*) =3D> ({ + &*String::from_fmt(kernel::fmt!($($f)*)) + }) + } =20 const ALL_ASCII_CHARS: &'static str =3D "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d= \\x0e\\x0f\ --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B9DB21BD4F7; Wed, 11 Sep 2024 22:57:08 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095428; cv=none; b=Cp+IxKK6K9V5FEwJLQiufRE7Rcsi8h4qne/RhS5uWaAf4RjxM2GEm0UEJ2h/oqO10Q6Qs1UxtQVwduPEpIMzE7RJyvf6ya4azsuHermtY4OUKsUuDJ28gYPQvqgTp7pdHLjolR+utoViMF3pRJtQxd2lZy1wKbOb4JZ+A/KqC9s= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095428; c=relaxed/simple; bh=CaTZ4LeQw3BXMae2HQHHYLspjHXmuSZPBFyX74iAlrI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=H7IN5aT3BDUWDmfZ9KYC4lBfRWUTaZ2b7N26DoFMmYgafYDNmSTWTitnQ6b+Q0q+Ni8mm6f50HlVaSCdtJOE/35K/jedrg/ApmGmQTGs5f0hHPXNOIyWOc0GU1bSlBG0ywvfea8DxKuv+2jiKatdbQ16XlBoFjG5vG+JXFx9F2M= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=DeYNstig; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="DeYNstig" Received: by smtp.kernel.org (Postfix) with ESMTPSA id BB78BC4CED1; Wed, 11 Sep 2024 22:57:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095428; bh=CaTZ4LeQw3BXMae2HQHHYLspjHXmuSZPBFyX74iAlrI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DeYNstigf7BHHg9d++A50T0ZQ9zMFq1waReAFW0v/ZrnJ+90tBwoD7PgbeF4thuof i3XNPIjRBtijEIA0nxiwycvxCAugZs86jOqN5t4jRtqK45uk1x1PkYuBSAEQohW7cw yVwCoOX1R2K7Iq435/pWkB1kT/wD12FV3Izg7eXiJj1rvy/enbnx8E+1YUlFUtt0xM EIEP9Oa9Pn4YFtFrSgX6cYyzz9Z5MD8Un7y3ZU6BJFW/LHNOOezUSQle2eKhPka9sA lgKCc9KYkGHqije8Fd5etGJJqlTEBy27G0XMcb1v9IGLRvgIA7uTazvfc5oDujnfWA EBJlCGcUZC3BQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 24/26] rust: alloc: update module comment of alloc.rs Date: Thu, 12 Sep 2024 00:53:00 +0200 Message-ID: <20240911225449.152928-25-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Before we remove Rust's alloc crate, rewrite the module comment in alloc.rs to avoid a rustdoc warning. Besides that, the module comment in alloc.rs isn't correct anymore, we're no longer extending Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index caa0b9dfac87..2170b53acd0c 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 =20 -//! Extensions to the [`alloc`] crate. +//! Implementation of the kernel's memory allocation infrastructure. =20 #[cfg(not(any(test, testlib)))] pub mod allocator; --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 208781BD4F7; Wed, 11 Sep 2024 22:57:14 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095434; cv=none; b=KnkZRqk4pNbCDnjl3iBcXygOzlb8mfsaQ7D41Ia+wge938yo2kkeZjwjFgcLY/J1wJi2gObxpMYb5kRIcKe1Oe1HY2KtnkWk7xI4G2cHC3BDjVWbYFzf+LADdEu0t2XsCxoe1ofRdtSSxBgRYGOS4hH/HOkW3HNg+CfjEwOsMN4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095434; c=relaxed/simple; bh=o6caLp0Bu4YVbIWrrELzNR9rfCWDUl8VF9Pzb1+OsjI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=UVZkfUcnxULNJoSlCN0i57vBLr8ACQSWaWGAZYFrSrmh+jHGmRmMEynET1JazdQ3CFMm5xSM9mW+ewPmjJf/L8gdcPF/PUl7WJcT097x8E7u/dyKfRPF3uukN5nv+qsxKZdSgraYCb6BK9cNrFEEb+hPBA0LU2aPalCBm48KfZY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=RJiNqnpV; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="RJiNqnpV" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 15EC9C4CEC0; Wed, 11 Sep 2024 22:57:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095433; bh=o6caLp0Bu4YVbIWrrELzNR9rfCWDUl8VF9Pzb1+OsjI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RJiNqnpVGf4zZcQHVQhvpOspMyZlXjOoqlNJFt4k8jHwZHt6rA/hbJ6Go4cS1F70R rMG7SoqHykwihqfvc61iv3atjBAk3Q7ln9TrwNwB62iMeLUtsqnIANHdzvGpPb1xrf KYI/wb4HrNGMNQrh11mTShj5B/2Ka5ojA4rr3kEa6lgqeibjsLSc67Q4veJXjRdeMN A9rxdTH1RXxs8wo5aD1uCJtGhJ6piqMT8XvSltpgy8GPJyvAfWmyq+wGRgSupc92qH Od9Wjzc2fqaN3mF70rSxQx0LOYQN4ATyAZbNbDu29+ToxTxvRqehsHrRhBEhbpmNha I1HHqup5V/65g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 25/26] kbuild: rust: remove the `alloc` crate and `GlobalAlloc` Date: Thu, 12 Sep 2024 00:53:01 +0200 Message-ID: <20240911225449.152928-26-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Now that we have our own `Allocator`, `Box` and `Vec` types we can remove Rust's `alloc` crate and the `new_uninit` unstable feature. Also remove `Kmalloc`'s `GlobalAlloc` implementation -- we can't remove this in a separate patch, since the `alloc` crate requires a `#[global_allocator]` to set, that implements `GlobalAlloc`. Signed-off-by: Danilo Krummrich --- rust/Makefile | 43 +++++---------------- rust/exports.c | 1 - rust/kernel/alloc/allocator.rs | 63 +------------------------------ scripts/Makefile.build | 7 +--- scripts/generate_rust_analyzer.py | 11 +----- 5 files changed, 15 insertions(+), 110 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 4eae318f36ff..a3ac60b48ae1 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -15,8 +15,8 @@ always-$(CONFIG_RUST) +=3D libmacros.so no-clean-files +=3D libmacros.so =20 always-$(CONFIG_RUST) +=3D bindings/bindings_generated.rs bindings/binding= s_helpers_generated.rs -obj-$(CONFIG_RUST) +=3D alloc.o bindings.o kernel.o -always-$(CONFIG_RUST) +=3D exports_alloc_generated.h exports_helpers_gener= ated.h \ +obj-$(CONFIG_RUST) +=3D bindings.o kernel.o +always-$(CONFIG_RUST) +=3D exports_helpers_generated.h \ exports_bindings_generated.h exports_kernel_generated.h =20 always-$(CONFIG_RUST) +=3D uapi/uapi_generated.rs @@ -53,11 +53,6 @@ endif core-cfgs =3D \ --cfg no_fp_fmt_parse =20 -alloc-cfgs =3D \ - --cfg no_global_oom_handling \ - --cfg no_rc \ - --cfg no_sync - quiet_cmd_rustdoc =3D RUSTDOC $(if $(rustdoc_host),H, ) $< cmd_rustdoc =3D \ OBJTREE=3D$(abspath $(objtree)) \ @@ -81,7 +76,7 @@ quiet_cmd_rustdoc =3D RUSTDOC $(if $(rustdoc_host),H, ) $< # command-like flags to solve the issue. Meanwhile, we use the non-custom = case # and then retouch the generated files. rustdoc: rustdoc-core rustdoc-macros rustdoc-compiler_builtins \ - rustdoc-alloc rustdoc-kernel + rustdoc-kernel $(Q)cp $(srctree)/Documentation/images/logo.svg $(rustdoc_output)/static.= files/ $(Q)cp $(srctree)/Documentation/images/COPYING-logo $(rustdoc_output)/sta= tic.files/ $(Q)find $(rustdoc_output) -name '*.html' -type f -print0 | xargs -0 sed = -Ei \ @@ -105,20 +100,11 @@ rustdoc-core: $(RUST_LIB_SRC)/core/src/lib.rs FORCE rustdoc-compiler_builtins: $(src)/compiler_builtins.rs rustdoc-core FORCE +$(call if_changed,rustdoc) =20 -# We need to allow `rustdoc::broken_intra_doc_links` because some -# `no_global_oom_handling` functions refer to non-`no_global_oom_handling` -# functions. Ideally `rustdoc` would have a way to distinguish broken links -# due to things that are "configured out" vs. entirely non-existing ones. -rustdoc-alloc: private rustc_target_flags =3D $(alloc-cfgs) \ - -Arustdoc::broken_intra_doc_links -rustdoc-alloc: $(RUST_LIB_SRC)/alloc/src/lib.rs rustdoc-core rustdoc-compi= ler_builtins FORCE - +$(call if_changed,rustdoc) - -rustdoc-kernel: private rustc_target_flags =3D --extern alloc \ +rustdoc-kernel: private rustc_target_flags =3D \ --extern build_error --extern macros=3D$(objtree)/$(obj)/libmacros.so \ --extern bindings --extern uapi rustdoc-kernel: $(src)/kernel/lib.rs rustdoc-core rustdoc-macros \ - rustdoc-compiler_builtins rustdoc-alloc $(obj)/libmacros.so \ + rustdoc-compiler_builtins $(obj)/libmacros.so \ $(obj)/bindings.o FORCE +$(call if_changed,rustdoc) =20 @@ -162,7 +148,7 @@ quiet_cmd_rustdoc_test_kernel =3D RUSTDOC TK $< mkdir -p $(objtree)/$(obj)/test/doctests/kernel; \ OBJTREE=3D$(abspath $(objtree)) \ $(RUSTDOC) --test $(rust_flags) \ - -L$(objtree)/$(obj) --extern alloc --extern kernel \ + -L$(objtree)/$(obj) --extern kernel \ --extern build_error --extern macros \ --extern bindings --extern uapi \ --no-run --crate-name kernel -Zunstable-options \ @@ -198,7 +184,7 @@ rusttest-macros: $(src)/macros/lib.rs FORCE +$(call if_changed,rustc_test) +$(call if_changed,rustdoc_test) =20 -rusttest-kernel: private rustc_target_flags =3D --extern alloc \ +rusttest-kernel: private rustc_target_flags =3D \ --extern build_error --extern macros --extern bindings --extern uapi rusttest-kernel: $(src)/kernel/lib.rs \ rusttestlib-build_error rusttestlib-macros rusttestlib-bindings \ @@ -311,9 +297,6 @@ quiet_cmd_exports =3D EXPORTS $@ $(obj)/exports_core_generated.h: $(obj)/core.o FORCE $(call if_changed,exports) =20 -$(obj)/exports_alloc_generated.h: $(obj)/alloc.o FORCE - $(call if_changed,exports) - # Even though Rust kernel modules should never use the bindings directly, # symbols from the `bindings` crate and the C helpers need to be exported # because Rust generics and inlined functions may not get their code gener= ated @@ -360,7 +343,7 @@ quiet_cmd_rustc_library =3D $(if $(skip_clippy),RUSTC,$= (RUSTC_OR_CLIPPY_QUIET)) L =20 rust-analyzer: $(Q)$(srctree)/scripts/generate_rust_analyzer.py \ - --cfgs=3D'core=3D$(core-cfgs)' --cfgs=3D'alloc=3D$(alloc-cfgs)' \ + --cfgs=3D'core=3D$(core-cfgs)' \ $(realpath $(srctree)) $(realpath $(objtree)) \ $(rustc_sysroot) $(RUST_LIB_SRC) $(KBUILD_EXTMOD) > \ $(if $(KBUILD_EXTMOD),$(extmod_prefix),$(objtree))/rust-project.json @@ -398,12 +381,6 @@ $(obj)/compiler_builtins.o: private rustc_objcopy =3D = -w -W '__*' $(obj)/compiler_builtins.o: $(src)/compiler_builtins.rs $(obj)/core.o FORCE +$(call if_changed_rule,rustc_library) =20 -$(obj)/alloc.o: private skip_clippy =3D 1 -$(obj)/alloc.o: private skip_flags =3D -Wunreachable_pub -$(obj)/alloc.o: private rustc_target_flags =3D $(alloc-cfgs) -$(obj)/alloc.o: $(RUST_LIB_SRC)/alloc/src/lib.rs $(obj)/compiler_builtins.= o FORCE - +$(call if_changed_rule,rustc_library) - $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FOR= CE +$(call if_changed_rule,rustc_library) =20 @@ -418,9 +395,9 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_rule,rustc_library) =20 -$(obj)/kernel.o: private rustc_target_flags =3D --extern alloc \ +$(obj)/kernel.o: private rustc_target_flags =3D \ --extern build_error --extern macros --extern bindings --extern uapi -$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/alloc.o $(obj)/build_error.o \ +$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/build_error.o \ $(obj)/libmacros.so $(obj)/bindings.o $(obj)/uapi.o FORCE +$(call if_changed_rule,rustc_library) =20 diff --git a/rust/exports.c b/rust/exports.c index e5695f3b45b7..82a037381798 100644 --- a/rust/exports.c +++ b/rust/exports.c @@ -16,7 +16,6 @@ #define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym) =20 #include "exports_core_generated.h" -#include "exports_alloc_generated.h" #include "exports_helpers_generated.h" #include "exports_bindings_generated.h" #include "exports_kernel_generated.h" diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index a5d7e66a68db..0b586c0361f4 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,8 +8,8 @@ //! //! Reference: =20 -use super::{flags::*, Flags}; -use core::alloc::{GlobalAlloc, Layout}; +use super::Flags; +use core::alloc::Layout; use core::ptr; use core::ptr::NonNull; =20 @@ -54,23 +54,6 @@ fn aligned_size(new_layout: Layout) -> usize { layout.size() } =20 -/// Calls `krealloc` with a proper size to alloc a new object aligned to `= new_layout`'s alignment. -/// -/// # Safety -/// -/// - `ptr` can be either null or a pointer which has been allocated by th= is allocator. -/// - `new_layout` must have a non-zero size. -pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, fl= ags: Flags) -> *mut u8 { - let size =3D aligned_size(new_layout); - - // SAFETY: - // - `ptr` is either null or a pointer returned from a previous `k{re}= alloc()` by the - // function safety requirement. - // - `size` is greater than 0 since it's from `layout.size()` (which c= annot be zero according - // to the function safety requirement) - unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, fla= gs.0) as *mut u8 } -} - /// # Invariants /// /// One of the following `krealloc`, `vrealloc`, `kvrealloc`. @@ -148,41 +131,6 @@ unsafe fn realloc( } } =20 -unsafe impl GlobalAlloc for Kmalloc { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero s= ize by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL) } - } - - unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { - unsafe { - bindings::kfree(ptr as *const core::ffi::c_void); - } - } - - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize= ) -> *mut u8 { - // SAFETY: - // - `new_size`, when rounded up to the nearest multiple of `layou= t.align()`, will not - // overflow `isize` by the function safety requirement. - // - `layout.align()` is a proper alignment (i.e. not zero and mus= t be a power of two). - let layout =3D unsafe { Layout::from_size_align_unchecked(new_size= , layout.align()) }; - - // SAFETY: - // - `ptr` is either null or a pointer allocated by this allocator= by the function safety - // requirement. - // - the size of `layout` is not zero because `new_size` is not ze= ro by the function safety - // requirement. - unsafe { krealloc_aligned(ptr, layout, GFP_KERNEL) } - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero s= ize by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL | __= GFP_ZERO) } - } -} - // SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees th= at // - memory remains valid until it is explicitly freed, // - passing a pointer to a valid memory allocation is OK, @@ -228,10 +176,3 @@ unsafe fn realloc( unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, flags) } } } - -#[global_allocator] -static ALLOCATOR: Kmalloc =3D Kmalloc; - -// See . -#[no_mangle] -static __rust_no_alloc_shim_is_unstable: u8 =3D 0; diff --git a/scripts/Makefile.build b/scripts/Makefile.build index 72b1232b1f7d..529ec5972e55 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -262,18 +262,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE =20 # Compile Rust sources (.rs) # ------------------------------------------------------------------------= --- - -rust_allowed_features :=3D new_uninit - # `--out-dir` is required to avoid temporaries being created by `rustc` in= the # current working directory, which may be not accessible in the out-of-tree # modules case. rust_common_cmd =3D \ RUST_MODFILE=3D$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \ - -Zallow-features=3D$(rust_allowed_features) \ -Zcrate-attr=3Dno_std \ - -Zcrate-attr=3D'feature($(rust_allowed_features))' \ - -Zunstable-options --extern force:alloc --extern kernel \ + -Zunstable-options --extern kernel \ --crate-type rlib -L $(objtree)/rust/ \ --crate-name $(basename $(notdir $@)) \ --sysroot=3D/dev/null \ diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_anal= yzer.py index d2bc63cde8c6..09e1d166d8d2 100755 --- a/scripts/generate_rust_analyzer.py +++ b/scripts/generate_rust_analyzer.py @@ -64,13 +64,6 @@ def generate_crates(srctree, objtree, sysroot_src, exter= nal_src, cfgs): [], ) =20 - append_crate( - "alloc", - sysroot_src / "alloc" / "src" / "lib.rs", - ["core", "compiler_builtins"], - cfg=3Dcrates_cfgs.get("alloc", []), - ) - append_crate( "macros", srctree / "rust" / "macros" / "lib.rs", @@ -96,7 +89,7 @@ def generate_crates(srctree, objtree, sysroot_src, extern= al_src, cfgs): append_crate( "kernel", srctree / "rust" / "kernel" / "lib.rs", - ["core", "alloc", "macros", "build_error", "bindings"], + ["core", "macros", "build_error", "bindings"], cfg=3Dcfg, ) crates[-1]["source"] =3D { @@ -133,7 +126,7 @@ def generate_crates(srctree, objtree, sysroot_src, exte= rnal_src, cfgs): append_crate( name, path, - ["core", "alloc", "kernel"], + ["core", "kernel"], cfg=3Dcfg, ) =20 --=20 2.46.0 From nobody Thu Nov 14 03:57:45 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id BDBBE1BC074; Wed, 11 Sep 2024 22:57:19 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095439; cv=none; b=O5LbY1QrkMk2ZnXXJJ8m0iyKHBMwSG5+Uo+VspCPnxxQaypn0XR+6v6eMGGZ4YgZ+M+NQFzegBvpkYIqoeQALg1miMOwi296uO+tk+af3x2hStS7vXG7G6xqNrZd3EVI44t418a5QOhW14NQ0Sw7xGa29XiPcCMQE/yt/R7Dnzg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1726095439; c=relaxed/simple; bh=MA63j2l96SFmNAW2ZFKeN7OYc4kzJPq4eXgb27o0nko=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=CgZOyKtz9k3duU6JubfvORWzvxYUhxMVzeSwqP5dexJJERsO2nM+AtPDysDcNFDGioOpI+X2tW3R5jL4bo7rkwlW8ggarw6d9IEA0ZRI9rvjDoQXnKfMN7fgFZyjg6nq7cLTtDUJwnLqH5dFRZHGa+pdQc58NhRdcu8m/nGSnkE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=NR2myOkh; arc=none smtp.client-ip=10.30.226.201 Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b="NR2myOkh" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6657DC4CECD; Wed, 11 Sep 2024 22:57:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095439; bh=MA63j2l96SFmNAW2ZFKeN7OYc4kzJPq4eXgb27o0nko=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=NR2myOkh+9gGnmPS2kTc/yg2gApS991zzrQnL13Z3QDyUHo8klpn52EysPtMFhadg rBBDarK2Lo3HtvcLZmyafp6cQ/NooD0a5Mr+BbG4ZDKrda9xzsWWbV5qJ8D+Rkk51x qmYHJcJl8x8siUwA9t2m9zPFZ0mXVEugSCkgMa+VUXsHZr+5nybS6F6pStN0zjZCMi fdyOg34SRfXUluMcm88odzsoq/DqrnOJ6Am3VF8g1/mcHzcvDXOOKyQ8oUHdexq4RP /wfna5X5/a7/6l/Dl6GecSb3Si8FLLzmMJzs96MWVGhq1LPrixpNmgFfXvKYxJzSVX hRx64lF9uLVdQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 26/26] MAINTAINERS: add entry for the Rust `alloc` module Date: Thu, 12 Sep 2024 00:53:02 +0200 Message-ID: <20240911225449.152928-27-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Add maintainers entry for the Rust `alloc` module. Currently, this includes the `Allocator` API itself, `Allocator` implementations, such as `Kmalloc` or `Vmalloc`, as well as the kernel's implementation of the primary memory allocation data structures, `Box` and `Vec`. Signed-off-by: Danilo Krummrich --- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 77b395476a80..f57e3b5bc410 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -19929,6 +19929,13 @@ F: scripts/*rust* F: tools/testing/selftests/rust/ K: \b(?i:rust)\b =20 +RUST [ALLOC] +M: Danilo Krummrich +L: rust-for-linux@vger.kernel.org +S: Maintained +F: rust/kernel/alloc.rs +F: rust/kernel/alloc/ + RXRPC SOCKETS (AF_RXRPC) M: David Howells M: Marc Dionne --=20 2.46.0