From nobody Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5BACF13B5B4; Tue, 23 Jul 2024 18:10: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=1721758259; cv=none; b=ZuWrXi5mBKArw1I4eKYp9W7dXm5fxbMRAH/BDzHQez/awFguV3aWWEUyHzTX7G+mv5rDvRXEkgUkZrE+SOntJMaNBhB8yjx4OL9nEC52EIBits67FAubRKA2i/TFKnEfBG9uTCOo36rWeNiDEmpcVzS723SCAhsA32/7RIg99LE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758259; c=relaxed/simple; bh=U0O51DFRkgND42OAvkxZ2VxyksXXw+gcqA7TuTA2fv8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=V9hsIKlgtynP8zqJMeDPXtdgCSa4jkTT0hY+RuHsR/VIrgvvEZHFgJEfMKrFi0ZHdVW1FvHff/2gcGhV4Js9a/SK6VkxP/J8nptDa8LBpqGfHbANaVAGjZYQrLjnUXo3/MHuvToWSzvzQQL8Z5BHn/373Hewni8gP/PvNg2AK0c= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=cjrbMJLC; 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="cjrbMJLC" Received: by smtp.kernel.org (Postfix) with ESMTPSA id AAFE7C4AF0E; Tue, 23 Jul 2024 18:10:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758258; bh=U0O51DFRkgND42OAvkxZ2VxyksXXw+gcqA7TuTA2fv8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cjrbMJLCrzNPfee1nrhopoa1trofVE4tsz7J1F3oNIona4S90KwXUIalrPc8F6Au1 46nGN4ic64WLD5fDUuucmc/HhC1cOY4syzUfFChpzeE4AM7ckrJeojfV8VwRDpRv0Z +/qyz4B/fZZirH7/DC0AhSHsYbcha0LPevAR7/vXcfTV358pu6PsnbaGR0olFKOvTH bz09bgRNONd+ULZe8XXTjlHDJjO4TgZCW7tmStTGIIUI/XbdiTIpIzsQ75GyEj9uLP 4WDgR1Dyd00ajlYfCKX0wINAWgV0usrCz2mK8CrH4RwG5Oo2heQxPXsUnejR22ymwV C5JRoF7PkYGxg== 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 v2 01/23] rust: alloc: add `Allocator` trait Date: Tue, 23 Jul 2024 20:09:50 +0200 Message-ID: <20240723181024.21168-2-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 --- rust/kernel/alloc.rs | 73 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 531b5e471cb1..11d12264c194 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. /// @@ -71,3 +72,75 @@ 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. +/// +/// # 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. 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 + /// + /// `ptr` must point to an existing and valid memory allocation create= d by this allocator + /// instance. + /// + /// Additionally, `ptr` is allowed to be a NULL pointer; in this case = a new memory 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id DC304158851; Tue, 23 Jul 2024 18:11: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=1721758265; cv=none; b=nC9mqAhnM3w5jt8Pv2Ol3C3IAFh8kz0dGOg4yK3Ruh8ttg/VZgGGmcmNTLefT8FgN8EaniC3MVn5YTAmIVeqfb3BtaMNT/Fjj6259/h9opnNOx14EUHxG10ImHplXrWNH3ZleyU/jVEjl6tH7lwmzcq8Q0oCFQyE0ixrFS6fayc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758265; c=relaxed/simple; bh=EF5TVGHtjh4ZWyprrgf/Kmvg5Hex1RNnX1bjJzrWn+g=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=tDtigKdDaLk1OwoqVq2s98Axe2oAleYZ3XPZTJhPHlm50wnHlC6WmEc5O8tKtyb0M0vGYIGKgD80q5ac5kzZidEjUJXEO4L8qhfhTgLBAyc7akcbiKc2f76G9U71E6a0dlUKrRhU5/LkgjeaAJt3ui1AzIhlphDkBgoUyq4ItJI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=G6jovfZm; 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="G6jovfZm" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 59F59C4AF0B; Tue, 23 Jul 2024 18:10:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758264; bh=EF5TVGHtjh4ZWyprrgf/Kmvg5Hex1RNnX1bjJzrWn+g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=G6jovfZmXmWU2u+CRVnM/WkrcdUz8kYHbBGAcB9lI6dbRqsuZp2V0ciRIaazVMLjy h8xvO988V8AjJvelD6vG/yuVh9BMRh1mA9kRWBQd8FqeHurCI46aZHyjv41Ycz3PSM 1eqKfbB6b7PdalMqqALZsnr3nuT4kIz29Dz0lX3jN3RW9frxXIICZgEQVNjKxiBo27 8Zhd9Y37MKGAHnXc9NI1sKCoTiQArx70KB19Q0NqLtw+SQUHP8xeCjV+vqfqXXBVIk 5Wq+ITwkanPAzm9XMDqxtswIgIak5p4Uq8ZiXnN8NEkaHYJ6SxCsrfVvpnybX7ZV9Y L1NIl3l8yVmEw== 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 v2 02/23] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Tue, 23 Jul 2024 20:09:51 +0200 Message-ID: <20240723181024.21168-3-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..6e133780a4a1 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,27 +8,35 @@ =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 { +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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A4A4F158D89; Tue, 23 Jul 2024 18:11: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=1721758270; cv=none; b=OMiMUkIxs0H5qXv4VC+dUzZhqmnJOzMVbkD9/kPu5eLrgXlwcVzj4l/JCQD4jo2Y4aoQQeDuMFyCdKPeKqMik6a+vzkbBnmSQXjfIU+ZeKOrAOHUxrLgH6D/RPwRn89Vu7BmELXrG1fWs3oQynKVkJPLdsqCAPpisvDQuvVf8NY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758270; c=relaxed/simple; bh=aW/HcnaSGCL2MNKjQfZpCrQAc7Fxs7Kovj68XjWpzPo=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=NrCerJ4bjHyY1yTDUxNVEZUkW+PcMruupOxdy31LHtl729TP329xwiEkjf2lGAwTopxaURffAnJarBiD2vTd+AlKK53CdTcmY+rVyuqJerkAxelbwFuOkJ7k0oAtKAQT4XgDTzqyTAyAa/WrwS/0FG2gtNMjksTiR2RWVrENUII= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=pV5PaiY/; 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="pV5PaiY/" Received: by smtp.kernel.org (Postfix) with ESMTPSA id EEC38C4AF11; Tue, 23 Jul 2024 18:11:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758270; bh=aW/HcnaSGCL2MNKjQfZpCrQAc7Fxs7Kovj68XjWpzPo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=pV5PaiY/63emituIHzEnCO4VEz5GBfDbCAwoMiSL7V6F2fKJYGO3Ayta7xK+BINIo ++51BxK7YS8+MqjyMdAiqWw3C4CHDV03TvVfp/djhbhMXimXjwKUXgKvBCG6+vMcuh XO7IrMkvHarKPe7FVVOdV5+epZ2974/DV75/rf/HBqBO2RI9Hz32cijHnkVlOwiSyB z68SncMnBkPvYgKFP4ymd9QDQlI/2EmevlcqVdqHThKTi/TFFqVYchGFtSOaPUtEcV /o7P6GDKwKWe1fIh1d5nMfeArdPSUAS6sp5sDmSLHHCykw5l8SEQNHk4Rz22zrF4+A jtX5QvdKRjr9A== 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 v2 03/23] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Tue, 23 Jul 2024 20:09:52 +0200 Message-ID: <20240723181024.21168-4-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 6e133780a4a1..10774c51ae26 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 fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size <= align, so pad first. @@ -39,7 +39,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. @@ -75,7 +75,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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E0764157E9F; Tue, 23 Jul 2024 18:11: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=1721758276; cv=none; b=MWV+Ogp2OyYhvdwwyVzKXjb4klMb57C0JtGX1kPKqM2HAnHeLqIv1gweAnCdEQonr5dUdFjhipi1OF2soRKLMLVphGP26O+lKn/7y4hXNthu4eEEkxCa4t1/YLX7VpD/HlapCA1a+cvE45vLLw//mAcgoKJaiOkqqhrxOGCnt1A= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758276; c=relaxed/simple; bh=LIUBeLsNsDjs5xTYqpQj2wzu9Kf9qHfPrPDSatbqKYw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=XZfWLo3IeW4kTJcliHaxaEyAAy0pOdkBquwIcHRp0laTWzBi4nokz3v6175Pqv4FvTdCeaDMQLw5rk/Eez5xvVB+OOi7bxtAek9zooGxqnPAiJY7hym/3d4LEVErAfgvBowfZ1U10derpO14hd+xTHzqQInzfEcIaxLJr/Pu+ns= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=RDOuFQ8+; 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="RDOuFQ8+" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8F4CEC4AF13; Tue, 23 Jul 2024 18:11:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758275; bh=LIUBeLsNsDjs5xTYqpQj2wzu9Kf9qHfPrPDSatbqKYw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RDOuFQ8+8bKHj3kQ5nWdYX5MCjfcmldiMQGhEIFnZxm/KBri2pLNVpBER8FMKqVci ZT92rVWWPBz+aDCzyZdSSlXazYnHOxRhSrZAF5QtXKwt6Yx/roa7uuwiT5e3gl2AS4 ntdGyFz4xLeHT1Odjc3gkiTPeQmqzUy5JSfBib2nOqbOmIBArs/cI3wHr+/Tcngfhh VY34vof/Bv2HOLTCI3+ufH6FwSU5SErRmZtq+aKhDsI7/BuNAW3/1MYF+7slArtDav LDp3Q+xY6tp5G2K70K4w2N47olFreJnlgve7+Lg6ah1OJeGemb78FuuGuCsBvXn0d4 T4QqZnGPBIRQg== 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 v2 04/23] rust: alloc: implement `Allocator` for `Kmalloc` Date: Tue, 23 Jul 2024 20:09:53 +0200 Message-ID: <20240723181024.21168-5-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Implement `Allocator` for `Kmalloc`, the kernel's default allocator, typically used for objects smaller than page size. All memory allocations made with `Kmalloc` end up in `krealloc()`. It serves as allocator for the subsequently introduced types `KBox` and `KVec`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 66 ++++++++++++++++++++++++++++++++-- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 11d12264c194..bf739ce65387 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 10774c51ae26..397ae5bcc043 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -5,9 +5,18 @@ 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; =20 +/// The contiguous kernel allocator. +/// +/// The contiguous kernel allocator only ever allocates physically contigu= ous memory through +/// `bindings::krealloc`. +pub struct Kmalloc; + +/// 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(); @@ -18,7 +27,7 @@ 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. +/// Calls `krealloc` with a proper size to alloc a new object. /// /// # Safety /// @@ -39,6 +48,59 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_= layout: Layout, flags: F } } =20 +struct ReallocFunc( + // INVARIANT: One of the following `krealloc`, `vrealloc`, `kvrealloc`. + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut cor= e::ffi::c_void, +); + +impl ReallocFunc { + fn krealloc() -> Self { + Self(bindings::krealloc) + } + + // SAFETY: `call` 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id DEA0F157E9F; Tue, 23 Jul 2024 18:11: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=1721758282; cv=none; b=JTzlgw2aCEAmWwxkQrVFqc2o9ITYd/OLmlqQZg+blMsNlNCGr8/PFRLzveVAmXjr76T64aroUUGynNacE7Kn2IdNwgR10+61hhiEnF7RNuIk923fzZABCt5+ECVit71g2X+mLFj+XuWEX4UhA8bVbM9WC/D7M+vnsgLvP2oSJ+Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758282; c=relaxed/simple; bh=/CAVj622i+EjUqJe9C6/xiYM7R6rhnj9Rb056J9W4L4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=fjevPj6wxNXmKhlSCyMTF/uQcq1v1woEvDWqT/Ly/y/NX71UUHM5VcTmPB7hq6mdR5q+fvO0UGcE0Lm+UdFBv/XzbfJsbBeUqCUQcKIETwtBRgi7rVzqnmrPxPQ1YX0SRqsu7r0pcHWhUgMSIh+Nc+pKgWgqEf69GZ6D+KbVOf4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=KMGsYeNW; 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="KMGsYeNW" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3A874C4AF0F; Tue, 23 Jul 2024 18:11:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758281; bh=/CAVj622i+EjUqJe9C6/xiYM7R6rhnj9Rb056J9W4L4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KMGsYeNW8i1peerLA/ZxLTXTQB9autbiVJPYjR+Z7R/ZSaXPgKMAOX82xJwY94ndK j6uF99PhRxWMBTW3xVh6hAyjUH8iSWR3Cqu5/pc6UVffMXJNCJyumJIBn131wOrlSe 8IFbhkCh1ORfxDTu/EGVqEmc0BgLW48bdJCypLh3aA4tHsvMaozfT/A9AYXOqgXpXJ 0cCRVVFRxfthxcjIODCObO9cZyV1r1/dBPiDqkIOB8F2MzBQ+PF3MQcjZCmS0SNVoV 1lYsPT8UEgprnAIv+APz1a2AhuCoGmxgUNwnbYiYShoWixYfSwlOobf+7ER2pcFhn8 DMVAdjIiCdnHA== 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 v2 05/23] rust: alloc: add module `allocator_test` Date: Tue, 23 Jul 2024 20:09:54 +0200 Message-ID: <20240723181024.21168-6-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 9 +++++++-- rust/kernel/alloc/allocator_test.rs | 21 +++++++++++++++++++++ 2 files changed, 28 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 bf739ce65387..90ebe79e86cb 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..3a0abe65491d --- /dev/null +++ b/rust/kernel/alloc/allocator_test.rs @@ -0,0 +1,21 @@ +// 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( + &self, + _old_ptr: *mut u8, + _old_size: usize, + _layout: Layout, + _flags: Flags, + ) -> Result, AllocError> { + panic!(); + } +} --=20 2.45.2 From nobody Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 69E8F157E9F; Tue, 23 Jul 2024 18:11: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=1721758287; cv=none; b=Y1etNrG7AstOkH8GOsfLuTPwZUJBHvWC6HNkcHTWOfAuV4xBQfVH9kBJoO9IXopn+1WfapOV+/tl/s85zlsPVXU7M6qHapGaReJN4UP+Izihfxczj5eYdHi5zQNcRBKZj1gv+McJKi97s/0otdzZfa6KB01Hiv56nx1Ho0a3AIU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758287; c=relaxed/simple; bh=YaemE3GyNUw6k5SxqCko0qV/GMMCyuitkbWwSJz9u6E=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=dMqygJIOQ+EQVA5CvaMQklxPIAm+SeDxPotAAd/79PPomoMoj5tYTNEyigw1vNDGngGmHmljj+xlCZczsCYtAokNJO/lxrZfJrc61H7xJjTN2dtA+SnMs1wa6YiyacXuPXW9eWTjxSbOQfIXbnXhtXsZL7OvHTFTJIMVghRzSJw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=baOAej1A; 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="baOAej1A" Received: by smtp.kernel.org (Postfix) with ESMTPSA id DBEB5C4AF11; Tue, 23 Jul 2024 18:11:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758287; bh=YaemE3GyNUw6k5SxqCko0qV/GMMCyuitkbWwSJz9u6E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=baOAej1Au7/hHblUtzSZcJOHCZz7qZr12SRUNNlEDYgjYE8epT7uQ6Ol6uKD0vVle 7KTQvroSucEVwHrGu82BmmATVO34yILswc2nfJqeTGChptNBIA2IaOeaev9rzZjGsg 5meeIrkW+uA5ZeBIitR9pR/a4Y8ngqdWbvCYEcf4QU18vwY3kKTPbK8bMyNMke3u0Z 4h8SOfuWi3fpJrF8AO46vqQI0DbAHLPLmlZdTIpdjq4+hDc6KtS4WMcxrWRSzvknT3 S8FSd0onOAXFkJCFP9n4LqJ67ES+ojOTTatk9WwKYHOAzbWDV9DJzwkMfmXPBErcuD b2mfW9M/rKnEQ== 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 v2 06/23] rust: alloc: implement `Vmalloc` allocator Date: Tue, 23 Jul 2024 20:09:55 +0200 Message-ID: <20240723181024.21168-7-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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()`. Signed-off-by: Danilo Krummrich --- rust/helpers.c | 8 ++++++++ rust/kernel/alloc/allocator.rs | 24 ++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 33 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 3df5217fb2ff..5ca7e4872ee8 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include =20 @@ -165,6 +166,13 @@ rust_helper_krealloc(const void *objp, size_t new_size= , gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); =20 +void * __must_check __realloc_size(2) +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 397ae5bcc043..e9a3d0694f41 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -16,6 +16,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. @@ -58,6 +64,10 @@ fn krealloc() -> Self { Self(bindings::krealloc) } =20 + fn vrealloc() -> Self { + Self(bindings::vrealloc) + } + // SAFETY: `call` has the exact same safety requirements as `Allocator= ::realloc`. unsafe fn call( &self, @@ -136,6 +146,20 @@ 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(); + + // 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 3a0abe65491d..b2d7db492ba6 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C54AB158A37; Tue, 23 Jul 2024 18:11: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=1721758292; cv=none; b=HvAVv5ZZrGCHPUjWYrn2goqdK4rUxaGI5VM0eAvHipOXa5AUZXIVfWOqT/Vws9877WIwBu7ixsImm0ZKSS2WpmcsrR3LyTM2zl/SQ6l+a1qevo57rQYqAn6Z983o9/YeIYV9+noduAyogT9ZgZCEd0qqiZp5YJbh6XF+PFoQvj4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758292; c=relaxed/simple; bh=VoSgcZBnVOwLP7rZy/xS0BTIj35SmIvHWDRctFLWgt8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=AsZhtdqXvTdvj545xeCLpA5qdD2L5rjL46YzmqNG5lXxAjqQswpXfjKmntlPniPxRDRckB3IMfwey+U0dzMBVY4YuusVXvPAzC22/5hgieyhUzPXSaQUzejowIS7jd4eR6UsgfNZZgUKIc+Or0pdjzarrz8YE9aKdSeEM5Oa+ac= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=P0fy4oHg; 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="P0fy4oHg" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7E755C4AF09; Tue, 23 Jul 2024 18:11:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758292; bh=VoSgcZBnVOwLP7rZy/xS0BTIj35SmIvHWDRctFLWgt8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=P0fy4oHgiIxm8fq1X97zoBznf3/NVarogrH+h0ecVwl2+FDYFNOUrCCy0ZNOG3Jm0 adQ50MkRsjoHOEd+Oc5uFHJbeibMZYhLLVzoVHjQD25QlzgVmqhoZkDozm+er2h1Pf 7q8u9sl1Bkhpo/f2FPlzT0E6H1kdmmhQQN9/yEevF+Z6pu97nY9WgN4drWO/N8wkRH Owu/UB9CgoG4HYoAfjgEMhUAl8uEkBtoBGlPL9NZwcBJ1gZsAqASGeeFsNxkoyk/KV 8cR5UTpSHU1s+WRfjTz6fAp3R5Pf/bE8F7tvuYMOu6vKAFuoLWE83As6FHoGyF8fus oo9UN0/r3MqtA== 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 v2 07/23] rust: alloc: implement `KVmalloc` allocator Date: Tue, 23 Jul 2024 20:09:56 +0200 Message-ID: <20240723181024.21168-8-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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()`. Signed-off-by: Danilo Krummrich --- rust/helpers.c | 7 +++++++ rust/kernel/alloc/allocator.rs | 24 ++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 32 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 5ca7e4872ee8..19a5e4a0c7ee 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -173,6 +173,13 @@ rust_helper_vrealloc(const void *p, size_t size, gfp_t= flags) } EXPORT_SYMBOL_GPL(rust_helper_vrealloc); =20 +void * __must_check __realloc_size(2) +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 e9a3d0694f41..1e53f149db96 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -22,6 +22,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. @@ -68,6 +74,10 @@ fn vrealloc() -> Self { Self(bindings::vrealloc) } =20 + fn kvrealloc() -> Self { + Self(bindings::kvrealloc) + } + // SAFETY: `call` has the exact same safety requirements as `Allocator= ::realloc`. unsafe fn call( &self, @@ -160,6 +170,20 @@ 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(); + + // 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 b2d7db492ba6..f0e96016b196 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6749D158A37; Tue, 23 Jul 2024 18:11: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=1721758298; cv=none; b=YaF0Fo7CYq6pA+CrJSNzFCNCq+HV6GjrbVq30K6UaubtlxfudiQTlXkmqAm18jdjjaRJlDKaWavtc9TSD6/yc7Qt/HT1tqvXVT81RuHpZ2cMSrLgmyvj3emLDIKDP7hFMC3o16NxnCpXx2mVfaJ4ZXkndHy/Drp0EvqgjA01qak= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758298; c=relaxed/simple; bh=EADnfi1fGvsx4VhAV2Fq3TLA5MaiZGvO/PM1XNctkMk=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=hNXDaizJE8rYXmO/ytqKaA7V48Au4OppRDanevYm9cKZa2YWuMEdATTe4+s2UhikEIs6gfADVK9o61fxcwkBIqsRAImP+ncf68Lqob3n4+sIE+8LBkEn5Bl3wfEmGrvhC7T5xMW9R85wqIpFtM14mFaBspPnJ7xA8RYfD9PsPcc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=jzRMYXdL; 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="jzRMYXdL" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 22C00C4AF0A; Tue, 23 Jul 2024 18:11:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758298; bh=EADnfi1fGvsx4VhAV2Fq3TLA5MaiZGvO/PM1XNctkMk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=jzRMYXdLknWKU0suCrVLj8MEFGuTCk7/uXsRG/mzuUaad6aFwdImo0hpVVrtIv7kH 0Rv1AXFLqi29AxP5TBXGlkF16TDnKbx4X3Cv8xPp6L3L5gcMSys9a9enKH5QrtEEMf GJWj+dRnU8pYOsxpsuvVbiLkTaJi+K3Av/YRPwhEiiXcDNbenfTiCEhgLVg/NRN6j3 vne/BLvKZRqxoVtlZ5qZ+4hIl7cVphYA1vSQMzC9xXLrnOFcCIMPXShVFDDPiSm+ZF 5ga/F3VxiqKohPR51k3FZes5jjxBRQtQqLSQ61rf6jJindASfC6V14JtEaD0+fBpHf cwIojKBj2UxmA== 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 v2 08/23] rust: types: implement `Unique` Date: Tue, 23 Jul 2024 20:09:57 +0200 Message-ID: <20240723181024.21168-9-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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. 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 2e7c9008621f..9cd20fe41c20 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,186 @@ pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `R= `. Right(R), } + +/// 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8461C158D81; Tue, 23 Jul 2024 18:11:44 +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=1721758304; cv=none; b=HDUIU28Zaehx002YNBc0CpOs/awLoAbZt39DnwHeWPOjfYlRuPT9fMOMFdSsz+s8zsChJoqbyUlE7q0HSAYUh4/9liysN83prNgI9W6dGONLmYzIoQnB9sAr5P7Kh/SeKnIjtDaaCQcCuwKY4NxwsxlamALRhXjwVppMpGY3Yuk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758304; c=relaxed/simple; bh=ITmzVZ1ozdPC3EpkKUw5PXAHmRHl6f/OyV+G/hFt6go=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=WyuoACzFmvYq9ovJ3Zjflhr9GaAF3fkgm5OlcgWxXy+w1fLge2E1qysEkNi68SSRzq+lyjFp9L4ECPyuMxXwwBeaDGp4c17edNz1ka72OZUJQ66oEp3yelw8Zlshj2tGC0RgLp4giny7DseuPsCYUkcyjz7NDR29d7zoW/Q1GJs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=p1x1UV6Q; 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="p1x1UV6Q" Received: by smtp.kernel.org (Postfix) with ESMTPSA id BBEE6C4AF0E; Tue, 23 Jul 2024 18:11:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758304; bh=ITmzVZ1ozdPC3EpkKUw5PXAHmRHl6f/OyV+G/hFt6go=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=p1x1UV6QZQmFQm9ajyXyqUWSDF8heHOtbK3W22bT6fY/vpirKkHlsBsc28w26zpyg IIZ1TnM4Ubox+kwaKEr+69eGZEBh65kwS2yt5KbWIw888g3KGVSvNiGEloahoNvXoO /LjzTfcpJfaK240ZGJr1c+5krXZ/GRU2tNdwU/RS8q9HBp4KgGyLIQRrah+cUXAE7d QHXxwKoctXEF9TB3h+/K3TWfGVY3PfzH3O62bbtYGzANqksggSqNuTJQI5XjSPiLuL IDQ8JPmt0+I5dMCEtBtpcV6VwMo4vYUDY3Od94KgLw2AUbySs16aIFQi/Cxm1I4ZI9 KzUkEqOAKpvlA== 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 v2 09/23] rust: alloc: implement kernel `Box` Date: Tue, 23 Jul 2024 20:09:58 +0200 Message-ID: <20240723181024.21168-10-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 | 32 +++- rust/kernel/prelude.rs | 2 +- rust/kernel/types.rs | 26 +++ 5 files changed, 394 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 90ebe79e86cb..d9809368643e 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..eb4a5ff500b8 --- /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::ptr; +use core::result::Result; + +use crate::types::Unique; + +/// The kernel's `Box` type named [`Box`]. +/// +/// `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 +/// +/// ``` +/// use kernel::alloc::allocator::Kmalloc; +/// +/// let b =3D KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// use kernel::alloc::allocator::KVmalloc; +/// +/// 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_alloc(raw: *mut T, alloc: PhantomData)= -> Self { + // SAFETY: Safe by the requirements of this function. + Box(unsafe { Unique::new_unchecked(raw) }, alloc) + } + + /// Consumes the `Box`, returning a wrapped raw pointer and the = allocator it was + /// allocated with. + pub fn into_raw_alloc(self) -> (*mut T, PhantomData) { + let b =3D ManuallyDrop::new(self); + let alloc =3D unsafe { ptr::read(&b.1) }; + (b.0.as_ptr(), alloc) + } + + /// 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. + unsafe { Box::from_raw_alloc(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(self) -> *mut T { + self.into_raw_alloc().0 + } + + /// 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(self) -> Box { + let raw =3D Box::into_raw(self); + // 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 boxed: Self, value: T) -> Box { + (*boxed).write(value); + // SAFETY: We've just initialized `boxed`'s value. + unsafe { boxed.assume_init() } + } +} + +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()) + } +} + +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: We need to drop `self.0` in place, before we free the b= acking memory. + unsafe { core::ptr::drop_in_place(ptr) }; + + // SAFETY: `ptr` is always properly aligned, dereferenceable and p= oints to an initialized + // instance of `T`. + if unsafe { core::mem::size_of_val(&*ptr) } !=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 68605b633e73..b34c8127b76d 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, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -1183,6 +1183,36 @@ fn try_init(init: impl Init, flags: Flags) = -> Result } } =20 +impl InPlaceInit for KBox { + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + let mut this =3D KBox::<_>::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 KBox::<_>::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 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 9cd20fe41c20..dd602b2efd90 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::{ @@ -89,6 +90,31 @@ 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 () { type Borrowed<'a> =3D (); =20 --=20 2.45.2 From nobody Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D5BD015B0F2; Tue, 23 Jul 2024 18:11: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=1721758309; cv=none; b=bGbvizXC/GUMbIv0HPhSAvtsrI9SY2XXI42johUyYFCVWJisuaXeTOAcmD7hvQnmojkhZdUW10lFIXlzx66MDPl+vjTDrXPqf6IhYBwR9muSGvteD4oX63kHeRN9HV+bkBbFkY1GoB1ujc/fMBF/LzEXa6m79t1YIVP+EWsqIP4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758309; c=relaxed/simple; bh=5g7r2VPtY3bDOuGLZSS4fG/C0++8XYbEf2Kc3K71oVA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=O7/nCpGY5Y8Qfu5g8Gq8lX3+T36DqYLCe0MdWTI5gp8g0CTrH+OmcAeRMRxeLeaROz9OktNcdrCgCUF8RvYiWAoUBUp0uimaqLGRy2Iv5F7PDdel9htRtzIymZdFZ1Fw1v7BBqUvYcWotl45qcsXK567gINk2jsEFUSJvKW6lBg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=BVyGfZg9; 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="BVyGfZg9" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8D0B3C4AF0A; Tue, 23 Jul 2024 18:11:44 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758309; bh=5g7r2VPtY3bDOuGLZSS4fG/C0++8XYbEf2Kc3K71oVA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=BVyGfZg9BwuMSiRJrU5u3Yg9Fq/8t98ebvlab9kPrBntYbGtdNFL3FQ0vLRgx5+CG mdGJgDIFXFqsf0qPVefQLHALrmEGCD5AvUo/4crl+N5z3oyBInFjL4axXoM2sY+Nh8 Zvxd+DCuCQbwAosh1M8IhtjqTIu0wzbBQj0Z0O71fqckbC/wqpvDVftj4xQlEp5XRx qodVyDjNpiNj3gbmKtV4cZI35/Ro0LuBFLmzAj3DRlnCR72CB9FY6yUo/bxG9bgfzQ sQ7ylymnNA0Qvz1ywYQ2QtBcoQACExyeVFNfW3qBwMM5/BHKZNVdEG1V150QZnCEta ba8W1frLcd+qw== 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 v2 10/23] rust: treewide: switch to our kernel `Box` type Date: Tue, 23 Jul 2024 20:09:59 +0200 Message-ID: <20240723181024.21168-11-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 --- rust/kernel/init.rs | 39 ++++++++++++++++--------------- 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, 43 insertions(+), 43 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index b34c8127b76d..f50b9bfe660f 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)?, //! }) //! } //! } @@ -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, @@ -927,7 +927,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, @@ -1013,8 +1013,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( @@ -1351,7 +1352,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 1cec63a2aea8..47c8a3df0b8b 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. @@ -563,7 +563,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, @@ -574,7 +574,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 @@ -582,7 +582,7 @@ unsafe impl WorkItemPointer for P= in> } } =20 -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -596,9 +596,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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 7634A15B111; Tue, 23 Jul 2024 18:11:55 +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=1721758315; cv=none; b=PovEWSLQ2ZWEhyKT7RnLDNtMvYdMhQymorrTWoEunYvBjWyMaJp+LB6DRhGZlTRbfsVogG5LsnfvbZQi2VYS83DqyBQG3YWdvmXoD7kb0xGZLTO7QNNUFMGB32OvpvYqXBg/mp09AiqE885kptFauXQS9g1+VuSKEbl6RbeUflc= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758315; c=relaxed/simple; bh=WKQ7MgfG0G2WqgFeLi609/hjUACQHn7VtgxgOOJDNdM=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=Ypnl7I1MlW+5Jo7xIoycLYRAK7Qzm74IwRIlHw/ZPcfsZ9GaxteP1SkOvtqttLwmN8mHdAf6BtWF+vA2X5LCGecAV8RpR70N6CBon5i9u9PPW07peiy1f7cGVCa4KSEjcsJY5ij9CywH7Gc620pxjdeveQ847nHUi5ZhuCu5QHs= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=e1HhX2TU; 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="e1HhX2TU" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 33385C4AF0B; Tue, 23 Jul 2024 18:11:50 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758315; bh=WKQ7MgfG0G2WqgFeLi609/hjUACQHn7VtgxgOOJDNdM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=e1HhX2TUsXA5lDi6g8kfBkK3mAIwKt9uoYOQdosNu+OHw1A7jqp8ZDRDhw+k+5wOe bAJnArcHiqoBqCIDImAag+HqFn491JNE26ZBL1A7F0BpHyPj4sWwtulN1JtiUmb4vz jiuBzOZF8ml+0GcUSsvb5UEPTB1YH6DsFjVaNu1r/dvPTI7V7EgriuZtaCsi7dyany 8Jt9U/bjJdqNKzHz4WUdkXW1ojIZp+S2zl6Samuh2aYbtA9q3RaiA2G2JR9SArjhXO /sLXOhPzPVNXn4qNn+pn331ORSDA5pVcKsK7WVscLQGuYTtyk7ef4zys6+KUAmNBp7 LoFtjsayUKEWw== 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 v2 11/23] rust: alloc: remove `BoxExt` extension Date: Tue, 23 Jul 2024 20:10:00 +0200 Message-ID: <20240723181024.21168-12-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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. 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 | 22 -------------- 6 files changed, 3 insertions(+), 115 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index d9809368643e..48c008ab340d 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 f50b9bfe660f..a1cd7ced70f9 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, Flags, KBox}, + alloc::{AllocError, 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 { @@ -1154,36 +1152,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 KBox { #[inline] fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 2cf7c6b6f66b..6ae20a23de46 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 dd602b2efd90..d67b37a5edb8 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}, @@ -68,27 +67,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 _) } - } -} =20 impl ForeignOwnable for crate::alloc::Box where --=20 2.45.2 From nobody Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 5B933158A00; Tue, 23 Jul 2024 18:12:01 +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=1721758321; cv=none; b=pYNHgPD05vie9XJbUa3hXd9puc95CVdo4bUMxxQUnicy3zQPxT3OzfX2ZQhLavY6iYqvP7qtYNVHScvODCu+6tXhoAo9FAiu1I1Ddn45oqjHnp1ymJ7PoVS2G2UfkWsVLThdwTdoeJsOSGqDnDiQexVnTiRYuuy6rc4qI2rLoNk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758321; c=relaxed/simple; bh=IsegupDL6dNouhj9LI4K0JPI4QQWWwWlwU04wMc/SwI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=fXsy+OgvpeeKa/6Gy8o7T5sJ/CLy0eQyJqlfxOC3goDUd+6F/Y1FkdyipNS1ks5UlkXTSbJANcfyOg6xQSj/7oIHOmV8jPDbPuiKWA/ASJrC9752B20KKoDll8jKxbv4Iyk5wNtRzfmEDbrYPBo+DO6AHyAiEUK14tX+u0GI6zg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=mz+c3jib; 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="mz+c3jib" Received: by smtp.kernel.org (Postfix) with ESMTPSA id C81ECC4AF0A; Tue, 23 Jul 2024 18:11:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758321; bh=IsegupDL6dNouhj9LI4K0JPI4QQWWwWlwU04wMc/SwI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mz+c3jibuWgJwcKZM7aGqSADuz6ejR/ZC+t7GQrirU7NnutbHsXT+uJXKZb4R9isB rHeWk5FliserG8OO84VXZRoBXyHeglwLW8dxd/RWCofCPQVFhOZ2t0qCXAXD0FRNuz Hle+I8HjZ/w5RNPtbZTY0zZTnON2De2BWvXnbDZBFrZKuqwn7iJ+ZbTU+50uGLYEmi Hr07A4LgDXLVHFapDWKC4BU+clELnUWbr7jFSqwK4IzENwCrlbHfypc6v9hOf2LeBg yOnDFA5qpGPFY56bCw6G28x9cbkY+/MIFWO56Xh/+hOnZaMs7pLCyS9C6CxGMoa1in rB73961xp9k5g== 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 v2 12/23] rust: alloc: add `Box` to prelude Date: Tue, 23 Jul 2024 20:10:01 +0200 Message-ID: <20240723181024.21168-13-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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. Signed-off-by: Danilo Krummrich --- 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id CE013158A01; Tue, 23 Jul 2024 18:12:06 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=10.30.226.201 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758326; cv=none; b=KQbIipLiEeyRwcDFd+LzD3tkln9URCnLj+TOsypOumjOA32RLyqUYZMdcZE+oDqX0eEwe3NvHf6fynuV8wShIbDKH4Q6eD8UcOg70Iz9/DmTA13TCodzrrMLV0kgABGWcehXRD0lGzpY0lE9gxnke9U859Y+/m8NAxIIaBeNKl8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758326; c=relaxed/simple; bh=/9+EutwFn2+cS9gNKuR0E554iCROCZoKL1CdsGgwb8c=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=l715DHye1H4LWaGZ9Kakt13R5d9fZ5MF3ctYexYj+aOm3XbqQ6hJOC93P5kZBZNOtyTxfwZCfiFcjGT7knhY5FKdllrgN2AL+nAIkj8imhF0L5UJMgTbk9gOB9mzVKm+MiCRG9OyBUbMJMyEFoO2SEEa0j7Qewe9it094KTFLTI= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=sLoQu3Om; 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="sLoQu3Om" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 78AACC4AF0B; Tue, 23 Jul 2024 18:12:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758326; bh=/9+EutwFn2+cS9gNKuR0E554iCROCZoKL1CdsGgwb8c=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=sLoQu3OmR4kR03BZ8aJlI9lV2J2cK5q15+YM0g9Mk3OdIv99lwhllIfwFbxAjDPC7 HEnHKhrUzctHyMCZubcBLDIYnasV0oih0b4l8i8KKkDl1cTVVSZeu5e8LCNtXC9umw ePCdXJCWkjhzKSab4zyxHHvCfTN1E96TI1Y98S+fDFoQZzdkh2+NlSOv7IoxINuKCO Zk2LoBFwQLTP4+xHE4wyhAHcPm8YeMUUFW0+qqSp6flIxknGQD42hXLewq85y1cAth FLFbS9W39HLuUQ5Wph9CZsa9pgiQFbH6DqanRCeBaRElTVvTKwdx9dPpacwWGPZdEF c8Bc9x1nNVNmw== 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 v2 13/23] rust: alloc: import kernel `Box` type in types.rs Date: Tue, 23 Jul 2024 20:10:02 +0200 Message-ID: <20240723181024.21168-14-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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. Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index d67b37a5edb8..ee0063a20d89 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, @@ -67,15 +67,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,7 +88,7 @@ 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 --=20 2.45.2 From nobody Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B446F158A03; Tue, 23 Jul 2024 18:12:12 +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=1721758332; cv=none; b=QI5XCvnuIYNMcSP4g6NGnZCeZpdv0V4nB724UfaL2jL2BHMj3wYYiC0RZUv6/PLh0/gdZ4emUcnO8XwtL9rRNXmBHDO5uCn+g2HsZLACO2ejZeGs5rQWfq+TUwb9JmUt8fiEl8VjNW1oFCMWetximIkYE91TMdoJqls7w1l6PFE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758332; c=relaxed/simple; bh=bZNDSa939dmJFDRhKIU+Bh6SyOAqA59VXE7BB2QVuYY=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=gfIrgb2mkkQb9roiy6gHKares5Brqd00+7vxZ3wp8jYsDQoG+52X/9mIGo/fdcLC6Ka6mPuSMLWbV2PljdCRMrzLGRbcXeIlhB50S9frm1NsWf3boUBID1cr5mQ9ZKAC830Mn9f8aKyYHz9nCFbF5SGn8h/23XSnReoeuezuLF0= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=hRmdw7g4; 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="hRmdw7g4" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1D9AFC4AF09; Tue, 23 Jul 2024 18:12:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758332; bh=bZNDSa939dmJFDRhKIU+Bh6SyOAqA59VXE7BB2QVuYY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hRmdw7g4ZHQEAB54I74N5jNbb7BYLMiZZjW0RmyrvhGUSnHwvEAepyIP6SgELeSof boD2uZxja24NGRFQiD7u/F1pfEG4fq5vcRW5mKNKm7ELlrHsV9XWUPhScJCHUGVKZp zDq1Y1ffxQTd3S+ikuqGnfQxiXtINa2c5RmW/zntn9xPAvK4ae3Rni101D433R/gGV 68GC+SMSckZr+Q/cWxD6hgtAVGBOvAaohKVlCyTs8ewatkaKEoTAJxhbNbjGKquxG6 Y5jSnol/aiy24ZW4JmSXu/NVVfhMblyRYAYpKPpnd6U3brpGmtrPEPfVGOZ87yrKDT 1XbX9yMViGeHg== 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 v2 14/23] rust: alloc: implement kernel `Vec` type Date: Tue, 23 Jul 2024 20:10:03 +0200 Message-ID: <20240723181024.21168-15-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 | 580 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 4 files changed, 602 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 48c008ab340d..827922e1f1d1 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 eb4a5ff500b8..d7b0b790a424 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; @@ -173,6 +173,20 @@ pub fn into_pin(b: Self) -> Pin } } =20 +impl Box<[T; N], A> +where + A: Allocator, +{ + /// Convert a `Box<[T], A>` to a `Vec`. + pub fn into_vec(self) -> Vec { + let len =3D self.len(); + unsafe { + let ptr =3D self.into_raw(); + 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..58b3f679ad83 --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,580 @@ +// 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, + ptr, 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 named [`Vec`]. +/// +/// 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, + /// Never used for ZSTs; it's `capacity()`'s responsibility to return = usize::MAX in that case. + /// + /// # Safety + /// + /// `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 a reference to the underlying allocator. + #[inline] + pub fn allocator(&self) -> &PhantomData { + &self._p + } + + /// 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 + } + + /// Like `new`, but parameterized over the choice of allocator for the= returned `Vec`. + #[inline] + pub const fn new() -> Self { + Self { + ptr: Unique::dangling(), + cap: 0, + len: 0, + _p: PhantomData::, + } + } + + fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // Note: + // This method is not implemented in terms of `split_at_spare_mut`, + // to prevent invalidation of pointers to the buffer. + 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 `alloc= `. + /// - `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`. + /// + /// # 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(); + /// + /// unsafe { ptr.add(len).write(4) }; + /// len +=3D 1; + /// + /// 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 { + 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 `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)?; + + // 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(); + 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)?; + + unsafe { + let mut ptr =3D self.as_mut_ptr().add(self.len()); + + // Write all elements except the last one + for _ in 1..n { + ptr::write(ptr, value.clone()); + ptr =3D ptr.add(1); + } + + if n > 0 { + // We can write the last element directly without cloning = needlessly + ptr::write(ptr, 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] { + 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] { + 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 122A515B972; Tue, 23 Jul 2024 18:12:18 +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=1721758338; cv=none; b=pJ9/jvb5w/lIz1csLm8zz2u6WtaykGa8GrA1tsN7cUOTQrjUmZrYf5ylXlere3yIZili4Cf+tKDcAy2cUCIJitLSJ2kCzHl9H1t+vZWF+9cNNGPDZDbXpeK4aaUGCTJojVN0REMyc67eFUxdFgH4hzRtapH15GRZF3ZA+Oj5N8g= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758338; c=relaxed/simple; bh=c3QAEBZXl3M1WsOmfNh19vNXUNzyZvBix2UsBjiGOtI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=sJkUM7Dnl5P5wgf+pTGC44ASK2D69rGeOHcLjnRa61hAQZUKZGSr4yedRGdhdoDfe0EguTNla5l7NMQhifEVxdftE4hWxuYXdN1S8RLYXAbXJ5Xft775+1eWVgWDCTyvkoX02ccG8r0qUiYA8fYYiB7LsF+zPF5mS5icjt7XfMc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=ASoYC5Ro; 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="ASoYC5Ro" Received: by smtp.kernel.org (Postfix) with ESMTPSA id B70FCC4AF0A; Tue, 23 Jul 2024 18:12:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758337; bh=c3QAEBZXl3M1WsOmfNh19vNXUNzyZvBix2UsBjiGOtI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ASoYC5RoyFxVt1qORsF7cKfWeydOo+meew08vpzJjAAxJiB8eIifrdSo9n0K9QN88 IoR3tEeo+y4EqksYwvQz/OPsRDe2OKxBfrdZqgY2g15Rto6/wMtHsHnQVuqZjxJpE3 KH20JQVp77kvTCJtWlrgxNSVDtLNhAbGePPbfNAXZ4ymEhnejSzwc4/FbCVWCKCSTX AyFoOjfoq4hoZtQf4lMM7MoYvUN5hxC3Y8SPnyYCC9yZKsJw+pp5CvjJf9r7+H5ps6 7JHpY+kwXX6Fo9b6XB4J/ZSkQoczgRAQ1O1ijBoprzvvG0tXCxOlUxbM6IfGA8tU2n W4T0bgS7ldmbQ== 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 v2 15/23] rust: alloc: implement `IntoIterator` for `Vec` Date: Tue, 23 Jul 2024 20:10:04 +0200 Message-ID: <20240723181024.21168-16-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 | 175 +++++++++++++++++++++++++++++++++++++- 2 files changed, 175 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 827922e1f1d1..19e0ad0bf98b 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 58b3f679ad83..fbfb755b252d 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -12,7 +12,9 @@ ops::DerefMut, ops::Index, ops::IndexMut, - ptr, slice, + ptr, + ptr::NonNull, + slice, slice::SliceIndex, }; =20 @@ -578,3 +580,174 @@ 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>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (ptr, len, cap) =3D self.into_raw_parts(); + + IntoIter { + ptr, + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +} --=20 2.45.2 From nobody Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id B286015CD60; Tue, 23 Jul 2024 18:12:23 +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=1721758343; cv=none; b=G9dgZgmjo0Mc8JcHKhGLZFaEZiCkS/yJ6wP69VFHt6o/Rh67f6n9+ik66IMiTiqvcxxU/FWYyzZoz4MLSmq88r0xkFpOLwKDrwV27Vc/kFTvVgMT0FV1JQC1NGqTRDMYqBntdcQz5kbsfh+J1VhOE1GJoA0xjLLS4M9wxARPcU4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758343; c=relaxed/simple; bh=ycTccZRzwhnWmuZYl2yN5kvt/i9Cmr0VW9EfC/7UA54=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=JeYBZ2WWJ5vTOwPP0ubuv0WtFJ6SV1TKnwUy45qxjPqDszysVyzclp+gUHgfLbI6xRwux2LT8z5FV7e1v1eZ17m+KvM2U9HPcPr9Pa4r/Fpzu3JZM+gOqIbBIbR1v0+YmepYv+JxP1lcVy5hvkioooAjTfIPoR7ltcJLRuUZitA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=b6wl7t6V; 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="b6wl7t6V" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 65FCAC4AF0E; Tue, 23 Jul 2024 18:12:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758343; bh=ycTccZRzwhnWmuZYl2yN5kvt/i9Cmr0VW9EfC/7UA54=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=b6wl7t6Vnx/yEyZvnuZI8xejX+EMDqYiC6oixtqi/wC6OK3zAe8IYO6hbfIV8Ma17 RLaPGrXo7rmTxgNQsHHTld9g3PEBCvQv37hOE6l4eGRycKf3zDA6Ds91DfzKciIRJa xrJISI+8CpDkcJvGGqsiv2f8NIOZoQaebEQGdV8TPKFui73DeJNhn/C0DdSKZD+W1N EWZuuocRtFqpv8tzGfD4nbDUCqzsDaPU0a8cpGlp1G6UQn08G1EvnJDiAkj/QNDeRa 4r+Y1p3whwd4s+LMBVGqd0ARazU1VyOY7jVc6P2Sel5BoUB+gK/Nn+ud9PeO7QF458 d5aCwheSsNJqw== 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 v2 16/23] rust: alloc: implement `collect` for `IntoIter` Date: Tue, 23 Jul 2024 20:10:05 +0200 Message-ID: <20240723181024.21168-17-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 80 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index fbfb755b252d..5c317931e14c 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -2,7 +2,7 @@ =20 //! Implementation of [`Vec`]. =20 -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use crate::types::Unique; use core::{ fmt, @@ -633,6 +633,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(); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn collect(self) -> 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, GFP_KE= RNEL) } { + // 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 97FFF158A04; Tue, 23 Jul 2024 18:12:29 +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=1721758349; cv=none; b=Zz4S0d5+sJUPKPwyTJFjLs3mJ00iyH4t+PBTzXjc/mWeCm9KF4OzCdNHwDo75/VKJhLotWjEohwNj1xJi/o/x5Q9ZqNSADOHtOMCKHsSgoXzJavYzggpDnWlahaQ4yvQCOSo0jVVtJyNOrYnKaFLXTEeKfHCDvkK4Jnk8y++KfY= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758349; c=relaxed/simple; bh=ZR4Fo+HZj9co1hH1bISCrg/JiIevl/irl2SNGK/8Ii4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=AJgSvJzkvPkXm0VR5NKhY5fLoNxOiREKt51naF9650i5BqQcRJsX+/t1nbG/s2wsPnppqb2GAGS3IAWQXoJq4bReICLusb+ZFOpVHw8GTAK+4v2SZx37NFwbHeSeOV/1+c1hTknGt/yCaLSmppdYOvdw7y2My6IrNtUfaTsHXp4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=RV28c3//; 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="RV28c3//" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 124D9C4AF0A; Tue, 23 Jul 2024 18:12:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758349; bh=ZR4Fo+HZj9co1hH1bISCrg/JiIevl/irl2SNGK/8Ii4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RV28c3//uLcAxuxyQ4q2PzPazVc7pkV/uDYzo584ecF2wHHFrQu1m5aYbduVs8IXV 3a9VimG5b8laP5/9+vN/6hKebRM5UOo85EsqOvFtKaKCWD6oSv78iUsKjGz0tvxyOz 7jRFR5awXL0QQTpgcB7UbgMw4rjF9FmpijHFYBCFSEKqVGenxjo2296lW9rSQxf+bm n/hwej7dKn+JCDtCXjKInZEjFJeal1gEigVrHxw86rZP18+xeMk8EYmH9T/EzdiQuS 4ErY6STPAia77ZCcEkMs2vB764hDJWzWGznqPy4VgOjoLgE2tJtsAMPqJU2XtMZ7Bd zmaR24IdxV2sg== 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 v2 17/23] rust: treewide: switch to the kernel `Vec` type Date: Tue, 23 Jul 2024 20:10:06 +0200 Message-ID: <20240723181024.21168-18-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- samples/rust/rust_minimal.rs | 4 ++-- 4 files changed, 9 insertions(+), 11 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 ee0063a20d89..05521403ed2c 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -158,7 +158,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/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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 0324C1586CD; Tue, 23 Jul 2024 18:12:34 +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=1721758355; cv=none; b=uhuWMCwf3H0bc9peN6HHtNB/SzTil1/YTPUiD68dzOE/UG6MqXiYGKENoEkdxHyLp5zJso9gtjZfWcxpw77XUbCZTBFJ/eZFifbczCqVc92lR9UYP/srocxt4zR79DOSljJ4jAVO36yRaX5HPbIYtUQFHoMdKw1G3ZobDJrIKxw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758355; c=relaxed/simple; bh=v+FEyM3f1W9pgO4n2QEpRohKmGGAf1lyhUx0wNLCTZ8=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=ZTINNF4V6pZ8zP1sluD0BUBtXAioL/FZURBiWRDVr7yFTU9tKTOrz4Ka4GgsGopeLsdEKc0/Mi8Yi8eoEf0/7jlbR1/KbL0SsKKCY1SomkgGrwmI1bn2BwzK0yaUmvtK0zMOIn05fEW/ROnwoTfWIZ/YFD4EtPyrE/9BiVL1FZQ= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=VnjfxRKx; 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="VnjfxRKx" Received: by smtp.kernel.org (Postfix) with ESMTPSA id AF969C4AF0B; Tue, 23 Jul 2024 18:12:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758354; bh=v+FEyM3f1W9pgO4n2QEpRohKmGGAf1lyhUx0wNLCTZ8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=VnjfxRKxJbjIo7fDXiWg8utw/tN1yQVjbRBRa7Gnkz5fHAQLnzcQup0oPSK2MVhXG OsH7P2CHWUArVtYdY6TCQ41C1E/BqzweQZmFJXPBzPDMzP6/61s4if+nhHMGxK4387 A7YnlMmPTi8w9gCpdE38+uwnWho7eTYj+SR43XtcbTqYujaBI2B09piLyuS3ZzJyN7 STTdiHR5y01vzyyDU1jAiHzhmZyQdLjT5MIxxg0Xsqv/n7mhoQdAZBE/XWo0HpVJKB LzfucShQemHBvNAvy+rXO9pGQmD6BJFIXV03h1hdB7+4SIdb5+O6vDwmj/P513zPNP 0um2jlDS9sxMg== 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 v2 18/23] rust: alloc: remove `VecExt` extension Date: Tue, 23 Jul 2024 20:10:07 +0200 Message-ID: <20240723181024.21168-19-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 --- 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 19e0ad0bf98b..62838738f409 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 095E91586CD; Tue, 23 Jul 2024 18:12:40 +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=1721758361; cv=none; b=A1Kwmw8NwfGg6qqvIB2/34uFq5Fut/50B1auHMkOQtlVm290PaTn/h7yaDRQ5BtwOHSMrfYr9r23pb7Nugo7NZdT/PNHxOPJM7Bu12Qu3oIO5hX83G5W420Xhu+XiovbyFbeZ0MUgF08QCUYjRFg+Hd8fdHXrqF9eRyU9AICbbE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758361; c=relaxed/simple; bh=x0JvvRfi87BBCBI94b39MtnQOfc5sS9njBcl08nLwWQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=g2ZID7nNN+qw4cEbOPTOJaSyvXEqjODrJ0Ont4eJpwdmW4kSjrzOxmc1aw8KdQErtJRDUvWxnbXcWjlM27lrBftnhWHwq/bTpE1tL0EnnfRyLTY0CeP3U3b+zvZ+rXM+I35SwVgzKBBCu/+uzS8mossIYf9YXp8g902Ac4j2b88= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=dF0TMqoc; 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="dF0TMqoc" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 57B0AC4AF09; Tue, 23 Jul 2024 18:12:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758360; bh=x0JvvRfi87BBCBI94b39MtnQOfc5sS9njBcl08nLwWQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dF0TMqocS5E0+WZ7U2tM4lCRj0VbkcHUh59kSwlafs/iP9FjkjwpShpZM0QwzVErE wr9urpHSVBr6lLNiqiL2kb+LUULbHpammoO8zdEmAkI2EesoB13TN0O+lOdaZIltvk KJ+wmaDX91QSC7JkZdJfG0MpyOCY01MofbIG5bu0mMKN7UY/2jghk5Nl4RtORfL4p0 sYyIl54YuE2r13obYVbDCfxyfLSB0xtNbK8bItOcY2BglI5tbcYd8Au8ax6Zg2Nt9K 2HS0o1kAJuKwdrf4nVZ9vviO/dhPbGQjYYDxMzpgfHytCXlSjj6+YPqD6foRlzNRhv zhkVkTY6S7ilw== 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 v2 19/23] rust: alloc: add `Vec` to prelude Date: Tue, 23 Jul 2024 20:10:08 +0200 Message-ID: <20240723181024.21168-20-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 --- 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8EED41586F6; Tue, 23 Jul 2024 18:12: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=1721758367; cv=none; b=KTro6QS7SJzuxaO9lbRl0Y3TzUlKQAcSgKy9NiZNR4tC6GZ5sdnonNiQMEvF2Ldb6L0WxQPZEMTp4hJrZxpHgE+4NMxoxRUcT7ivbO2sC6MP8XZUruJxx6BxpHUUbCA4bximdAzMeieRMR5+P/9PsYZ9tpLmcIW9vnPYmJYfcL8= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758367; c=relaxed/simple; bh=hs6yx2vsssnsC1cMGPjQ8GCbMEe+TcUfgVzllRdmHcQ=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=jptD7DaayNgMmjbWnRqQ9vJaTkn1nQkw7HR2PbXH7fJThDHseaiL8F61rRRKN2Gp0Won+OTnYNs3wbXPPIXFQXt1qE3edBk1+PIn0L0CT5TWx+2PzCu+7vAmYQpG64XoehAmy7NxLlt3x+Yqe6tlvLT67s+2Zqy2cWi8a+7iRKc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=QrqjLlOl; 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="QrqjLlOl" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 01C23C4AF0F; Tue, 23 Jul 2024 18:12:40 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758366; bh=hs6yx2vsssnsC1cMGPjQ8GCbMEe+TcUfgVzllRdmHcQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QrqjLlOlUH7v2hvkeiyaOJgc8Oh7GHD2if+LolauVZpdSjXJUzYAuQSO2G/BzwM5a AiiIxDaMskwTxGJy7m1wRE3mRn+MgcsrMoFfCM2jX0p1VeXsMAdcuVKwrBcxbtAVap N8yVJHcsAAoTB1CKwwVVjKF9duYwYdIOfsGllMFjDQI0TlX/+Nvm54Os3pUOrmTdvp 8QwWTfKrIcqQDSHMODvSnN7m7+O4chstkokwWJnPrzXHLHbSa4PcpOpxKw9Spm5ecv SK/gnFUPteAQ6WvAFwlrrE4SkuWjarVlw4ifOSDMcOzGALc0arYSU0kyzasYjAL0MR aSvxiwry37BOQ== 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 v2 20/23] rust: alloc: remove `GlobalAlloc` and `krealloc_aligned` Date: Tue, 23 Jul 2024 20:10:09 +0200 Message-ID: <20240723181024.21168-21-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 1e53f149db96..fbee89ac3be4 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 @@ -39,27 +39,6 @@ fn aligned_size(new_layout: Layout) -> usize { layout.size() } =20 -/// Calls `krealloc` with a proper size to alloc a new object. -/// -/// # 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 - } -} - struct ReallocFunc( // INVARIANT: One of the following `krealloc`, `vrealloc`, `kvrealloc`. unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut cor= e::ffi::c_void, @@ -121,41 +100,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>, @@ -184,9 +128,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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 4B10F158A32; Tue, 23 Jul 2024 18:12:51 +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=1721758372; cv=none; b=d8zV1d20BL45PmAZ6Iax9g8HJ7rVfhOzNS18AN01UkCOi436IyOArcExSa5W+zzGP6dOeOwIqUh866RG0ze0Fgx3J844Ga0iH5e+NKR1+z1V/KhqvvDIpkAY4+/8uIPhbv1wxxjbkweejk5KR+c123G5BnY5H0VM/J5rCDko9wo= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758372; c=relaxed/simple; bh=ifLa6ui520OxD4tx6GpOL1mZtUOCjuqJJxFCxi3qo5o=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=rIH1KdPu5iJambbGMnZ/eIt0uR+awNsAjuuJB+Etryb61ossl1YnGlsZGMgMzhoImOAQGb1ZnX3nBz9slD2jz8hsfZ71G026fgcVCUhzh6OLj63/tWTR4wXOIjYvK6kiUXTkYw46BByQKHQODEO4XZ7JLiF+p+YHqA00Y3k2Zr4= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=hdTrNimT; 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="hdTrNimT" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9BDDAC4AF09; Tue, 23 Jul 2024 18:12:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758371; bh=ifLa6ui520OxD4tx6GpOL1mZtUOCjuqJJxFCxi3qo5o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hdTrNimTX0/gfTHgSGZoFmyF1daiFhFp3RcVFXy3Z1FWilSHjnN5DFRMjhFSO6rbd qgu6sUkW92cLIqvrtJFtPWeF1TILjkgG42fMbLGKsBZSPcbXQBiM/t0QcJamXj5lY5 wR8QhjcGGIUaBUSxDPcWTaXp8/EQ5aYE/eIIeBx6RcX4JNYqQwGeoz3pgtjD975Z3y L5fvLLI7EeXF1LtxDngf/2iwXpEeiKjBWktrSadsuMQFLf3XU6GzkSABFzV92OhF0o 3qfWeDp9ONMjDc7tGt3Vmlc9VT509onYY9nqkJCQ11DguV42LBzkkPySGyQAeaIL+W OP4Xqx2ia0+sQ== 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 v2 21/23] rust: error: use `core::alloc::LayoutError` Date: Tue, 23 Jul 2024 20:10:10 +0200 Message-ID: <20240723181024.21168-22-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 --- 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 Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A3E6E15ECF2; Tue, 23 Jul 2024 18:12: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=1721758377; cv=none; b=HE500U9xoW8lwzF+Xjxjfrwyvw6I73IO5nUrs0TZKpqoD5RKbon89DBqDY1TcRcXEh4T8M2AgsjNK2aGsCpflT3ick0ne8ZsYdP552N5dzIUxxh8hQ0ugQx6HvS7hA+CyD/Wqo3ca7ebSCPbJUmOX7b5bemiOdGRDK7lAvT+c84= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758377; c=relaxed/simple; bh=T1EttxerGLScRoG6GW0jYhIkm3ad2nbCx6FWpPy4fh4=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=qbwUUY+dkN61BJ3zSPP0jgIn9WoYeOk5Vcvrnsfd85ArAPzaKJPa/o1OXbzlcoFKJCSKI+wUXNaGlwEv3LTfnMkLHyuysyQ8FUjEbxZSXn2c99aeVFRq7/dJpQziCpyqFV+Gqdl3mFoy4dIC4yxxqu2fov6D6puLzPemRvFn+JM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=J0RXP0db; 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="J0RXP0db" Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4AFC6C4AF0B; Tue, 23 Jul 2024 18:12:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758377; bh=T1EttxerGLScRoG6GW0jYhIkm3ad2nbCx6FWpPy4fh4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=J0RXP0dbPwGzR+rORI/s2uRU5IGUpMivgIb5y0Am/yl8eA32+7NG9CPLBs6JsISP+ Pv723LUGJdQxGRf9xDdWrzBujCnAShAT1yjsnxaA/yjBOI1l3D4LvZd4l51gvJbDQl 3R6fdXefl3BpmHurcim61dOTdk3cbHf/k5zWSFbMbBLELXXTDnADzrxvTC/3QuqK/L dhF0fWDxWnhntIsInBNPgUYtHsm4/UqrNMyBoDbuAot0v/lPxBeGrU9koUaTZ2Ru67 wMxeC7muSNLYaueEb4/YrzDLpcjhh7Cr2wOC1EH9d52fqOXT9gF+kjU/G6y2f55w3Z szHse+m56vEbg== 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 v2 22/23] rust: str: test: replace `alloc::format` Date: Tue, 23 Jul 2024 20:10:11 +0200 Message-ID: <20240723181024.21168-23-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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, we could implement `format!` for `CString`, however `CString` uses the kernel `Vec` type and hence the kernel allocators, which can't be used for tests run in userspace. Instead, implement `fmt_assert_eq`, which formats strings into a stack allocated buffer for comparison with a `&str`. Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 66 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 0b6ffbade521..539be40754f4 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,6 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; =20 const ALL_ASCII_CHARS: &'static str =3D "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d= \\x0e\\x0f\ @@ -539,6 +538,33 @@ mod tests { \\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\= \xed\\xee\\xef\ \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\= \xfd\\xfe\\xff"; =20 + fn format_into_buf<'a>(args: fmt::Arguments<'_>, buf: &'a mut [u8]) ->= Result<&'a str, Error> { + let mut f =3D RawFormatter::new(); + f.write_fmt(args)?; + let size =3D f.bytes_written(); + + assert!(buf.len() >=3D size); + + // SAFETY: `buf` has at least a size of `size` bytes and is valid = for writes. + let mut f =3D unsafe { Formatter::from_buffer(buf.as_mut_ptr(), si= ze) }; + f.write_fmt(args)?; + + Ok(core::str::from_utf8(&buf[0..size])?) + } + + macro_rules! fmt_assert_eq { + ($str:expr, $($f:tt)*) =3D> ({ + let mut buf =3D [0_u8; ALL_ASCII_CHARS.len()]; + + let s =3D match format_into_buf(kernel::fmt!($($f)*), &mut buf= ) { + Ok(s) =3D> s, + Err(_) =3D> panic!("Could not format into buffer."), + }; + + assert_eq!($str, s); + }) + } + #[test] fn test_cstr_to_str() { let good_bytes =3D b"\xf0\x9f\xa6\x80\0"; @@ -566,13 +592,13 @@ fn test_cstr_as_str_unchecked() { #[test] fn test_cstr_display() { let hello_world =3D CStr::from_bytes_with_nul(b"hello, world!\0").= unwrap(); - assert_eq!(format!("{}", hello_world), "hello, world!"); + fmt_assert_eq!("hello, world!", "{}", hello_world); let non_printables =3D CStr::from_bytes_with_nul(b"\x01\x09\x0a\0"= ).unwrap(); - assert_eq!(format!("{}", non_printables), "\\x01\\x09\\x0a"); + fmt_assert_eq!("\\x01\\x09\\x0a", "{}", non_printables); let non_ascii =3D CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").un= wrap(); - assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); + fmt_assert_eq!("d\\xe9j\\xe0 vu", "{}", non_ascii); let good_bytes =3D CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0"= ).unwrap(); - assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + fmt_assert_eq!("\\xf0\\x9f\\xa6\\x80", "{}", good_bytes); } =20 #[test] @@ -583,47 +609,47 @@ fn test_cstr_display_all_bytes() { bytes[i as usize] =3D i.wrapping_add(1); } let cstr =3D CStr::from_bytes_with_nul(&bytes).unwrap(); - assert_eq!(format!("{}", cstr), ALL_ASCII_CHARS); + fmt_assert_eq!(ALL_ASCII_CHARS, "{}", cstr); } =20 #[test] fn test_cstr_debug() { let hello_world =3D CStr::from_bytes_with_nul(b"hello, world!\0").= unwrap(); - assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); + fmt_assert_eq!("\"hello, world!\"", "{:?}", hello_world); let non_printables =3D CStr::from_bytes_with_nul(b"\x01\x09\x0a\0"= ).unwrap(); - assert_eq!(format!("{:?}", non_printables), "\"\\x01\\x09\\x0a\""); + fmt_assert_eq!("\"\\x01\\x09\\x0a\"", "{:?}", non_printables); let non_ascii =3D CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").un= wrap(); - assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); + fmt_assert_eq!("\"d\\xe9j\\xe0 vu\"", "{:?}", non_ascii); let good_bytes =3D CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0"= ).unwrap(); - assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""= ); + fmt_assert_eq!("\"\\xf0\\x9f\\xa6\\x80\"", "{:?}", good_bytes); } =20 #[test] fn test_bstr_display() { let hello_world =3D BStr::from_bytes(b"hello, world!"); - assert_eq!(format!("{}", hello_world), "hello, world!"); + fmt_assert_eq!("hello, world!", "{}", hello_world); let escapes =3D BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); - assert_eq!(format!("{}", escapes), "_\\t_\\n_\\r_\\_'_\"_"); + fmt_assert_eq!("_\\t_\\n_\\r_\\_'_\"_", "{}", escapes); let others =3D BStr::from_bytes(b"\x01"); - assert_eq!(format!("{}", others), "\\x01"); + fmt_assert_eq!("\\x01", "{}", others); let non_ascii =3D BStr::from_bytes(b"d\xe9j\xe0 vu"); - assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); + fmt_assert_eq!("d\\xe9j\\xe0 vu", "{}", non_ascii); let good_bytes =3D BStr::from_bytes(b"\xf0\x9f\xa6\x80"); - assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + fmt_assert_eq!("\\xf0\\x9f\\xa6\\x80", "{}", good_bytes); } =20 #[test] fn test_bstr_debug() { let hello_world =3D BStr::from_bytes(b"hello, world!"); - assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); + fmt_assert_eq!("\"hello, world!\"", "{:?}", hello_world); let escapes =3D BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); - assert_eq!(format!("{:?}", escapes), "\"_\\t_\\n_\\r_\\\\_'_\\\"_\= ""); + fmt_assert_eq!("\"_\\t_\\n_\\r_\\\\_'_\\\"_\"", "{:?}", escapes); let others =3D BStr::from_bytes(b"\x01"); - assert_eq!(format!("{:?}", others), "\"\\x01\""); + fmt_assert_eq!("\"\\x01\"", "{:?}", others); let non_ascii =3D BStr::from_bytes(b"d\xe9j\xe0 vu"); - assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); + fmt_assert_eq!("\"d\\xe9j\\xe0 vu\"", "{:?}", non_ascii); let good_bytes =3D BStr::from_bytes(b"\xf0\x9f\xa6\x80"); - assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""= ); + fmt_assert_eq!("\"\\xf0\\x9f\\xa6\\x80\"", "{:?}", good_bytes); } } =20 --=20 2.45.2 From nobody Mon Sep 16 18:54:56 2024 Received: from smtp.kernel.org (aws-us-west-2-korg-mail-1.web.codeaurora.org [10.30.226.201]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9DE881598E3; Tue, 23 Jul 2024 18:13: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=1721758383; cv=none; b=M2+43LCuX5A+gBiF+jpxGcywM8AbFxuljM0+onsZ2SCiFfiWnPwvjdnpjNu4QD1122MMFbBhABYpxEMhEQi795WlFe7ACxkNriBGlKOEhqnCi1F3efOKif/T+4x/pYw76PrzuGtUSPgBakTKeP3UdYdwSx1K4eNbFHrd7rdUuR0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1721758383; c=relaxed/simple; bh=HhWO+rhzutQW6+RMZ9ncpHmhaR4fD68LK5Csi2zjXug=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=QbZJSF71/oJ7gciN/R9OI8ASRUBeXj0v7clB5G+uQoiZlIGlOQG9qgQHb8JMZYYYZ8BUlNndbw4f96lP6I4be7Q2nkhFxKoFR0f3yHEOi7Movgub+EEddhGqewo0I5yY3K3/UP21iyAx51WaZCwnf+wxKLFE7LS+T2wcORk0bkk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=kernel.org header.i=@kernel.org header.b=GDrEwRtU; 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="GDrEwRtU" Received: by smtp.kernel.org (Postfix) with ESMTPSA id E76F7C4AF0E; Tue, 23 Jul 2024 18:12:57 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758383; bh=HhWO+rhzutQW6+RMZ9ncpHmhaR4fD68LK5Csi2zjXug=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GDrEwRtU2FwzMwAPQUuxnZ8qfEDD+lPzQTCAk85GkkQHagtelzU+hW543pFjAZTWG U8bDqvgxafueyad167YsF8/VUBKrF/B83jgnmVC+LYyZu58G5w5bH3uAIGrVFka3sQ rtaTjf/THkXAqHZbCwGTm4waG9woowf6iW+TFtslGJwd/1N/jM/eh7a2NhV0+zNvmr leS6rELow94lTrR46+nD2cOC+AK2Kjw8LW2lL4wrobTXU5G2vV6n2Shv4BpmYC3rEK b6aPKKoPLuqb2+0PwImS92Cbwa8uy/3ZHe8b0iAJhAf7NANbyxs3ufiPmemUdfdCin 3bDQGBYuBRiiw== 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 v2 23/23] kbuild: rust: remove the `alloc` crate Date: Tue, 23 Jul 2024 20:10:12 +0200 Message-ID: <20240723181024.21168-24-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-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 f70d5e244fee..409be08ad09a 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 @@ -60,11 +59,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)) \ @@ -87,7 +81,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 \ @@ -111,20 +105,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 @@ -169,7 +154,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 \ @@ -251,7 +236,7 @@ rusttest-macros: $(src)/macros/lib.rs rusttest-prepare = 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 rusttest-prepare \ rusttestlib-build_error rusttestlib-macros rusttestlib-bindings \ @@ -364,9 +349,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 @@ -402,7 +384,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 @@ -434,12 +416,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 -Dunreachable_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 @@ -454,9 +430,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