From nobody Fri Dec 19 22:01:16 2025 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 0EE4A2D7B8; Mon, 5 Aug 2024 15:20: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=1722871219; cv=none; b=iTksfi4iTqtWpg6WdPE/Ov9ncW3nzMWJD5/a7pIymxe0upjDdHN/2WBpeUVfchdXq5kb4/WYmfPUp+cnStdmPwhGC+RBwozzTySeGJ090qgwIQA5r5PZ/bDhLP/P50N5AjCa6dxrismYXROL/M7Ohk/YmbEf8eqwqhJ8zmytQL4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871219; c=relaxed/simple; bh=bj2UZpRhWMoc+XVgxuPd+wiqHp6BzB0ewgAdFDBiTYg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=KofUgaucSd5JVO1PdIS/OXa4dpHS2Wgpy1QjHmk4EHtN50zZ7a4jsj0+PyjlUJLQlzXMQN/j3I+S4sBiQgqG2pc0TfG7aARpHipgUH/4JaZVqvDyVKJvDMlpvx7kXdvs4gpv3reln1pE12jTR7NIKGfG7TRD6+gPm/x4PLzeCLg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=VAqcutSL; 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="VAqcutSL" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C6339C4AF0B; Mon, 5 Aug 2024 15:20:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871218; bh=bj2UZpRhWMoc+XVgxuPd+wiqHp6BzB0ewgAdFDBiTYg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=VAqcutSL+jtXhIoRiTSkMmZPCI/bBw3pmkzBP8y2/RKxoqqrgTmBCuv07L8Iry7FG NT2oRfpAarApvL7iwz1AChRLNislMw1SRumZx0OJN2RUOInTDpwna/9AudOBqeXaas NtiHLp1V7RyLar9j3jOLHHQY1wCFnYmRj7XndwW+QkisRNcEYP2hodWSAE4U4lkJ/k QF/m40DR9nXme8xAsCTSNfMtGHmYASh0XxAyI+bL9DFk9aqL1aVsr7+7xGl/GL/qN/ mTObrcHiOO3uxo9FZ5CEIXnOXpJLv4ANJ4VS8ESiTb/M3LMiILxa7UllD0tlUkS/Pc 577mQVpjXuo9w== 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, acurrid@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 v4 01/28] rust: alloc: add `Allocator` trait Date: Mon, 5 Aug 2024 17:19:20 +0200 Message-ID: <20240805152004.5039-2-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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`. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/alloc.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..8a71a589469d 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,81 @@ 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 buffer 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 +/// +/// Memory returned from an allocator must point to a valid memory buffer = and remain valid until +/// it is explicitly freed. +/// +/// Any pointer to a memory buffer which is currently allocated must be va= lid to be passed to any +/// other [`Allocator`] function of the same type. The same applies for a = NULL pointer. +/// +/// If `realloc` is called with: +/// - a size of zero, the given memory allocation, if any, must be freed +/// - a NULL pointer, a new memory allocation must be created +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 a NULL p= ointer. + fn alloc(layout: Layout, flags: Flags) -> Result, AllocE= rror> { + // SAFETY: Passing a NULL pointer to `realloc` is valid by it's sa= fety requirements 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 `free`. + /// + /// 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 + /// + /// `Some(ptr)` must point to an existing and valid memory allocation = created by this allocator + /// instance. The alignment encoded in `layout` must be smaller than o= r equal to the alignment + /// requested in the previous `alloc` or `realloc` call of the same al= location. + /// + /// Additionally, `ptr` is allowed to be `None`; in this case a new me= mory allocation is + /// created. + /// + 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` + /// instance. + unsafe fn free(ptr: NonNull) { + // SAFETY: `ptr` is guaranteed to be previously allocated with thi= s `Allocator` or NULL. + // Calling `realloc` with a buffer size of zero, frees the buffer = `ptr` points to. + let _ =3D unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), F= lags(0)) }; + } +} --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 CA59613CFAA; Mon, 5 Aug 2024 15:20:24 +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=1722871226; cv=none; b=knCo0hcCsAKacOtAv5vQeT+aB/UP3OlnBS6TEigVEr2mpqCOrBtzWI3IiPo+Yi39mEM2QV8cCZv+d/d3BJm+IpsVnbAJPM2r/MbKxQo6f7ExVjGU8RngRgbq1DsNsb5BJnbLqkVRZ6gkFRYYrDdrQDsvsm1KduTeBreKc+ZGjIA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871226; c=relaxed/simple; bh=PKEwZd3yHqQQqT8mEHKKvphM2Pe67I1NR1OPtC0T0To=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=vGAu4ghJvji412UdmsXfnHfHPuI+Z42S3JV5h8/l4MX0XXhv9nh89YgFizDn7OEOWtFcgi9fokz/qK6j4aycPfKiwLWWMvypdHbM4HFkwTI6b0FVreuOeFBi3gf66HBjaN/mW1OjO9OmuosDWwNWX4Kzgznj9vkJSLH0MjWQn68= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=X77UjPV2; 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="X77UjPV2" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 53277C32782; Mon, 5 Aug 2024 15:20:19 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871224; bh=PKEwZd3yHqQQqT8mEHKKvphM2Pe67I1NR1OPtC0T0To=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=X77UjPV25pEFDWaPq84AeyqAqV6uAdZksZPYQUqppUCz33XeJi1l7MK10KLbf0tbV 1gzJyR/gqXeboD6/+PfujdxjK/K4YorMQKV2i+6CtJjJTkdm31OPPP4WGDsy4wM/wE iCsc/dfVvk0YM4EQNp02su+KeYPCYvQp/Qz0O3UCPWA81wABOZR3++cXO71S3jytsL 3j2+CK5sJAdYdHLX5ornikWobgm9ufjXlj46zb+RBB1jQm+QeqMSgCABFndl+5xVe8 aMqMS0NjQ8nrvu61TGZ05I78vnCyrNNzHV9terWU4iL/PgCi/NJd09luI4ht5nHBGL uSXgPuiwLcsJA== 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, acurrid@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 v4 02/28] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Mon, 5 Aug 2024 17:19:21 +0200 Message-ID: <20240805152004.5039-3-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/alloc/allocator.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..e7b7eba84acb 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,27 +8,36 @@ =20 struct KernelAllocator; =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 { +/// 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(); =20 // 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(); + 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 { // 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 } + unsafe { + bindings::krealloc( + ptr as *const core::ffi::c_void, + aligned_size(new_layout), + flags.0, + ) as *mut u8 + } } =20 unsafe impl GlobalAlloc for KernelAllocator { --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 8735A13CFAA; Mon, 5 Aug 2024 15:20:30 +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=1722871231; cv=none; b=TXhBDtl6NqO04+8A/L4hbF6QSt3hPBOI61TTBxqeV8TikOPqVTz6smzkMXxhckAzOkvKOi59296AkiMKOW4NOEp798gkYA/ZHfuruhYj+ACyIta6reIjmrDPEPdwIYWmxyowA8a1ArK+N7lxNfNouDt/KHyON0f+2DYJYAkQUac= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871231; c=relaxed/simple; bh=OtT50VkQ4IhBDfNNG3JPXaxsaB7mAc0R/AyuRkhis70=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=GFghPahH0bfg846IIP0UUE0ZDTIQ6U2sApd4XFyAclQT2bqRfXFsQCW1wbShKzIQI4KxyAQDkLhXMELwH+04fcMngvGQw3mVSXknR0GIdH7n6P84A1X6Vvjl/NnhdBG4ljfFx9U4H4U5HB46axVX2suKkXHyX7Z77Dxle/vG+4w= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=DAEFhR9a; 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="DAEFhR9a" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D8AE8C4AF10; Mon, 5 Aug 2024 15:20:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871229; bh=OtT50VkQ4IhBDfNNG3JPXaxsaB7mAc0R/AyuRkhis70=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DAEFhR9aVevAgqQ6ElgV7Cw56P/HwNiDuiiitRoBj9UULByi45M7SLaTEVX68yLmV cjn4/P0ycimIRj27eLfZXkyB/YZuTg2IiwHFXQYw2pc02ImwN2/hwReybehcWo5NQm Nk1muDVH1Iey7GlX6fYVgMS55urQaTDSBArGzS5Xws58PEdKZFHHS4+7e88i2wfgU5 vCGS0oDPXlR3Bzx/VKH7n16V/KuUiVLF+GS2ldj6mdojwW5fa5Wz/hhvYcyOHnlrw7 q8jpo71RaebkuQPg8UrUT6y6eJEL+jwkelqbO27EsFg5UIXz5QZPEWviuJgkEctN5M RtGhnHltjm3Iw== 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, acurrid@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 v4 03/28] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Mon, 5 Aug 2024 17:19:22 +0200 Message-ID: <20240805152004.5039-4-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin Reviewed-by: Gary Guo --- 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 e7b7eba84acb..2c1eae25da84 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 { @@ -40,7 +40,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_l= ayout: Layout, flags: F } } =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. @@ -76,7 +76,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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 F22ED15B54F; Mon, 5 Aug 2024 15:20:35 +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=1722871236; cv=none; b=Si6M6gZPx+LKcPyifliRkZxOxFU57w1nhM5lzfa5Wy5sMnAEdxL1PnkgfY1TaQYo/87IdPWnx6tGvkORJrUtKw+4VvNS2NqDYJJJOlmrEHHZV1uRNmM+sDBT1JbxGBldKUeoz2RmjiztKhHx3ECMgJ+nqGLDXwy99jODxxCPR5Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871236; c=relaxed/simple; bh=KUN3egAY7JyTXEWIOlIzv3zwwD5pg50NL+IK/lAWQ2g=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=TOcUEyJ8JQOIw8/F1GviuZj5wBSc7GdzduN6PTBpu721HuVeUwZgcAC9bEDlRo5v/HhVYTHP1nOan5uHGDUka7hTVTw7h6zbDAYiJcxUNTMj0yfR2iWiuCnfp4rUpiuMlJw0Qgwmo/hqegpUumku6SlOHBYDmbL68wp7Wtpuw6o= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=EMxxVbqZ; 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="EMxxVbqZ" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 697CAC32782; Mon, 5 Aug 2024 15:20:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871235; bh=KUN3egAY7JyTXEWIOlIzv3zwwD5pg50NL+IK/lAWQ2g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=EMxxVbqZsYS6nje0qCRhq8ZjYYic641hDJRMsjp6Pa5Ba7wKckgxEzzaVkWT4c7E4 tY9hyufAZRqbEWsqp+jP1c0nJdb4JIGFs6/3mKu6g0HwA3prX2eDxZWIHeieyQ7zkw msTYgDTMoxrHx9Kfdysi8sOAVZmA8GbTMIvk/Gatky1A38ZHuV4WLGPyEQIChmxeM/ sdjY4dYgVjDkpONE5ArmejxyhKkv7F8zgYza4kcdEJpyQzUSNLaPCoiPAFpq2MqJK4 s5qsHODvwWTrJn3dJcGxBsVJWuLDQ9HO9Ln6kp/S5ofY9gnIuFimqfJCsRSx9VFpSO V4zwpKrFBpwrA== 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, acurrid@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 v4 04/28] rust: alloc: implement `Allocator` for `Kmalloc` Date: Mon, 5 Aug 2024 17:19:23 +0200 Message-ID: <20240805152004.5039-5-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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/helpers.c | 3 +- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 68 +++++++++++++++++++++++++++++++++- 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/rust/helpers.c b/rust/helpers.c index 92d3c03ae1bd..9f7275493365 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -193,8 +193,7 @@ void rust_helper_init_work_with_key(struct work_struct = *work, work_func_t func, } EXPORT_SYMBOL_GPL(rust_helper_init_work_with_key); =20 -void * __must_check __realloc_size(2) -rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) +void *rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) { return krealloc(objp, new_size, flags); } diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 8a71a589469d..bc01a17df5e0 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 2c1eae25da84..c6ad1dd59dd0 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -5,8 +5,16 @@ 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. +/// +/// The contiguous kernel allocator only ever allocates physically contigu= ous memory through +/// `bindings::krealloc`. +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 { @@ -40,6 +48,64 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_= layout: Layout, flags: F } } =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. + fn krealloc() -> Self { + Self(bindings::krealloc) + } + + /// # Safety + /// + /// This method has the exact same safety requirements as `Allocator::= realloc`. + 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: `ptr` is valid by the safety requirements of this funct= ion. + 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)) + } +} + +unsafe impl Allocator for Kmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc =3D ReallocFunc::krealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid me= mory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 888F015AD9C; Mon, 5 Aug 2024 15:20:41 +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=1722871241; cv=none; b=EQHqvEFJuPMAbf4ovsx4nEDRVROmrryYQ1x4QgZy++IkaQDesTCJkiGVsIACQTDhw6fd0Zhm3e08cJSoquvYSkUdaXhwRSmVM0Bezr/i+STO7Jl1tvNY6ErM7Gr91XLoovVsK3IHElq9ukZZvhMBQgblu2vcoX3H4fcFED6JnUo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871241; c=relaxed/simple; bh=/7W8GCJx8ZaHy6t5I1ObMJj1vrI+veTwVNr/WbX4NOU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=H39GPrC70yAw0z/Nr0ZsZLpMNo27kHd6tARocSiXfACtzUsQ6sjdxdhYY3uHfnHbAjRmprv+u813GCAwX/3XkY7C9P4Ij0L0oI79SyPie9ExwWc6x7jfcwWNeQHxGMgZ/7FPlQ0rpbrvK+nhb2shBufsEdTCc1c64sprAIe3scE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=MoML3ZgK; 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="MoML3ZgK" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EBDF7C4AF0C; Mon, 5 Aug 2024 15:20:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871241; bh=/7W8GCJx8ZaHy6t5I1ObMJj1vrI+veTwVNr/WbX4NOU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MoML3ZgKxFmsuOSbgCE56/itM8cvkuK//0MYyC4C4aunRsn7Dl8fWhcGWz2EqaJyp iHmE9IwsJtEQ+EHgu7FFHPV8ZnWnUXwA3+lh0gbW7Gkz97Saj+UQ1ofrBSyD+ZQUo3 pXNgjDlKvZFkzNmoyhI7ay9CSn95HVw7vMzY9GS8rJ39uNMYW0RinE+hhJ369gKnk3 K2RjcUnjvR1xVZL/IS3DK/iAjMJ5gw4T/18OQCFeghsNoP9FzgX2br/uRV43bDHpMv jIID+fqZFGd148UqPzOEokjka8CVFv71Ml3Ma+1USIivms//SQzAIrG+TPd8bivRVa l2P/zx6yd+lAA== 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, acurrid@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 v4 05/28] rust: alloc: add module `allocator_test` Date: Mon, 5 Aug 2024 17:19:24 +0200 Message-ID: <20240805152004.5039-6-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 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 bc01a17df5e0..942e2755f217 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 B8EE915C15A; Mon, 5 Aug 2024 15:20:46 +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=1722871246; cv=none; b=BFe9J6lHY+bhnuEQxO3ZgHdELLT5Xu3aNVYeJdUQfwc/XEboFJuBDO2TRjNfZEFPC3NMuZ+esdNzIhtI69CL7Wbn2mgOa6znBORGDWeXL24QIV3LpQgHg0XVJKEYhPi2ZT3wqN04qnI+4izSSTrdc+NVUGl3Ulho4+Kiin2q82Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871246; c=relaxed/simple; bh=pL/2tk9r+RNw9Wnwj5An+62HaTNk3XqGiHLSI686pwI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Kt8RWpgad/oemVRgMO1TpZVo3C5tjMEMIB5rcuIBJUnoummGd5SS1ybT0viBctw3V1vh4rjeTqMIrS2z7Z5mKvLWiup/MXKjpyx5eu7uWFLq4IUM0kj4RLU3sdZ4Nyat+mHxelq8qxDdezp1W48Gif6d0rR5EtV0TsA2r/VnNGI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=oXd667Z+; 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="oXd667Z+" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8143FC4AF10; Mon, 5 Aug 2024 15:20:41 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871246; bh=pL/2tk9r+RNw9Wnwj5An+62HaTNk3XqGiHLSI686pwI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=oXd667Z+v76rsJOSJiwugYw609RU4d6zvS4IpyxU3I92MkwzAqckdCues4v2T1H3A vkNdhCTwWgRMUDvgFaBOa4CrrpzOesoJFqdWJ6s5Ur+j1mSjOVvnC6CHSRNSy02wF8 1vz1ux3aD2y8DiGsV6Qy6v9tyQP7p4fpsN4M8C4TPWzqAxiQ5Ghaigs4Ib6+QGFBDY HwBY/mF2ukc7pbEUUFvR6HJnpCx4dqW2N7+r/MBeru8bfevLcarBnon3YJlxnqLRVo OFkXc6ZGL7uSiXg29DTUz8afCaANoREEuu2D9NqxQ8XEIYAb8hSoHDax9s9v8CgShz wB6sBGnyImjxg== 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, acurrid@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 v4 06/28] rust: alloc: implement `Vmalloc` allocator Date: Mon, 5 Aug 2024 17:19:25 +0200 Message-ID: <20240805152004.5039-7-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 --- rust/helpers.c | 7 +++++++ rust/kernel/alloc/allocator.rs | 32 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 40 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 9f7275493365..7406943f887d 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include =20 @@ -199,6 +200,12 @@ void *rust_helper_krealloc(const void *objp, size_t ne= w_size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); =20 +void *rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) +{ + return vrealloc(p, size, flags); +} +EXPORT_SYMBOL_GPL(rust_helper_vrealloc); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indi= ces. diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index c6ad1dd59dd0..bb55895cbd03 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -9,6 +9,7 @@ =20 use crate::alloc::{AllocError, Allocator}; use crate::bindings; +use crate::pr_warn; =20 /// The contiguous kernel allocator. /// @@ -16,6 +17,12 @@ /// `bindings::krealloc`. pub struct Kmalloc; =20 +/// The virtually contiguous kernel allocator. +/// +/// The vmalloc allocator allocates pages from the page level allocator an= d maps them into the +/// contiguous kernel virtual space. +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. @@ -61,6 +68,11 @@ fn krealloc() -> Self { Self(bindings::krealloc) } =20 + // INVARIANT: `vrealloc` satisfies the type invariants. + fn vrealloc() -> Self { + Self(bindings::vrealloc) + } + /// # Safety /// /// This method has the exact same safety requirements as `Allocator::= realloc`. @@ -141,6 +153,26 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut = u8 { } } =20 +unsafe impl Allocator for Vmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc =3D ReallocFunc::vrealloc(); + + // 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 { realloc.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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 993CF15E5BD; Mon, 5 Aug 2024 15:20: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=1722871252; cv=none; b=UaAiwqNnHZ0jMTjy4WCImnr/7L57xLRP9st4z4XbWMkwOOJUbXbEg6W7AZEmLTpcmSuTj9f4QkrpJWReZVjGhxPkfVhouIXVkmqIiDofLmzo8Q+T/V5DhUdexnPAYEq8bJMFw41V+7WnwyI8M7A3YxXrAJ6TKHLbv6uIYVqdZwk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871252; c=relaxed/simple; bh=4X9wSdLX4mWoeYIrAd5wlz1K/X7N03r6vTnYVQGkAO4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=HexsrV6JQSldxAXoy64AUaQw8iWFYtyyt5fHD+BIhsBe92WEtosxATNjKLxv1/xAdCPncfyizuOXX19gGruL20dygvFNY3onAv/eW+w3Z8cZStehf0BCawcWCxyCh1V+QowZTv/WBgHYmlL9uFCsJ/wwRs/HrPb86qiQTKX0QAk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=GJAyHZFL; 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="GJAyHZFL" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 13970C4AF0B; Mon, 5 Aug 2024 15:20:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871252; bh=4X9wSdLX4mWoeYIrAd5wlz1K/X7N03r6vTnYVQGkAO4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GJAyHZFLBa7Fe6Up0rMI4tOEodUpG6ICWZsYB2kS9icTwHsv0wtG66ktGFCoOjyxY pXCRPWZeor7R6vBE9LRo5MJNRiM4BLH8xXJI0PIBnIyvPd/YHQmtjyKZ9m/jKa8bTL VZd48fllVOFNugpuOyQOJWmnk7hjLZQPVN0ha/0JFtJrb6oF/A0kXmCcBG17FIZtWn 1xTk0MDC4qqfztXrPzUFAVOzBguUtCZHmg1pKUEEQCZqyIslqywKAbJ2MBEq+2ZAFG ZKjqokDjnAsjTlUD/6tbLaa5ffRzlKIlpoxxiV/EsMBdEOW2q5N3RO8OhT02M4Fvay jHkfPN2IYfWaQ== 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, acurrid@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 v4 07/28] rust: alloc: implement `KVmalloc` allocator Date: Mon, 5 Aug 2024 17:19:26 +0200 Message-ID: <20240805152004.5039-8-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 --- rust/helpers.c | 6 ++++++ rust/kernel/alloc/allocator.rs | 31 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 38 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 7406943f887d..3285a85765ff 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -206,6 +206,12 @@ void *rust_helper_vrealloc(const void *p, size_t size,= gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_vrealloc); =20 +void *rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags) +{ + return kvrealloc(p, size, flags); +} +EXPORT_SYMBOL_GPL(rust_helper_kvrealloc); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indi= ces. diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index bb55895cbd03..91ff21372a8f 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -23,6 +23,12 @@ /// contiguous kernel virtual space. pub struct Vmalloc; =20 +/// The kvmalloc kernel allocator. +/// +/// Attempt to allocate physically contiguous memory, but upon failure, fa= ll back to non-contiguous +/// (vmalloc) allocation. +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. @@ -73,6 +79,11 @@ fn vrealloc() -> Self { Self(bindings::vrealloc) } =20 + // INVARIANT: `vrealloc` satisfies the type invariants. + fn kvrealloc() -> Self { + Self(bindings::kvrealloc) + } + /// # Safety /// /// This method has the exact same safety requirements as `Allocator::= realloc`. @@ -173,6 +184,26 @@ unsafe fn realloc( } } =20 +unsafe impl Allocator for KVmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc =3D ReallocFunc::kvrealloc(); + + // 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 { realloc.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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 46E452D7B8; Mon, 5 Aug 2024 15:20:57 +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=1722871258; cv=none; b=k4LZslfl4ypD+fZZFayu9P2WPf3Gh0VwBPdNv4rAkKZIKGuhvF2lY+pjJRCpoQUmpposzSdijddZeXOkywS/KWIGEL6ctWUK7HGat4D1rfX/C7nw3sKtkIYSUMRCl4X/3Wmk3ToQctBEuFg+YsWm1QzGbVgbtzHGNPLJCWAVAZk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871258; c=relaxed/simple; bh=rMcjDrrKtW/xMLE5lbZxePxiklFMyzPsbOBl2rb1EqA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=WCTN4jYG4fcfoZzt/Ll4hNE3T0/do+2GZiJxvN+K17sLv/+I3Qa4fmg14bgMhTCkHyP+PWjKrNqTefmsR5cQVgE+6u+owiKOv0+Pa0tL9p+COTQf2PvWfa56iEYcInWTRHINEWlTHn3yjC/19Tx8TfdxKFMSkNeutC9NWPDAYeI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=cdxAs5b/; 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="cdxAs5b/" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9C595C32782; Mon, 5 Aug 2024 15:20:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871257; bh=rMcjDrrKtW/xMLE5lbZxePxiklFMyzPsbOBl2rb1EqA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cdxAs5b/1Fe6xH8UKlGLdCCUCLDyjtSIBAnMG1ZUwkJr+9PDvew0haUEFRz6oVaaY +YuEuWuCcXfnTBKs4xHAToRDnUf+9uqy7/Flc/5TavUzriCPgQ6cE8RHHYwNVHox5S 8pOVIj6lILYgorP6kthArTsoN8FhBOSaAEkHfEuifWjQ2cAP3jhSPE6FBgDOyBazpN EmuPcKnqbrOByXqFZeoLTp9fUbm58JnaZdJwXpoDJKzCESgWuoaMkd217KtrD6alyI zO1Qajazexhllns3D4lxkOtexDp13fjM7Xg13mYjgtox/2+d8j9qU9gFwVKnI9P7X2 sxe2H+a2IgvFw== 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, acurrid@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 v4 08/28] rust: types: implement `Unique` Date: Mon, 5 Aug 2024 17:19:27 +0200 Message-ID: <20240805152004.5039-9-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 the `Unique` type as a prerequisite for `Box` and `Vec` introduced in subsequent patches. `Unique` serves as wrapper around a `NonNull`, but indicates that the possessor of this wrapper owns the referent. This type already exists in Rust's core library, but, unfortunately, is exposed as unstable API and hence shouldn't be used in the kernel. This implementation of `Unique` is almost identical, but mostly stripped down to the functionality we need for `Box` and `Vec`. Additionally, all unstable features are removed and / or replaced by stable ones. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 183 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index bd189d646adb..7cf89067b5fc 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -473,3 +473,186 @@ unsafe impl AsBytes for str {} // does not have any uninitialized portions either. unsafe impl AsBytes for [T] {} unsafe impl AsBytes for [T; N] {} + +/// A wrapper around a raw non-null `*mut T` that indicates that the posse= ssor +/// of this wrapper owns the referent. Useful for building abstractions li= ke +/// `Box`, `Vec`, `String`, and `HashMap`. +/// +/// Unlike `*mut T`, `Unique` behaves "as if" it were an instance of `T= `. +/// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies +/// the kind of strong aliasing guarantees an instance of `T` can expect: +/// the referent of the pointer should not be modified without a unique pa= th to +/// its owning Unique. +/// +/// If you're uncertain of whether it's correct to use `Unique` for your p= urposes, +/// consider using `NonNull`, which has weaker semantics. +/// +/// Unlike `*mut T`, the pointer must always be non-null, even if the poin= ter +/// is never dereferenced. This is so that enums may use this forbidden va= lue +/// as a discriminant -- `Option>` has the same size as `Unique<= T>`. +/// However the pointer may still dangle if it isn't dereferenced. +/// +/// Unlike `*mut T`, `Unique` is covariant over `T`. This should always= be correct +/// for any type which upholds Unique's aliasing requirements. +#[repr(transparent)] +pub struct Unique { + pointer: NonNull, + // NOTE: this marker has no consequences for variance, but is necessary + // for dropck to understand that we logically own a `T`. + // + // For details, see: + // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-gener= ic-drop.md#phantom-data + _marker: PhantomData, +} + +/// `Unique` pointers are `Send` if `T` is `Send` because the data they +/// reference is unaliased. Note that this aliasing invariant is +/// unenforced by the type system; the abstraction using the +/// `Unique` must enforce it. +unsafe impl Send for Unique {} + +/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they +/// reference is unaliased. Note that this aliasing invariant is +/// unenforced by the type system; the abstraction using the +/// `Unique` must enforce it. +unsafe impl Sync for Unique {} + +impl Unique { + /// Creates a new `Unique` that is dangling, but well-aligned. + /// + /// This is useful for initializing types which lazily allocate, like + /// `Vec::new` does. + /// + /// Note that the pointer value may potentially represent a valid poin= ter to + /// a `T`, which means this must not be used as a "not yet initialized" + /// sentinel value. Types that lazily allocate must track initializati= on by + /// some other means. + #[must_use] + #[inline] + pub const fn dangling() -> Self { + Unique { + pointer: NonNull::dangling(), + _marker: PhantomData, + } + } +} + +impl Unique { + /// Creates a new `Unique`. + /// + /// # Safety + /// + /// `ptr` must be non-null. + #[inline] + pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { + // SAFETY: the caller must guarantee that `ptr` is non-null. + unsafe { + Unique { + pointer: NonNull::new_unchecked(ptr), + _marker: PhantomData, + } + } + } + + /// Creates a new `Unique` if `ptr` is non-null. + #[allow(clippy::manual_map)] + #[inline] + pub fn new(ptr: *mut T) -> Option { + if let Some(pointer) =3D NonNull::new(ptr) { + Some(Unique { + pointer, + _marker: PhantomData, + }) + } else { + None + } + } + + /// Acquires the underlying `*mut` pointer. + #[must_use =3D "`self` will be dropped if the result is not used"] + #[inline] + pub const fn as_ptr(self) -> *mut T { + self.pointer.as_ptr() + } + + /// Dereferences the content. + /// + /// The resulting lifetime is bound to self so this behaves "as if" + /// it were actually an instance of T that is getting borrowed. If a l= onger + /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`. + /// + /// # Safety + /// + /// Safety requirements for this function are inherited from [NonNull:= :as_ref]. + /// + #[must_use] + #[inline] + pub const unsafe fn as_ref(&self) -> &T { + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a reference. + unsafe { self.pointer.as_ref() } + } + + /// Mutably dereferences the content. + /// + /// The resulting lifetime is bound to self so this behaves "as if" + /// it were actually an instance of T that is getting borrowed. If a l= onger + /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`. + /// + /// # Safety + /// + /// Safety requirements for this function are inherited from [NonNull:= :as_mut]. + #[must_use] + #[inline] + pub unsafe fn as_mut(&mut self) -> &mut T { + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a mutable reference. + unsafe { self.pointer.as_mut() } + } + + /// Casts to a pointer of another type. + #[must_use =3D "`self` will be dropped if the result is not used"] + #[inline] + pub fn cast(self) -> Unique { + Unique::from(self.pointer.cast()) + } + + /// Acquires the underlying `*mut` pointer. + #[must_use =3D "`self` will be dropped if the result is not used"] + #[inline] + pub const fn as_non_null(self) -> NonNull { + self.pointer + } +} + +impl Clone for Unique { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Unique {} + +impl From<&mut T> for Unique { + /// Converts a `&mut T` to a `Unique`. + /// + /// This conversion is infallible since references cannot be null. + #[inline] + fn from(reference: &mut T) -> Self { + Self::from(NonNull::from(reference)) + } +} + +impl From> for Unique { + /// Converts a `NonNull` to a `Unique`. + /// + /// This conversion is infallible since `NonNull` cannot be null. + #[inline] + fn from(pointer: NonNull) -> Self { + Unique { + pointer, + _marker: PhantomData, + } + } +} --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 00D45156F36; Mon, 5 Aug 2024 15:21: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=1722871264; cv=none; b=u6/1WgpLn3Z+uhR7wW2hMQtCOpVuP6myh2VK+oMlkuGfv8a4ss6+faBmUwl4rHeVQusUOte6u15xJJQJ0BYiqFu3cKsJOvwIaYheToszFmnQtMbYVm8GSBnjugE96Mx+W9kzrjChguxOFy5AuEnO+2sg/eIETrBddRSEQQs10f8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871264; c=relaxed/simple; bh=3qegzxF0CAqZElJOf/fc4vi4CYGZNhd1qrq8DwG4IkE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=knHOAVG5G9aDBOgSHgRMTEvq7kfTVuciC/0o/DcSpFVkpKeGoq3I1i18J0dnYsYe4QKZCgt6oImO1b/wq+ZYjRTkwwSxTroG/GEokRGZCU10F8t7+tSV22yJjE9Qsz242ojGlwDueU8WnGK/f0Ob+twC1xrhqmPo9lvhh5xlnzY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=ge0Xaxvi; 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="ge0Xaxvi" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 338F7C4AF0E; Mon, 5 Aug 2024 15:20:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871263; bh=3qegzxF0CAqZElJOf/fc4vi4CYGZNhd1qrq8DwG4IkE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ge0Xaxvikgpg6uiVTL9CSOEiG0ZMde5q5iorlV3mzzxtuB9522yCoHvEra9TMh/la i8InoGWDWVn2GqE5XkTEJk1g9s3cimELmk6kxrJ8JsfCTy2JerBeH1aQAIWoVLAqKY cj/13OE5hWdx/D7RDfa1t3m5N1w5efVQl8//szQZ6p4XpORhTzZB3vTSIQKR4kTX0s IXxjKV5jzUr3qWtDu5pibl0djk6NIDJZ3uinepRykeeaMX0cn1WVAegsNQAhJCYnYG vT6w/pPWtPrTUCdm0gBLYBeCX+5C/JZUPmtJHb1YFE8jHacqc01fV6WEoxqButYT50 UCtNC59Ebnz3A== 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, acurrid@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 v4 09/28] rust: alloc: implement kernel `Box` Date: Mon, 5 Aug 2024 17:19:28 +0200 Message-ID: <20240805152004.5039-10-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable `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 --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 330 ++++++++++++++++++++++++++++++++++++++ rust/kernel/init.rs | 35 +++- rust/kernel/prelude.rs | 2 +- rust/kernel/types.rs | 56 +++++++ 5 files changed, 427 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 942e2755f217..d7beaf0372af 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..4a4379980745 --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +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::result::Result; + +use crate::types::Unique; + +/// The kernel's [`Box`] type. +/// +/// `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`. +/// +/// For non-zero-sized values, a [`Box`] will use the given allocator `A` = for its allocation. For +/// the most common allocators the type aliases `KBox`, `VBox` and `KVBox`= exist. +/// +/// It is valid to convert both ways between a [`Box`] and a raw pointer a= llocated with any +/// `Allocator`, given that the `Layout` used with the allocator is correc= t for the type. +/// +/// For zero-sized values the [`Box`]' pointer must be `dangling_mut::`= ; no memory is allocated. +/// +/// So long as `T: Sized`, a `Box` is guaranteed to be represented as a= single pointer and is +/// also ABI-compatible with C pointers (i.e. the C type `T*`). +/// +/// # Invariants +/// +/// The [`Box`]' pointer always properly aligned and either points to memo= ry allocated with `A` or, +/// for zero-sized types, is a dangling pointer. +/// +/// # Examples +/// +/// ``` +/// let b =3D KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// struct Huge([u8; 1 << 24]); +/// +/// assert!(KVBox::::new_uninit(GFP_KERNEL).is_ok()); +/// ``` +pub struct Box(Unique, 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; + +impl Box +where + T: ?Sized, + A: Allocator, +{ + /// Constructs a `Box` from a raw pointer. + /// + /// # Safety + /// + /// `raw` must point to valid memory, previously allocated with `A`, a= nd at least the size of + /// type `T`. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // SAFETY: Validity of `raw` is guaranteed by the safety precondit= ions of this function. + Self(unsafe { Unique::new_unchecked(raw) }, PhantomData::) + } + + /// Consumes the `Box`, returning a wrapped raw pointer. + /// + /// # 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`, returning a mutable reference, &'= a mut T. + #[inline] + pub fn leak<'a>(b: Self) -> &'a mut T + where + T: 'a, + { + // 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) } + } + + /// Converts a `Box` into a `Pin>`. + #[inline] + pub fn into_pin(b: Self) -> Pin + where + A: 'static, + { + // SAFETY: It's not possible to move or replace the insides of a `= Pin>` when + // `T: !Unpin`, so it's safe to pin it directly without any additi= onal requirements. + unsafe { Pin::new_unchecked(b) } + } +} + +impl Box, A> +where + A: Allocator, +{ + /// Converts to `Box`. + /// + /// # Safety + /// + /// As with MaybeUninit::assume_init, it is up to the caller to guaran= tee that the value really + /// is in an initialized state. Calling this when the content is not y= et fully initialized + /// causes immediate undefined behavior. + pub unsafe fn assume_init(b: Self) -> Box { + let raw =3D Self::into_raw(b); + // SAFETY: Reconstruct the `Box, A>` as Box n= ow that has been + // initialized. `raw` and `alloc` are safe by the invariants of `B= ox`. + unsafe { Box::from_raw(raw as *mut T) } + } + + /// Writes the value and converts to `Box`. + pub fn write(mut b: Self, value: T) -> Box { + (*b).write(value); + // SAFETY: We've just initialized `boxed`'s value. + unsafe { Self::assume_init(b) } + } +} + +impl Box +where + A: Allocator, +{ + fn is_zst() -> bool { + core::mem::size_of::() =3D=3D 0 + } + + /// Allocates memory with the allocator `A` and then places `x` into i= t. + /// + /// This doesn=E2=80=99t actually allocate if T is zero-sized. + pub fn new(x: T, flags: Flags) -> Result { + let b =3D Self::new_uninit(flags)?; + Ok(Box::write(b, x)) + } + + /// Constructs a new `Box` with uninitialized contents. + /// + /// # 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() { + Unique::dangling() + } else { + let layout =3D core::alloc::Layout::new::>(); + let ptr =3D A::alloc(layout, flags)?; + + ptr.cast().into() + }; + + Ok(Box(ptr, PhantomData::)) + } + + /// Constructs a new `Pin>`. If `T` does not implement [`Unp= in`], then `x` will be + /// pinned in memory and unable to be moved. + #[inline] + pub fn pin(x: T, flags: Flags) -> Result>, AllocError> + where + A: 'static, + { + Ok(Self::new(x, flags)?.into()) + } + + /// 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 Box::into_raw(this); + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { core::ptr::drop_in_place(ptr) }; + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { Box::from_raw(ptr.cast()) } + } +} + +impl From> for Pin> +where + T: ?Sized, + A: Allocator, + A: 'static, +{ + /// Converts a `Box` into a `Pin>`. If `T` does not implemen= t [`Unpin`], then + /// `*boxed` will be pinned in memory and unable to be moved. + /// + /// This conversion does not allocate on the heap and happens in place. + /// + /// This is also available via [`Box::into_pin`]. + /// + /// Constructing and pinning a `Box` with >>::from([= Box::new]\(x)) + /// can also be written more concisely using [Box::pin]\(x). + /// This `From` implementation is useful if you already have a `Box= `, or you are + /// constructing a (pinned) `Box` in a different way than with [`Box::= new`]. + fn from(b: Box) -> Self { + Box::into_pin(b) + } +} + +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 ptr =3D self.0.as_ptr(); + + // SAFETY: `ptr` is always properly aligned, dereferenceable and p= oints to an initialized + // instance of `T`. + let size =3D unsafe { core::mem::size_of_val(&*ptr) }; + + // SAFETY: We need to drop `self.0` in place, before we free the b= acking memory. + unsafe { core::ptr::drop_in_place(ptr) }; + + if size !=3D 0 { + // SAFETY: `ptr` was previously allocated with `A`. + unsafe { A::free(self.0.as_non_null().cast()) }; + } + } +} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 495c09ebe3a3..5fd7a0ffabd2 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! =20 use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{box_ext::BoxExt, AllocError, Allocator, Flags}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -1178,6 +1178,39 @@ fn try_init(init: impl Init, flags: Flags) = -> Result } } =20 +impl InPlaceInit for crate::alloc::Box +where + A: Allocator + 'static, +{ + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + let mut this =3D crate::alloc::Box::<_, A>::new_uninit(flags)?; + let slot =3D this.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 { crate::alloc::Box::assume_init(this) }.into()) + } + + #[inline] + fn try_init(init: impl Init, flags: Flags) -> Result + where + E: From, + { + let mut this =3D crate::alloc::Box::<_, A>::new_uninit(flags)?; + let slot =3D this.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 { crate::alloc::Box::assume_init(this) }) + } +} + impl InPlaceInit for UniqueArc { #[inline] fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index b37a0b3180fb..39f9331a48e2 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}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 7cf89067b5fc..9fe87528d129 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,6 +2,7 @@ =20 //! Kernel types. =20 +use crate::alloc::Allocator; use crate::init::{self, PinInit}; use alloc::boxed::Box; use core::{ @@ -9,6 +10,7 @@ marker::{PhantomData, PhantomPinned}, mem::MaybeUninit, ops::{Deref, DerefMut}, + pin::Pin, ptr::NonNull, }; =20 @@ -89,6 +91,60 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) ->= Self { } } =20 +impl ForeignOwnable for crate::alloc::Box +where + A: Allocator, +{ + type Borrowed<'a> =3D &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + crate::alloc::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 { crate::alloc::Box::from_raw(ptr as _) } + } +} + +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. + crate::alloc::Box::into_raw(unsafe { Pin::into_inner_unchecked(sel= f) }) 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(crate::alloc::Box::from_raw(ptr as _))= } + } +} + impl ForeignOwnable for () { type Borrowed<'a> =3D (); =20 --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 324B915B132; Mon, 5 Aug 2024 15:21:09 +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=1722871269; cv=none; b=CNdLt2ABITdDaFbwB4A2Qc8FWxHulNjB9ApiCTwjFTWWoP23Rv31yTXEsI4xEidZEsIZC516Tx/FjcTb4qXObxSD/dhq24Z71cZTuDBHtP5qG+GgI5yr+C+YZvgVRlT43HFd14Js4otScdLN5lfzHZcyKWIRmR0/UqQBGRdWQ9o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871269; c=relaxed/simple; bh=udM8gowoRtDWYZ1bTx/TqIq3PTvtL9tWCZwGcw+omGE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=c1QDkErJ6gemkoLTYQP1m7jR4nL5+LGRkoigzjnQtWrFhvtyoRuRoNqMuVqVA0Gyz7nL6w3e1q+ngBZKYrOMNmW6SIehiaG936sFIdi/HmoWNPBJrMPvG+9+EeZO+V9LwXEdTEdAyJipSaBAKBzY+7edjtok2YdY8rDoQTKGRHw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=GUwMSH70; 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="GUwMSH70" Received: by smtp.kernel.org (Postfix) with ESMTPSA id F1FACC4AF0B; Mon, 5 Aug 2024 15:21:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871269; bh=udM8gowoRtDWYZ1bTx/TqIq3PTvtL9tWCZwGcw+omGE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GUwMSH70agnUMAzx7yZkpnGV4nptO10VaFFsLrPUEo9muwql4SwsID1SRHjtqdjMT C44glyquZiQp/db1l0+rW8SwTL6hem0dQpXoLkSjdfwasdSOPx2zRyMnucGMEUdMZ6 64Nf/2sdgn00efWpO0BVhpmfdsJ2NMwIm2i0fBCzjkNh5DW3om4T5jcwKvijE10OaQ EPn6zcLNOndnIfh+c1sxOm48LB4p3c5Cb8I51bP+1bfI7PN7U5+Mk9HJfALEMwFw4q ZeSCHRQVX0HjkDQfYXUKmdelOG/CqxM0abj+OxoE1iAf/wpahqkSn7UDJnSD8oA4zl xO3c+2zA5e6Aw== 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, acurrid@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 v4 10/28] rust: treewide: switch to our kernel `Box` type Date: Mon, 5 Aug 2024 17:19:29 +0200 Message-ID: <20240805152004.5039-11-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/init.rs | 41 ++++++++++++++++--------------- rust/kernel/init/__internal.rs | 2 +- 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 +++++++-------- 7 files changed, 44 insertions(+), 44 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 5fd7a0ffabd2..b3159eb1eb02 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -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, Allocator, Flags}, + alloc::{box_ext::BoxExt, AllocError, Allocator, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -297,7 +297,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -306,7 +306,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)?, /// })); @@ -323,7 +323,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -332,7 +332,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)?, /// })); @@ -391,7 +391,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. @@ -461,7 +461,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: @@ -593,7 +593,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, /// } @@ -601,7 +601,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) @@ -693,16 +693,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) /// } @@ -825,7 +825,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, @@ -924,7 +924,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, @@ -1008,8 +1008,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( @@ -1349,7 +1350,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 db3372619ecd..dfb2204918c7 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/sync/arc.rs b/rust/kernel/sync/arc.rs index 3673496c2363..b5c84995d7d2 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -16,13 +16,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}, error::{self, Error}, init::{self, InPlaceInit, Init, PinInit}, try_init, types::{ForeignOwnable, Opaque}, }; -use alloc::boxed::Box; use core::{ alloc::Layout, fmt, @@ -203,11 +202,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 /// Use the given initializer to in-place initialize a `T`. @@ -422,8 +421,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())) }; } } } @@ -668,7 +667,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) = }), @@ -678,8 +677,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) }; --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 F401F158DD2; Mon, 5 Aug 2024 15:21: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=1722871275; cv=none; b=e++Pxan6FOp7aXgvR1Lr7tLCliPNhB77DqcxH5s2W7DFMP5vy6+X//KF6eYL2zMPRjE3O57Wbz6kyCuyZ/yVUwnAKRNBig5bVHzWEEyZShZFfPu7w75fiOscdk39U4VvOp+bayjozBsNEs3nwOGCySKAT8Ygx4CaIa9dN3UDWYQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871275; c=relaxed/simple; bh=A4qZq0jLBGmSr7W8ys6nCHz+lSRSI4/dq4nSwiqm/08=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=B/YyaiopsJ6z44Fh+uqpBfEE8QrVR3JEpfO9gYsDX7CBlZgLk2S2BnlXVLpaJ8P8nl1fA98KiaRjH4Hj69dCaq9myuPLD5SXxMKSMtw1rRyVlSUP4wNLFj4oIUc7xNPFz7hfgdgQ3/5SZRXB8plch5p+LVAz7cTjP2BT9VySvG0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=kZTuri7Q; 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="kZTuri7Q" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 82AD8C32782; Mon, 5 Aug 2024 15:21:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871274; bh=A4qZq0jLBGmSr7W8ys6nCHz+lSRSI4/dq4nSwiqm/08=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=kZTuri7Q9pVK1y336Rl+9BIudUi4Dtxb/4ueoJsMygn/Qz1UmoueAnLaQ1E+2sAuM 6oqjcTTXrSUYNa51oCpWuWi+hfQpB+GuoemZy1HgkSaH0wYq0x4J99m0urEdClI+LH EY53DYm9XTRkQXtkfI6IfByOK+ayHdZ+Wi6gJNlIDrLgmj9AfNDeemuPH0s4z6qHYV NgXmFBdx7MfhsmfkQ4nqJQhj51B/7w487MhEMBGnrsqxunuJ8QTZdEtFU5tpArnPo5 s9/W8DYH+oz5876dvkSxyl8WU44lxGVZpi0GEF8RSL9u8MvujKq25qCcpTp9aLE4La YQvQAMPOHV6GA== 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, acurrid@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 v4 11/28] rust: alloc: remove `BoxExt` extension Date: Mon, 5 Aug 2024 17:19:30 +0200 Message-ID: <20240805152004.5039-12-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 56 ------------------------------------ rust/kernel/init.rs | 34 +--------------------- rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +-- rust/kernel/types.rs | 23 --------------- 6 files changed, 3 insertions(+), 116 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index d7beaf0372af..f578175ff010 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 829cb1c1cf9e..000000000000 --- a/rust/kernel/alloc/box_ext.rs +++ /dev/null @@ -1,56 +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; - -/// 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>; -} - -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) }) - } -} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index b3159eb1eb02..ae533305d40e 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,12 +211,11 @@ //! [`pin_init!`]: crate::pin_init! =20 use crate::{ - alloc::{box_ext::BoxExt, AllocError, Allocator, Flags, KBox}, + alloc::{AllocError, Allocator, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, }; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, convert::Infallible, @@ -589,7 +588,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1149,36 +1147,6 @@ fn init(init: impl Init, flags: Flags) -> e= rror::Result } } =20 -impl InPlaceInit for Box { - #[inline] - fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> - where - E: From, - { - let mut this =3D as BoxExt<_>>::new_uninit(flags)?; - let slot =3D this.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 { this.assume_init() }.into()) - } - - #[inline] - fn try_init(init: impl Init, flags: Flags) -> Result - where - E: From, - { - let mut this =3D as BoxExt<_>>::new_uninit(flags)?; - let slot =3D this.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 { this.assume_init() }) - } -} - impl InPlaceInit for crate::alloc::Box where A: Allocator + 'static, diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 274bdc1b0a82..042f05c45214 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 39f9331a48e2..a8018ef2e691 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 9fe87528d129..b80a3b2b62ac 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -4,7 +4,6 @@ =20 use crate::alloc::Allocator; use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, @@ -69,28 +68,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 crate::alloc::Box where A: Allocator, --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 5DA29158DD2; Mon, 5 Aug 2024 15:21: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=1722871280; cv=none; b=t/l0bFTD0Q2pVpYc1PcM2GYE9/CLThOrAGYLs15dYTXd+qE7qeT/BSNvwIwdslAA3dKjK/aWMWkWAOMCqIJJO2E3Jt90LC8s7R3279wPluum2tY9IcBK4+rOKsc9bCCVb5deLawYEn5NUUTZvfyiQfIdFp2YA3yTpfrNbi0TWEc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871280; c=relaxed/simple; bh=Z6ThON8OGnmMolEbvMDlA1wqJrU2Ykqt5/dZHEIEb08=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=iTD17ah0X/bkgavZZfMCi0U7U7l4v3VdfhUeuEVuCw8pU05w+fpfzlXadoljcgLBbWPIRI3ZAH1SCppxOFCTCHs9ZHCRRu/n/vFDnEpEKtWwvSIgL9pcEiiklU3RqRHtkVimPWT3Jkiw0AJgoF1APiwmUG8Gotp6Fqz6srZAXak= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=FbMFBnAD; 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="FbMFBnAD" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1BAE4C4AF0E; Mon, 5 Aug 2024 15:21:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871280; bh=Z6ThON8OGnmMolEbvMDlA1wqJrU2Ykqt5/dZHEIEb08=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=FbMFBnAD+ONdyGOCxHDO68tIE5VH0ljFw7qk6sCE9LKSrEA9wwnt9OIhcQRVytJey UkxpPeVw0PTJpMDao+P/27nZDKGuWL5G1UOMe1vxrWCZFO5GYBJLtb5Jb/IGJu0iP2 b6ROc0rutdvuGbgr3jbmz2vlcc1+Ast709UwwCvlgC2BCs1dNiaFTyVHl/v3ViRxfT R7Wzps/B4vwrPUcspPvb1M3ze8H32abAV3r8+mHhsT2GuJ2MVXLrkcpXgEGIRZjKb2 f3b1nXbEbbNUpBurUduGALmQ/3efASeaPucqbUSzzSpWmBigo9rJ9fY5VCA2pvpoWJ QQsKOCQ12WosQ== 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, acurrid@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 v4 12/28] rust: alloc: add `Box` to prelude Date: Mon, 5 Aug 2024 17:19:31 +0200 Message-ID: <20240805152004.5039-13-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- 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 a8018ef2e691..6bf77577eae7 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 DDA68159217; Mon, 5 Aug 2024 15:21:25 +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=1722871286; cv=none; b=j2ywWnKoHlvXBM1f+hgqewNiPessN5o+3YgFrXTjjLJie9l57m6dRsrYVAdOaKOuQkva6BSCOO3y5+BYjorAyipHRwxqUsSl92kNpZMlaCvtvkV8pel6SBwZ4QosiEGrfyu794E9W7HgLiCDNf7iky+B9TApMsQP67bN0bcwTrs= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871286; c=relaxed/simple; bh=pVB6WWQkYTknQoh+SglRWl5bEx9KaiouK24Dn9ENpJE=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=kDZ77P5spUjA3Q4mw0JBJEKf1w8I3MZOx2K+OuNMe+OsN3W8j/yU1W/+VuQISZGMZT5wRlsxuRelQsDy1TIqZvP2wvDkc9c2/74g12ncBJLOB6AFzaUmFjB88cR4A2PyuoxL9bWAl6yMvusluLrreHNDFFuJHq6+8rXDme4vNLc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=DQYjAm2s; 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="DQYjAm2s" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A8145C32782; Mon, 5 Aug 2024 15:21:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871285; bh=pVB6WWQkYTknQoh+SglRWl5bEx9KaiouK24Dn9ENpJE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DQYjAm2sn0N6rVEH3rEmI88pOgI8cRwdDI2RVbhONdO8s774rHc+/ZyM38gA+TMDz O/mocm5GbuEzpZg9UYh4Uwo3tfa9QKVP5kxgGdwkxx/2Hvom/KgwaRf5pVIRcDUZ/N YtdkmL3LWu/gXveCzX1gQHv6V1pHg1AJwxZ+Njgnuq8lvmWDSetGbAcqgsArJAmgrN Q8O7wXU6pwrOYxUmXiKZFxHufxGJ7Vl3EHSde2TIC27WBazAjWKa7npwrVpWmxmqtq Sti3WOICk5Z7VUtMscEnq3sH83gFrz8TCDCqC8vn5tEk/WU2R4Ti+ANG/IvBqcYkAL sVr3GPTAsR56Q== 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, acurrid@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 v4 13/28] rust: alloc: import kernel `Box` type in types.rs Date: Mon, 5 Aug 2024 17:19:32 +0200 Message-ID: <20240805152004.5039-14-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 types.rs, add the new kernel `Box` type instead. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index b80a3b2b62ac..25761da5a816 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,7 +2,7 @@ =20 //! Kernel types. =20 -use crate::alloc::Allocator; +use crate::alloc::{Allocator, Box}; use crate::init::{self, PinInit}; use core::{ cell::UnsafeCell, @@ -68,14 +68,14 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_voi= d) -> Option { } } =20 -impl ForeignOwnable for crate::alloc::Box +impl ForeignOwnable for Box where A: Allocator, { type Borrowed<'a> =3D &'a T; =20 fn into_foreign(self) -> *const core::ffi::c_void { - crate::alloc::Box::into_raw(self) as _ + Box::into_raw(self) as _ } =20 unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { @@ -89,11 +89,11 @@ unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> = &'a T { 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 { crate::alloc::Box::from_raw(ptr as _) } + unsafe { Box::from_raw(ptr as _) } } } =20 -impl ForeignOwnable for Pin> +impl ForeignOwnable for Pin> where A: Allocator, { @@ -101,7 +101,7 @@ impl ForeignOwnable for Pin> =20 fn into_foreign(self) -> *const core::ffi::c_void { // SAFETY: We are still treating the box as pinned. - crate::alloc::Box::into_raw(unsafe { Pin::into_inner_unchecked(sel= f) }) as _ + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ } =20 unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { @@ -118,7 +118,7 @@ unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> = Pin<&'a T> { 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(crate::alloc::Box::from_raw(ptr as _))= } + unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } } } =20 --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 6DD7A159217; Mon, 5 Aug 2024 15:21: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=1722871291; cv=none; b=fyZ3vw3rm1GetPg/DlEEm28ldN0xh+3CVmnLwPwWfVgJNh7Q9cta1Si88/t6Lo4PYblfwTYwCP3b7j5sN6kZu7ekkks1sI7RhvVSD/7UeLRNvCNqyOB7Az36t9u1neAqpUjUpwUekvZz+vfiDK62h8Mrik3xjk4kVW1d2CKUOeQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871291; c=relaxed/simple; bh=Lu3sR+WGYMF1UUYzfkZ9j2xNETNWcnAc7sJFrR4A4JQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=EWg4z7/AhpoL7QmdTke93uaijlOofqG7ZQifEbfsI1VFt2AbZn0Q3AiH/0IOnZW0UGyohkf/jBgrBOsZBdVzeXOpc1ox5RBelOhpIFLC8CDWChtZEX5ZKnnpD0RrjngOMwo2DXi63BHkrRYy3BESNMKeL+1jFQTtwbNcgy/erkk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=O1oXHRoz; 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="O1oXHRoz" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 37E80C4AF0C; Mon, 5 Aug 2024 15:21:26 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871291; bh=Lu3sR+WGYMF1UUYzfkZ9j2xNETNWcnAc7sJFrR4A4JQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=O1oXHRozCxElqWOZx7zUrpBUJXCIC5CrgbAKeFrqcKlcOBNs9+XpKdfy265PO/e2n 0GUo+PujPXsi41M3hy94E7O07PgxZUBhl0OgrkJ0S6nULlWzvpKrgUIEBg0GWG7nJL E3mn/JFadLIHEbOEsL3MQWJ3IdCYLT0JfGQ6cj5mhTUxBnpdtJ14VGxCnUZRyUb4If 1HQONpQID/uAQoBZH93bhl3KmSVoVKgO5rLNsLNr5bwE8QvS1oMqiE/Xmuofhnq0fD vmMbWClGaZPm9KtavkN4Jyq2LQxp6+IOqM/891vzyrtx2CP/fH8mwZGZny4FXDatGR UEkMf7445vvKw== 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, acurrid@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 v4 14/28] rust: alloc: import kernel `Box` type in init.rs Date: Mon, 5 Aug 2024 17:19:33 +0200 Message-ID: <20240805152004.5039-15-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 init.rs, add the new kernel `Box` type instead. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/init.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index ae533305d40e..350582662964 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! =20 use crate::{ - alloc::{AllocError, Allocator, Flags, KBox}, + alloc::{AllocError, Allocator, Box, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -1147,7 +1147,7 @@ fn init(init: impl Init, flags: Flags) -> er= ror::Result } } =20 -impl InPlaceInit for crate::alloc::Box +impl InPlaceInit for Box where A: Allocator + 'static, { @@ -1156,13 +1156,13 @@ fn try_pin_init(init: impl PinInit, flags:= Flags) -> Result, where E: From, { - let mut this =3D crate::alloc::Box::<_, A>::new_uninit(flags)?; + let mut this =3D Box::<_, A>::new_uninit(flags)?; let slot =3D this.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 { crate::alloc::Box::assume_init(this) }.into()) + Ok(unsafe { Box::assume_init(this) }.into()) } =20 #[inline] @@ -1170,13 +1170,13 @@ fn try_init(init: impl Init, flags: Flags)= -> Result where E: From, { - let mut this =3D crate::alloc::Box::<_, A>::new_uninit(flags)?; + let mut this =3D Box::<_, A>::new_uninit(flags)?; let slot =3D this.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 { crate::alloc::Box::assume_init(this) }) + Ok(unsafe { Box::assume_init(this) }) } } =20 --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 5783115B995; Mon, 5 Aug 2024 15:21: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=1722871297; cv=none; b=MQDrp7tBWSG7G8OjA4p7IQu07GHbzJ2fvZ0NLXFkPfMUIdNi8luSM6fv/ABLV0+sfJF0lQIS3k07h0pTu3GUWiAFiur0XFRCbM6OZP+r03U8ZnfzT+4He/2KFueNnmvPIY0Zd5S6eitaL6V+n1P4PyVS6QmH8RmlppNZNcvrXPc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871297; c=relaxed/simple; bh=cr1cmTv5QS3td1mUWLd800K7nmZjFcH5mHeUUy9c9lA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=TBbpLnKTDY8HWBdBgybkzUB0Qb/DIEQcBix9Z+qLNv3QJQ4zlp9WSCNZ4q7YK/LDvhK6dW2h66cI2rG6XqxqK1rX9OctBHDklydfw+Nx6jkr/sFfhwS7zXcp/A6cQjOI/s5jx4gZUKXDgu4+XaPxO6RTEAru/Vl4hi0C7BCI8l8= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=l4TJfxzS; 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="l4TJfxzS" Received: by smtp.kernel.org (Postfix) with ESMTPSA id BF289C4AF0C; Mon, 5 Aug 2024 15:21:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871296; bh=cr1cmTv5QS3td1mUWLd800K7nmZjFcH5mHeUUy9c9lA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=l4TJfxzSrnWuBELuNzaXCR3jG4s6NRrfF4HaaoCv6cm1XmnJxVQakLiCZ6KbqQVCd 99iquM1lCTXB2mBYWf8dsl8jFzGclMZN93MfrADoZ53qy1qe21aatiT+sFe/AY2PLh +0NxNBgwbyeEwncwLs52xo97Pu//mQwfGguTZ7dyZUqSN5A/J6XoADAjblK3XOHoTd zG10MQf1UeAgqLTUoi2BJkolHmDeanktLVSyxTZLeWGJoDYzIBYQmvZErz2U7X6OTd dJt33WTRlT2+0QYwAbgd0x2Z2T3hGlbvzrVin/GxXr63bLmXkX16ibLR94JZx8hZK8 CclNjOl0oGTJQ== 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, acurrid@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 v4 15/28] rust: alloc: implement kernel `Vec` type Date: Mon, 5 Aug 2024 17:19:34 +0200 Message-ID: <20240805152004.5039-16-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable `Vec` provides a contiguous growable array type (such as `Vec`) with contents allocated with the kernel's allocators (e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`). In contrast to Rust's `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/kbox.rs | 16 +- rust/kernel/alloc/kvec.rs | 591 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 4 files changed, 613 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index f578175ff010..28c186906e1b 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/kbox.rs b/rust/kernel/alloc/kbox.rs index 4a4379980745..02aae24edda8 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -2,7 +2,7 @@ =20 //! Implementation of [`Box`]. =20 -use super::{AllocError, Allocator, Flags}; +use super::{AllocError, Allocator, Flags, Vec}; use core::fmt; use core::marker::PhantomData; use core::mem::ManuallyDrop; @@ -150,6 +150,20 @@ pub fn into_pin(b: Self) -> Pin } } =20 +impl Box<[T; N], A> +where + A: Allocator, +{ + /// Convert a `Box<[T, N], A>` to a `Vec`. + pub fn into_vec(b: Self) -> Vec { + let len =3D b.len(); + unsafe { + let ptr =3D Self::into_raw(b); + Vec::from_raw_parts(ptr as _, len, len) + } + } +} + impl Box, A> where A: Allocator, diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs new file mode 100644 index 000000000000..6cf62e7dd36f --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,591 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{AllocError, Allocator, Flags}; +use crate::types::Unique; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + 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([$($x),+], GFP_KERNEL) { + Ok(b) =3D> Ok($crate::alloc::KBox::into_vec(b)), + 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` 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 +/// +/// The [`Vec`] backing buffer's pointer always properly aligned and eithe= r points to memory +/// allocated with `A` or, for zero-sized types, is a dangling pointer. +/// +/// The length of the vector always represents the exact number of element= s stored in the vector. +/// +/// The capacity of the vector always represents the absolute number of el= ements that can be stored +/// within the vector without re-allocation. However, it is legal for the = backing buffer to be +/// larger than `size_of` times the capacity. +/// +/// The `Allocator` of the vector is the exact allocator the backing buffe= r was allocated with (and +/// must be freed with). +pub struct Vec { + ptr: Unique, + /// 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; + +impl Vec +where + A: Allocator, +{ + #[inline] + fn is_zst() -> bool { + core::mem::size_of::() =3D=3D 0 + } + + /// Returns the total number of elements the vector can hold without + /// reallocating. + pub fn capacity(&self) -> usize { + if Self::is_zst() { + usize::MAX + } else { + self.cap + } + } + + /// Returns the number of elements in the vector, also referred to + /// as its 'length'. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forces the length of the vector to new_len. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity()`]. + /// - The elements at `old_len..new_len` must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + self.len =3D new_len; + } + + /// Extracts a slice containing the entire vector. + /// + /// Equivalent to `&s[..]`. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Extracts a mutable slice of the entire vector. + /// + /// Equivalent to `&mut s[..]`. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + /// Returns an unsafe mutable pointer to the vector's buffer, or a dan= gling + /// raw pointer valid for zero sized reads if the vector didn't alloca= te. + #[inline] + pub fn as_mut_ptr(&self) -> *mut T { + self.ptr.as_ptr() + } + + /// Returns a raw pointer to the slice's buffer. + #[inline] + pub fn as_ptr(&self) -> *const T { + self.as_mut_ptr() + } + + /// Returns `true` if the vector contains no elements. + /// + /// # 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 + } + + /// Constructs a new, empty Vec. + /// + /// This method does not allocate by itself. + #[inline] + pub const fn new() -> Self { + Self { + ptr: Unique::dangling(), + cap: 0, + len: 0, + _p: PhantomData::, + } + } + + /// Returns the remaining spare capacity of the vector as a slice of + /// `MaybeUninit`. + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // 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( + self.as_mut_ptr().add(self.len) as *mut MaybeUninit, + 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)?; + 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(()) + } + + /// 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: 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(()) + } + + /// Creates a Vec directly from a pointer, a length, a capacity,= and an allocator. + /// + /// # Safety + /// + /// This is highly unsafe, due to the number of invariants that aren= =E2=80=99t checked: + /// + /// - `ptr` must be currently allocated via the given allocator `A`. + /// - `T` needs to have the same alignment as what `ptr` was allocated= with. (`T` having a less + /// strict alignment is not sufficient, the alignment really needs t= o be equal to satisfy the + /// `dealloc` requirement that memory must be allocated and dealloca= ted with the same layout.) + /// - The size of `T` times the `capacity` (i.e. the allocated size in= bytes) needs to be + /// smaller or equal the size the pointer was allocated with. + /// - `length` needs to be less than or equal to `capacity`. + /// - The first `length` values must be properly initialized values of= type `T`. + /// - The allocated size in bytes must be no larger than `isize::MAX`.= See the safety + /// documentation of `pointer::offset`. + /// + /// It is also valid to create an empty `Vec` passing a dangling point= er for `ptr` and zero for + /// `cap` and `len`. + /// + /// # 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>(()) + /// ``` + 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 { Unique::new_unchecked(ptr) }, + cap, + len: length, + _p: PhantomData::, + } + } + + /// Decomposes a `Vec` into its raw components: (`pointer`, `len= gth`, + /// `capacity`). + pub fn into_raw_parts(self) -> (*mut T, usize, usize) { + let 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 SZTs, we can't go = higher. + return Err(AllocError); + } + + // We know `cap` is <=3D `isize::MAX` because of it's type invaria= nt. 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.as_non_null().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().into(); + + // 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> { + 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.reserve` not bailing out with an error guarantees= that we're not + // exceeding the capacity of this `Vec`. + 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.as_non_null().cast()) }; + } + } +} + +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 $(where $ty:ty: $bound:ident)?) =3D> { + impl PartialEq<$rhs> for $lhs + where + T: PartialEq, + $($ty: $bound)? + { + #[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 6bf77577eae7..bb80a43d20fb 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 88EF71662E2; Mon, 5 Aug 2024 15:21: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=1722871302; cv=none; b=DffwVDrDbOWraSAuNl1jha80yR7xOpUC3GF4zv5qPy4tSONln3r8QhYD7Avjk/y7GLJYcT3MDbgMRaDY7hgGqOkFlHJeLNjFQqD6TqpbkrxU+I6+HxTINBfn6/VY9kx6qBpgUtPN5kuhIaHxlbIZAPmtlnfmBOWpYP6iWjmthYE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871302; c=relaxed/simple; bh=EOv825N2AZNtDITSBB60LhXsn2pwxBz/HyLjwhp7xNk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=kkhm08kSjX2OQVbW4mquURY6jQPoh8IXLoWVEt0QoGFrED+JtOpMENvcS2IrYxaYxcCesUFeZ9OnK2UrH6wR7h7+SWJoDrnlcGON2+yDcymFGxI5e82qye7MdCU7mr4ImiDuRxNq+AWWuf7AR3buDLfQcp3KV13d4xFD/NMxTSQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=gYzOyUPG; 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="gYzOyUPG" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5138BC4AF0E; Mon, 5 Aug 2024 15:21:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871302; bh=EOv825N2AZNtDITSBB60LhXsn2pwxBz/HyLjwhp7xNk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=gYzOyUPGGvzsiMCuH+V0ldzMfE7hiGbdGKAbK0Tqa6euhkVivoi0+hDENWQHThRWX 2w3a6tls/UCFaVEKHsLRO/Q6FcpFslG5N1YkJRZedT/KojKDdDCeuiEd/Xq5ddWU6r /Iis8UdRt68YDCxh1Agab0XRwfReNwszxWXPVnUoxXuigGnHnZa2i985IhIIqWqtTM UzhIiI6lhVyQ8iLU3RHkQAsSZlfUwQ/7VGf5ejaE1bFFHRvERoofuYrFSFeCxqkNFe 1vesmYCILN1fNzoBV69DgiNt2r/AcfQyaEAz3pCUSha/OFhcumt5MJUu+VIjUPcpv+ 4TBxhXiqojWPQ== 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, acurrid@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 v4 16/28] rust: alloc: implement `IntoIterator` for `Vec` Date: Mon, 5 Aug 2024 17:19:35 +0200 Message-ID: <20240805152004.5039-17-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 186 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 187 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 28c186906e1b..86648037b3dc 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 6cf62e7dd36f..51426e0b28e0 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -12,6 +12,8 @@ ops::DerefMut, ops::Index, ops::IndexMut, + ptr, + ptr::NonNull, slice, slice::SliceIndex, }; @@ -589,3 +591,187 @@ 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 that moves out of a vector. +/// +/// This `struct` is created by the `into_iter` method on [`Vec`] (provide= d 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 ptr =3D self.ptr; + if !Vec::::is_zst() { + // SAFETY: We can't overflow; `end` is guaranteed to mark the = end of the buffer. + unsafe { self.ptr =3D self.ptr.add(1) }; + } else { + // For ZST `ptr` has to stay where it is to remain aligned, so= we just reduce `self.len` + // by 1. + } + self.len -=3D 1; + + // SAFETY: `ptr` is guaranteed to point at a valid element within = the buffer. + Some(unsafe { ptr.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: Drop the remaining vector's elements in place, before w= e free the backing + // memory. + 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; + + /// Creates a consuming iterator, that is, one that moves each value o= ut of + /// the vector (from start to end). The vector cannot be used after ca= lling + /// this. + /// + /// # 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 6F2DF15C131; Mon, 5 Aug 2024 15:21: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=1722871308; cv=none; b=orAI72nRLiEXfFttbAGos/RD38C0sN/U9naGVjDNiVzqlQDr7QHC1OY4aXqNkx3AUCM+7QNplbja6pHhpPOPs9C/RgVaqAg4jKf9A1MTA63iyuUYHMTFZ2CVjy8YjqaTWRI9aCFGDlG7QfMDXRoKrgcbBpVrNugPnetDIdxffNY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871308; c=relaxed/simple; bh=XOcjCrkdVgWqenxc2S4POpPouyHf3iALRM/oI15aNRQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=RXZjqv8NHAv0Igw4sIYqWkj9t7ZHSIefqFTGuzZqk+3DdHuoFhLB6Y1cyzjyg65I3fYHMcFtGqvG51BTmuTD69jlmuhRUxIICGMJbmk9lUe2FlRbRniXudM/fl/NcfBNO5QwOCDBMezi3/gmvjH9S3NgX4rULL+mc9Xjcj6OtLY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=ID+VTQPg; 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="ID+VTQPg" Received: by smtp.kernel.org (Postfix) with ESMTPSA id D1739C32782; Mon, 5 Aug 2024 15:21:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871308; bh=XOcjCrkdVgWqenxc2S4POpPouyHf3iALRM/oI15aNRQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ID+VTQPgxM4/fo/86PhXM8wRLmUNRAGD0AtIR9PtyYSxsVsHuIDvWngmOC+r+/vdl cIN5C0KpCslxLORbqND66Zfvihy6aQlgFRHQSOk+wpPpD6no4Yud3FS3rT5/CDIs+Q BXWO+4zgoIp3+nxfgwueV/3Up8duKjAUksUMzqgF9+qdt+ovvcXwaop8+MVbGixguk J37SZmf69xbVFHxg4sKet5BDZPN8wgDPz2zaed4SF2pBsXmPcOIYsKi3/lRW5i0dhD GYikD+tDejphoiiin0o0ZiQI8f3sVZyMcYBKWRWvI1mrEHnXAvU4qMpi8FZ/YZw/ab ZS9nCCDnFf1ig== 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, acurrid@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 v4 17/28] rust: alloc: implement `collect` for `IntoIter` Date: Mon, 5 Aug 2024 17:19:36 +0200 Message-ID: <20240805152004.5039-18-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 --- rust/kernel/alloc/kvec.rs | 78 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 51426e0b28e0..160c6b3868fe 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -644,6 +644,84 @@ 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`. + /// + /// 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. + /// + /// # 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>(()) + /// ``` + 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 { + // SAFETY: Copy the contents we have advanced to at the beginn= ing of the buffer. + // `ptr` is guaranteed to be between `buf` and `buf.add(cap)` = and `ptr.add(len)` is + // guaranteed to be smaller than `buf.add(cap)`. + 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 buffer. `cap` is either th= e original capacity or, + // after shrinking the buffer, equal to `len`. `alloc` is guarante= ed to be unchanged since + // `into_iter` has been called on the original `Vec`. + unsafe { Vec::from_raw_parts(ptr, len, cap) } + } } =20 impl Iterator for IntoIter --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 D23E915CD58; Mon, 5 Aug 2024 15:21:53 +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=1722871313; cv=none; b=HGG467gYXY9HUy71CwZLXzRVEQqbBBTIp0JJ7g0pSvJ2fselK7+bq8cZNP1FnesNElwVELd928bPPSfvouOP4YdzrNmBOpmxEq080P/nj8xc0vMKBV/osmKyUG4Z0/WowqMd5AbImjHjls+lKRLaxnj8PryrZucEtFa7X7yAICI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871313; c=relaxed/simple; bh=sdhZZznOxeJHYY2QktGYlgQTOZb5ZmWJzNbZi+z/9XQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=PFfUZvatzAfrjFLEslQEyrStjunbVXcsg5W+OAXGOHNfUMbZkzRPnOVLVL5o3c3F3W3dv0X/3fAPZafR6olsLhdVR1yOMrmkICF3D/ktks0LQQaWkpW+UgDK+feaQeLK/eGcJN9r46M+Ns3dFb8zy8uR1ucQnz9ban3cHnHK4C0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=MkQ4E7lU; 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="MkQ4E7lU" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6B1DFC4AF0B; Mon, 5 Aug 2024 15:21:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871313; bh=sdhZZznOxeJHYY2QktGYlgQTOZb5ZmWJzNbZi+z/9XQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MkQ4E7lUhaA0lmzYa1EHdFvKHEGKH3UaU98g02eHPsVkpZdobEUsgc6JS0S4ZeS7w 0OEYLvf80LOr0XH2SuWFHa650YREeChd5r+BWZdapI8e0XQarq9g0G4TCdCCafzNDz Yveqv1PSPCmyYHRfql+7X1bDpnOoCYH4OMQHrXYH/K+7Uazzk+gAga/H3DkSJQOGdq 587aaNTegtnnLZ8Cht4vWh+KJE0P6u4fmkd/qbAz24AqY7F2NoUjNdEsy+F5jwi+D/ VXFPCh4t4eQmfdJb8/5B3yD1nWZAGK+1lwvwIZoJP5sm0r9PS7YiLRz5JgJcnntiE+ bOpo61yC90QRQ== 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, acurrid@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 v4 18/28] rust: treewide: switch to the kernel `Vec` type Date: Mon, 5 Aug 2024 17:19:37 +0200 Message-ID: <20240805152004.5039-19-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- rust/kernel/uaccess.rs | 15 ++++++--------- samples/rust/rust_minimal.rs | 4 ++-- 5 files changed, 15 insertions(+), 20 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..0b6ffbade521 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)?; + KVec::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KE= RNEL)?; =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 25761da5a816..25f290428c8d 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -188,7 +188,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..d19002308636 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,14 +75,14 @@ /// 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); /// } @@ -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)?; + KVec::::reserve(buf, len, flags)?; =20 // The call to `try_reserve` was successful, so the spare capacity= is at least `len` bytes // long. 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 8A11B15DBAE; Mon, 5 Aug 2024 15:21: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=1722871319; cv=none; b=NvqwKTPtKZlAh+ZsGsjR8ZKUliHDAkeJaA83duCD7MemihpkYCSvfD8h43imzDBggdBbINZWhj6lQPa2kOVblqrkH+MPJeRkz8bt6OR6KjQRfZ76DE6+4ry/IZoknU0/GtWuID4rNj3tqYjtPFzZHTxCqTVthJCg3wb9mGkHxkM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871319; c=relaxed/simple; bh=ypL6fvsZDuvmX189rxd6X6uwkZYnuKjYNcyeZ7x+t1k=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=SyYWrzsMMuvyJ2lsDXuOWRLvxvXBnPClgIEtDhxH1Da8FPqCJWeOaOenv9M1aZ/AQIurSYuhMlC5YdnzOyJqg/A6jhJ7FZhCNG9zrYbqOFnms9HI127wTZUmPNlZ4AxobBmAZDQGyuM/kLdTTxkOjKnCo47C1ZJ1Y9YAO5NfBHI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=vEdXdA7H; 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="vEdXdA7H" Received: by smtp.kernel.org (Postfix) with ESMTPSA id F250DC32782; Mon, 5 Aug 2024 15:21:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871319; bh=ypL6fvsZDuvmX189rxd6X6uwkZYnuKjYNcyeZ7x+t1k=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=vEdXdA7HSshrjfYIce17wK6XwMWAxL5/nLqSzAiU/5cLytRr96oxtI7KOaSfS0RsO oSbmtmEyXJ+dKvnZBNHUa0PdVCxoOQxyHTf5obH45VXEvZMpJ9B1BkPekczRj8hMuE q24Aj+MKfpnljYS4ADNghs0T1tvARk+aMXIKthsops+ru9pwa52jeLuMgu0rcK/NZr Yx59pGZn64/lzczgduEr7+lfY55W+MjDyxNNUIXWAD/+c/OYNeWK7IQ3FdN0K7doHX 2LTX3nxg2DzkQNZ3PBmCYdAof2gRyaitYq2Vgd7Fh+Jkaay4eX7I0NepviC4ypI2gl qzWCOjBZxaIvw== 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, acurrid@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 v4 19/28] rust: alloc: remove `VecExt` extension Date: Mon, 5 Aug 2024 17:19:38 +0200 Message-ID: <20240805152004.5039-20-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin --- 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 86648037b3dc..8a1cecc20d09 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 bb80a43d20fb..fcc8656fdb51 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 C798D15E5CB; Mon, 5 Aug 2024 15:22: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=1722871324; cv=none; b=qa8+miU1bmin9gAWy1MpJx0NywsIeZ75bj7kcGSUssZxtMufqbT8ndv2qFge3OZ3PMaKmanDmx8FvxD+oILcw1FPO6nOj0Wc92So0IhVzpGWnE7JVc6yjrQkgDFenaov+Fku3yTBKsi301BIj/IqH+gNB82wBehIFGTBmLvU1zg= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871324; c=relaxed/simple; bh=x0JvvRfi87BBCBI94b39MtnQOfc5sS9njBcl08nLwWQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Tw0Rdyx4cSrQOlNl4F6v8W6TMj8sTIbfZEkMYd+UE90vMIpij3eCZ3s8AUzHiXm+YYI03I0JERl+TR17oCGkXX2xEU5GbQ60TQ+jPAgt8aUtyT42bGovQYx+QhZtFlSEKIfTfoNmCwPSOBhIDogt6hDrQ9A257VWfzW7kcqn5G0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=GiluqMtX; 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="GiluqMtX" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 88645C4AF0C; Mon, 5 Aug 2024 15:21:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871324; bh=x0JvvRfi87BBCBI94b39MtnQOfc5sS9njBcl08nLwWQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GiluqMtXdZRrGxd8njXJGzh/Cnf1XJFc2iZ23I6ziKDaiDjT0f3p1u4HPaC1G4uah l/YEiiIvjf0b4ltjN1ueSK3zylXBNT+K5g3kxc5BVTvZikzngFX62UcXk2YpAXbB0K MI7i5QKXgq/K8AEsUY4PueIhpjWMF69MREMH628K7zjwnNn0tHp+bGVhN1o/5K1edB XPtQDYlm69lFVM1TWny+/5dfby4rl7p6JyoEqgxH35gdvfGTk1MZNfQ5elSVOtDc1P +YkOJ0aKYgxQjOzrh5iu1d4rfGViA3aD/ymffHIe5ZVsmU6RqHWOj631lcpYfb/NEd ua2KgmEVCJ1gA== 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, acurrid@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 v4 20/28] rust: alloc: add `Vec` to prelude Date: Mon, 5 Aug 2024 17:19:39 +0200 Message-ID: <20240805152004.5039-21-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin --- 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 fcc8656fdb51..b049ab96202e 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 A466D15E5C0; Mon, 5 Aug 2024 15:22: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=1722871330; cv=none; b=Rq2d5WfiFPcoctweVfhmYAuQoQ1JS32tJyvH/b6mbJLVZe5XwJXIinLT7/1Qffy9ZEbB7j3/vXhlh4G2qokaw+JZB1tsaQbsGsq4umY5dvEQLxseJxmKde0beLsbkQolA8nOcfWmEaC9LiCEmMrKis560NdSS9ArkCvkk2nhDDI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871330; c=relaxed/simple; bh=7OXF+mdH/VtP3EJJlqmokN5UjBwgO5IftFjHmEHegv0=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=MA7uAG48bi54HPY35XWvfzzqq7iUACgK5HXR5/XD06ys4rMditWa5atYVMVMayiKCw/yIBkufBZms5+BBxDrXC5n+Y8NpzfmtPIrBxXw5D97G7TEwrrRgE6WK1T5CMMiVv/03GycOXyxsQLtn7VViIM3OZeoHQaMXCdN6+lAq3Q= 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/S0kpnJ; 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/S0kpnJ" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 22FE0C4AF10; Mon, 5 Aug 2024 15:22:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871330; bh=7OXF+mdH/VtP3EJJlqmokN5UjBwgO5IftFjHmEHegv0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=d/S0kpnJEA53HZxx/ByKgPAnMqA2hpXuuhUkXibFqKo49ZEoH76Oj4hJ8SqrD3aqT ohaViLeqbOK0gaZsi/YhrEPpZXklRe02xuggdqQSFZM7frZqBv26bR1J7bFaq3GfZr kCFuJqcRX6kpxTcvMNk1xoMkNxQpXXosWPQGfg/G4D24VbC0zsc9n3E1NFT6mukVqo TaHwHMYBskm5uZKwmvD4+BhLRnXthAhNxE0EtTCneiAwCmfULUVtNOZQpZ7/OvOZSz hp4bWiQFIIkrm7CnkC811aoijDzacgxc6d8ngbYyU7Kdo4HynY54SZYCf7p2cgxEBy Q1M+GE4r/RV1A== 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, acurrid@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 v4 21/28] rust: alloc: remove `GlobalAlloc` and `krealloc_aligned` Date: Mon, 5 Aug 2024 17:19:40 +0200 Message-ID: <20240805152004.5039-22-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 all the `Allocator`s and the kernel `Box` and `Vec` implementations in place, remove `GlobalAlloc` and `krealloc_aligned`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 63 ++-------------------------------- 1 file changed, 2 insertions(+), 61 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 91ff21372a8f..6abd55694422 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -2,8 +2,8 @@ =20 //! Allocator support. =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 @@ -40,27 +40,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 { - // 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, - aligned_size(new_layout), - flags.0, - ) as *mut u8 - } -} - /// # Invariants /// /// One of the following `krealloc`, `vrealloc`, `kvrealloc`. @@ -129,41 +108,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) } - } -} - unsafe impl Allocator for Vmalloc { unsafe fn realloc( ptr: Option>, @@ -204,9 +148,6 @@ unsafe fn realloc( } } =20 -#[global_allocator] -static ALLOCATOR: Kmalloc =3D Kmalloc; - // See . #[no_mangle] static __rust_no_alloc_shim_is_unstable: u8 =3D 0; --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 E29A415ECE1; Mon, 5 Aug 2024 15:22: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=1722871336; cv=none; b=mopOtEZLZ88armdKAkEdX0WyRaUBpAjONzPjoqD08P7+JlFv+7dZuv5WN5nRlTwMCuoXN73E219C2LvBeFthyFOcodlNaVXPXPGRfr1K46NLf9X4mVzak4VQxjsJPdmH+seQE8zGTA3z5WPEnBC5LU/S3K2M5/2m+BgTUt6NiN0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871336; c=relaxed/simple; bh=ifLa6ui520OxD4tx6GpOL1mZtUOCjuqJJxFCxi3qo5o=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=E8BlABCq4YwEzyIXiJDOyLgQZzJyQlNE9mbAqhFXJpnQFCQuinR4r3SjOIZf7TsYVu8OyghPU+i2nP/jvvBtronXKEVxYPHPbKJJ9n8RdKzTLGXQUr7gZUKIYmlThLzfYYk2EuyVvXv2IfPXma3J45Rr402ilNSDTvZzFbWe4N4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=fLVr7YbN; 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="fLVr7YbN" Received: by smtp.kernel.org (Postfix) with ESMTPSA id A8DDCC32782; Mon, 5 Aug 2024 15:22:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871335; bh=ifLa6ui520OxD4tx6GpOL1mZtUOCjuqJJxFCxi3qo5o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fLVr7YbN264rVMq6UBxDkj9mLkDKu+lSnJRLG7ZDHjikHSZtClMvS0zahZgkPnYnC 8g//sl6JDeyuCBMEHtPPyasEONse+pNBUhjzv+LJcoYMBSaH/8Dz2uwMj08S1/d687 gpXy+kODqrOIBDERW7L+MmgNouc+BgymUOc1ddUgOKnaNmndK6eQWQCy5IrEvrpGOf MAzoF3+bKOWT4uc1/CUC04cf119BepvY7K7jvxanIMQeDHIXUYk/iG+0TVUqUCE4mP fXvjpu/uQPXoBJeF6GCTy4zLnn3y7+EvbMgnsFG8kA4WfqgKwTg1ujG6yKE4SKvFZw kwgaUYAhHVjuw== 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, acurrid@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 v4 22/28] rust: error: use `core::alloc::LayoutError` Date: Mon, 5 Aug 2024 17:19:41 +0200 Message-ID: <20240805152004.5039-23-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin --- 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 145f5c397009..2d012cc3881a 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 7D32B16D32C; Mon, 5 Aug 2024 15:22:21 +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=1722871341; cv=none; b=IAlrrlGsNKDVsKDaeLL2v08jaTUnod4+69Enir0bdl7XF8oH4DhXJv1vj1wv9l4v/8dmeVaADDhWmRdGs6fkV2VyFfUBFadwNb7DS4uiQHRX3qkttRpiufOBufWh/P64GVN317zSgCr9mcCoUSIn1KCZ73pPGrM9C9PGhTVD3uA= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871341; c=relaxed/simple; bh=EhvuU5VnVA5zmjTNVXg5lAn5aUpDsOgozY6sKUH/Zyw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=D0YIYK9/rn0HuKv8GLgjhIvF0ReBPMAPI7Q0ahQ8WyIcb9DgraqlrRRqe5AD7qjWi2aBjG3awuKDezB1svNuoBZYG9sCN0QccWjo3tp9Dzf390DDXpvaP2vKdQ4TbbGvV2smLbHTuEgIRY0tvFfeMu70+eZCc/zOqCrH9rbGK4s= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=vEmVFRkO; 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="vEmVFRkO" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 42B82C32782; Mon, 5 Aug 2024 15:22:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871341; bh=EhvuU5VnVA5zmjTNVXg5lAn5aUpDsOgozY6sKUH/Zyw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=vEmVFRkOg+K1zHXflqDDLqMsFN5JV8HF2isrn3XG9SHLQENzOcT1gsu+4+g9o/IzO i1NcdMbFG58zjVRkRc8yw/6WVmKfBbia9zg9ZCiJXfUuQ3LyVj5VN/oa0PoAO1m01I MvEgr/p5ZsWrWwkny74Vk6sUqDTVENSSe4P7kEvbpyZHeukri9Abj45hY5u8CkXoCh aN2L+tN6VhYoOARZWnKwC/hxOobR4fqHcZaFq4TnhdsVuma4wHYELV1bVW+P3pV54S mAJX732Y/F1kZcbxCvivOKl4QFC3ef7HJjrVY4T7QgWrZtHUOWkFlOz0riRnp+tfdU 3D1Tn2ABbHY+A== 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, acurrid@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 v4 23/28] rust: error: check for config `test` in `Error::name` Date: Mon, 5 Aug 2024 17:19:42 +0200 Message-ID: <20240805152004.5039-24-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Additional to `testlib` also check for `test` in `Error::name`. This is required by a subsequent patch that (indirectly) uses `=C3=88rror` in test cases. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- 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 2d012cc3881a..7adf889b9526 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -140,7 +140,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) }; @@ -157,7 +157,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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 14B9E16CD35; Mon, 5 Aug 2024 15:22: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=1722871347; cv=none; b=pCgPleqXGmvRUWd+RjoIgdIz8LU6XGETnBqqhn/saMy4bbmZA97vkdB0CbWA4jqQIMpugmKq22DcQkYM7wFsRbTPssDtx9ZQK9GfZjf4g8AGwM30d7dHktD/68j5D1BNPcYYdhI9feb97GiNyojyYS0gomAf3UyPygOp/NgZ98s= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871347; c=relaxed/simple; bh=Io2x+G7qKjrcvouOx2NWqdpFm0dKR4v0O7CzrkJKPPg=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=TUX2JMqQlXKc9R43trz2o4N5gQfxvAAn5fcWaPbQyu1McBFqRk9fokz4wdBAtVeNEqPFTMJi79ZA8wEj9Yj+bbFR2yPzAdtx7kiSz5v8mE+ddfppOnADTZX7kmOuNLf8OPBdIlzvvm1B49FwS+RgDlWKDXlU4E+dXQy2LhyfPlU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=qoHEC5Ud; 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="qoHEC5Ud" Received: by smtp.kernel.org (Postfix) with ESMTPSA id CE009C4AF0B; Mon, 5 Aug 2024 15:22:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871346; bh=Io2x+G7qKjrcvouOx2NWqdpFm0dKR4v0O7CzrkJKPPg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qoHEC5UdKarefAWF6zWNd2LvFyyq/4wBYNZgs6miJ6rFtPBVvOsC30fAeL88n+Gh5 uZQNESyqL8aEbnOBYoCjniO/U2YgYO2ZrKTcn/Iy6ZJrdJhFF3xntpiryK9mUD5Z+l O5+q1s6FdysGzpYj+MpoBf4qKrVa3yUjrwqvN8gepAUkriIFx8hfj58N0LJT1RRfv+ a/Ro1u7l7plrczaR2exu4kVSBXWVNl3R3urzO/Yn52zdjxC5SW2XcgZjzoixC0Ix7x SPxqv5DDTj8XOdWvdLo+wRTff1SDyK9iT5KFg9Bx//qbpsmRKsw9ZLtl+GHe8C0Lsz ym3ShTTtCvHmw== 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, acurrid@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 v4 24/28] rust: alloc: implement `contains` for `Flags` Date: Mon, 5 Aug 2024 17:19:43 +0200 Message-ID: <20240805152004.5039-25-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- 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 8a1cecc20d09..615afe69d097 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 9CC7A15B0E4; Mon, 5 Aug 2024 15:22:32 +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=1722871352; cv=none; b=jBlyHqpojoI9ATD0E2gSrwuIZzpdObWy79NX0jg5vfDtxO6K3a1oTlK01NNHOsgRg7ndImZQVTkY2iu7p0F86czDBx858tzHo9RSzsYCeul1eLyWWdytzFSTrnhO7S4NB8Vln+q0vk5IwYucR5x2JrlsmamTjfed8cTMzUbSkvY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871352; c=relaxed/simple; bh=iMS9KiH08GatcQmOb0IQ1b8oJCGscNUEkjpp2MaItTs=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=eC1bq7Rh/EjBSIpZQkVUUioO3B58gM4OPWFTYmQ1d88K7RJWY4d7a2PD8E0labWgi2nVdcOsN/nnZT3jywgU2vsbSnFGctRB4r/sRNIcyP8VHD/HMCJFj1AzpKBA+2K6tcGYgRoD4+i7Qf97yK8wmjQxhlGXA9DhE6kRJaxxzN0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=LZruvTTd; 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="LZruvTTd" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6509BC4AF19; Mon, 5 Aug 2024 15:22:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871352; bh=iMS9KiH08GatcQmOb0IQ1b8oJCGscNUEkjpp2MaItTs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=LZruvTTdj2MIMJkKEyIhRIp90mWSRe8963+FYjpGWG7TDpKeL61kjFpJq6XTHRRsR eJ+XQFqJGJmV7k8G/0tlaqfID7YOd2M4FckoJbAm9lYxR8q2AapulfeMNA3ncLjQ2k 5olemvFRi749j1zdg6uxd6KavaIYdMpYze3FXFv1vsJ8vaKPX/KNZV+yL4qJFAnhlV NnWSpoAORm9LM5eYLguKloPcUkXwkZsC7f52Oyu0NNzLc6HjUjgsfIsUqMIlQFIUOk Qfr5K7Sl3G2P96mhhtgNIOu3QGl0TmfOI8HUNePueD1JH5f/4tRXiodHg4fwi0eNd9 rczgS8BGkBgxA== 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, acurrid@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 v4 25/28] rust: alloc: implement `Cmalloc` in module allocator_test Date: Mon, 5 Aug 2024 17:19:44 +0200 Message-ID: <20240805152004.5039-26-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 --- I know, having an `old_size` parameter would indeed help implementing `Cmal= loc`. However, I really don't want test infrastructure to influence the design of kernel internal APIs. Besides that, adding the `old_size` parameter would have the consequence th= at we'd either need to honor it for kernel allocators too (which adds another source of potential failure) or ignore it for all kernel allocators (which potentially tricks people into taking wrong assumptions on how the API work= s). --- rust/kernel/alloc/allocator_test.rs | 91 ++++++++++++++++++++++++++--- 1 file changed, 84 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/alloca= tor_test.rs index 1b2642c547ec..05fd75b89238 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -2,20 +2,97 @@ =20 #![allow(missing_docs)] =20 -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use core::alloc::Layout; +use core::ptr; use core::ptr::NonNull; =20 -pub struct Kmalloc; +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); + + // Do not use this function for production code! For test cases only i= t's + // probably fine if used with care. + #[link_name =3D "malloc_usable_size"] + fn libc_malloc_usable_size(ptr: *mut core::ffi::c_void) -> usize; +} + +unsafe impl Allocator for Cmalloc { + fn alloc(layout: Layout, flags: Flags) -> Result, AllocE= rror> { + let layout =3D layout.pad_to_align(); + + // 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; + + if flags.contains(__GFP_ZERO) && !raw_ptr.is_null() { + // SAFETY: `raw_ptr` points to memory successfully allocated w= ith `libc_aligned_alloc`. + let size =3D unsafe { libc_malloc_usable_size(raw_ptr.cast()) = }; + + // SAFETY: `raw_ptr` points to memory successfully allocated w= ith `libc_aligned_alloc` + // of at least `size` bytes. + unsafe { core::ptr::write_bytes(raw_ptr, 0, size) }; + } + + let ptr =3D if layout.size() =3D=3D 0 { + NonNull::dangling() + } else { + NonNull::new(raw_ptr).ok_or(AllocError)? + }; + + 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 layout =3D layout.pad_to_align(); + let src: *mut u8 =3D if let Some(src) =3D ptr { + src.as_ptr().cast() + } else { + ptr::null_mut() + }; + + if layout.size() =3D=3D 0 { + // SAFETY: `src` is either NULL or has previously been allocat= ored with this + // `Allocator`. + unsafe { libc_free(src.cast()) }; + + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0= )); + } + + let dst =3D Self::alloc(layout, flags)?; + + if src.is_null() { + return Ok(dst); + } + + // SAFETY: `src` is either NULL or has previously been allocatored= with this `Allocator`. + let old_size =3D unsafe { libc_malloc_usable_size(src.cast()) }; + + // SAFETY: `src` has previously been allocated with this `Allocato= r`; `dst` has just been + // newly allocated. Taking the minimum of their sizes guarantees t= hat we do not exceed + // either bounds. + unsafe { + // Always copy -- do not rely on potential spare memory report= ed by + // malloc_usable_size() which technically may still be suffici= ent. + ptr::copy_nonoverlapping( + src, + dst.as_ptr().cast(), + core::cmp::min(layout.size(), old_size), + ) + }; + + Ok(dst) } } --=20 2.45.2 From nobody Fri Dec 19 22:01:16 2025 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 2B45516F824; Mon, 5 Aug 2024 15:22: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=1722871358; cv=none; b=ipH8E5tJXatWNv8/zpWR/kszwc9SzTH2nXrQS7ZrFg+Lb3pIAyes9a2mxvlvR2MrCgyR/KdCFE9iLJDqRRA+a7lzmdB96va1eCr9mS16FqpcrAuYzhG2NWFcC6VJGWCQOBtnuJ2r0uau6Ylqc7yf+Kr7VSXghoutawIt8GB3a3g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871358; c=relaxed/simple; bh=6dLN6QohX0ktcU4cWe7TRCkIGusnQOXkZAPpBQ1FLWU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Wdh4ouv4kY4sMU1GTXe5IRBkoiyHR35mSqGriHGRe3rC+OX3ZnnvosXWGqZS7OwL9Kh2EIuqFNPgeqonhLM+DPkHJzgkhwJPB18O6C0XviIVCHi2NNFueySa07Wo4cNgKqyED+BNYsVI7/LV339vMpAOS09MGy+ZrxupZHXL9oY= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=uc9cVv7E; 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="uc9cVv7E" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EE08AC32782; Mon, 5 Aug 2024 15:22:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871358; bh=6dLN6QohX0ktcU4cWe7TRCkIGusnQOXkZAPpBQ1FLWU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=uc9cVv7EEGEFQxjC4dwhg3zVwyiZ6SxOToMFUCRbQVqM16pUaXc+fZlyaIuu7Frtu NDJPcUyyZsri9m6uxCaouTJDUyTn+TWuVOk9yGLqOPI8Hv8+Fz9y0bT5pvkaO4Q92u N6maC4dN3Y+PW6mixAbH4phOt+o6zomDCYBcUaUyQc0VZI+BuzVDShLPiaoTLNIxPA ADzFXCXhJEV/3uBxq0mK01Cm43A4x58uvAMs0f0RqRGngixezRZG+Ib22n4Q1Wfstm 4L0sh3jjULPRSEozDeAdICVRsE9LtDVeLSGocoEd0pjyL+E/2FdsA88HTkU86M33oG oXaa/CY92g80g== 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, acurrid@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 v4 26/28] rust: str: test: replace `alloc::format` Date: Mon, 5 Aug 2024 17:19:45 +0200 Message-ID: <20240805152004.5039-27-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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`. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- 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 0b6ffbade521..8f234224cbf5 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 1C19815B10A; Mon, 5 Aug 2024 15:22: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=1722871364; cv=none; b=XHavl0YzJJPrz1W7VfyJdHSGg2wwExEIK98rUYIEf5ZaVjzNtwOTUlNrIxXx7SnwRWQISEE9shLKuzE5JpaV0OoqjhaIQnq8z5rwpzTICY4BV50J7P4AVHU3Pd9KW7FZOr5tzEW4BbZdvYiQypPKmGuOYA2Grt+VCQLUCzZgMK0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871364; c=relaxed/simple; bh=yqZfDZklljbN0uO3lQJvfzXfJFBboT5n5ZoqxzlseQQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=NCrXBVoECrQ4WGf9Kjt2+qQXCPObTr93g1hJcdKTtsHV6n6Vne1dyHAbsMbxJCX7Vmd38j/MiS4U9aLlldktJ4cLtDJXNRMwY+O6CJuj48uAr/L7tK0cn3IXt1pA9LvXtFyTZSOLaa76V3Kft2tNEOKPWoKUBXH+ZbbT1+AcqkU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=bYI9PdiH; 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="bYI9PdiH" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7B800C32782; Mon, 5 Aug 2024 15:22:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871363; bh=yqZfDZklljbN0uO3lQJvfzXfJFBboT5n5ZoqxzlseQQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bYI9PdiHMEa6z+y4a49v74LXqpDE47khUkbXxwkn7JYJYv/DZQXc3MSTZ/urywyFv atR7cWe7kP9ojhrrPjeXzdwpLW5B2kqLlZV4q3SWIiqkRhYsDlXQk8VOhHar7GSrul OEJ5fsIxT7PzlDXt9Qhf6ElEZjeBGlY9ucX75YFzAN/lCYSU71WbrPUOHriRCkvNJh jHsqsqgSPK7T1H7fJqIabk5l4385QPeLFQXDP/EFQSg20ALuU3yAOU6hy1H70UMRj0 5AeKx4fuuC9Ximy7trO2gaPMkBbXWTijm+t/VfnZpLpfZlUuDmitxWYYoCS4Nq4CI2 vpc0lH5iTtJsg== 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, acurrid@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 v4 27/28] rust: alloc: update module comment of alloc.rs Date: Mon, 5 Aug 2024 17:19:46 +0200 Message-ID: <20240805152004.5039-28-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin --- 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 615afe69d097..ccb9f5ddc4bb 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.45.2 From nobody Fri Dec 19 22:01:16 2025 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 44A7615B13A; Mon, 5 Aug 2024 15:22:49 +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=1722871369; cv=none; b=YsUjkfC3lberVNiemCwGPZV72MjP5hYaS2LEd4qHK+2GBEsVAs/2JDTDuyvKTiGcFh6hCg4CZSezLgfUHRaTTewdRt06GPTONv8Ta+5lOq3fEslT4QxEow3lkiyhRP+0xEOwBxh5xTUogs+4ls+Ft0Z5d+rtUb4VG/6srRqLd7c= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1722871369; c=relaxed/simple; bh=BnmAT9t/c5IIktW7mx1EDTKEy8RKB4RK+wsZKxEJOuw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=q7GNKSHv3sFkoyt5vyjZAcenaAiYHx4FSx2GPzHueQSH9+kTN9NfAh22//KfJX0ANUfAABPtcpzOU5zFhWeuouIWe4Mjj7QKhuGkJlv+pe3jvS7bJJ/quswqv65iAqUp66uLNmu630pe3899/pnt2jjcGpcoE/Yr37VZbIpg6iU= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=pl2BM5uH; 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="pl2BM5uH" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 156FEC4AF14; Mon, 5 Aug 2024 15:22:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871369; bh=BnmAT9t/c5IIktW7mx1EDTKEy8RKB4RK+wsZKxEJOuw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=pl2BM5uHuxVh2a3ewPaeBnItwpN6qT28JvjVi6r0MOje8zHSfXRetvnJLWC6T49A8 rwdcD1TSgUTpp1k2MqPPot84sHMYLF12u1EsPNcc6ClTtsoU1MmFSFBnk1ZOsGE0hf 1xqdBj5O1ox/Bd8l8Uco5iMJLT5irpSKsbgEBXPmqjxtTdlb5ca+o9AH9P8qwmtm9W +OoTPTk6xDVV6tNUBK4PzZSZ7A5d1QyQhrWiUFScIxMwYDaPy8l+gYHOiJb0laa0Qa YzBbQm4ZoyG2rZ3XfiYe+WPNG6t+hU6hfFCQ+z55H5oVI1/drRVmyrhiGb4focDIAg OCLXWBKdlIKjA== 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, acurrid@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 v4 28/28] kbuild: rust: remove the `alloc` crate Date: Mon, 5 Aug 2024 17:19:47 +0200 Message-ID: <20240805152004.5039-29-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-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 corresponding unstable features. Signed-off-by: Danilo Krummrich --- rust/Makefile | 44 ++++++++++-------------------------------- rust/exports.c | 1 - scripts/Makefile.build | 7 +------ 3 files changed, 11 insertions(+), 41 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 1f10f92737f2..8900c3d06573 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -15,9 +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_bindings_gene= rated.h \ - exports_kernel_generated.h +obj-$(CONFIG_RUST) +=3D bindings.o kernel.o +always-$(CONFIG_RUST) +=3D exports_bindings_generated.h exports_kernel_gen= erated.h =20 always-$(CONFIG_RUST) +=3D uapi/uapi_generated.rs obj-$(CONFIG_RUST) +=3D uapi.o @@ -53,11 +52,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)) \ @@ -80,7 +74,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 \ @@ -104,20 +98,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 @@ -161,7 +146,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 \ @@ -197,7 +182,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 \ @@ -310,9 +295,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) - $(obj)/exports_bindings_generated.h: $(obj)/bindings.o FORCE $(call if_changed,exports) =20 @@ -348,7 +330,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)) \ $(RUST_LIB_SRC) $(KBUILD_EXTMOD) > \ $(if $(KBUILD_EXTMOD),$(extmod_prefix),$(objtree))/rust-project.json @@ -380,12 +362,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_dep,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_dep,rustc_library) - $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FOR= CE +$(call if_changed_dep,rustc_library) =20 @@ -400,9 +376,9 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_dep,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_dep,rustc_library) =20 diff --git a/rust/exports.c b/rust/exports.c index 3803c21d1403..1b870e8e83ea 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_bindings_generated.h" #include "exports_kernel_generated.h" =20 diff --git a/scripts/Makefile.build b/scripts/Makefile.build index efacca63c897..7e7b6b3d5bb9 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 \ --=20 2.45.2