From patchwork Tue Oct 1 14:59:36 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818220 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id E5FF3CEACDC for ; Tue, 1 Oct 2024 15:00:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7424E680005; Tue, 1 Oct 2024 11:00:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6F221280068; Tue, 1 Oct 2024 11:00:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5BB43680005; Tue, 1 Oct 2024 11:00:27 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 3D653280068 for ; Tue, 1 Oct 2024 11:00:27 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id AE60E121477 for ; Tue, 1 Oct 2024 15:00:26 +0000 (UTC) X-FDA: 82625344452.11.CB7D8D4 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf24.hostedemail.com (Postfix) with ESMTP id C01CC180026 for ; Tue, 1 Oct 2024 15:00:23 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hx6rOwgd; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794683; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=CXBFRHwXUbS7Tr/infYoiNrJ0DQJtSF6TY2nk6jPC3s=; b=etokPClbVHlygPCr9aFxTYJs4qNs6UFOUc5EmQM+drw3BVV0NTA6bQd0DneyxcQQ2+/jGu Bf25bEhsSStvp2ys3Hm9jUZwvXhpb3RY4P0cQo/xmiSiMHs1AYsXFE47bO6cnMw5Rkc0l8 +mn/D1ZmgTpLIdVERzLBrtfOBGMP8BQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794683; a=rsa-sha256; cv=none; b=1HdMamUaEFxXw6aSL+lvD6EOqzpCmWHllt5CvqkZ24F3JuUxiXeCeSPrvOyo7uNX1tFN94 7d9m7OBXgE/p3vviCy0YbCixVBJq2WWd++53/hiV6ohiudsRTYYsCOiDbB2IG2BcFv5iiu UerLtavdwy0rwyzUzz9KLGcwJcJyYsU= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hx6rOwgd; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 20401A4381B; Tue, 1 Oct 2024 15:00:14 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 33311C4CED2; Tue, 1 Oct 2024 15:00:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794822; bh=LFLXrXtZbe/puBmhEZdj7dt2Ld/jyYgOKMUua1Snsrs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hx6rOwgdkDdyOk+OI9PzxJNX6LUO2zgzRz35qMibhc3q4YyFPr8Kmn34CMWbb63Ua AT42hkFApCUfTVKZt+yfhrDVTORR9wIhiAxhX1K6zz3dHMTWRLrzNSRdCuKAKiPx5s AqaUT/nGfK8qJP/eshnYf5wQwXaOkFM3GdTp0l0jMLw0FpgYFz+xtHV/7iiC+YVniN iM8ANXoUsH3OEaK12KT5Gvd2kXqTcPl3ETot+dhr0UEoRGafIJtgX33acLod/naref BwluFtf9g7NEsetCGFDUtNQjzcvYiWAeOSGUv/QkXZkpCFwNV24UZ4gZFnPY7BZzpH oCJH8aO/gXHng== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 01/29] rust: alloc: add `Allocator` trait Date: Tue, 1 Oct 2024 16:59:36 +0200 Message-ID: <20241001150008.183102-2-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: C01CC180026 X-Stat-Signature: ky6ugrxd6jbq5nsxsg7mrkcs3osygx1y X-Rspam-User: X-HE-Tag: 1727794823-204109 X-HE-Meta: U2FsdGVkX1/kzwhRjlQqE/wHbBLmAp5YnZjaRwLwIcv3MR1wrJAL9fcgO3osgtiPEdu6FCZONjTUCE3Zr+2ythv5+HhGTB2mCKUonDmwshbm6wM2uB9nZLLvY9AdVv7z8VEeKymX/N66pq1csbjpkPPxLwgzOAdtnfwKoy59dNMOuCekdp4J5lHWs0rygYVZRu3SxEdBw5OIdye0iIadUKhtnX1qNmMfaDZbfSt+Tq8QexTSutOAyzzjYGDQLTT4wf+nSuqOjwqo2VtAmNmlF3fpGNmsMVws5olgdW+iIGAc/KJJ09fN0My5si4bXrEemT++oEVsPKW4XAEJraHp0J+ek6aoxHgdVjXGGu7cFYjPcfSeLH4yIpI+o34AZsow4kC1O+Hk46n/c8Cy94fvq+mWQ+6tx3MygS5kkxv6knbA108oByPIyGSOAgPC6v4R9adPdnWeESGcgyXLUSBN7g5N+7wYmoJaaCiC36QFnF8QqHJ8qrGdLcr8Ft8VKSGhY8+ge+o5/dq4Nx5HoQJ1XqluGdIEIBRTdkl1WLfO6+likHN5VHDige6AiebJbbTrx0dnvGgOWtTTIxUpbtQkR1FNotpXvdaJ/2lMGDJsobDAJTAU19KJ8RjcseDrXlos7Ob6e7JkUSdoKu6nF1x2g6ThzWwtr38XBbQMbhde6wvJhPbU8PBbwoHjj7DnN+5eAkoHj+0heC/9yDZw0AlFS+O8F7TRPXRAW2xplNF2ELV3vkb1u5R0Y0J3cMUFb5IPMBHej2uhvrKzOcS3aFHX7H64WUsyZn2hvgTiDSENZEADy3yZhnIpXx6woGkgQ92ScXtiQ4wwcrPUa+YfeUkY8c9aC907XXa6xPFm1E9vUrIDLmk2ohBppWPEwtoHWbZFeOf5ILw/wRqk0gzQbvHPG6H6kP0gqphaCNlVuylQJAJEIYxZCrNjpniDRtomTDxt95dmvN0PldCqVFKzJvZ NHXHg9Md QRSFxQhL3bXt7fsM+PBxTaxNW/iv7HiadzCf3R+AL5PeYUr4bI0VSla3gWMgiOM1LT2/S7yqC9KTlpn4JkjbchcjfDMXxSV7S0wVc1B8KH/Tin35wYbUy8t4To/A98y0BezodKR7HgB3+dXJ0ctDzWjXXIs9ydcf5iNGn8MUkcoNRTaYYAiaCjll53rbAwxEZRW35kLA/vuMOeMCXLs8FRk21HMUMNepUEqtd9qm/pkZyWoZaWTMGz2otfr4t0kyO/q2u9hVEGtCiAJL6SDKerkpb2Byl3bWTj+T2eqkALpdPsEiY3vYdzhAJvReBIheT4ZoFUwWf0BUSe/0TQKt0EKZ8zV0njqNCesLz X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Add a kernel specific `Allocator` trait, that in contrast to the one in Rust's core library doesn't require unstable features and supports GFP flags. Subsequent patches add the following trait implementors: `Kmalloc`, `Vmalloc` and `KVmalloc`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo Reviewed-by: Benno Lossin --- rust/kernel/alloc.rs | 101 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..4deeea3488be 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}; /// Flags to be used when allocating memory. /// @@ -86,3 +87,103 @@ pub mod flags { /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); } + +/// The kernel's [`Allocator`] trait. +/// +/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described +/// via [`Layout`]. +/// +/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on +/// an object instance. +/// +/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design +/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind +/// of `self` parameter. +/// +/// # Safety +/// +/// - A memory allocation returned from an allocator must remain valid until it is explicitly freed. +/// +/// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`] +/// function of the same type. +/// +/// - Implementers must ensure that all trait functions abide by the guarantees documented in the +/// `# Guarantees` sections. +pub unsafe trait Allocator { + /// Allocate memory based on `layout` and `flags`. + /// + /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout + /// constraints (i.e. minimum size and alignment as specified by `layout`). + /// + /// This function is equivalent to `realloc` when called with `None`. + /// + /// # Guarantees + /// + /// When the return value is `Ok(ptr)`, then `ptr` is + /// - valid for reads and writes for `layout.size()` bytes, until it is passed to + /// [`Allocator::free`] or [`Allocator::realloc`], + /// - aligned to `layout.align()`, + /// + /// Additionally, `Flags` are honored as documented in + /// . + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + // SAFETY: Passing `None` to `realloc` is valid by it's safety requirements and asks for a + // new memory allocation. + unsafe { Self::realloc(None, layout, Layout::new::<()>(), 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 allocation, 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 allocation, `realloc` may or + /// may not shrink the buffer; this is implementation specific to the allocator. + /// + /// On allocation failure, the existing buffer, if any, remains valid. + /// + /// The buffer is represented as `NonNull<[u8]>`. + /// + /// # Safety + /// + /// - If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation + /// created by this [`Allocator`]; if `old_layout` is zero-sized `p` does not need to be a + /// pointer returned by this [`Allocator`]. + /// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and + /// `old_layout` is ignored. + /// - `old_layout` must match the `Layout` the allocation has been created with. + /// + /// # Guarantees + /// + /// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then + /// it additionally guarantees that: + /// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new + /// and old size, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] == + /// p[0..min(layout.size(), old_layout.size())]`. + /// - when the return value is `Err(AllocError)`, then `ptr` is still valid. + unsafe fn realloc( + ptr: Option>, + layout: Layout, + old_layout: Layout, + flags: Flags, + ) -> Result, AllocError>; + + /// Free an existing memory allocation. + /// + /// # Safety + /// + /// - `ptr` must point to an existing and valid memory allocation created by this [`Allocator`]; + /// if `old_layout` is zero-sized `p` does not need to be a pointer returned by this + /// [`Allocator`]. + /// - `layout` must match the `Layout` the allocation has been created with. + /// - The memory allocation at `ptr` must never again be read from or written to. + unsafe fn free(ptr: NonNull, layout: Layout) { + // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this + // allocator. We are passing a `Layout` with the smallest possible alignment, so it is + // smaller than or equal to the alignment previously used with this allocation. + let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) }; + } +} From patchwork Tue Oct 1 14:59:37 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818221 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 48E51CEACDE for ; Tue, 1 Oct 2024 15:00:31 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D35C4680006; Tue, 1 Oct 2024 11:00:30 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D1658280068; Tue, 1 Oct 2024 11:00:30 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BAFAE680006; Tue, 1 Oct 2024 11:00:30 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 99C60280068 for ; Tue, 1 Oct 2024 11:00:30 -0400 (EDT) Received: from smtpin24.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 49F97815D1 for ; Tue, 1 Oct 2024 15:00:30 +0000 (UTC) X-FDA: 82625344620.24.20E9C6A Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf16.hostedemail.com (Postfix) with ESMTP id 8E50D180039 for ; Tue, 1 Oct 2024 15:00:28 +0000 (UTC) Authentication-Results: imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=BGo62r01; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf16.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794789; a=rsa-sha256; cv=none; b=Unwdtp8q5Lu1K8TFRtY05XcogDaLxeR5YEgyMpTShT23lI/ck3paNKdArvCLIK8ksZS8qU xMdpqPoqCR9Ft5VwLOFsIoyZ/hT+YUU18F8XFFafgEmjGSgdHgk2eSF1pnbmlZ23RqbDCL GlsATvIo607sICX4wUA1PGyYDzp4viM= ARC-Authentication-Results: i=1; imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=BGo62r01; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf16.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794789; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=uOHEks+bEcqRvCkbiLubZ6JHXOyJKoVQ/J784rpHDbk=; b=FRGCcdCER3d40/PtqAgnFFyHv3KSyKkt42NTd2+kOLoGe+IydSs+bQ91LGsNLeQka2f/tw ZMC8i3B2o7aG0L5Q1IAx0VfAyh27BoQVPtJBbaBXWZPl8ad6FiS/qaWHt4BloPsXppICaf HMu3a0dBCujS7WOTDYFL/hh2FiLyCms= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 78D64A41B68; Tue, 1 Oct 2024 15:00:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 88260C4CECF; Tue, 1 Oct 2024 15:00:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794827; bh=jkwVy/FbAq0lpqNfRj/9CuxBTqWwT6EE++N0UM3hdBg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=BGo62r01HZ4eL65H3mCyFpgGOTQKvCWr2+bW2JgJ1Ko1mMbKZlA6duZ2ud2iVEtpT KQ88lS2emAf0fKqC2+u4I6M43AEqks4SCWnLzlBrL5mT9m/Y/oO8bsz/MoBt+bQEcS EMRYn/Vpns3NG8LnnIhww9TPSL00Q3jwY4NY1jogyeFSs8GfWp9qiyqrnY1Frp4cGK B9fSPlq066mUidESfW6zuiumnHN8q9tIdADqjrj167+nDyhNLvOr3KISdUBHFa00gw jc/Sp+9Mlyc7xwtZwaMWE1DUFxev08Lz/pZYwgLLfKvcYzGEiW0npAYhoX662y1GUh lWrI0YugSlX7g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 02/29] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Tue, 1 Oct 2024 16:59:37 +0200 Message-ID: <20241001150008.183102-3-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 8E50D180039 X-Rspamd-Server: rspam01 X-Stat-Signature: oh8x9abexktugc553syw1b4prioecd7h X-HE-Tag: 1727794828-799537 X-HE-Meta: U2FsdGVkX19XUqa4Bz+NE6ZsPd0zMqoIZrTyF2d7ImQJTL6heHXaIMuwswwHPrhUqi4iKhk+t4TzKDoSXsv3OX+4KXSaAJwiqUZFd2Qq9eQElJwjch39c8CF7mGTWibQFittbuF8UJt4y8YZwNtP0pyFNJl8+gz98gln4jToS7Xze+w9x7+kOCpw9NelIzuDKOUnODbiyOV9oDo2MgulxBs24tVyQAN85j64U2pYrZC04SzL96WyeiCMGbVvkXjbm6zkFjAGgaA0FLTyVsn1HJ8u3MuuPwiOjgNQcFoNUXhmofchi2DGpYv75E8jDfEGN2z/Z3fzBHqQ5NoC0/vU1AnfNUGTd+u2W3916pac9LJGyhRoiWwEnaHMIBQlf2iIvpW6oQJGNcwIGnuN71ONP8/lCqNMk8uZiB1R5V74o9GeOBiORSbiTV8743KnpoTpB4LprpKfpejABCmnhbmLlDdtC2C+8Rpz9+eQ7Fg0838fGdiYwE0RpZagaUerNOljBXiYMcRrrqQ4B3urSvIaIYskCa+gwa5uD2+oVjXIgXmcem3pBhtRAkeh8aWSah4jYAYJf8Kj8RDaqIiAtE3UgbMQWMTQdz/um9jpufcInToOSqK2FcEufpjjBjV3vvLeLow0hnI31GWk5TMvG+vcectR4otYm3fMrrhKikaxhizL9pNyzn/hzQwhqeTzlwrLxXKhMPUtNAXpNN5AZO5pjwr7q7wdjzliaD84Lk3RZbzrNYne/lAwKYpAzxdEFnrbA446Zg0soxx3f9tdkdQQJlhjRWXn+P4q1HkmCFnujVypNb9vmCnwQfLd8RutDEejGmxLjbNcQwPWBNFLOnbDF5SFWu3avdvxn9U71FkWL/RPtWbiEiIQwRvF5Yrcbr218i/c3bVGDr7iduQTiYrZhx7RsQ6FwXY6ktEyzfyUCGRSrA0PMS+bPykwlTutEZfrb1VjhtSyv3SkQRq8bu+ VsI7Mfyq jA7WipKhjstnLhLFw+BOWs2WWWaguDgl5HNMTyQntKdyCcAirkCXxK7Qu1kklJWXaAfJPP6Ni2cAjUZQSsWf/UndffL4p+B1b7ptPJ2E8FOd0gifiOTnbsvoxz0sOpMRYQBGa6WK3g2fbM3YB9/+fulPEAO7QjMsdft8aUcx+RMehv39IA5tvn4cJzMRYSLfeZO+mGQJXU4/k0Bs0G4LryXvZJa/XQSMJlGEqqkoS78I1w8IJdPsSgtY83iY1cFhswrwH92I+NV4QwTbt5hhTy9ZM8Pj7RdRm3YcXubZoD9i3I6WPODqxi0KAUWyjzoIOjqVJ9dGxv+pWbvNuJvoKoK8ZgKEmMF1x0SgjV4P9XQqWCBeWKYwmgfCESk5bE4uOgZp88gFHJ0PUhN7qmtOoO63chVlvCnxdCOlQx8YmP1sEgQjLirhqFFUtsQ== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Separate `aligned_size` from `krealloc_aligned`. Subsequent patches implement `Allocator` derivates, such as `Kmalloc`, that require `aligned_size` and replace the original `krealloc_aligned`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..c83b6dff896d 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,6 +8,17 @@ struct KernelAllocator; +/// 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 = new_layout.pad_to_align(); + + // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` + // which together with the slab guarantees means the `krealloc` will return a properly aligned + // object (see comments in `kmalloc()` for more information). + layout.size() +} + /// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment. /// /// # Safety @@ -15,13 +26,7 @@ /// - `ptr` can be either null or a pointer which has been allocated by this allocator. /// - `new_layout` must have a non-zero size. pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. - let layout = new_layout.pad_to_align(); - - // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` - // which together with the slab guarantees means the `krealloc` will return a properly aligned - // object (see comments in `kmalloc()` for more information). - let size = layout.size(); + let size = aligned_size(new_layout); // SAFETY: // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the From patchwork Tue Oct 1 14:59:38 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818222 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id D03E9CEACD5 for ; Tue, 1 Oct 2024 15:00:36 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5E371280090; Tue, 1 Oct 2024 11:00:36 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5931D280068; Tue, 1 Oct 2024 11:00:36 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 40D91280090; Tue, 1 Oct 2024 11:00:36 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0017.hostedemail.com [216.40.44.17]) by kanga.kvack.org (Postfix) with ESMTP id 2155F280068 for ; Tue, 1 Oct 2024 11:00:36 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 9C4C7414B2 for ; Tue, 1 Oct 2024 15:00:35 +0000 (UTC) X-FDA: 82625344830.23.BE1BAF2 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf23.hostedemail.com (Postfix) with ESMTP id 029FE140024 for ; Tue, 1 Oct 2024 15:00:33 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HSUQr0fi; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794665; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=QqhVF17FL+TpDQ3D9EFd1/mNN3744U5WFfkVwM0Lty8=; b=CFlfiH9WfMS/6NLrh1IA8g0qjtAs5G9FVdABhVefu9C9KJZDSQoYwgoAhMAWQ4OATyB9M0 AHhh5UBr+p2dipnYhWcu05sSJatSV/+iOfzT4usVP/Sg5ce7m7lsCWnLfOYTrMyyLaaK/i Qb0+B2QFSPPrh5eSb+nGLXGz2xKFFd0= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HSUQr0fi; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794665; a=rsa-sha256; cv=none; b=Du2cczgH5uXdonKtV57q4x247PTAOR97vsk1870s5wqvnhluSe42y14JsdfY4bXQZ4VY3m l3D1U2LMizJwspPGngwfQJZnb9NTWq7Jgxxnly82DYLy4uaKXMfoB2ew5VpFaIdbhpelQ/ /mQ7rupetOV9Yv382rXSD8+b+PTYNA4= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id D51CEA41B5B; Tue, 1 Oct 2024 15:00:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E27FDC4CED2; Tue, 1 Oct 2024 15:00:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794832; bh=QNiYbpuM4lhKU5PUzac8sp1oQTQY1U9z8BelyYqtrhQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HSUQr0fiwqq9quB2232UQ5QYNfe5VMt5SueyMP+/RzqnRG1+0LKVAwJaWDK0LQ4QA VORCLeljJzcuaQYXFY8LeK02zyxGdvvsRdfpQvaTf1pBHFBn7ntBc4Mm3Dv80lc4Bf hNQQKtpH9zjDHnKWkdVZm5E21wUNSgOAilw6yHFRZG/t96WaLGSWSK0i3Tuvna++2Y QknYitfbqiDAjvv7Y0hVG3094W2M3xubi7S/VPz7JYANbYmKC5g7mvrhL1P3Om6SUo rAE3s7lYN5C/fcV91ivOHGz45xmZT/+nDlshYHSQJbozezcudk10KNqtHAWt7J+Zet ct0LaTl5bcEEw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 03/29] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Tue, 1 Oct 2024 16:59:38 +0200 Message-ID: <20241001150008.183102-4-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 029FE140024 X-Stat-Signature: zrg91syby9q8hjebxx3qz6zszw5zuja5 X-Rspam-User: X-HE-Tag: 1727794833-491781 X-HE-Meta: U2FsdGVkX1/WK6aT1eplx6/TrUnAQ/sm0dOYWFztozXGWTc+9HX2XqESxq7k5T/bLH4Au9paZDC//M4fo6PTe4dzmqu/cP/0Sx7Fp57lNRB0f244itPwQybD13HNjgoyYZVX2ApWSdvfImq2obo1NHYhEqbKWs8H06uojw2OO1Q8XRMa1xQK392E2Q6lduUOE6lKymMhZSztkU4SjygBtA0euk40kZHh5f5ILIiO9cyvM2XiCBZEPkPghAFAo9VA39rTNsiuKsgBt+CRtkWBCtMVzVUjMFkz9nZ/G/DButJ5lpmIM6lfTg3S01OmXcOH/7zVWS76q/xW2EJFjvEiHoukYSVx/eLV3aSfYrJed65fM/qoiiK2OTIIEr6vkmmmD+ALRHazDQxB421EjuLROnweQRtTWt92RMTrafkXmkCnOyXyHNa1AXWHdTRpE4VJlDKqpkOp4gKwmryve+jCptglegjOK2ArbPzDrpXhQ1+r1JepMnsR2rLTQ9zcwkGZAzGotIkeuno9CEvQuTZKor5yjKIwGMH0q4UdLHz8T9VPKNPdDOLVUIqc+aTky4aGNxW29OYzS+GEJOgAkglarLtVbk1/KtG70pMTUfaGoQ65m1wsrywH/A/HwAG8LR5fTIZtz+m9Ek6bQyLsFuaHGCQGeOLmcmrMNGquUk57Ii3vrcAe4YAKzp18z9DuYnkUAVttJdzr7hCaKW5Vm+tTp7NxwongBODPnvcFOgpAN33Z/cC5Vda4Hdvzolj6DUKmjdb9RADpQF11oEv4+cszqR0T2DNQfd5sCiSqRFzUMd1C0jMpItRRbEcfq4uHiUbH70OgmUhsItitQc73JOKNveB05IahqHITpOL7N5dYW98ROjjg/2shMxavV3WseUACkFe7WuMJJhFCBQIQOfJ/xwuZnRUr0p84dX1Hy6trAjcNP89B00zNMMm95+IRBGH5rAa2NRXWVo8HXrqcEM0 w3qjVn2u k3oO8xCPpKonKR2OnmhiQO8m0riJXOhP6agfprynB9Q9REyAFfwjmUHd34pbsX7ONa2Dz3hRsQWNzCapd4uTLUphKlKlyK2gLOsgbr/raE4gXehhDMzY8YVd3lu+Av4XQDC6iHhlJFTHHhXfEJyJ/D5RM6hgDAKWQtX7Khau3dkvl5wxWwFNZOj9R5OxDt8tKDYnFMy1jfymZ5F29gG484XApUbRThLnhjyiOxYAV+KZI7XL0jzfRZVLKEQYatB395pc5J/brwHAsM7nV97pg+jQ1GOgTz7eMv/vD3Y4GVlL/heGQWMWpJJnWr2i419lYwq1UiNzzkYywkgn3BEF2+R81b9gYzexyG7iPIXN2wzFBSPz0lsMWcQdfdQ3FSXVrG4VHLnDKkMcgz2oePYi1rwqxxS6LAStR+uBh X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Subsequent patches implement `Vmalloc` and `KVmalloc` allocators, hence align `KernelAllocator` to this naming scheme. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index c83b6dff896d..e32182f91167 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -6,7 +6,7 @@ use core::alloc::{GlobalAlloc, Layout}; use core::ptr; -struct KernelAllocator; +struct Kmalloc; /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -36,7 +36,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } } -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 size by the function safety // requirement. @@ -72,7 +72,7 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } #[global_allocator] -static ALLOCATOR: KernelAllocator = KernelAllocator; +static ALLOCATOR: Kmalloc = Kmalloc; // See . #[no_mangle] From patchwork Tue Oct 1 14:59:39 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818223 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id BDCA9CEACD5 for ; Tue, 1 Oct 2024 15:00:42 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4D1BC680007; Tue, 1 Oct 2024 11:00:42 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 4AB03280068; Tue, 1 Oct 2024 11:00:42 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 34AEF680007; Tue, 1 Oct 2024 11:00:42 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id 1412D280068 for ; Tue, 1 Oct 2024 11:00:42 -0400 (EDT) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 5AEAAC15FE for ; Tue, 1 Oct 2024 15:00:41 +0000 (UTC) X-FDA: 82625345082.05.ECC1738 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf08.hostedemail.com (Postfix) with ESMTP id 4287E160019 for ; Tue, 1 Oct 2024 15:00:39 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=rcjoRaVU; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf08.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794818; a=rsa-sha256; cv=none; b=rc4HnOQzyPqZP5EerBLA4XgROlldW6xpevIxJpRVuS0/AcPpudCIWIBdR8VbY9HSL1DKAm nmOXr/qSlpaX+YkanqDyxhUcV9SUXQKo34aMXXH/Ijsn0PCUvCMRpqUlM6j/AwDZnfZ9/4 qL/Azl9jRJRCvU/lNPZuCuQ+o/sUGFA= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=rcjoRaVU; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf08.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794818; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=qFrmP5157eCfDsowG9v7lcPreOrVZv3LnPoMdyp9W3k=; b=dXwqhHXokIJ7e9KYy6HdLBeNJCIIm+gtqBhhkKQyNy3XHB2Um3wHZVrHD7Y9Rxok4Z0uOY 1QUqD9vhqf8GZDX0qovKDDRDS4q/46ZDmcKq2piF9KJMMXLUyYv4KvcRkWbKY9g7IQNLnf zLPanIcslwTR/1LDcZn1ngjuBHnLckg= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 3A889A4027C; Tue, 1 Oct 2024 15:00:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 48AA0C4CEC7; Tue, 1 Oct 2024 15:00:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794838; bh=84o4HmTQOhnlx31XPrRNPs5XQKdYhsElQs3aIrFeaTI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=rcjoRaVUcimcVWFSIYbTey2Zty6FitSgX28zPXXGv3J4oTA5yd/hfYFdzB/n+l75o qnSvFkhWtKNtmz45G4qZF64m36g2H6/ZDxKdo+2SmCx7Wwp7UuiJ0S/g/iI3i9tqyy A46Mn9wREIFPNL+jg+tsrhNCa+TLeN+1RFfuNheG9k9wISBVu6E3+e3FMk0B5c8dov VZTc/yvDh8Pw+pNY3ImItb0cvMxQUystEcFWtjiybDx2q9il/MYsdDmoE3dkJHF3EY PWIICYZxmnEzpP6lx3n9B7qdpmS6fYBEoixfEDiNLbqvq+cNFbgHX6sa9KrHSmYtMp Lioa9e+QOJhKQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 04/29] rust: alloc: implement `ReallocFunc` Date: Tue, 1 Oct 2024 16:59:39 +0200 Message-ID: <20241001150008.183102-5-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: qpphfbtispwnkr4ssedeawg1fsejigzd X-Rspamd-Queue-Id: 4287E160019 X-Rspamd-Server: rspam02 X-HE-Tag: 1727794839-177950 X-HE-Meta: U2FsdGVkX19+IfIqt+qdJLjirklM/06e2YC8Z2aExX+Y+D7pfEk8fsck/i7Lw0dloAYRQrr3mXu58NyFJTMfZP4/P/ds2ObOs+PLAzQMu8f8W0+rr7wj5JO7Ja2TOajKUearOb9ZyHFapOANBkZzdtsVKg8U2y5bh9oWBBTA0kxv8Z1WDwoYfKE22MVMrXGzAP+JACZ6Uas2BrpTBvryW4K+sT1Vtac48MhDkITc30TpTStDOmWXggv0zrQCGvye/AO/i1NtHZj7IEn3o/KIxcCRROlPBQfEkoEYnibkiBEsPqC0/EMvgNtD4He+g16MkXmg6LMP6zsgX+Il22kJ8hKWQ7QrwNn6vEi9b6NYy8+yMsME0DbJTbNM/hT3WXlBuTWGf2Q7x8TFtBO1QXW8XhzQBxFVF0qesWoqIL+E6w+guOtsO5bzSV1er2USjLMTfq74c1e1OFeebAFpkAJPNwYwz6/yNeqkvIqAa0AYwws8csW7EksvAavUTfLMiLDCGBEcU0OkNVM6UBmNnPqMo+n520A6sMSVuNIC8Qc759TdlduUqKlbhCZZfwWmOKkjDh/4WqRIRrdSeJzOR0M41e+Iavu0CTc4mIURXB5pga5J5n9EXIGsa9rfozmJLb91YUPFfkOq2NZARkn2Sz8pXLM+BBNFWhG+nKdrsOwBd+x/IoITPG+3nsnwACKGRwgBA9A0xYt3pJalJzOs/+dMeCMpCmPjipy4K84ulqX0w/PMbf3e5CglLfHB3jhyRAehG79rv9RNJOUyl9CLyOnI8OWJ3p5ooVM0yExFJnmVD5ajXoO99dskj1+mWf/ovoOu/WoGSHLZXO3JzkcBQelCg+dGHkqPhsGZfBec0XYxTg0NIt8x+O/av1XznxOSbs74BvO43A8b0fUfZshs8jp85sAP9k3CPAz8koDun0nxuGa/lkKBKLVZgV07T7esmsQmMeOrMPfjtu0OdeO87tE +Y7DdZhu LTrVWOU/oH44YQN4TOcnWusOtGTSzzriCFiyBhcxW6aF+e6cQDuy3fOi+GE5PxQQlic45doQcYQZg2t4lnqPl0mw2AUAi6IEc/4Dr8ZugWF+eSm2ClRJhcMx0x4As9TtEr7qz4iqtzKn15eUcEsnr9uCwwn6EotwBRhyFpjm73rQ0tQdkepcnSDQlA0fesm2qQE+nXNbUcCSzNzDdkXrMzlHNgPaMx8gYLqc5ze/B335tDu7B/+HSF6qv8SsfgN40l7XS/YqmzGE7QuQEgiKhBihlmktNJ4quK2s8YO2Z0eDr3M3Tw2mjn0z9KsUKd5w9CBskg4XlHDRoC+U= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000005, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `ReallocFunc` is an abstraction for the kernel's realloc derivates, such as `krealloc`, `vrealloc` and `kvrealloc`. All of the named functions share the same function signature and implement the same semantics. The `ReallocFunc` abstractions provides a generalized wrapper around those, to trivialize the implementation of `Kmalloc`, `Vmalloc` and `KVmalloc` in subsequent patches. Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 8 ++++ rust/kernel/alloc/allocator.rs | 70 ++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 4deeea3488be..da49c5306431 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -187,3 +187,11 @@ unsafe fn free(ptr: NonNull, layout: Layout) { let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), layout, Flags(0)) }; } } + +/// Returns a properly aligned dangling pointer from the given `layout`. +pub(crate) fn dangling_from_layout(layout: Layout) -> NonNull { + let ptr = layout.align() as *mut u8; + + // SAFETY: `layout.align()` (and hence `ptr`) is guaranteed to be non-zero. + unsafe { NonNull::new_unchecked(ptr) } +} diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e32182f91167..1f28b004b447 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -1,10 +1,20 @@ // SPDX-License-Identifier: GPL-2.0 //! Allocator support. +//! +//! Documentation for the kernel's memory allocators can found in the "Memory Allocation Guide" +//! linked below. For instance, this includes the concept of "get free page" (GFP) flags and the +//! typical application of the different kernel allocators. +//! +//! Reference: use super::{flags::*, Flags}; use core::alloc::{GlobalAlloc, Layout}; use core::ptr; +use core::ptr::NonNull; + +use crate::alloc::AllocError; +use crate::bindings; struct Kmalloc; @@ -36,6 +46,66 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } } +/// # Invariants +/// +/// One of the following `krealloc`, `vrealloc`, `kvrealloc`. +struct ReallocFunc( + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, +); + +#[expect(dead_code)] +impl ReallocFunc { + /// # Safety + /// + /// This method has the same safety requirements as [`Allocator::realloc`]. + /// + /// # Guarantees + /// + /// This method has the same guarantees as `Allocator::realloc`. Additionally + /// - it accepts any pointer to a valid memory allocation allocated by this function. + /// - memory allocated by this function remains valid until it is passed to this function. + unsafe fn call( + &self, + ptr: Option>, + layout: Layout, + old_layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let size = aligned_size(layout); + let ptr = match ptr { + Some(ptr) => { + if old_layout.size() == 0 { + ptr::null() + } else { + ptr.as_ptr() + } + } + None => ptr::null(), + }; + + // SAFETY: + // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc` and thus only requires that + // `ptr` is NULL or valid. + // - `ptr` is either NULL or valid by the safety requirements of this function. + // + // GUARANTEE: + // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc`. + // - Those functions provide the guarantees of this function. + let raw_ptr = unsafe { + // If `size == 0` and `ptr != NULL` the memory behind the pointer is freed. + self.0(ptr.cast(), size, flags.0).cast() + }; + + let ptr = if size == 0 { + crate::alloc::dangling_from_layout(layout) + } else { + NonNull::new(raw_ptr).ok_or(AllocError)? + }; + + Ok(NonNull::slice_from_raw_parts(ptr, size)) + } +} + 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 size by the function safety From patchwork Tue Oct 1 14:59:40 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818224 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 79B25CEACDC for ; Tue, 1 Oct 2024 15:00:47 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 0673E680008; Tue, 1 Oct 2024 11:00:47 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id F0985280068; Tue, 1 Oct 2024 11:00:46 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id DAA86680008; Tue, 1 Oct 2024 11:00:46 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id BD483280068 for ; Tue, 1 Oct 2024 11:00:46 -0400 (EDT) Received: from smtpin04.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 5247DACBC0 for ; Tue, 1 Oct 2024 15:00:46 +0000 (UTC) X-FDA: 82625345292.04.89EA19A Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf23.hostedemail.com (Postfix) with ESMTP id A20CB140034 for ; Tue, 1 Oct 2024 15:00:44 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=k6HrTB7k; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794718; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=vtK7pwCIp1XWr8gylUfXucmct7iS+W71YhesijIHKKo=; b=78l+Mq+lykg+ydSJEAZ7HJ4x+tnJyh67wjOCR9VU7nzUvK+QfY1RuS6BvFYJ6vic0+J5Gg oYv2dW+H7XGQ3Gqu5nFhMqANT4S8AdL+pMlOiDNadF3vl0x96ZkL/d0+Lu8weCldjtHLdo 6JfSZ4pe6Jmw5hV5Q7IGuDUMr1RCoxs= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794718; a=rsa-sha256; cv=none; b=5iOgVc3l8FN1zwFUujK2rvAy3ol9iOa+D5RH3lAor2qwAJFPt9qSZYOLlrF+6AUheZG58F rRAgzECvf0j2mt4m6RPpqo/9vGy2RGrym8bHdYGr7/FfmQY0pRGHXDY+ROEwIY1v1bqCKM gpZKxqHPRgN9oa4S4l7kNtQAY5Be22A= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=k6HrTB7k; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id A9177A43636; Tue, 1 Oct 2024 15:00:35 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A251FC4CED5; Tue, 1 Oct 2024 15:00:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794843; bh=Q8k1CNJBRt+py+dbCiPnncTCxkP76JA0XnMHDcdIPww=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=k6HrTB7kXzr7UXNi/oqSSMVdSvQbzfQ2Hm1qoZEOXD1oExN1ccaOqbAue+hMgqwlG aFuaTfrxYlEDY1OsaerO20MVWs+GrHT93LlBRHbNM3oWblgJzg2DIULKyJbvqQKHMM uRUFIu5Uvno/CWEOQEboF+pHcqnLzvQrGoJNSVp6TUomfHRf2Y/F8eo03ZTQNRYiXc 7Zj4zUSlObmvhv5Fjaq4wKqXQKAUL4P7Bp4k76qq56v7MB2xHZUAnZUwfemwdeXfRt hVhXC0aAcrna0GqlbxFIa+jc3xp2yTJlzmqQd+peDun2KTOyoIfnvIgVnCq51XYigd 1HKYsOhwyklkw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 05/29] rust: alloc: make `allocator` module public Date: Tue, 1 Oct 2024 16:59:40 +0200 Message-ID: <20241001150008.183102-6-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: A20CB140034 X-Stat-Signature: ihoxmdihbx6yino1u5uetkpymcz9sp1t X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1727794844-339947 X-HE-Meta: U2FsdGVkX18yVSldyv9KMGiA3Z6bcyemdtLbGWjkwJebI5Fx6kaQWcIF7SxfIOpyMdCMKYq/NnVXOQdu/7FbysFfYF9xrK8Ibk1VqdHOMFzFX47FyyM5tSDHBm9MZrtU4H3Y7x0gWlgkOUklrZdUZClUZQaYHlcc6zYskQ5jasRr1D8xJb6L9vNKiAy9ZSH/fh12WthiWVV591q4UcoyPIeoGeUmDnyuhasO53IJCvt0BhUuaqUVH3+jrz93hYgAAkgN2t5XMuBgYg158NXN28wWjxMr+5pi1/LPXqOqxdtM6nU68QCggbjIh9b0L13Npxnm4u0RL25AgDJ8hZGAeenou/18HV/EoiVzrhzwgcA3WBEbRZOzmgejxU3jHWuAuhGP99lFdOTgTRId9DfUHd1REqNmF8h7XGrnLyJXQNRX94glFjVuCUDuz+B3sKjff95rUjgFRgZMcWSgsVZcYMr2/DtspdFgvzFPRsea9Lj9qwredGY9Qh8aWZYSixmQoeTvxMJhEL+eO4w1tCey554xlLdU+YGb9Ewx5/SWjat9HTULysrpI6Qq8NJVtQ/JxLuUNOY5byA9XDYElDOHsfm+44JLtbTLsYTpzeB92aNydNlYeCpoc1F6QIEOHfTvH24bJB7sxmsVKBpL/1lcP7lRpBrd/3x+1zitUbCU9w4axgCI7oIMC0vjPIXpvQbF+IJWD7aMpnVpDJnOdubBdrifKn9SL9i+zmIoP1VlPVa/UGjXTJbsInXtXyWwuUCaQ0AS7q+uPLP8cv8QQ2sUWye5QRedC7do2rtqRlEd6BXuTNXrcYleYF19/bVyfDc2CPDuXBzQeWvdpINwdqiLesymU9lYKKVqEGgIHaHfgx71HdrUZMjkqT6dQgNfUQ1XKANTecD92YTRWt87rKYzRqL9bjlfk3w+P0wk1JS6CG6FSPQSJJLggLzB+VE3YAovjJcYuu+3EbwfxgUSlpI TPkx+sVd lCJ+P76aXrwqTHrcybB4Twe33/Bb5kVbVEIJ/DZS3cOhOa4S3WqaoitGieG6UfUOrUWIxzG5ws1NTQ6NCFr13tVjORIKudZ5K+yLNKHbXGbThBIaFZSiINB1vGqClsBMwu7Af5SU+yvi/O0ih/MfVRPVJyvHrOOJiz1rsqCAdMoGIvR1gpOPxisJL4oezir/lduXw3TKowU1VgjNTv9RObzd2zd3Kd0ifx3B+YMheEjPTCacJ5/EM5wzRt5Ks8DbMIAyTG06FYvhUH4lT2KdSSVpZvLWmDLBLkVhmYZfXm2cDbJ9UAnO2J7H8nQ== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000002, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Subsequent patches implement allocators such as `Kmalloc`, `Vmalloc`, `KVmalloc`; we need them to be available outside of the kernel crate as well. Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index da49c5306431..91b2a26faf3d 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -4,7 +4,7 @@ #[cfg(not(test))] #[cfg(not(testlib))] -mod allocator; +pub mod allocator; pub mod box_ext; pub mod vec_ext; From patchwork Tue Oct 1 14:59:41 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818225 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 94E9FCEACD5 for ; Tue, 1 Oct 2024 15:00:53 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 2D6C2680009; Tue, 1 Oct 2024 11:00:53 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 28609280068; Tue, 1 Oct 2024 11:00:53 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 14DCB680009; Tue, 1 Oct 2024 11:00:53 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id EB96F280068 for ; Tue, 1 Oct 2024 11:00:52 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id AA435141463 for ; Tue, 1 Oct 2024 15:00:52 +0000 (UTC) X-FDA: 82625345544.10.1DB71E8 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf03.hostedemail.com (Postfix) with ESMTP id A0F912001A for ; Tue, 1 Oct 2024 15:00:50 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=oKjAMs00; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794723; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=SyowH/p4NUPulUsdmcadFC0xwJkaVb+cMVVdMicS9JM=; b=r57AFeMYXlEwCMD/xpSKfk4vn0tXHiFuvifoeCNpk6NYk7XTjFDwSd/6Ij9ELJE1Ry6M2E 1MBnsFofnHM7uj+taDGSsTtcgkpnZAf6FJbEZU7leW33NgvEQ0kDg4PnbJvL72baX+XS7I c+I7pBrcZDwKzIoLy5OjfmoRcmiEXQI= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794723; a=rsa-sha256; cv=none; b=wFcHhpi+GKN5mNruqANJZUVDKVmj4Z+srZBh/tzNiFwORbN5bSWj/5lA6jUsoyA/34bZ3J fCzEthbwHzzxe2Y79iyU46DcA2Go/2vsZ+Z47nxAgIyjclxspGpMSQQqnvy1MS3gqWpk7/ m8DF9gtpsBEc2uzeE0Fu0AFJhsBCX4w= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=oKjAMs00; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 381505C044F; Tue, 1 Oct 2024 15:00:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0B144C4CED2; Tue, 1 Oct 2024 15:00:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794848; bh=LpkjNNodsESQX/WH+zGgYq9+ft7IaGarSymkz3GKdgI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=oKjAMs00KvN55r37SyGM4QVoo7q+wPKTB0KrHiVJx+r0UGrHFtGwN1Yajw5GL9Qbs BB47x+26Q5zDuMCc7Z6iS1by4ZQVrjAmcqG5WB354Wn5wdD/YQrCoiOBfmRDoWEzgS wPOWrfw9e+HqxQKjTBJWU4mR7fyMMhwWxV4oLWhgX3zKTR7PFyoFiX5dLkDZZ1kmVd DF2uzhaxykw0AXrgL49xD283mOwBcGZDn9OGv9NyLWUldBgin+l3Bw9HkmlmoL/7OM idDCJ/8oiY1FKg+1EJh1sgupAr6nTB7eXXWRRiJN+YkiGDwTuwhg39iyw2G/UwJel2 cvqdQJxR99h6A== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 06/29] rust: alloc: implement `Allocator` for `Kmalloc` Date: Tue, 1 Oct 2024 16:59:41 +0200 Message-ID: <20241001150008.183102-7-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: qyf6yge3bojco6sik3ogz6bzn95rim3n X-Rspamd-Queue-Id: A0F912001A X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1727794850-278674 X-HE-Meta: U2FsdGVkX1+RicfEHSMS5XK5vuss6bio2mYM/q6VRgBehz3M4XOLFwcX48me7i3izYEe9YXmMQ4yUabsCUrtNhau4mSl5za8FKmBN87ejcdbBoxo4VFKuXg9nAqUYZcgnUWFqFaiM/ZA0Ax6QCurHabzlc4ZTd527bjMB18H6gEm2MZXXTKvhJ1ohFMm/Ckr4m73RM7NjbccFndKjmGxbVxRK8TukVdIG9E/n8evMBMNIOrT2EJ/1wNrPamxy5qB4CTPU3SfBLy5Yc65BT/5uW7+jO8xOHe/aHdsaJ/y9yMqNabA5CWwdHmTFTS4TX/EkaxHXsVXMF8jUf8NmzYiQZJd3h7RAlKjGBRfVj/8RKlL1doBf79WiR0Kpf7Zsd/buWxCAU8JpKkBcOxYSHtO/JlTrmhaZUFeBZm13W9tSksJjo8OBPCc1VgcFFlb1t4gG5tF+prZxsApE1WQ8U4mAtExWk1GN8hrEvcU8tSgQtXsuoCSjwxlZFOzZq7FMXFneLzU4bIZfdz7etPjKGiW50VVME3KDeea3LALbx3VtRAIOsBauYcym8nPs7qkMqy0nRhv7fGbRFioUcs86BgB8kVdKHPZUjeD/4+VygatvJEgGm6WGBuaQH0H37Sey278msDPrikpwwJJhgGw+HJ1b9863pHyIRQFrizRXFbAzkwrrkMRMAKAT38Z/UhdX5Yxw1iDohwGs1C38Qj5H6OiofSHz2lRCXxZ8M7yhiS6JfCczByAD+ynkAuw6LpzZUKl8VGgapidAyGibk3Y9kJTIJ7XcEGCm0874UHjjgE3YEQIax1Ky3+kSsMOQ0RQCgzmT7D37XLNdcjp7y231UnK6C7tY/8GJwWpvPBVo9SSZPg65IUebLA9cyHsHMm9hlX5bufxV0OL8anx/YJRT/Jpopcipak5H+yDu9LO8knlAMM36Vum9exw7l9qa6hOpcIAyAIVyvkbz4gHwu6W5uU ykn7xU23 rUOTDWDcOpkmTBNbljNusdfvcRVKi/bgzagTUK3TEKCDiiHvDClf2qEBOn98TNSmfmS59iaZWg7BsXI8oh+LRf2g7g428OGsn4YHSk7sOKBCNRc7Ey6DWJcrkBC/oquR7QW+6se0ZxdbtxPKvFhyG2Bk4oaI5C3+WBzXhdsyrWuKlKid2Qa5lPGhwY6NWVq2EUt5fH1a7HaR04eAfq03cSjtcoCEEbZV+YLpz4DmEHxAia0KoXW5h++BsgQZtfkupiEerM4Cn3I/J9cQ8BiT/FwEXnMD6SN3yIGs7qHzr4d9NFUEe5nY3jKdfmg== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: 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 Reviewed-by: Benno Lossin Reviewed-by: Gary Guo --- rust/kernel/alloc/allocator.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 1f28b004b447..4f3c3ab7c7a2 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -13,10 +13,16 @@ use core::ptr; use core::ptr::NonNull; -use crate::alloc::AllocError; +use crate::alloc::{AllocError, Allocator}; use crate::bindings; -struct Kmalloc; +/// The contiguous kernel allocator. +/// +/// `Kmalloc` is typically used for physically contiguous allocations up to page size, but also +/// supports larger allocations up to `bindings::KMALLOC_MAX_SIZE`, which is hardware specific. +/// +/// For more details see [self]. +pub struct Kmalloc; /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -53,8 +59,10 @@ struct ReallocFunc( unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, ); -#[expect(dead_code)] impl ReallocFunc { + // INVARIANT: `krealloc` satisfies the type invariants. + const KREALLOC: Self = Self(bindings::krealloc); + /// # Safety /// /// This method has the same safety requirements as [`Allocator::realloc`]. @@ -106,6 +114,23 @@ unsafe fn call( } } +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same. +unsafe impl Allocator for Kmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + old_layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // SAFETY: `ReallocFunc::call` has the same safety requirements as `Allocator::realloc`. + unsafe { ReallocFunc::KREALLOC.call(ptr, layout, old_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 size by the function safety From patchwork Tue Oct 1 14:59:42 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818226 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 8E716CEACDC for ; Tue, 1 Oct 2024 15:00:58 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 1EE6D68000A; Tue, 1 Oct 2024 11:00:58 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 14DA5280068; Tue, 1 Oct 2024 11:00:58 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id F311468000A; Tue, 1 Oct 2024 11:00:57 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id D569C280068 for ; Tue, 1 Oct 2024 11:00:57 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 91901ACB85 for ; Tue, 1 Oct 2024 15:00:57 +0000 (UTC) X-FDA: 82625345754.25.8665560 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf13.hostedemail.com (Postfix) with ESMTP id B720A2002B for ; Tue, 1 Oct 2024 15:00:55 +0000 (UTC) Authentication-Results: imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=nburJpip; spf=pass (imf13.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794790; a=rsa-sha256; cv=none; b=trqK7ZmAnMH6DkJ7mj9/P3wymGB51psg+W0E4f3Ck5AxH1iHc8YsDak6DpGoPOLihEgnyA XJ4nmRnXGl5mAGRvDQNVnDex1KWUSqP2qD4RVj72bLQ226aLWCKtaYRcOhGz6xl+KBpRpt 90DsqQXc2YNnrkftawYs7fcrKFdruAU= ARC-Authentication-Results: i=1; imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=nburJpip; spf=pass (imf13.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794790; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=EX4TD+JjJBRwfO1wVqGhdkQ8i5QCl+pKthOi/HJZgzA=; b=Qr89309DnBYDSPh5/nCTa8oGoOq9g0xx7+J+A0L5Lt8ZFRef0p4t1nPrMn3Kf6AZPBjw5T KzoCAxotoGntLLOYeRo/AsWpKzi0gVzvX6OKyrp/IVSHt5dA/IBGRekgR5P2uD3SFBP4s7 Iuouc0XRchDaxX9KQ/367+JdIb9I700= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 686085C4BDF; Tue, 1 Oct 2024 15:00:50 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 63E80C4CED4; Tue, 1 Oct 2024 15:00:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794854; bh=qlNC8elt2DUs+OwvKv1BnkmPQ4QqoPQad7Orfyq3Sws=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=nburJpipekwBNlmE6dN8wfGmOc2kFh4n72pl9CpCALXem0j8JOwKAFG77QHaZvEQY 3CemEpvBKNVUSjy11W4O2PLdpLUiY14++u33wr/yxPRJ3EWQi72+mhnZPIdoyuI3Wg W0bG+JLdTIQ6cfYScfymaSNHJeqQwQ4fqw6Zl4jHg/wn7mgj9/oMx9+pFgI+hI+BB1 arM/cnIZQOmB72mh6dTqEXQkwKqhlnEuJ5gt83e/j4RkGrVqFM411vN+qNI35VUvoX YkCtJuNDfaUMUPb/SjEK42U/gf8cbtmcJ67hiv1Q81+mlyMInW1qsJ6TVa/6a1BUwX /CP7sio9x81KA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 07/29] rust: alloc: add module `allocator_test` Date: Tue, 1 Oct 2024 16:59:42 +0200 Message-ID: <20241001150008.183102-8-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: w3f5mhh1gti4xd5cc9kwngjbiy967qmx X-Rspamd-Queue-Id: B720A2002B X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1727794855-746398 X-HE-Meta: U2FsdGVkX18qt+A5Bo2cdudJlhoWXjOIumYRbBttKCHIX8L+2y+gCuXukx60q2IJQoGb/RyPLJMX8tKWXNIWvmJ2BhC/xu2026MNMEgoD6c1j9K2rTHib1+ctqqgkoDxT/dUXUDL+Hetr4SMeZVjUASQwaOG6O4UBShwfPpVvmO5kKQEyeeTg7RqI9ca5vnoQqMV0QKffsksR8e/kXO+t8/hoOvqD4w0XkGHljPl6PuwAj+1HGiAkXny+fAy7iXFeo9c2IcA1dBvGKCnFzCVsIZw4XUEGi5RMuH7PIVPd+KouIIJt/xevMHgPLAz4kpi5bKe5Xa1VYicU3cqnJ5sUpsy3t8L6Vld5NwhmCorU7iNGTkxF6/IX9lpiYmucsXkBK3ea59JjeQgPs5+YlYjoDAXwuYwkyF2ODJevOw9Wm9+Sjb2QZhy5UXCl1MSz00RzOOFSzsHOz6rRJRx3gwY4vEVV/yGx5cTogY7+xh24POSBiQXtGIWyMjHuR1vH+Fg3963xo/LwMnaZLs8XXhOJXi2Gwx4frsr52Pu5KSsOmH+foMwV/edeoR+V7Bir03FCPuqhhAmWm5sduhdo2ElSq5bXQsAVJrBQb9L7d+ylIIp3O4lhzmw3VvDmI8Mg5yg3NY7l0KeKo9KWll1XTIhaKvAK9jF/T94NCkR0zWwvCkW98PYhfmsQiMv+mN6cM0xnnQwkB+C3cc9pzKMlcBxaDY5mX5JT5Wt9Udtj3SdahJJpGPL07Or40t0be+/dC0vt6oHaDKTfvOOzfH45yZJFMn00WXLfQEy1o42uMaPgDgNuDJyRA4qxLY0aqto3luVtYFbANNjk3QZuIJNn0ltQFr5J4pzNUOeUY84DdLAxlqyXFe9UgqYxBiIomQ/CwgVewsG5Ab11uDsx7SFzWvT9ut/mtpX6GouZ1CxyG9dR/gZFP6LrO8dX6FszT8WXtPd798dfuP0xhJErf13PXQ b9WwA2Dr 78tIWdHI8+txE/wy1vjuv4P85fKqyt03KX37sX9tV0Cr8kI3U1+0JPhQz6UWIntazKtlJgfZ+RllsXuYZe8+02TzG55uKN8fwjNmVojSY3vh2egzJZh4JgJixRFWkNFBxbqa18HBZx280g//DztO2gTQZGk82gD4JTMkmirKNeIqZE7e1sPg71yKRzPEpU376ARlh4WknmqolHym0Hm/5fGz8ymPUcV233KEPj0CMupwlh5DtV0xs1Yl2uMD/T+D8LxYUkxZhz0Z01xKK30MEVONuthrCbI8EpNQK8FGQhCk7nbbPW2ugiRMHyqpu/1INSYTrPEC9bO2XT+QHN/iEOWstn+vu3u2WAz+xUMciAGSLXh8oYa6fZ9Z2K2+BA9qucTWwRcAfCFIShwS0HStu4Qsz7I07ESBkit6Mqdeb9dME0hQLi7gFyPfM2Q== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000001, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `Allocator`s, such as `Kmalloc`, will be used by e.g. `Box` and `Vec` in subsequent patches, and hence this dependency propagates throughout the whole kernel. Add the `allocator_test` module that provides an empty implementation for all `Allocator`s in the kernel, such that we don't break the `rusttest` make target in subsequent patches. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 9 +++++++-- rust/kernel/alloc/allocator_test.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/allocator_test.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 91b2a26faf3d..f8ddc8d96da9 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -2,12 +2,17 @@ //! Extensions to the [`alloc`] crate. -#[cfg(not(test))] -#[cfg(not(testlib))] +#[cfg(not(any(test, testlib)))] pub mod allocator; pub mod box_ext; pub mod vec_ext; +#[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/allocator_test.rs new file mode 100644 index 000000000000..4785efc474a7 --- /dev/null +++ b/rust/kernel/alloc/allocator_test.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0 + +#![allow(missing_docs)] + +use super::{AllocError, Allocator, Flags}; +use core::alloc::Layout; +use core::ptr::NonNull; + +pub struct Kmalloc; + +unsafe impl Allocator for Kmalloc { + unsafe fn realloc( + _ptr: Option>, + _layout: Layout, + _flags: Flags, + ) -> Result, AllocError> { + panic!(); + } +} From patchwork Tue Oct 1 14:59:43 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818227 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 2692DCEACDC for ; Tue, 1 Oct 2024 15:01:04 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B622268000B; Tue, 1 Oct 2024 11:01:03 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id B1274280068; Tue, 1 Oct 2024 11:01:03 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 98DCB68000B; Tue, 1 Oct 2024 11:01:03 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 774EE280068 for ; Tue, 1 Oct 2024 11:01:03 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 2FBFE8078E for ; Tue, 1 Oct 2024 15:01:03 +0000 (UTC) X-FDA: 82625346006.26.3706C00 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf07.hostedemail.com (Postfix) with ESMTP id EB14140032 for ; Tue, 1 Oct 2024 15:01:00 +0000 (UTC) Authentication-Results: imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=FEC2PB2q; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf07.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794840; a=rsa-sha256; cv=none; b=mzYzQB6m+jS0naEiTyklUoekV4aluoDQllzkIMH74TYJpQGXNTS1NU+x3UXR7gcGk4VIEo A/2kqzma8sEzJOKapixRJKBIRqZ9x9+ECgdatz5xXSLZ9ZkTx5+47eAxrdJUBIv21rXTnz i07r0GkyaJzcEjrg+dLS+YcTgy5fi04= ARC-Authentication-Results: i=1; imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=FEC2PB2q; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf07.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794840; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=WtZZ2bG4XnoH3WGdqtUBe6ZQ6u5YKaVoKQCrrwITC/I=; b=dy04nuUenzz4JTkchlcJdv13Za52e2lxi1OzyyhczR+LHJBjJGiYR5sxTUeg7v8IPNBRVf hTWE4Xm8gSqbakiqrZfor1NBJzOsVY0ykQw6n/j3+MHvvUTd0Y02TdiZAvQxPqaicQyOQd mhwlQIrHEmdXEpTaD3PHq+Iluc7rmBY= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id EF4725C02E0; Tue, 1 Oct 2024 15:00:55 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B9F07C4CEC6; Tue, 1 Oct 2024 15:00:54 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794859; bh=HLcg425F90NHvfln7+CkNFLbyp+1IauQlWGwrTXVWkQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=FEC2PB2qqWlaxBrCYs0tyLDHvYQfQynYdKreOHCr6nywYxT6IzPfGdvyLLVujp+1c IDSftsjEYeaOIcOKZp5tq+lv+9qQkWTeM9RUsOZeFduP3EpcAUZfRSbC0APhvmic8K 9NlxqiCYYaxMtFvZhXV8SBZCR4GCD07CTRhc52RKjG3gkNmQ4w+7uS4jrzwBd37x3k pf5ch8ng/WAb8VeDeZmI+Vres6Sbx77xHRWw1bvS2A1qHj9EJeWEGkCR+YviUl2Jn8 00cTL1V7LwXT2aG58SmKOypU6fCUb+q+aHxLoIj3SbF97PG3K4613T1gEFvGesC+er PQvO1BPB05kow== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 08/29] rust: alloc: implement `Vmalloc` allocator Date: Tue, 1 Oct 2024 16:59:43 +0200 Message-ID: <20241001150008.183102-9-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: gp51od114aaabrfh939naou7t5s46r6h X-Rspamd-Queue-Id: EB14140032 X-Rspamd-Server: rspam02 X-HE-Tag: 1727794860-290689 X-HE-Meta: U2FsdGVkX1/o49tlZ7F9DbABDOQAC9rJOjz5rhgT4a6y8fYGaeORho0oppRtBvUJEhDCQEU6qhOUT0xl1wNyuyl59l2w96fuWqDhbkTlxFnybjjZYuFq1JvVuB2JLL3FEiwv4sIKWJ+tCeM5CPckaaOu74RHWvpaEpD334BGc76JC+goGSrCxZDhnm+YDHQ3TYKVRSQ2zhiN8tNAj/IM8SCd++GTt8FZJ1rpbLTtlRF7T34rJ0STdrUqRNJfJyg9oD06Y6llL85DL1kVMX22mDmbfO/k25+zWGR1RktFAwpbawTOs3WV4cJtRaLj5NqRyt3hCsztrCFGda2yKgO63O6QDSa+YoX4WnMKcDqIkKNz3pbXjoeFDLmT6U2LymGtzK8HSra21vqEQbYRNy8z2YOJR1ondq/CD7z0y+eJRKfW3U8f/kIsOooG9BivyUSl3SU3o3R839qgAUoDUNkvaBHgsrMqKJsthayUBnMr20hnBtINV5MEmELverGaD8aWRK9roW7qp5aCLBRVgorMls1Z2UsH9pPvKEPD7Bgjyi0fa7HRhDFUBHZaEatzwZa3ixPZTFg9INu3UU5lKlnE43VT7MkhtsopHr7nnwBgUBd+fyjkRiTTQBtGH+nyPsnXrbAjH1uXMKh3lFsXqbt1AKsxRrsoT8x5h7CjkkDA5MTiL3vBH9nZKvmqKxXOSfyJjE+t97zBOfdG+o1TILG+vcBgvY8XbcVtpDC+50spS8xkgvHFHVvYleS60V7bzeng710sy7RNzzBRAxzHCWAbrhuvshXkXcdKPo7OCv0C6JMPKxdHCgWy2vcykoAiH8r0ELtGbWguw5mokyIH/zCPTzNtlXx9mgomh+s0OVBcQHWWmbtQOQ7PL97dsVj62kIBAU3qrD2Eg/4pW4x8EPGXngbOxoPnMUgJvwoyMzxEbGoi3F/zDs9/JXpomup38lfF/pG+lcfmxrp2Z9C4Fi0 IfpjMOXX AlxRhWgWQ+06zBCVoRGWRKS/TbsPPnpDrhCYoAlGgNmtsNMDq8fRGyQwlEVRu7WbZgyhorDwoQL/0Yhn0wcRplobvjpm1m166b9nbsNTohDpeekSws01PCu+8BM4YnW8pSXPqC9Oc6mkz2iMbdOiunJmJZh6dHn4+84KMl07CBx4LNh1oljdifSPDQi5zTUZx5XvmYz6aUhXW62Z8x1c9RKLcp5pAESwwJRuVXAApYlssSUCSk1sLRSbTXGrVFDXIhO1BEHRNcFGsN4hA4KhydHGxjwyzpopA/MGkaYEnzPqf18jUtF/I9uEtPpcycTW06JqiEChrGRJMlks= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `Allocator` for `Vmalloc`, the kernel's virtually contiguous allocator, typically used for larger objects, (much) larger than page size. All memory allocations made with `Vmalloc` end up in `vrealloc()`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/helpers/helpers.c | 1 + rust/helpers/vmalloc.c | 9 +++++++ rust/kernel/alloc/allocator.rs | 37 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 4 files changed, 48 insertions(+) create mode 100644 rust/helpers/vmalloc.c diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 30f40149f3a9..20a0c69d5cc7 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -22,5 +22,6 @@ #include "spinlock.c" #include "task.c" #include "uaccess.c" +#include "vmalloc.c" #include "wait.c" #include "workqueue.c" diff --git a/rust/helpers/vmalloc.c b/rust/helpers/vmalloc.c new file mode 100644 index 000000000000..80d34501bbc0 --- /dev/null +++ b/rust/helpers/vmalloc.c @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +void * __must_check __realloc_size(2) +rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) +{ + return vrealloc(p, size, flags); +} diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 4f3c3ab7c7a2..f341e9ed5b7c 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -15,6 +15,7 @@ use crate::alloc::{AllocError, Allocator}; use crate::bindings; +use crate::pr_warn; /// The contiguous kernel allocator. /// @@ -24,6 +25,15 @@ /// For more details see [self]. pub struct Kmalloc; +/// The virtually contiguous kernel allocator. +/// +/// `Vmalloc` allocates pages from the page level allocator and maps them into the contiguous kernel +/// virtual space. It is typically used for large allocations. The memory allocated with this +/// allocator is not physically contiguous. +/// +/// For more details see [self]. +pub struct Vmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. @@ -63,6 +73,9 @@ impl ReallocFunc { // INVARIANT: `krealloc` satisfies the type invariants. const KREALLOC: Self = Self(bindings::krealloc); + // INVARIANT: `vrealloc` satisfies the type invariants. + const VREALLOC: Self = Self(bindings::vrealloc); + /// # Safety /// /// This method has the same safety requirements as [`Allocator::realloc`]. @@ -166,6 +179,30 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } } +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same. +unsafe impl Allocator for Vmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + old_layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::VREALLOC.call(ptr, layout, old_layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc = Kmalloc; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 4785efc474a7..e7bf2982f68f 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -7,6 +7,7 @@ use core::ptr::NonNull; pub struct Kmalloc; +pub type Vmalloc = Kmalloc; unsafe impl Allocator for Kmalloc { unsafe fn realloc( From patchwork Tue Oct 1 14:59:44 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818228 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 446DDCEACDC for ; Tue, 1 Oct 2024 15:01:09 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id C73A568000C; Tue, 1 Oct 2024 11:01:08 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C24A4280068; Tue, 1 Oct 2024 11:01:08 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AA00068000C; Tue, 1 Oct 2024 11:01:08 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0012.hostedemail.com [216.40.44.12]) by kanga.kvack.org (Postfix) with ESMTP id 83C33280068 for ; Tue, 1 Oct 2024 11:01:08 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id E9260413B2 for ; Tue, 1 Oct 2024 15:01:07 +0000 (UTC) X-FDA: 82625346174.25.E141D36 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf08.hostedemail.com (Postfix) with ESMTP id 308EB160036 for ; Tue, 1 Oct 2024 15:01:05 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="Jb+L/974"; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf08.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794763; a=rsa-sha256; cv=none; b=AdH6dKJ+084bv8m8pI4a7+FFv3+AUT7XcQ1Y6MkpPl6KxnMNSsW0vzKKxqHC82SBlsL85J K6VVUvoFV8TfPLtMKFf88M44Kzh+i6Tkqu3crgZJsy9t4X/MqXFr7Vr5Jlxxp58bA1vBzV uzNPe61Bu7s3GfvWmWC87tIXDtuhMIM= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="Jb+L/974"; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf08.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794763; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=mTVTvWKBANHMJZHeH6BJATxo69A42yUtQyl4pBz6v5Q=; b=GQDWAsExw7WWdxwxg7KayoB4LYjDExSokbAxHeGxJVjy0iuH/Q0kmWMBy4zRDmwQpNUz9y oSpWChf7GV3Z7QcFO/xzYwlGReq725/QFmc1E1ZJfI34uuzWkNpdBEFajWr48oI3CVtsCJ B4zsDOpLt0tzuxG5OV1iVNzSxEl8RiI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 51C995C05AF; Tue, 1 Oct 2024 15:01:01 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 242ECC4CECD; Tue, 1 Oct 2024 15:00:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794865; bh=25/QaXEy+FB9oK5Q0dGNxbiEnTbfCEBUqqsWLlj6o/M=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Jb+L/974KTCo1VTgtjLQzagR16hrKSSSSmPbdgDVllc+ydBuPYpR38zx/QFIVGmEE 0V6iGjMj6CbPKi25I33ZhHZri+vbXNmsL5rnZ2I1TRzwD6hhyF9JcNeh2O4nEJu5Gr HMg6pAUP6lGE89yX3/8NqWZXOgSFTqk+RBq1Gzq4XsiJHvRPCSed0rJcZhyG0IBCZC r7Yo6hocN2eiC0fiaURlaXaI1q7EIDdU1FDF+mFFdO9Yyg2YaS9wOTSwmUQUR8KZj1 3L7fQPAcnOw3zFQ6iaY8nqyWNWITQP9YI3Z2I7g8eVu9NAi4E4C/8uxf1OGFPJY1Ff WxoyilgZnMdFg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 09/29] rust: alloc: implement `KVmalloc` allocator Date: Tue, 1 Oct 2024 16:59:44 +0200 Message-ID: <20241001150008.183102-10-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 308EB160036 X-Stat-Signature: qhyxbsocwe1b4uigjazttqd5qdibjrfg X-Rspam-User: X-HE-Tag: 1727794865-792854 X-HE-Meta: U2FsdGVkX19pllndnAcW7Pv3fpzoQhPwtHJPX6yotPi31PiG4u/rqws1BSVErVDpHmW8XrcUFydDtsvX1zx5ADXc7aJXNjcQXpEkt2ALY/9ssp5h4KVKQDUj55z5JItFopqG4Yil8A9o9cyk2dzPNP3EjnwiiDmVi1Kxs4X14kjuS2pHB2ylFSG5GUWIGiTEjAKN8+4QUez8FIWH21p5nQQPxh9cu83HEAUSA6jncOR6ZtBs9rypvpqDgZUhs5dvqLToBi/Qdh3CS2pBWil2l+h0/3VOn7fKWAX9uf2cKQFAFyB3qIC/xpdCWgs/vv9XLK+K5K8thkZ62FkQwSuK41jfRk4+k5dr1J5wv+D1EmZw62Z4aB23beIMYeaXWGiMfoeKDbAHEQxb/ZfNMTPxpCPe9w1v3w30rAP27UQjQOc6wXQm6bZnFKFX7+q6xQi8HbD3u7TkRyeMVcoQ9bmPRISrmtpbh1I/+iCa0p8O/ibMdyYCE3BAFGS4KuZq1g/tznjDUC56edK48hjydX6uifi0o1hZMtEsw7/CnUg1OZn6dr8WwOZ3AttG2F173LgvE0D8l1Pexleu1bLb+2vuxNVDNnKrD0zMg1Um4x+44fNoujKiqs6h0bZ0TzboD+D7Qs7SAGyg8Xw5UOSBrTdxIHpbYxUirUw+ANKsev6Bm2aJWzvxm3c+IbXm5pg8o5/ryMiY/Cie93783w5UlIwalD9qFlpUp3ASs97ulYThZ01HUSWuVPVxZ7LqAI9msk6RnZ2FzY/yXBIXXfSLgIuVCJlEjm7iXr3X+1D560n5r+spfT6AK3DqsDyMW5g9U5OSMtNbchNLMKrVdmCP6TnYK5vQo5PPxapI4AMnVxpiYqJ31u/FBYRZVKiMxzRW1ThBwiWM8a6qv480mbH4BB/wDOqiUDoDFekbZ/n0+hHcYeuvIGvD+FR/TYrAk6j1DjMEnSMpLgsJqiDZTHkbjkx fPm6cz9O NkYXM6KicuIFvn943a8/0cE7OOoB1sir5b1JXckaSx81/BoA6XgiLPQonhmuJj1gNriXYlpLKgQFfSoribFBFulJ1vOEyTJDpblk4dOyjp96lWZ2WqwKENLcmF+lztR5qRZa4QC6dO8l79QHeghKWOZ1G9Hnow1E1KD5A2s51Mv0ue8l0dq7rUeq6/jmcNXuy11Cc50JmiUeKK2cE/CSyczfkjVxV9O664IKqhpIuIvER6OU4pU5aEEgOCnjexY8qedPzGTy6bd0kL3oR55532qRYKrlzrbVjbfC/tzVuK2mTW2e/lwMW4m1mbyLyvRiP7+fZquTTT9cLfYE= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `Allocator` for `KVmalloc`, an `Allocator` that tries to allocate memory wth `kmalloc` first and, on failure, falls back to `vmalloc`. All memory allocations made with `KVmalloc` end up in `kvrealloc_noprof()`; all frees in `kvfree()`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/helpers/slab.c | 6 +++++ rust/kernel/alloc/allocator.rs | 36 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 43 insertions(+) diff --git a/rust/helpers/slab.c b/rust/helpers/slab.c index f043e087f9d6..a842bfbddcba 100644 --- a/rust/helpers/slab.c +++ b/rust/helpers/slab.c @@ -7,3 +7,9 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) { return krealloc(objp, new_size, flags); } + +void * __must_check __realloc_size(2) +rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags) +{ + return kvrealloc(p, size, flags); +} diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index f341e9ed5b7c..d0a8819c6741 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -34,6 +34,15 @@ /// For more details see [self]. pub struct Vmalloc; +/// The kvmalloc kernel allocator. +/// +/// `KVmalloc` attempts to allocate memory with `Kmalloc` first, but falls back to `Vmalloc` upon +/// failure. This allocator is typically used when the size for the requested allocation is not +/// known and may exceed the capabilities of `Kmalloc`. +/// +/// For more details see [self]. +pub struct KVmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. @@ -76,6 +85,9 @@ impl ReallocFunc { // INVARIANT: `vrealloc` satisfies the type invariants. const VREALLOC: Self = Self(bindings::vrealloc); + // INVARIANT: `kvrealloc` satisfies the type invariants. + const KVREALLOC: Self = Self(bindings::kvrealloc); + /// # Safety /// /// This method has the same safety requirements as [`Allocator::realloc`]. @@ -203,6 +215,30 @@ unsafe fn realloc( } } +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same. +unsafe impl Allocator for KVmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + old_layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("KVmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, old_layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc = Kmalloc; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index e7bf2982f68f..1b2642c547ec 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -8,6 +8,7 @@ pub struct Kmalloc; pub type Vmalloc = Kmalloc; +pub type KVmalloc = Kmalloc; unsafe impl Allocator for Kmalloc { unsafe fn realloc( From patchwork Tue Oct 1 14:59:45 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818229 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id BE2BACEACD5 for ; Tue, 1 Oct 2024 15:01:14 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5709068000D; Tue, 1 Oct 2024 11:01:14 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 51E91280068; Tue, 1 Oct 2024 11:01:14 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3E60468000D; Tue, 1 Oct 2024 11:01:14 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id BA8F2280068 for ; Tue, 1 Oct 2024 11:01:13 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 5D3E1C15ED for ; Tue, 1 Oct 2024 15:01:13 +0000 (UTC) X-FDA: 82625346426.11.5242181 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf05.hostedemail.com (Postfix) with ESMTP id 81041100015 for ; Tue, 1 Oct 2024 15:01:11 +0000 (UTC) Authentication-Results: imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="eX/pCXoP"; spf=pass (imf05.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794807; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=ZDarUeJtIOZtgw3vVOZFHi4KS4Nr8i9TiefmdjI2B94=; b=IT1suGGGOgkLyJr50Zsa+YbWxYWwYEUb6xbDNkb6exqi6DrQFG6jNuLE8+bhTjTmZonphI d3ysEMXpaLOv3XTlMQGhE4PPoEam8tdaXbGGHXBoxG2b9lhizL8qOCGmnIbJtrDScnRGTT k86QUU32iHyBN1Fm58jf6amQw50dyP4= ARC-Authentication-Results: i=1; imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="eX/pCXoP"; spf=pass (imf05.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794807; a=rsa-sha256; cv=none; b=sL71CXMENV39sY44ScG8gyPlKCqlpFUqmr9tpgblzjiHvSgrf2UkH4/K4DoTbcXiv0HGuS roYP0SPQToTunXZNu1drMzJGinZGQD4Qx/gVIMl53sFQCSLUWlBSfp18E71nqZWJgRzrRh U/oh8qwvYoV+0PTH91YW162gYRxs1Kc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 6C8C5A40104; Tue, 1 Oct 2024 15:01:02 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7C0C2C4CEC7; Tue, 1 Oct 2024 15:01:05 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794870; bh=k3fbnNVumq3p6Zkau+316hxp1LWKMWboxrOE8MJqOiY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eX/pCXoPRhyOmXYyOPVzht3yy9z5YJVXCN4wjr6d0yZ3yRhqbVpOK25ffqa0UL8Iy f3jGHRHK+mesXMDFknMJiYadA36F0PrGV7JQzdGjGpdOiuR0/AXauGiCWavvjZzAu0 XBlwh/zdQtHtokWbfzMxPkdizphnoHAedrV+PhPp60PdVsRQaESFMf6+b5Aib0o2+2 XS1Qg16naWyV26GPvVV96HcRXkKXbiNvgNLvtYgqiCR4ezElSU/ZJ3cdL6YA4xUVM+ o+ZWGeatWYieA1tRRrkYnBwQiaL7zro2CFal/Ere6tpWcsfasea0dqtxywBDrgo1mo VH97ydCLtiWeA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 10/29] rust: alloc: add __GFP_NOWARN to `Flags` Date: Tue, 1 Oct 2024 16:59:45 +0200 Message-ID: <20241001150008.183102-11-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 81041100015 X-Stat-Signature: rarm75zwzrpejhshcuc6m7ea6htikewo X-HE-Tag: 1727794871-320925 X-HE-Meta: U2FsdGVkX19lvhTUlyqPdMDnS2BO9+s65k3+PKlqB1z/UyyufMYbqFbnQwGPDmWWOkkav1kMfLAN1D0ON13l6MDqDDeiy+BHggaadbUZ5dQwL54+9ztzgot6/yRU5qOMshQ6xaUJWR8XGitE6zSOiEX2aZVqBzWITvD5ZuAK2s7Od4HvQ8y6mznwmfgfMg0sp3v2RPvpNF2UlAo8U5mm9a6X7UGYR9ZvR6P19nZanQhc9V/3fHMUNoD9TmzwMYFirCjBoQj5lm1FYv5fpNq92u3SJ72hW2YxnIivTJ/Thwg+IOdP7Q+YUIS0v8ckdnIetBuMp+KooYquNrzYL3U8HRt5dDJdf+SZCv8BKb84jipJ8lfS34VBBhbXYJ+/yWkN2mfCFvD29ceE17btkxsp+O61qdNhrI9wC6BmmOmSeWR079eA5fRWcmORoBUuiw9VEHJVWL0SmcbLP/oxV0CsVPZYRxLF95qLBpNfYGgbM5OFatCcRhJmNKzbSwXtF4YLT3+pS9yWoro1t9kS0GCOhIMYY+pMRC34cR0VRCRZlKD5RnOmpPfWxpy7gU90qBlHVFNlftNn7Fb0jcbhcgLBa7Ohm8/pJgq2T/X67ZVGFh4B3gEM4tbvH5gb/ndgbBSGUddlTmhrdb7Ih7+7CzNkZx6anZxOSRL4LxcEiTNUjS2oIrnxCAU0R9quAayQ9PgZ3Dk/B6QiLFID9Khv2aEAkXORVschdl+UJHREbhV4BGKxVbbcFJhCdj74QdbYB8Y6WqYBtT1B7hqLsYHHz/KefzI6FFJkvp1yZ7VTsLbblj159ktV1no1IH+tB3+9OOqQYB1wDfwmRW8a1yfTQPTItdC+5DNUdZaIFsyUAvhnWjAGDaFRpZ1TBs6kirKj3wLawY/KJerbyUtQrYlr+IeXcecjPGBu5V3PxZc6x08gD84aBdxdRvOu78SrWlh9MuA6zYCBLZbmLiIywQN06Fb UudeHiVR T1aMCD6V03JUDx1UELaoeiINF4HgVfqk0wjU25KXhtpwRdLJgYz3m6bjYb06oNpOrjHUpVv3pZp4cdZyBOT2lgNp/l0cjPSApfc4vLwj7zlsWmCXCMn/KX6bEki3nbitoDLKLtvpx6ctJsVS++FyWzVH2HIsJVO3n8CoSxQbwVhwiMHMhshYIHrvKZrfQ7IDtHR6A+B/hqndSw9wvHBzhXlj0GKjlGIQqgHVVg4rjbN6wVoaZo/3CIXTEe51cDUwiIK4YmcqSzezQuj5MV9LDw/aavTiNm+HLAhqNQspfczb68XP9kJ16A6K4gExkDEUsI0vFs5+618GTCteFu/TgSgLRwqToGEyWA+cz22XWUhLiSQpk9LGdpu+VjrzploFXCx66bUsNAGS/tZvuAJo5Ncbmr/Pb4Q6myDmXdKJGRvcBUAVKy+fjDqkq9w== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Some test cases in subsequent patches provoke allocation failures. Add `__GFP_NOWARN` to enable test cases to silence unpleasant warnings. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/bindings/bindings_helper.h | 1 + rust/kernel/alloc.rs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index ae82e9c941af..a80783fcbe04 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -31,4 +31,5 @@ const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT = GFP_KERNEL_ACCOUNT; const gfp_t RUST_CONST_HELPER_GFP_NOWAIT = GFP_NOWAIT; const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO; const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM = ___GFP_HIGHMEM; +const gfp_t RUST_CONST_HELPER___GFP_NOWARN = ___GFP_NOWARN; const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL; diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index f8ddc8d96da9..97defee1d6a1 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -91,6 +91,11 @@ pub mod flags { /// use any filesystem callback. It is very likely to fail to allocate memory, even for very /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); + + /// Suppresses allocation failure reports. + /// + /// This is normally or'd with other flags. + pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN); } /// The kernel's [`Allocator`] trait. From patchwork Tue Oct 1 14:59:46 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818230 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 76F6ACEACDC for ; Tue, 1 Oct 2024 15:01:22 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E4B9368000E; Tue, 1 Oct 2024 11:01:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id DF90A280068; Tue, 1 Oct 2024 11:01:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C982668000E; Tue, 1 Oct 2024 11:01:21 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id A4CD2280068 for ; Tue, 1 Oct 2024 11:01:21 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 571D11C7304 for ; Tue, 1 Oct 2024 15:01:21 +0000 (UTC) X-FDA: 82625346762.02.4B4D50D Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf30.hostedemail.com (Postfix) with ESMTP id 90D018002D for ; Tue, 1 Oct 2024 15:01:17 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=slhpRMrr; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794708; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=lGC4lY8OLqYM2KfB6Cdd2RTZ9DjKAuA3zB4vvkCpGPw=; b=rB0PWLuFLKjwjuTNrELrXmIT6ifZ4cj5C+HBESBSsz1dfyM0fIJQ8MkCe9nERDxykeImmA zFbNWBsv6FJUEwXgWLG8sPQ+wODZ7guSDve7vnZA6csNOQ4kz/vwkxt94sYZNA4aGwRQZt w69StgtTFeHlfgQS8Nd075MKll2Rdlk= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=slhpRMrr; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794708; a=rsa-sha256; cv=none; b=fnWghKDCyUqZh2rUl27Kq5PiqrwYzoNTFEyn7aunjsKLYpWYb5dITczXqNjw//qehG8RpD tyo3dYzPxcvf+mh3l4HP012BVaCbQGdQSy8cfd7X3koJtrLkA3Fze/135UaCHO8JndX27R duTbi561MQ7EirMjVpnliuNBRDees6o= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 5FFB8A40147; Tue, 1 Oct 2024 15:01:08 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D61CAC4CED3; Tue, 1 Oct 2024 15:01:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794876; bh=C4v1ht7OKunqf+Ny0BVa/7C/LCxjX/4Ly+dP3+llXIE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=slhpRMrrpy0XYGM55zD7fWysg2C+1I7A18aA2+G+uKycL0fcvuO9sJ++IScP6hZL+ 0Al5TjuXNvYNzYR4FRYK280+9jKKehaQPB7j9Uo4hYp4x25GyVgNch31hKTxypWE4y qgPJ9u2jT12gvqqdckS9sq9+eiqu2uOlL6xWKHghwo1bzdQjLdFbOdoIgZ6ibf4tn9 58yJ5zufF9WjUc8aqBvKeIcdapsTNsqJECzxt0huVbkl+RqSdZe/zWBDo5R0lOmuhf /uwsz31hndl4m1vytTBXVu6L3OVxyPlMAI/DlCYm2pxzZ1fiJOjsyO6YXfFyQURaeg 61q5/0g5T88sQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 11/29] rust: alloc: implement kernel `Box` Date: Tue, 1 Oct 2024 16:59:46 +0200 Message-ID: <20241001150008.183102-12-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 90D018002D X-Stat-Signature: 6dnhxqqgswxfnu8kg67eh953s7uuebos X-Rspam-User: X-HE-Tag: 1727794877-338438 X-HE-Meta: U2FsdGVkX1+VBtQ6rwLvChtgPlwtpc18h7kyKMvcGt07BLoH2c5P1xt9ZcFTbzavmZ0qnMTz5B6i6l2Y0MkAWp6Ie4O3AOMt1dD25tc0X6aP3MTySLZw6GHQnee7vDJju4Bkaz9E2yakczDeDtjNvhgi+bmVUIjT12J7Mrbh6aMlgHgVgmJ/ZsJO9U0NRhIUuWh7UsOlrDDT4511pKv7TbCpFfLr2NsoLXg1KuY3Pwob7J7XSwx1ysz1JOsAPE7bvZaCnLWMahBKw0h6MdY84YGpUldf+HrwPNKxQ7ya3JBJ8gGoCxBAW/6YFO5BOVSt1brXJMWmkc5W3spZv+1Qolj1YzmlOYWOV3cbNHh6PAjVO9vtxGHzvlWakBXNsaaybjUbVptnRCyvlqIzDpneCs0hbVM1i5DpUV9xVPQtFb3Jd1HWYWD38ZfVU+B/ni+K3S+mnt+hEn5RJEWmXRK4vIjwY3esgW5CvQ9J2ttJlsB2YbrrnU/JASpQAdoK5xwMBVYzlslnlF4IQzIB4uJWFBrK7mja4g/cdx6XDwHyKGNqo8OYxyKL7XMsMNNtYPrPskCffdRtg6uYt1K944st+5vl8yFts8L21wxq4jcBFWRx875XfguwXBU9Asb0TU0s+9XOA17AGg49tsSKudw1ESmPgz0K0SV70OhhslGSDoQU+v/7ud7f2HsoZe7z0dAASTZSXeoCXwKvZOeiHhTq490OF66UcMYUmhSn56dXSDhRzVzb9xaOmzMc/4RXjlKOWs36xrUbGO4QRhE+6DKH4Bra58MqZDfm1EhGh2t62l+H8xx5hV8SSxNMKg7s8liogvk1O4VfU42g/yb3RpysiZbozYjm6qyWbmVJGNwc17lT/3JiQnVIbHq2I3YMBpCxzRdNaIC+ceu9dPnI4pi3gOfSbntrvFdo4YbaP5WtkVu/EgxaxYAo1A4UvyPfUX02MJVPBOF3R0ENXbZTY/5 uLV44BTT +hfEJ7GWAM3c8aY0tu3lV0NY55ZGsv0zOkP6YLr7dpclHrqQVTq82B6fSc13M7QqewmXC9dXudptrPokQk3bNuiEoLTHnTvw+8bABvpVd6A4/t5mqGXzPxDKid42b54kmlvvvqcqImTF6l5zatfy6VfwHn0oRfeURzznRstrfbe4dAMOfqkiZk5WiCk2F0Cx7cgG5I8JzyDb2bToySglgt0/3DQevYRSO7JWDPfxiPsGjOovk4MEtZOOZGdSHCYJ9b0swFizHek19XMFvhd3qEEyNwuhkgSdqZ97mf5fGorAKkoSxjnc/gwVUDPcf4YPN78iUytj7XWOIP7l9kU77CmNpnQ== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `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. Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 455 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 462 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 97defee1d6a1..12cd52f83222 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; #[cfg(any(test, testlib))] @@ -13,6 +14,11 @@ #[cfg(any(test, testlib))] pub use self::allocator_test as allocator; +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..5d20f6112cc2 --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,455 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +#[allow(unused_imports)] // Used in doc comments. +use super::allocator::{KVmalloc, Kmalloc, Vmalloc}; +use super::{AllocError, Allocator, Flags}; +use core::alloc::Layout; +use core::fmt; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::pin::Pin; +use core::ptr::NonNull; +use core::result::Result; + +use crate::init::{InPlaceInit, InPlaceWrite, Init, PinInit}; +use crate::types::ForeignOwnable; + +/// The kernel's [`Box`] type -- a heap allocation for a single value of type `T`. +/// +/// This is the kernel's version of the Rust stdlib's `Box`. There are several of differences, +/// for example no `noalias` attribute is emitted and partially moving out of a `Box` is not +/// supported. There are also several API differences, e.g. `Box` always requires an [`Allocator`] +/// implementation to be passed as generic, page [`Flags`] when allocating memory and all functions +/// that may allocate memory are fallible. +/// +/// `Box` works with any of the kernel's allocators, e.g. [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`]. +/// There are aliases for `Box` with these allocators ([`KBox`], [`VBox`], [`KVBox`]). +/// +/// When dropping a [`Box`], the value is also dropped and the heap memory is automatically freed. +/// +/// # Examples +/// +/// ``` +/// let b = KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KBox::::new_uninit(GFP_KERNEL | __GFP_NOWARN).is_err()); +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KVBox::::new_uninit(GFP_KERNEL).is_ok()); +/// ``` +/// +/// # Invariants +/// +/// `self.0` is always properly aligned and either points to memory allocated with `A` or, for +/// zero-sized types, is a dangling, well aligned pointer. +#[repr(transparent)] +pub struct Box(NonNull, PhantomData); + +/// Type alias for [`Box`] with a [`Kmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b = KBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type KBox = Box; + +/// Type alias for [`Box`] with a [`Vmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b = VBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type VBox = Box; + +/// Type alias for [`Box`] with a [`KVmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b = KVBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type KVBox = Box; + +// SAFETY: `Box` is `Send` if `T` is `Send` because the `Box` owns a `T`. +unsafe impl Send for Box +where + T: Send + ?Sized, + A: Allocator, +{ +} + +// SAFETY: `Box` is `Sync` if `T` is `Sync` because the `Box` owns a `T`. +unsafe impl Sync for Box +where + T: Sync + ?Sized, + A: Allocator, +{ +} + +impl Box +where + T: ?Sized, + A: Allocator, +{ + /// Creates a new `Box` from a raw pointer. + /// + /// # Safety + /// + /// For non-ZSTs, `raw` must point at an allocation allocated with `A` that is sufficiently + /// aligned for and holds a valid `T`. The caller passes ownership of the allocation to the + /// `Box`. + /// + /// For ZSTs, `raw` must be a dangling, well aligned pointer. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function. + // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer. + Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData) + } + + /// Consumes the `Box` and returns a raw pointer. + /// + /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive + /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the + /// allocation, if any. + /// + /// # Examples + /// + /// ``` + /// let x = KBox::new(24, GFP_KERNEL)?; + /// let ptr = KBox::into_raw(x); + /// let x = unsafe { KBox::from_raw(ptr) }; + /// + /// assert_eq!(*x, 24); + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + pub fn into_raw(b: Self) -> *mut T { + ManuallyDrop::new(b).0.as_ptr() + } + + /// Consumes and leaks the `Box` and returns a mutable reference. + /// + /// See [Box::into_raw] for more details. + #[inline] + pub fn leak<'a>(b: Self) -> &'a mut T { + // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer + // which points to an initialized instance of `T`. + unsafe { &mut *Box::into_raw(b) } + } +} + +impl Box, A> +where + A: Allocator, +{ + /// Converts a `Box, A>` to a `Box`. + /// + /// It is undefined behavior to call this function while the value inside of `b` is not yet + /// fully initialized. + /// + /// # Safety + /// + /// Callers must ensure that the value inside of `b` is in an initialized state. + pub unsafe fn assume_init(self) -> Box { + let raw = Self::into_raw(self); + + // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements + // of this function, the value inside the `Box` is in an initialized state. Hence, it is + // safe to reconstruct the `Box` as `Box`. + unsafe { Box::from_raw(raw.cast()) } + } + + /// Writes the value and converts to `Box`. + pub fn write(mut self, value: T) -> Box { + (*self).write(value); + + // SAFETY: We've just initialized `b`'s value. + unsafe { self.assume_init() } + } +} + +impl Box +where + A: Allocator, +{ + /// Creates a new `Box` and initializes its contents with `x`. + /// + /// New memory is allocated with `A`. The allocation may fail, in which case an error is + /// returned. For ZSTs no memory is allocated. + pub fn new(x: T, flags: Flags) -> Result { + let b = Self::new_uninit(flags)?; + Ok(Box::write(b, x)) + } + + /// Creates a new `Box` with uninitialized contents. + /// + /// New memory is allocated with `A`. The allocation may fail, in which case an error is + /// returned. For ZSTs no memory is allocated. + /// + /// # Examples + /// + /// ``` + /// let b = KBox::::new_uninit(GFP_KERNEL)?; + /// let b = KBox::write(b, 24); + /// + /// assert_eq!(*b, 24_u64); + /// # Ok::<(), Error>(()) + /// ``` + pub fn new_uninit(flags: Flags) -> Result, A>, AllocError> { + let layout = Layout::new::>(); + let ptr = A::alloc(layout, flags)?; + + // INVARIANT: `ptr` is either a dangling pointer or points to memory allocated with `A`, + // which is sufficient in size and alignment for storing a `T`. + Ok(Box(ptr.cast(), PhantomData)) + } + + /// Constructs a new `Pin>`. If `T` does not implement [`Unpin`], then `x` will be + /// pinned in memory and can't be moved. + #[inline] + pub fn pin(x: T, flags: Flags) -> Result>, AllocError> + where + A: 'static, + { + Ok(Self::new(x, flags)?.into()) + } + + /// Forgets the contents (does not run the destructor), but keeps the allocation. + fn forget_contents(this: Self) -> Box, A> { + let ptr = Self::into_raw(this); + + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { Box::from_raw(ptr.cast()) } + } + + /// Drops the contents, but keeps the allocation. + /// + /// # Examples + /// + /// ``` + /// let value = KBox::new([0; 32], GFP_KERNEL)?; + /// assert_eq!(*value, [0; 32]); + /// let value = KBox::drop_contents(value); + /// // Now we can re-use `value`: + /// let value = KBox::write(value, [1; 32]); + /// assert_eq!(*value, [1; 32]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn drop_contents(this: Self) -> Box, A> { + let ptr = this.0.as_ptr(); + + // SAFETY: `ptr` is valid, because it came from `this`. After this call we never access the + // value stored in `this` again. + unsafe { core::ptr::drop_in_place(ptr) }; + + Self::forget_contents(this) + } + + /// Moves the `Box`' value out of the `Box` and consumes the `Box`. + pub fn into_inner(b: Self) -> T { + // SAFETY: By the type invariant `&*b` is valid for `read`. + let value = unsafe { core::ptr::read(&*b) }; + let _ = Self::forget_contents(b); + value + } +} + +impl From> for Pin> +where + T: ?Sized, + A: Allocator, +{ + /// Converts a `Box` into a `Pin>`. If `T` does not implement [`Unpin`], then + /// `*b` will be pinned in memory and can't be moved. + /// + /// This moves `b` into `Pin` without moving `*b` or allocating and copying any memory. + fn from(b: Box) -> Self { + // SAFETY: The value wrapped inside a `Pin>` cannot be moved or replaced as long + // as `T` does not implement `Unpin`. + unsafe { Pin::new_unchecked(b) } + } +} + +impl InPlaceWrite for Box, A> +where + A: Allocator + 'static, +{ + type Initialized = Box; + + fn write_init(mut self, init: impl Init) -> Result { + let slot = self.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid. + unsafe { init.__init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(self) }) + } + + fn write_pin_init(mut self, init: impl PinInit) -> Result, E> { + let slot = self.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid and will not be moved, because we pin it later. + unsafe { init.__pinned_init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(self) }.into()) + } +} + +impl InPlaceInit for Box +where + A: Allocator + 'static, +{ + type PinnedSelf = Pin; + + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + Box::<_, A>::new_uninit(flags)?.write_pin_init(init) + } + + #[inline] + fn try_init(init: impl Init, flags: Flags) -> Result + where + E: From, + { + Box::<_, A>::new_uninit(flags)?.write_init(init) + } +} + +impl ForeignOwnable for Box +where + A: Allocator, +{ + type Borrowed<'a> = &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + Box::into_raw(self) as _ + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Box::from_raw(ptr as _) } + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { + // SAFETY: The safety requirements of this method ensure that the object remains alive and + // immutable for the duration of 'a. + unsafe { &*ptr.cast() } + } +} + +impl ForeignOwnable for Pin> +where + A: Allocator, +{ + type Borrowed<'a> = Pin<&'a T>; + + fn into_foreign(self) -> *const core::ffi::c_void { + // SAFETY: We are still treating the box as pinned. + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + let r = unsafe { &*ptr.cast() }; + + // SAFETY: This pointer originates from a `Pin>`. + unsafe { Pin::new_unchecked(r) } + } +} + +impl Deref for Box +where + T: ?Sized, + A: Allocator, +{ + type Target = T; + + fn deref(&self) -> &T { + // SAFETY: `self.0` is always properly aligned, dereferenceable and 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 and 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 layout = Layout::for_value::(self); + + // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant. + unsafe { core::ptr::drop_in_place::(self.deref_mut()) }; + + // SAFETY: + // - `self.0` was previously allocated with `A`. + // - `layout` is equal to the `Layout´ `self.0` was allocated with. + unsafe { A::free(self.0.cast(), layout) }; + } +} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 4571daec0961..a9210634a8c3 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt}; +pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; #[doc(no_inline)] pub use alloc::{boxed::Box, vec::Vec}; From patchwork Tue Oct 1 14:59:47 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818231 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 7CA6DCEACDC for ; Tue, 1 Oct 2024 15:01:29 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 08FBB68000F; Tue, 1 Oct 2024 11:01:29 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 03D4B280068; Tue, 1 Oct 2024 11:01:28 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id DD22D68000F; Tue, 1 Oct 2024 11:01:28 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id B8630280068 for ; Tue, 1 Oct 2024 11:01:28 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 566EEC1609 for ; Tue, 1 Oct 2024 15:01:28 +0000 (UTC) X-FDA: 82625347056.10.ED53FC1 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf12.hostedemail.com (Postfix) with ESMTP id 3CAB240024 for ; Tue, 1 Oct 2024 15:01:23 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Xfh3owNs; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf12.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794844; a=rsa-sha256; cv=none; b=ZDVQGcUguj6ppgEZuyULR9X+htsv1BGSxA8zIqRAELd/5YV/LT2MpYGONGzc2bCrK+82dq 4n8Mkzh13c6jjKOYFWLhlHkTfAOc7uqkqcXtVvwD5+iejurt5WgAUxWPfnm8DFKcPMEtdD 9smZzAsW2eSDWLwBpNzG8JRJdYhbco0= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Xfh3owNs; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf12.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794844; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=WUSNjVJHP8fxoyDgmsaC26F5iWOdaAb71PHCBh6V1q8=; b=BcaagIapn1vXXFFkpNS/E1eiI5HgWkb4svZc2S2mr9HGRQzkYJMXoxdH4ThlV4TcXnWV8z I1oajsITCkoZ2rQJLSd3fZ7eKNQk3iXD5dpPItATfbrk7A3Ct9YWn4Yi+r2iy+4KR/vXVM 2e626HXVmaBpE/Q3+P3fK/63Rrw26sE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id DD5E5A40226; Tue, 1 Oct 2024 15:01:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C5E62C4CEC6; Tue, 1 Oct 2024 15:01:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794881; bh=kutKwLZsnU8bVf7wfBchbdlBBLTYMY46/fD4vuQR9YE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Xfh3owNsF6BKl1myePFCW+EYNfeWUasV8xx5t36g87EVa+86w1XpHI7devlVbyRzN O+qUYwHD5z0RQEPtmv3jyVeu7g4eIaLuy6qhfem5FV8i4X7CjoPvzHN37Ei+Sz54MH JcUs4ffFeZwCxS6zc3n77IsYdjNAzmSI4HgNcrjo/UcNBEIhrSdUnCEwJQ9C+5b3F+ /CPMnkCsFZo5HwGuFIGJgZfcIc+7RcpKjoCif5IhRPZCgjxCNKXOF/BXE9TlJ7quOp KdZRJxSPzKlNYqaXMvwY9bGbcZ84mHDss0sCC95F+faVWtX5b4ZamP0A4kWXgEbf2L t9Ht3meZiEWRg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 12/29] rust: treewide: switch to our kernel `Box` type Date: Tue, 1 Oct 2024 16:59:47 +0200 Message-ID: <20241001150008.183102-13-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 3CAB240024 X-Rspamd-Server: rspam01 X-Stat-Signature: 4rinncmwzf5iii98kouh9ejxcsasj83m X-HE-Tag: 1727794883-718972 X-HE-Meta: U2FsdGVkX19HNZ6CCURIOd9z2panbVS5/I0faqkNWxjmZBk37t0w+0Sd0VxL3v1IqCr4UQcCRzSm8H4xebtbJIqTYXlzfnv7xu22U0hE2cEf5BG4upor3Zh4zNrW/THK3mcTawzh+98gd4xJGbuAzFO+Ew9zWycReemEEAVeHWbXvFpTWBW2pwUNzGIg51mo3QzO7+JVWxcU3T6hfE8CWnmsSz3xTISFCZjd5d7PA8ZtBxjix+i2GbbGCwOCgYodKvmYWQ2IT4vSOrvZqJd57nPtBx9cXcHhWWhQwv2xcytqwgwFoic7vH0mVRMP5OxjeebjNXfWHDQYljQFxFt8WQoAbrOcSzRM1TfWr7M9Aff+8cf9/JNfeV1sB1ZmvAI4CGKcTaDH5f8ETqW/UUs/H48A71vpyqMiBUSoP13QVqdOYYlKK7k1v3eCgbRWivfukyYxmDG3ws6QjoCVE/Ok455iEZQndViaFspkfRJW2vEcurzUFQpZuqyOGqY80Uxt47Is2nWN2cZIJqH5aDfC/xS1ty3Q3SFc+9FeWLDwe4D1YoW3ajotdcpQLEtTgyZNgtig5tfcYI11m3SsA0cXeObhsK84wx8bzx5toE0oAVE60977sMTtDRM3OKGXSLlFfUkD0Wff40hfQNjOWvdAyP216vpApjSKtTNOZZOBpKFQFI4+RHg4cv672SqPnyMCNXnqAx5/0KaUDZhc56o6mS2f1BPMYB74CK+8fe6Oay4El8r6WdxE+uMYMFDWmecfWrnkHjJtNFVBvdqIGY6MC83arQe95+P1LFCEt+6DM7p2QizzpEvy5yZkZJGDGXnndA8+oDq48DiF4U+5W/jivDKw09XET+u3ZsG9MyD+YCsaHBEXsBq7QJehMB8XFw/HDunz8zVrN/0WuzBYA3gCNg6nUSGkJAB0OMqUvmvtRh6mvbVzv4xWcXHgRUwHhEWuYWjuOrnjJwK34yJYmiR AJ3DPBmw 7ysA8ZnO4nmizpIE+TVBKOjqvswzSeTzRCgphSk7s0ukfV5Qw3nq79bqiJSGBYx6MSmOSguKyoFU92vxKr9hEZUnKcPgTCTKjdZh/vd345PFB1PLmFHf2EBC3Lu1CDapkLrip0dbN1kXOGoBeHzsQFx9rll2CqZidfS2Xh+qSUR+gGP8uhSKjGQQ5oiTlgtEX+Gb5bkGDYOJqSfSecMSRt6e2KKe5xUj340DIJdC/Nd2EyBKmBwxYpSahsXawTYcoP0Aj+NBGR/Kroc6LmWWZkrO+0mfLkUeNsbPzEPHaeN5MhYRiHG1TLx4D9xVo/0Ra/izF/nyS46WqfTBHRPBGLjjI2mbe/DZfMnvg2A1Fnnl4MBDnMHO59bzPMyGKEc0uA59CDMKixJHmMBYfqNzRnYwvzkAqwrG87efBfjMfTmwUyKtThyn9xGBEDZRJA8DdXCVe/MwbiNQ81nRHI70g4WQNvDFkBye2CgAi20XeYF7x/yaV56fduW1/TQ== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we got the kernel `Box` type in place, convert all existing `Box` users to make use of it. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- drivers/block/rnull.rs | 4 +-- rust/kernel/init.rs | 51 ++++++++++++++++--------------- rust/kernel/init/__internal.rs | 2 +- rust/kernel/rbtree.rs | 49 ++++++++++++++++------------- rust/kernel/sync/arc.rs | 17 +++++------ rust/kernel/sync/condvar.rs | 4 +-- rust/kernel/sync/lock/mutex.rs | 2 +- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/workqueue.rs | 20 ++++++------ rust/macros/lib.rs | 6 ++-- 10 files changed, 81 insertions(+), 76 deletions(-) diff --git a/drivers/block/rnull.rs b/drivers/block/rnull.rs index b0227cf9ddd3..5de7223beb4d 100644 --- a/drivers/block/rnull.rs +++ b/drivers/block/rnull.rs @@ -32,7 +32,7 @@ } struct NullBlkModule { - _disk: Pin>>>, + _disk: Pin>>>, } impl kernel::Module for NullBlkModule { @@ -47,7 +47,7 @@ fn init(_module: &'static ThisModule) -> Result { .rotational(false) .build(format_args!("rnullb{}", 0), tagset)?; - let disk = Box::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?; + let disk = KBox::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?; Ok(Self { _disk: disk }) } diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index a17ac8762d8f..e057b374f255 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -13,7 +13,7 @@ //! To initialize a `struct` with an in-place constructor you will need two things: //! - an in-place constructor, //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc`], -//! [`UniqueArc`], [`Box`] or any other smart pointer that implements [`InPlaceInit`]). +//! [`UniqueArc`], [`KBox`] or any other smart pointer that implements [`InPlaceInit`]). //! //! To get an in-place constructor there are generally three options: //! - directly creating an in-place constructor using the [`pin_init!`] macro, @@ -68,7 +68,7 @@ //! # a <- new_mutex!(42, "Foo::a"), //! # b: 24, //! # }); -//! let foo: Result>> = Box::pin_init(foo, GFP_KERNEL); +//! let foo: Result>> = KBox::pin_init(foo, GFP_KERNEL); //! ``` //! //! For more information see the [`pin_init!`] macro. @@ -93,14 +93,14 @@ //! struct DriverData { //! #[pin] //! status: Mutex, -//! buffer: Box<[u8; 1_000_000]>, +//! buffer: KBox<[u8; 1_000_000]>, //! } //! //! impl DriverData { //! fn new() -> impl PinInit { //! try_pin_init!(Self { //! status <- new_mutex!(0, "DriverData::status"), -//! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?, +//! buffer: KBox::init(kernel::init::zeroed(), GFP_KERNEL)?, //! }) //! } //! } @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, error::{self, Error}, sync::Arc, sync::UniqueArc, @@ -298,7 +298,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -307,7 +307,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Result, AllocError> = pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -324,7 +324,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -333,7 +333,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -392,7 +392,7 @@ macro_rules! stack_try_pin_init { /// }, /// }); /// # initializer } -/// # Box::pin_init(demo(), GFP_KERNEL).unwrap(); +/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap(); /// ``` /// /// Arbitrary Rust expressions can be used to set the value of a variable. @@ -462,7 +462,7 @@ macro_rules! stack_try_pin_init { /// # }) /// # } /// # } -/// let foo = Box::pin_init(Foo::new(), GFP_KERNEL); +/// let foo = KBox::pin_init(Foo::new(), GFP_KERNEL); /// ``` /// /// They can also easily embed it into their own `struct`s: @@ -594,7 +594,7 @@ macro_rules! pin_init { /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// ptr: *mut u8, /// } @@ -602,7 +602,7 @@ macro_rules! pin_init { /// impl BigBuf { /// fn new() -> impl PinInit { /// try_pin_init!(Self { -/// big: Box::init(init::zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init::zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) @@ -694,16 +694,16 @@ macro_rules! init { /// # Examples /// /// ```rust -/// use kernel::{init::{PinInit, zeroed}, error::Error}; +/// use kernel::{alloc::KBox, init::{PinInit, zeroed}, error::Error}; /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// } /// /// impl BigBuf { /// fn new() -> impl Init { /// try_init!(Self { -/// big: Box::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// }? Error) /// } @@ -814,8 +814,8 @@ macro_rules! assert_pinned { /// A pin-initializer for the type `T`. /// /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use the -/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use +/// the [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. /// /// Also see the [module description](self). /// @@ -894,7 +894,7 @@ fn pin_chain(self, f: F) -> ChainPinInit } /// 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)>); // SAFETY: The `__pinned_init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -920,8 +920,8 @@ unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { /// An initializer for `T`. /// /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use the -/// [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on this. Because +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use +/// the [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on this. Because /// [`PinInit`] is a super trait, you can use every function that takes it as well. /// /// Also see the [module description](self). @@ -993,7 +993,7 @@ fn chain(self, f: F) -> ChainInit } /// An initializer returned by [`Init::chain`]. -pub struct ChainInit(I, F, __internal::Invariant<(E, Box)>); +pub struct ChainInit(I, F, __internal::Invariant<(E, KBox)>); // SAFETY: The `__init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -1077,8 +1077,9 @@ pub fn uninit() -> impl Init, E> { /// # Examples /// /// ```rust -/// use kernel::{error::Error, init::init_array_from_fn}; -/// let array: Box<[usize; 1_000]> = 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]> = +/// KBox::init::(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(); /// assert_eq!(array.len(), 1_000); /// ``` pub fn init_array_from_fn( @@ -1451,7 +1452,7 @@ macro_rules! impl_zeroable { // // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant. {} Option>, - {} Option>, + {} Option>, // SAFETY: `null` pointer is valid. // diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.rs index 13cefd37512f..b31f498f4f8e 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -102,7 +102,7 @@ fn make_closure(self, f: F) -> F } } -pub struct AllData(PhantomData) -> Box>); +pub struct AllData(PhantomData) -> KBox>); impl Clone for AllData { fn clone(&self) -> Self { diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index 25eb36fd1cdc..a63d4b0fe485 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -7,7 +7,6 @@ //! Reference: use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::*}; -use alloc::boxed::Box; use core::{ cmp::{Ord, Ordering}, marker::PhantomData, @@ -497,7 +496,7 @@ fn drop(&mut self) { // but it is not observable. The loop invariant is still maintained. // SAFETY: `this` is valid per the loop invariant. - unsafe { drop(Box::from_raw(this.cast_mut())) }; + unsafe { drop(KBox::from_raw(this.cast_mut())) }; } } } @@ -764,7 +763,7 @@ pub fn remove_current(self) -> (Option, RBTreeNode) { // point to the links field of `Node` objects. let this = unsafe { container_of!(self.current.as_ptr(), Node, links) }.cast_mut(); // SAFETY: `this` is valid by the type invariants as described above. - let node = unsafe { Box::from_raw(this) }; + let node = unsafe { KBox::from_raw(this) }; let node = RBTreeNode { node }; // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so // the tree cannot change. By the tree invariant, all nodes are valid. @@ -809,7 +808,7 @@ fn remove_neighbor(&mut self, direction: Direction) -> Option> // point to the links field of `Node` objects. let this = unsafe { container_of!(neighbor, Node, links) }.cast_mut(); // SAFETY: `this` is valid by the type invariants as described above. - let node = unsafe { Box::from_raw(this) }; + let node = unsafe { KBox::from_raw(this) }; return Some(RBTreeNode { node }); } None @@ -1035,7 +1034,7 @@ fn next(&mut self) -> Option { /// It contains the memory needed to hold a node that can be inserted into a red-black tree. One /// can be obtained by directly allocating it ([`RBTreeNodeReservation::new`]). pub struct RBTreeNodeReservation { - node: Box>>, + node: KBox>>, } impl RBTreeNodeReservation { @@ -1043,7 +1042,7 @@ impl RBTreeNodeReservation { /// call to [`RBTree::insert`]. pub fn new(flags: Flags) -> Result> { Ok(RBTreeNodeReservation { - node: as BoxExt<_>>::new_uninit(flags)?, + node: KBox::new_uninit(flags)?, }) } } @@ -1059,14 +1058,15 @@ impl RBTreeNodeReservation { /// Initialises a node reservation. /// /// It then becomes an [`RBTreeNode`] that can be inserted into a tree. - pub fn into_node(mut self, key: K, value: V) -> RBTreeNode { - self.node.write(Node { - key, - value, - links: bindings::rb_node::default(), - }); - // SAFETY: We just wrote to it. - let node = unsafe { self.node.assume_init() }; + pub fn into_node(self, key: K, value: V) -> RBTreeNode { + let node = KBox::write( + self.node, + Node { + key, + value, + links: bindings::rb_node::default(), + }, + ); RBTreeNode { node } } } @@ -1076,7 +1076,7 @@ pub fn into_node(mut self, key: K, value: V) -> RBTreeNode { /// The node is fully initialised (with key and value) and can be inserted into a tree without any /// extra allocations or failure paths. pub struct RBTreeNode { - node: Box>, + node: KBox>, } impl RBTreeNode { @@ -1088,7 +1088,9 @@ pub fn new(key: K, value: V, flags: Flags) -> Result> { /// Get the key and value from inside the node. pub fn to_key_value(self) -> (K, V) { - (self.node.key, self.node.value) + let node = KBox::into_inner(self.node); + + (node.key, node.value) } } @@ -1110,7 +1112,7 @@ impl RBTreeNode { /// may be freed (but only for the key/value; memory for the node itself is kept for reuse). pub fn into_reservation(self) -> RBTreeNodeReservation { RBTreeNodeReservation { - node: Box::drop_contents(self.node), + node: KBox::drop_contents(self.node), } } } @@ -1161,7 +1163,7 @@ impl<'a, K, V> RawVacantEntry<'a, K, V> { /// The `node` must have a key such that inserting it here does not break the ordering of this /// [`RBTree`]. fn insert(self, node: RBTreeNode) -> &'a mut V { - let node = Box::into_raw(node.node); + let node = KBox::into_raw(node.node); // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when // the node is removed or replaced. @@ -1235,21 +1237,24 @@ pub fn remove_node(self) -> RBTreeNode { // SAFETY: The node was a node in the tree, but we removed it, so we can convert it // back into a box. node: unsafe { - Box::from_raw(container_of!(self.node_links, Node, links).cast_mut()) + KBox::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }, } } /// Takes the value of the entry out of the map, and returns it. pub fn remove(self) -> V { - self.remove_node().node.value + let rb_node = self.remove_node(); + let node = KBox::into_inner(rb_node.node); + + node.value } /// Swap the current node for the provided node. /// /// The key of both nodes must be equal. fn replace(self, node: RBTreeNode) -> RBTreeNode { - let node = Box::into_raw(node.node); + let node = KBox::into_raw(node.node); // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when // the node is removed or replaced. @@ -1265,7 +1270,7 @@ fn replace(self, node: RBTreeNode) -> RBTreeNode { // - `self.node_ptr` produces a valid pointer to a node in the tree. // - Now that we removed this entry from the tree, we can convert the node to a box. let old_node = - unsafe { Box::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }; + unsafe { KBox::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }; RBTreeNode { node: old_node } } diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 3021f30fd822..d7adbad7d3b4 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -17,13 +17,12 @@ //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{AllocError, Flags, KBox}, bindings, init::{self, InPlaceInit, Init, PinInit}, try_init, types::{ForeignOwnable, Opaque}, }; -use alloc::boxed::Box; use core::{ alloc::Layout, fmt, @@ -204,11 +203,11 @@ pub fn new(contents: T, flags: Flags) -> Result { data: contents, }; - let inner = as BoxExt<_>>::new(value, flags)?; + let inner = KBox::new(value, flags)?; // SAFETY: We just created `inner` with a reference count of 1, which 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()) }) } } @@ -401,8 +400,8 @@ fn drop(&mut self) { if is_zero { // The count reached zero, we must free the memory. // - // SAFETY: The pointer was initialised from the result of `Box::leak`. - unsafe { drop(Box::from_raw(self.ptr.as_ptr())) }; + // SAFETY: The pointer was initialised from the result of `KBox::leak`. + unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) }; } } } @@ -647,7 +646,7 @@ pub fn new(value: T, flags: Flags) -> Result { /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. pub fn new_uninit(flags: Flags) -> Result>, AllocError> { // INVARIANT: The refcount is initialised to a non-zero value. - let inner = Box::try_init::( + let inner = KBox::try_init::( try_init!(ArcInner { // SAFETY: There are no safety requirements for this FFI call. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), @@ -657,8 +656,8 @@ pub fn new_uninit(flags: Flags) -> Result>, AllocError> )?; Ok(UniqueArc { // INVARIANT: The newly-created object has a refcount of 1. - // SAFETY: The pointer from the `Box` is valid. - inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, + // SAFETY: The pointer from the `KBox` is valid. + inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) }, }) } } diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs index 2b306afbe56d..2081932bb4b9 100644 --- a/rust/kernel/sync/condvar.rs +++ b/rust/kernel/sync/condvar.rs @@ -70,8 +70,8 @@ macro_rules! new_condvar { /// } /// /// /// Allocates a new boxed `Example`. -/// fn new_example() -> Result>> { -/// Box::pin_init(pin_init!(Example { +/// fn new_example() -> Result>> { +/// KBox::pin_init(pin_init!(Example { /// value <- new_mutex!(0), /// value_changed <- new_condvar!(), /// }), GFP_KERNEL) diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index 30632070ee67..f8f6d530db7d 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -58,7 +58,7 @@ macro_rules! new_mutex { /// } /// /// // Allocate a boxed `Example`. -/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = 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/spinlock.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 = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 553a5cba2adc..94318472507f 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -216,7 +216,7 @@ pub fn try_spawn( func: Some(func), }); - 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 { } impl WorkItem for ClosureWork { - type Pointer = Pin>; + type Pointer = Pin>; - fn run(mut this: Pin>) { + fn run(mut this: Pin>) { if let Some(func) = this.as_mut().project().take() { (func)() } @@ -297,7 +297,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput /// Defines the method that should be called directly when a work item is executed. /// -/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be +/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`] /// instead. The [`run`] method on this trait will usually just perform the appropriate /// `container_of` translation and then call into the [`run`][WorkItem::run] method from the @@ -329,7 +329,7 @@ pub unsafe trait WorkItemPointer: RawWorkItem { /// 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 typically be `Arc` or - /// `Pin>`. + /// `Pin>`. type Pointer: WorkItemPointer; /// The method that should be called when this work item is executed. @@ -565,7 +565,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput } } -unsafe impl WorkItemPointer for Pin> +unsafe impl WorkItemPointer for Pin> where T: WorkItem, T: HasWork, @@ -576,7 +576,7 @@ unsafe impl WorkItemPointer for Pin> // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. let ptr = unsafe { T::work_container_of(ptr) }; // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. - let boxed = unsafe { Box::from_raw(ptr) }; + let boxed = unsafe { KBox::from_raw(ptr) }; // SAFETY: The box was already pinned when it was enqueued. let pinned = unsafe { Pin::new_unchecked(boxed) }; @@ -584,7 +584,7 @@ unsafe impl WorkItemPointer for Pin> } } -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -598,9 +598,9 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily // remove the `Pin` wrapper. let boxed = unsafe { Pin::into_inner_unchecked(self) }; - let ptr = Box::into_raw(boxed); + let ptr = KBox::into_raw(boxed); - // SAFETY: Pointers into a `Box` point at a valid value. + // SAFETY: Pointers into a `KBox` point at a valid value. let work_ptr = unsafe { T::raw_get_work(ptr) }; // SAFETY: `raw_get_work` returns a pointer to a valid value. let work_ptr = unsafe { Work::raw_get(work_ptr) }; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index a626b1145e5c..ab93111a048c 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -243,7 +243,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` /// @@ -252,7 +252,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// @@ -282,7 +282,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// From patchwork Tue Oct 1 14:59:48 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818232 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 72D5ECEACDC for ; Tue, 1 Oct 2024 15:01:34 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id F3281680010; Tue, 1 Oct 2024 11:01:33 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id EBC33280068; Tue, 1 Oct 2024 11:01:33 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D0DB1680010; Tue, 1 Oct 2024 11:01:33 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id AF545280068 for ; Tue, 1 Oct 2024 11:01:33 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 339C5161659 for ; Tue, 1 Oct 2024 15:01:33 +0000 (UTC) X-FDA: 82625347266.23.5A8C0C2 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf12.hostedemail.com (Postfix) with ESMTP id AF53D40024 for ; Tue, 1 Oct 2024 15:01:28 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aYqvZ+st; spf=pass (imf12.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794761; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=0woxBVxQJA2CBqphiqhxyvbbrsNdu3NfX0yUPSe+zsQ=; b=1uFqZA5ZUtvbYuRuwZ02KQN66TVvEOMGt63tY9VYWGwcghcJvgJQWqPDO304cN+jJkjHuP bB5ImSxXY+S0FEQtI7cupFYW6lPScn+MRDA9T/EUgDD+YvoxMn8hiwUr6eOeqKqYj+ouTi 9G5RKWLVBh1xr/EMcYTaQq+VECPa/8s= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794761; a=rsa-sha256; cv=none; b=Jr9h+UAyajUaeX25PmlEVW6DpLeWdhX7hBCsF2WU1LgocdfiMcrBsUwPIPtM5otbRQvRVS s3E3E9ZCjArbjWG7fM0VWmCsl16CS2mfyetRVSUcvN0CwcU6O2kk0vWFS9sutvYx6Sbmw9 6k0b5FgEm4mqdZbnuH/U9RZS9OtcmTg= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aYqvZ+st; spf=pass (imf12.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 6AB62A40276; Tue, 1 Oct 2024 15:01:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 53BE1C4CED2; Tue, 1 Oct 2024 15:01:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794887; bh=Zu8P7MuHt7+xm2sEdwuDsQEd5JSKWYbaqyjWfsTh9ss=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=aYqvZ+sthieCtuiBhk7fCt/Why2VKoE45Gis6Ra+HG3EvVij1GQl/pC6Es4E9LDNs nqvylaoLi7ei34TFV1bt5SXkGxuynbhJiI67vsT3fRxpWx8F/fiNGgFEm9z6AeQAJJ hxOv1j1a9+RiRqHvMOe9RjTfqw3b/mZCj5qJGa0dfREgqZoFEG72P4HB+AJXcxImsd D3vxOhvWAqZghudDcFQ0d25mf2EyRrsGMWVu+GJLaFHiJpyp9ipn58OcNDUopcL3Cl ecf73h0UmY6x7iOnWP5HzHxneMU8FRbzFK8N1oIY921Cm7HeReBeWi+LsMRoWhBzXv QZqDQnGeysaKw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 13/29] rust: alloc: remove extension of std's `Box` Date: Tue, 1 Oct 2024 16:59:48 +0200 Message-ID: <20241001150008.183102-14-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: ko9rqnswqsytcb59xcontdmzqkacd7jz X-Rspamd-Queue-Id: AF53D40024 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1727794888-421977 X-HE-Meta: U2FsdGVkX18FMpsw1DY7Dk5SnQAWb8wZx7MAkldlnTAxPgkTQliR9aUh4u6ngPQUkODtXwGnwj4pVYapmctoCjWs6YChoB+aodD+/aeoornnNmruIA1K9OBW5j6vN2tg8fCKYtSawKZZDSYRWYM8wLKq/MnbaB3l/sazW6g0S1TG1N55yWydDxvZNdUERUdaSu0mMJ20JGFZPfpqdmFVueurgku+771TWfJFwYwIqIRi0qN1p8HwDkAiVVSCcE1GA/mothE1XFCZy9sspDMvveHmS2hj4TOFnb3ltjXOZnzLTtNKjx+8/f1qyYldIOw+KXm07HZdFKVc/55ENnrJ/ZDqQiqAbDHCVEka08ZlcPXHZ5QbSc5PTsyYVMRes3lqoMsFVBoOvHYkABPAjBoz+QEYcB5RtBjOOn8WMvXh2El+3fKAFdUILBVOdH1cXha+G6x42qdC+tYQc76//jFAXyFevhEMlBQqXiKocfSTZi9kFXLfy8vcSWQumSkVGco5Unn7Ld/KOyX4Welp3pI8d1KUiqu09XqCDI+ozyazr+/Rd9sYGiCOfavgXg+nytlzR91JyHPCbdG1PIIzFgVmx+dLE97uE7Nd6aYAcVzPWTmekANjgiAUyptR2G1ZnpOc4GUokfxH/NNcRAl89FzGPCHF6PEXV7QoUGRoMFgcGDoIPvTcKRK9O5u8+QwPvhMA5/XflDAxiT/SYm9jwuC2WIaFWq51wKjCFhegsXvX0a2t9xX+5SvmukUeKCQdfHrUAfLrPU5eX64ItPW2F8HkrSao9Op1oUPsKwRxgYlrQimsCfWXtP0Oo1NNTCHqm954sgOmZwQWzwQEmMspnTJjuS8xSjhfKiosl1b+EWSPnDThOFAh29u6w103aPcEc9Fy07m810b4rIllx5LwZv47UV97ycwX+1jc00uyNys4pm3R/yIyDCK6r6GMxq4+dVZvZxE5v6PRpC5bt43+zGd olkymH2G IhTkwO4b/q5j7WabXLvqvOgzWoPAmY+5TCa/kLi0/5/SK30MAC6XucTIVJErp5uzSKs5z7gO+N0Pqe69AnglARh8Klrr1RoCbptRziMJUsI/LIAi9K/+BEyTGpdR23Pqe5RMG8qXK808CWCywlGGicDovgcR1fwlL/At+a5Q7jSz01OCLtt/gzHwCC1M7E3sTfHgEt28IcCtwY+BDd3Zznb1l/xYcgs/54BSDjFXWcrGCmB395pmmc9xVLvOwycXDv6v8CaWR1Ynl1yXDkaKH5bpc6QvdzqJYU7U9ObvhSX8ErCw3Kcr3cxcKcEH0PfWwajdxHCdG1bqh/XcaTQ0r5bOwpflPn1NrkAr4D5SSnK/9tN+Tr0FsOPdz6DWnqDb3ESdX X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that all existing `Box` users were moved to the kernel `Box` type, remove the `BoxExt` extension and all other related extensions. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 89 ------------------------------------ rust/kernel/init.rs | 46 +------------------ rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +- rust/kernel/types.rs | 50 -------------------- 6 files changed, 3 insertions(+), 188 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 12cd52f83222..ebe58247504f 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -4,7 +4,6 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; -pub mod box_ext; pub mod kbox; pub mod vec_ext; diff --git a/rust/kernel/alloc/box_ext.rs b/rust/kernel/alloc/box_ext.rs deleted file mode 100644 index 7009ad78d4e0..000000000000 --- a/rust/kernel/alloc/box_ext.rs +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Box`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::boxed::Box; -use core::{mem::MaybeUninit, ptr, result::Result}; - -/// Extensions to [`Box`]. -pub trait BoxExt: Sized { - /// Allocates a new box. - /// - /// The allocation may fail, in which case an error is returned. - fn new(x: T, flags: Flags) -> Result; - - /// Allocates a new uninitialised box. - /// - /// The allocation may fail, in which case an error is returned. - fn new_uninit(flags: Flags) -> Result>, AllocError>; - - /// Drops the contents, but keeps the allocation. - /// - /// # Examples - /// - /// ``` - /// use kernel::alloc::{flags, box_ext::BoxExt}; - /// let value = Box::new([0; 32], flags::GFP_KERNEL)?; - /// assert_eq!(*value, [0; 32]); - /// let mut value = Box::drop_contents(value); - /// // Now we can re-use `value`: - /// value.write([1; 32]); - /// // SAFETY: We just wrote to it. - /// let value = unsafe { value.assume_init() }; - /// assert_eq!(*value, [1; 32]); - /// # Ok::<(), Error>(()) - /// ``` - fn drop_contents(this: Self) -> Box>; -} - -impl BoxExt for Box { - fn new(x: T, flags: Flags) -> Result { - let mut b = >::new_uninit(flags)?; - b.write(x); - // SAFETY: We just wrote to it. - Ok(unsafe { b.assume_init() }) - } - - #[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 = if core::mem::size_of::>() == 0 { - core::ptr::NonNull::<_>::dangling().as_ptr() - } else { - let layout = 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 addressed by klint. Lastly, - // the type is not a SZT (checked above). - let ptr = - unsafe { super::allocator::krealloc_aligned(core::ptr::null_mut(), layout, flags) }; - if ptr.is_null() { - return Err(AllocError); - } - - ptr.cast::>() - }; - - // SAFETY: For non-zero-sized types, we allocate above using the global allocator. For - // zero-sized types, we use `NonNull::dangling`. - Ok(unsafe { Box::from_raw(ptr) }) - } - - fn drop_contents(this: Self) -> Box> { - let ptr = Box::into_raw(this); - // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. - unsafe { ptr::drop_in_place(ptr) }; - - // CAST: `MaybeUninit` is a transparent wrapper of `T`. - let ptr = ptr.cast::>(); - - // SAFETY: `ptr` is valid for writes, because it came from `Box::into_raw` and it is valid for - // reads, since the pointer came from `Box::into_raw` and the type is `MaybeUninit`. - unsafe { Box::from_raw(ptr) } - } -} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index e057b374f255..2f562642e9a4 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,13 +211,12 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, + alloc::{AllocError, Flags, KBox}, error::{self, Error}, sync::Arc, sync::UniqueArc, types::{Opaque, ScopeGuard}, }; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, convert::Infallible, @@ -590,7 +589,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1244,26 +1242,6 @@ fn try_init(init: impl Init, flags: Flags) -> Result } } -impl InPlaceInit for Box { - type PinnedSelf = Pin; - - #[inline] - fn try_pin_init(init: impl PinInit, flags: Flags) -> Result - where - E: From, - { - as BoxExt<_>>::new_uninit(flags)?.write_pin_init(init) - } - - #[inline] - fn try_init(init: impl Init, flags: Flags) -> Result - where - E: From, - { - as BoxExt<_>>::new_uninit(flags)?.write_init(init) - } -} - impl InPlaceInit for UniqueArc { type PinnedSelf = Pin; @@ -1300,28 +1278,6 @@ pub trait InPlaceWrite { fn write_pin_init(self, init: impl PinInit) -> Result, E>; } -impl InPlaceWrite for Box> { - type Initialized = Box; - - fn write_init(mut self, init: impl Init) -> Result { - let slot = self.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid. - unsafe { init.__init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { self.assume_init() }) - } - - fn write_pin_init(mut self, init: impl PinInit) -> Result, E> { - let slot = self.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid and will not be moved, because we pin it later. - unsafe { init.__pinned_init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { self.assume_init() }.into()) - } -} - impl InPlaceWrite for UniqueArc> { type Initialized = UniqueArc; diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 22a3bfa5a9e9..e6e0f748f8a8 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)] diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index a9210634a8c3..c1f8e5c832e2 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,10 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; #[doc(no_inline)] -pub use alloc::{boxed::Box, vec::Vec}; +pub use alloc::vec::Vec; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 9e7ca066355c..53d3ddc0b98c 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -3,13 +3,11 @@ //! Kernel types. use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, mem::{ManuallyDrop, MaybeUninit}, ops::{Deref, DerefMut}, - pin::Pin, ptr::NonNull, }; @@ -71,54 +69,6 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option { } } -impl ForeignOwnable for Box { - type Borrowed<'a> = &'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 the 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 `ptr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr as _) } - } -} - -impl ForeignOwnable for Pin> { - type Borrowed<'a> = Pin<&'a T>; - - fn into_foreign(self) -> *const core::ffi::c_void { - // SAFETY: We are still treating the box as pinned. - Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ - } - - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { - // SAFETY: The safety requirements for this function ensure that the object is still alive, - // so it is safe to dereference the raw pointer. - // The safety requirements of `from_foreign` also ensure that the object remains alive for - // the lifetime of the returned value. - let r = unsafe { &*ptr.cast() }; - - // SAFETY: This pointer originates from a `Pin>`. - unsafe { Pin::new_unchecked(r) } - } - - unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { - // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } - } -} - impl ForeignOwnable for () { type Borrowed<'a> = (); From patchwork Tue Oct 1 14:59:49 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818233 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id E7D4FCEACD5 for ; Tue, 1 Oct 2024 15:01:37 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6F63A680011; Tue, 1 Oct 2024 11:01:37 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 67E89280068; Tue, 1 Oct 2024 11:01:37 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 4D400680011; Tue, 1 Oct 2024 11:01:37 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id 2E877280068 for ; Tue, 1 Oct 2024 11:01:37 -0400 (EDT) Received: from smtpin21.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id D597716164D for ; Tue, 1 Oct 2024 15:01:36 +0000 (UTC) X-FDA: 82625347392.21.65B5F43 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf03.hostedemail.com (Postfix) with ESMTP id B930220010 for ; Tue, 1 Oct 2024 15:01:34 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QzjWXBk4; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794855; a=rsa-sha256; cv=none; b=FZWFA90GNgv6EMW9TF6i8HpSMkCGYh4MuJwiF0W14jboizaZmvLFJ1cXCIk7M5K8YidEhT jrMQ+/Md6rizqkNXO0YMam29xZKBxGU0zi3cSMz6rzG8zQycsXMTYw8H6CFNaP97vtJxgM kR7qOg9GQ+Y+JJw1hjvLx0FXpO1gfbk= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QzjWXBk4; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794855; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=E7l3jw4VzmVq8jCvm8AbHDaiauwez7wdevDnzoPUpMQ=; b=bAIo382zTdmiDqUpRikfJPWM0XTOCpxmH9MvoKZV3kVI/ykJGQw3pfJT1nu0JI8imHrigu Jz/yzS1J660v+MMzyDTfJC09j/5EWkz3UGZLCmgnkJdUOQRL578jKGk18ZdP9VYqUkX3O8 0x44SVMsgp+YY5wOyEJDURAy7/PCl2E= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 8C065A40147; Tue, 1 Oct 2024 15:01:25 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A25B2C4CEC6; Tue, 1 Oct 2024 15:01:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794892; bh=83eAnIr1D5O9vSM1uHBUzB+eFQ2uxXd/+rUZl+c6k2o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QzjWXBk4vQneZyy/BjBLIim5d7KxHk36k2ryWrmaJJ/F6O9n8xp7Aieu8M3ZuEDe8 klTebPqsb+t4fEBdrdr1WqOR2SZtTB0qYJBwJZHT49UoShqrYC74vS5RTr1iJ6mnCo Cy2xNgeFsNPnn5EKfR2Cjxq4/3EFuDFXAL8N//ZAY83r7hd1HtZMOuXuwGA9wX1V2N OkwUkpeIluaq7tnDsSpSh2X24hAxzhJ/2/QfxqUzsnyBVIVKkveltPvdGIlMaACgrp vQCiKfN0PL0URFWoD5gF8w8aIFG8+7Xji1HUcRSr9JajIGPiSuVAQTCA7MxFqZin3s UXqoqOE8rcM/g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 14/29] rust: alloc: add `Box` to prelude Date: Tue, 1 Oct 2024 16:59:49 +0200 Message-ID: <20241001150008.183102-15-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: B930220010 X-Rspamd-Server: rspam01 X-Stat-Signature: tgcgq6ayyehmiy1y7sdfjx631m8yg63x X-HE-Tag: 1727794894-735969 X-HE-Meta: U2FsdGVkX19szgYbU2flrxvCzA6WMuDl0RT62v3zZ2fICwzzVScumPjgzs2dOcjOj2f08omfQ+dSViuMaFB6g0DPhTAveg87fi/ioYPh5oqRFeUCdZP1e3APqzJ3k4yghAiyHAlGKW/qLnyBaoyyccY0ir5pygH9MwI5zQaczX+v96wafKS4mLauJUDquDYW7wB3biTlNRMeS35pjnbqq0ATeRqlTsQj7q1KDfp06eXxb8Rkcicd61qYsj1y1sjc+e1vLVKXHQjf79eRDYtE5dMG6hW62YAnmrJ+wYRBn5bJfPMERqI1SZ2pGHasp7Bz8fQKFwiNzUfO0RtklVtiv1VpPJTU9P4c9JXFQfxekzBPkaIjYZaEaNFq7I+rYkWyWYyBowcPCrb9l+iN7fABhvdcLQ54oJxQ/RNeUd5hanA7vdynKslTOCoytsM1ZruFdtIEHW4iKk1xGEt9HAeQqCmbEhPbu49KSlmC9jShyp7yOBZvR4nZ+1to6gbAa6PY/YU+OhEoqnR+8qHXBfg9884tfLL7mbj0HldNirp7pHq67OpyK1YGsVaHNF7MtjgD27c5YFr4GH4qH/m1sp1m55dUYx+IHyjzX2ygTbxIcS6oMuyUECSE5xXlcmhFzErQfwP2mSJVo/DrokiGbZgq7ejnpcHlg/f/E61lezY1xpqKcGvrphsgiXZfYbzlwQJ/MF8kAqAyWt2Gf7ZuWeGBsnihgG9tg+tp0VXgs+44d4i6oQh7sykrq6K8wBLMo07Ncijgg7KZ3VwrdJyJPQJCnQCTqtblHuUJ73CURrqFurUDVVJ2myi0tptPoLfcbb7XSVQaiKE5UC/SFWrsAED6+/FGObuJuyi4UrojO0dTrqHbf82/8LQIs+vU7ZOOi1F1cOQxgMJ1aan4K7bUFGv6gKQZ1NbEX8t6Hliuo3hs7C1oHRhh6Y0OeuX6ibfbYJRkfhXpgKT2lZ+/Al/UW8T p3JIi/zq 5xkpJEmjkww0uAT9tgQcL6YbHeRbJ6O0K4opxhtIgyEhsqFr4olSqZFO8F+otA8xlJLbvLnqb+0SB+mAEx8B1ulcx7OcnOWXgBt8sbwUpqHtN8KuV6qtQKLuMF18wbaCF70q5BtvO1ceFlFY9u7zpSz1H5aEKX1YmqsYYxU3THrD7fpko0z1kzrKOuLnyVIASklWtbOj2mWynNK6FsCBMFKIIIvYgk0pigoavSz7B/Y4c7lQVyHyqht+tyStZTvj4qKwtVVOeTmTPRMAlqkKH7etbr12bZo/YKRHvJPf5ZEB15BQPuo+RnxhUHbUYj/yNNxvGIsvP/TzNqwhyRDkQ8tMz1Tq4tqiPOTWo1pMZGGZ4+5h/m6B7mZhDTG9aUY7f0QYl X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `BoxExt` and the corresponding includes in prelude.rs, add the new kernel `Box` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo 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 c1f8e5c832e2..d5f2fe42d093 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox}; #[doc(no_inline)] pub use alloc::vec::Vec; From patchwork Tue Oct 1 14:59:50 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818234 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id B9825CEACDC for ; Tue, 1 Oct 2024 15:01:45 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4100A680012; Tue, 1 Oct 2024 11:01:45 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 397AE280068; Tue, 1 Oct 2024 11:01:45 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 238DF680012; Tue, 1 Oct 2024 11:01:45 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 01DF3280068 for ; Tue, 1 Oct 2024 11:01:44 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id AD7F0161659 for ; Tue, 1 Oct 2024 15:01:44 +0000 (UTC) X-FDA: 82625347728.01.117CFE6 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf14.hostedemail.com (Postfix) with ESMTP id 17B3B10003E for ; Tue, 1 Oct 2024 15:01:38 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f2MmSos8; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794805; a=rsa-sha256; cv=none; b=V6Eu3/gdlIHrdMLL5+Tj3UoakgWX5KYDwjjwtpuvkZX1tO62atGN6mKd8jgap+5jV3AawK /FdR2rXI+IkMVQ5WgnFr8how8YGsIbigemW0SLQEZP44P/OTR6M/ej0k158sk427dJqsWX wLGVViK7MmxSijLQKXS/5A8JnQeVdFM= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f2MmSos8; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794805; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=rHyFQBBk5RrGDk8w+tgTdk7ajuh4HCOorMplvVjfkmM=; b=PbT3pMukKMR+je4u566pUgdVfHS3zl8GJ/m9SlKDfpe1OB7gEJJKll1X90ZHwIh0Gz3tFM ggKjU9V10ei/NIfG2zOf6n+upmqgZ9wdsD6vf4eGy0K6qJBmfSXncFuYnSBlBWlCnXOyEz tH+PA2L6gAzPWSHxyvp1ooJquqMi2Hk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id E53ADA40276; Tue, 1 Oct 2024 15:01:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0317CC4CED4; Tue, 1 Oct 2024 15:01:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794897; bh=p24MKJcAJjQGLu5qkqjJ+M2DWuKlcDIgb3JoJfs9n3E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=f2MmSos8vj270iKzg1Gd1ajTMn1iamxKzb6p6Kq7NIGGkGp+bd2EQjmTp2iiwAU9M OgfxOrLOq5lLJz2Eb6XY9YFUl9FNrYqBf7NsR2ebhpGoea959lfPbDAvA72PqerXBi Urq54dnJmsLqzHcjYKaYwfxUJjSVoDkJ1wa+8EdrQ2WfVwQXsHmu02sHOsXHgs3lKl tvKUCEzVWOvOK+MqTaU+J3GhmkBn3tP314jCa/8tmjJIT2k/IEF7k1UOG9vgzDhuwy dt63f5s4DYvjact7iJYzeMReTeRQbjaUjC4g6KXXpDPooIACjc65RgkDG50OXuIz2V 9kXt0QYmCngCA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 15/29] rust: alloc: introduce `ArrayLayout` Date: Tue, 1 Oct 2024 16:59:50 +0200 Message-ID: <20241001150008.183102-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 17B3B10003E X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: cxtjrja6ykzp3xok14y4eyj9doi1p4ow X-HE-Tag: 1727794898-206630 X-HE-Meta: U2FsdGVkX1/ZLD9WzE4aIVpcgtdcphXxWK7FI98pGRdJaH3Iwusl/35lgXga7KJ/QuMCkLsP51wFb4PcMvpmKZTQNZTPctIQDsUYQAvr2NCIzJ9baWuY4aVXov4Utb0dkdMoGf8VNfQGi6edQcpEcqG5ZwuHTbAeDeLXq6g1AO1rW+saMtTs0ruXl9GTuru1JHD59wQ8zunZoj3MZJbXvdm15JXPylR/hgAPY1Bw61BxB5P1+OC7i0K97b4RdgjbuTmF7UngeKZd9wFueeXhmIdgfmUUhsjKATiOdRMCIKYASvL1F+R2JQZH+gaLnaftCc+Vo1qSiIzAQHtLeSgxIWF53s0tjbnKL4LXhcXPMK3/dfNZ05AYhD7sD8UXj333OpI2+ItvTE+IBL/uCEtbUIIEGYNRSBlvxjEwdrnTglS3i58sTUq/6n7u3tCl7qk8g+5e+Phdc3f4A56ZNX57cnN1dwMaB0pUEGZN6bdgs7GNE4OTbTT0/0CnXTS5W1KBaEJbhlZRRS+rcgClevz/7LgAi+6ITufx8CJ5gkiZ/dQL6M1gmls+FdCn1vzLtbFMQ9rrSEp5Tu4C25r9k6ZmkavxN8qQeoXkGY+Ml9XBqz3YzYy2oB2EGpCe6NN5OjNxjzyG2HLgt8DUK8tNABO0hAIprLQQzx65CydvKKvEeLQrNADH5kcZQZAKXAROYzcVz2LKt79bYNw5Ghh8GtoV3IPqInOk9OS5IOb3afRbDZb0sSqioMIlHdMZ6E9nlqerm/vZ5B7uU5GVnULuDb5IW7k2I+YCTGMKsOKnlntS8kda8O6zgvY0YkUkCCkFdUbHa8HafWABFQy6c4AF7OWm8R4BdbWFbg87G2tKaLTO3CKkkrCaS7IIFtWvnTQdYbGHLoRHbyCyz5eoEsoCFalBqaPIPRMK4EeET+fmgjzZ0GV82wB+y1tVn2+/KCfQeJo4mEDYlW73hGadvcQuBVP pzK/0w0r VGBcQ1MLlx+hQSfg1u6TCnHHeejWWhOp8o0y5GOZwjTtolLSNuT8ESaRyP2zKzV4rmpaGiYKC4lWMmMbdh5Zn6uiqwGHIBDAzoMgrd0Yo9Ks7PpbBndZCPNrF6vnF/K5WA0oz5nRe/tExHH2+gBUkss0PxgZvILwxtFyGdq8+r9/ujOrr3EriXN+STQu5eNLEH+5ZR9tTm8ot/bUZm5TiGPAY20yIkUulPc5HkW6W+BV3e0CvAxdqgSmO45/eMZLPBIy/Q89YR6aJZIOVPnQSUIgBArvMi651szXXu/wzBSsaVw33Uz4vqUpnLA== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: From: Benno Lossin When allocating memory for arrays using allocators, the `Layout::array` function is typically used. It returns a result, since the given size might be too big. However, `Vec` and its iterators store their allocated capacity and thus they already did check that the size is not too big. The `ArrayLayout` type provides this exact behavior, as it can be infallibly converted into a `Layout`. Instead of a `usize` capacity, `Vec` and other similar array-storing types can use `ArrayLayout` instead. Signed-off-by: Benno Lossin Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/layout.rs | 91 +++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 rust/kernel/alloc/layout.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index ebe58247504f..bf143a71d53d 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 layout; pub mod vec_ext; #[cfg(any(test, testlib))] diff --git a/rust/kernel/alloc/layout.rs b/rust/kernel/alloc/layout.rs new file mode 100644 index 000000000000..a9c987aad8fb --- /dev/null +++ b/rust/kernel/alloc/layout.rs @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Memory layout. +//! +//! Custom layout types extending or improving [`Layout`]. + +use core::{alloc::Layout, marker::PhantomData}; + +/// Error when constructing an [`ArrayLayout`]. +pub struct LayoutError; + +/// A layout for an array `[T; n]`. +/// +/// # Invariants +/// +/// - `len * size_of::() <= isize::MAX` +pub struct ArrayLayout { + len: usize, + _phantom: PhantomData T>, +} + +impl Clone for ArrayLayout { + fn clone(&self) -> Self { + *self + } +} +impl Copy for ArrayLayout {} + +const ISIZE_MAX: usize = isize::MAX as usize; + +impl ArrayLayout { + /// Creates a new layout for `[T; 0]`. + pub const fn empty() -> Self { + // INVARIANT: `0 * size_of::() <= isize::MAX` + Self { + len: 0, + _phantom: PhantomData, + } + } + + /// Creates a new layout for `[T; len]`. + /// + /// # Errors + /// + /// When `len * size_of::()` overflows or when `len * size_of::() > isize::MAX`. + pub const fn new(len: usize) -> Result { + match len.checked_mul(size_of::()) { + Some(len) if len <= ISIZE_MAX => { + // INVARIANT: we checked above that `len * size_of::() <= isize::MAX` + Ok(Self { + len, + _phantom: PhantomData, + }) + } + _ => Err(LayoutError), + } + } + + /// Creates a new layout for `[T; len]`. + /// + /// # Safety + /// + /// `len` must be a value, for which `len * size_of::() <= isize::MAX` is true. + pub unsafe fn new_unchecked(len: usize) -> Self { + // INVARIANT: By the safety requirements of this function + // `len * size_of::() <= isize::MAX`. + Self { + len, + _phantom: PhantomData, + } + } + + /// Returns the number of array elements represented by this layout. + pub const fn len(&self) -> usize { + self.len + } + + /// Returns `true` when no array elements are represented by this layout. + pub const fn is_empty(&self) -> bool { + self.len == 0 + } +} + +impl From> for Layout { + fn from(value: ArrayLayout) -> Self { + let res = Layout::array::(value.len); + // SAFETY: by the type invariant of `ArrayLayout` we have + // `len * size_of::() <= isize::MAX` and thus the result must be `Ok`. + unsafe { res.unwrap_unchecked() } + } +} From patchwork Tue Oct 1 14:59:51 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818235 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 51CE4CEACD5 for ; Tue, 1 Oct 2024 15:01:48 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id CC35F680013; Tue, 1 Oct 2024 11:01:47 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C72AE280068; Tue, 1 Oct 2024 11:01:47 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id A779C680013; Tue, 1 Oct 2024 11:01:47 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 75FCF280068 for ; Tue, 1 Oct 2024 11:01:47 -0400 (EDT) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 0C2331607D7 for ; Tue, 1 Oct 2024 15:01:47 +0000 (UTC) X-FDA: 82625347854.07.587E007 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf24.hostedemail.com (Postfix) with ESMTP id 03654180029 for ; Tue, 1 Oct 2024 15:01:44 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mrgsxoOa; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794840; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=ES0m52DDnl1W3HB6nVDxRanlAfu6yDRsly/vUQhKX3Q=; b=7AaLK/j9QW1A4T2duBWYA2ibBQDNT+X9DCUNRkqzeRS6PNzR4xG1W04kshNf5RSea4sXBe TtGhD+oIiMujQLJWYq5e+wYqwyxUVZKgWUZ5ukBsZys4tW3K8B8/XiHRLCzV95vacPg0XH 3q1MUqP+b2IpHFyKOaIeMdnrP6iCkoY= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mrgsxoOa; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794840; a=rsa-sha256; cv=none; b=JOI/IAOzgqdAY3b3GzwCFUBX1km7r9ERB9eKwyYxP4oULnFfD6hdCcfaZhcTkiwJc5Pwfw QaeaHEKl80wVfY/bS3tXqhY2nlhW4YzottwOKjh0Nr76rpuu7Lg6zM599yKHgMnvop835G 8svp9Hc7Q7azR229RFMv0RF3cxewMqQ= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 71DCCA40098; Tue, 1 Oct 2024 15:01:35 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5B53EC4CEC7; Tue, 1 Oct 2024 15:01:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794903; bh=nVfTojkIIMBN0cH18if1sl/P3q/RENaMg4y+WVZW+0c=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mrgsxoOaXehiXzu+5PZ6/bo5jDeqf13xeH5NYj1mCT4JqznL8MaplLnXyzw5UxYRB 2c/w9lkPhUUBs/vdEgGHMa+BAPg6ldr8+y4Yfcvf9CeEisu7joy2W66P3UFVOKvi+K 63qnYXZqhKfVHlNdjYWtOaAYixNraUMOYedF6Iieol6QAIL8FdMeMKxtH9QZx0bz1k BBGM4kdGjkhdlKpoMvWpRtrZc8UGfOVPyzv+z3OZS6rQjJn4ZxmTFYFi0Yg2gAAuI0 XhrpsJxqn3smLYelLCQB3y6rTFPXjd5e4yS3Paa+KrcBpkpdYLkmYrvzV+s4Pb8lzt E8877npmCjuhw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 16/29] rust: alloc: implement kernel `Vec` type Date: Tue, 1 Oct 2024 16:59:51 +0200 Message-ID: <20241001150008.183102-17-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 03654180029 X-Stat-Signature: 5facou7ui898cuq4bccqg4nfffzfhaw4 X-HE-Tag: 1727794904-622309 X-HE-Meta: U2FsdGVkX19smoOmW8BJpudgLW7RQ812pbz6pEnY04mBB5h6yoFo6SsLTysFRteqdVhQJbLwpim72eL5Se8QoRbN7oiwd89ZKMp5sn0P87QwRqfkSQdDeAEf2fYHQUMtMHJOdjLh9MgmiZZgV1pZxQfjNBAtkuzb4Sa2DhGvwmbMHZ1OJSVGWw5voG8RCPKIdbsChT2fJosdSHTUAOnGPqMvuTjeXXWFt3TU8S3uAJ7JLCYJhkA0W6y96VR1y1x0vBeoBMbV4LPwULtro2aSlqS57mz8HaRvbzQbbsvlc/sXaw5JWBBBUtZX9x5ctRBF38CI4gI/kH6d0p3EsdFFRp7dPt18MKc7ke6ICaiA14vU7SEkZS9IOtner4OUNLUC7o7E+fWwlz/t6R8nvIxrE7qrURqV2jatpcTGen56LwbXpatZ2xipgdzrlSz9da/H/JslR6UA0n0aDk2zwZQcVN42rWb3fRwms9jklOkI/q8MD7gB5ZfqLonrM6d7cX2BTgSKn21x5zCWOOKNLfV9PuMMsfxDbvp+4VmX9FlVmaghwkKs9huhAZ9ZwYwlYxPSlrjVSwnSVu6PBj+e6FsfKlauv+D/XFyaITW3XWu/8GPZIVinYaiHcnXU9t/V+zkHYSU1JKKiEDqWYBZiYzhKbbFsqA5idR8l0t0EpE9Fx+T6oMsFYPEyk6e2BqUUReeNkuVdwCt7lFSqOHf/qNJIJzY7DVo9Bdq3niG1KoBUQpjcH2nmNxDAzO3YS8YBhZtBdSCY6QmT0RyoPW5I2OQ9GKCa9sUb8OmdlCtXKS22eNa5Io9fAADI0tv62IZ7fBWEmv7VXegGx+R7En7YOmq1n3Ar1tS3bWCs/+egi2JrU6n9X3R/+XhAW+kHE8cP1AdbzmHMZAjZwVYlVF7JnsLIx/g5moFPJ4ojI7kmxCAYh1Hgx7mJI5ypBGch33v8kx85khqCbLRClllU6LM1Xjd 65OFPDZD HTfc+2MAER8FMjgTTyhEv1HwdDDNrRKHb7oPvIntyHSsRHJKv3B2nE+NvcookkBjANX6ul59MNP4LxychsV8GwJfuvFYIgJugc2gJs4RGgjJ9WWmVZC6zhEw4ChM6xCdcz+of9m3YTiHZrhxNl6ucu1a7OEWSITP0eUAcytMv40MIoYduE28IgIp5YQ5tEdaqGG+8aL6/tsZdV9XXGN3j6Sx+JuagW4q5wTThnvfopQxYhR9pz6nmIaOIxLj0MglHvePu40cBToZA/ifNwsO2T0/ICwv/ODJ6IgTqbhF2JBQMkvVVck7HYycE9g== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `Vec` provides a contiguous growable array type with contents allocated with the kernel's allocators (e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`). In contrast to Rust's stdlib `Vec` type, the kernel `Vec` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo Reviewed-by: Benno Lossin --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kvec.rs | 637 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 644 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index bf143a71d53d..961070daf6db 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 layout; pub mod vec_ext; @@ -19,6 +20,11 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; +pub use self::kvec::KVVec; +pub use self::kvec::KVec; +pub use self::kvec::VVec; +pub use self::kvec::Vec; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs new file mode 100644 index 000000000000..44aade0a653b --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,637 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{ + allocator::{KVmalloc, Kmalloc, Vmalloc}, + layout::ArrayLayout, + AllocError, Allocator, Box, Flags, +}; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + ptr, + ptr::NonNull, + slice, + slice::SliceIndex, +}; + +/// Create a [`KVec`] containing the arguments. +/// +/// # Examples +/// +/// ``` +/// let mut v = kernel::kvec![]; +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(v, [1]); +/// +/// let mut v = kernel::kvec![1; 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 1, 1, 4]); +/// +/// let mut v = kernel::kvec![1, 2, 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 2, 3, 4]); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[macro_export] +macro_rules! kvec { + () => ( + $crate::alloc::KVec::new() + ); + ($elem:expr; $n:expr) => ( + $crate::alloc::KVec::from_elem($elem, $n, GFP_KERNEL) + ); + ($($x:expr),+ $(,)?) => ( + match $crate::alloc::KBox::new_uninit(GFP_KERNEL) { + Ok(b) => Ok($crate::alloc::KVec::from($crate::alloc::KBox::write(b, [$($x),+]))), + Err(e) => Err(e), + } + ); +} + +/// The kernel's [`Vec`] type. +/// +/// A contiguous growable array type with contents allocated with the kernel'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 the `Allocator` type used +/// to allocate (and free) the backing buffer. +/// +/// A [`Vec`] can be deconstructed into and (re-)constructed from it's previously named raw parts +/// and manually modified. +/// +/// [`Vec`]'s backing buffer gets, if required, automatically increased (re-allocated) when elements +/// are added to the vector. +/// +/// # Invariants +/// +/// - `self.ptr` is always properly aligned and either points to memory allocated with `A` or, for +/// zero-sized types, is a dangling, well aligned pointer. +/// +/// - `self.len` always represents the exact number of elements stored in the vector. +/// +/// - `self.layout` represents the absolute number of elements that can be stored within the vector +/// without re-allocation. However, it is legal for the backing buffer to be larger than `layout`. +/// +/// - The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer +/// was allocated with (and must be freed with). +pub struct Vec { + ptr: NonNull, + /// Represents the actual buffer size as `cap` times `size_of::` bytes. + /// + /// Note: This isn't quite the same as `Self::capacity`, which in contrast returns the number of + /// elements we can still store without reallocating. + layout: ArrayLayout, + len: usize, + _p: PhantomData, +} + +/// Type alias for [`Vec`] with a [`Kmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVec = Vec; + +/// Type alias for [`Vec`] with a [`Vmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = VVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type VVec = Vec; + +/// Type alias for [`Vec`] with a [`KVmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVVec = Vec; + +// SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its elements. +unsafe impl Send for Vec +where + T: Send, + A: Allocator, +{ +} + +// SAFETY: `Vec` is `Sync` if `T` is `Sync` because `Vec` owns its elements. +unsafe impl Sync for Vec +where + T: Sync, + A: Allocator, +{ +} + +impl Vec +where + A: Allocator, +{ + #[inline] + const fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Returns the number of elements that can be stored within the vector without allocating + /// additional memory. + pub fn capacity(&self) -> usize { + if const { Self::is_zst() } { + usize::MAX + } else { + self.layout.len() + } + } + + /// Returns the number of elements stored within the vector. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forcefully sets `self.len` to `new_len`. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity`]. + /// - If `new_len` is greater than `self.len`, all elements within the interval + /// [`self.len`,`new_len`) must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + debug_assert!(new_len <= self.capacity()); + self.len = new_len; + } + + /// Returns a slice of the entire vector. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Returns a mutable slice of the entire vector. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + /// Returns a mutable raw pointer to the vector's backing buffer, or, if `T` is a ZST, a + /// dangling raw pointer. + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + self.ptr.as_ptr() + } + + /// Returns a raw pointer to the vector's backing buffer, or, if `T` is a ZST, a dangling raw + /// pointer. + #[inline] + pub fn as_ptr(&self) -> *const T { + self.ptr.as_ptr() + } + + /// Returns `true` if the vector contains no elements, `false` otherwise. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// assert!(v.is_empty()); + /// + /// v.push(1, GFP_KERNEL); + /// assert!(!v.is_empty()); + /// ``` + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Creates a new, empty Vec. + /// + /// This method does not allocate by itself. + #[inline] + pub const fn new() -> Self { + Self { + ptr: NonNull::dangling(), + layout: ArrayLayout::empty(), + len: 0, + _p: PhantomData::, + } + } + + /// Returns a slice of `MaybeUninit` for the remaining spare capacity of the vector. + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // SAFETY: + // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is + // guaranteed to be part of the same allocated object. + // - `self.len` can not overflow `isize`. + let ptr = unsafe { self.as_mut_ptr().add(self.len) } as *mut MaybeUninit; + + // SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated + // and valid, but uninitialized. + unsafe { slice::from_raw_parts_mut(ptr, self.capacity() - self.len) } + } + + /// Appends an element to the back of the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v = 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> { + self.reserve(1, flags)?; + + // SAFETY: + // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is + // guaranteed to be part of the same allocated object. + // - `self.len` can not overflow `isize`. + let ptr = unsafe { self.as_mut_ptr().add(self.len) }; + + // SAFETY: + // - `ptr` is properly aligned and valid for writes. + unsafe { core::ptr::write(ptr, v) }; + + // SAFETY: We just initialised the first spare entry, so it is safe to increase the length + // by 1. We also know that the new length is <= 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 = KVec::::with_capacity(20, GFP_KERNEL)?; + /// + /// assert!(v.capacity() >= 20); + /// # Ok::<(), Error>(()) + /// ``` + pub fn with_capacity(capacity: usize, flags: Flags) -> Result { + let mut v = Vec::new(); + + v.reserve(capacity, flags)?; + + Ok(v) + } + + /// Creates a Vec from a pointer, a length and a capacity using the allocator `A`. + /// + /// # Examples + /// + /// ``` + /// let mut v = kernel::kvec![1, 2, 3]?; + /// v.reserve(1, GFP_KERNEL)?; + /// + /// let (mut ptr, mut len, cap) = v.into_raw_parts(); + /// + /// // SAFETY: We've just reserved memory for another element. + /// unsafe { ptr.add(len).write(4) }; + /// len += 1; + /// + /// // SAFETY: We only wrote an additional element at the end of the `KVec`'s buffer and + /// // correspondingly increased the length of the `KVec` by one. Otherwise, we construct it + /// // from the exact same raw parts. + /// let v = unsafe { KVec::from_raw_parts(ptr, len, cap) }; + /// + /// assert_eq!(v, [1, 2, 3, 4]); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// # Safety + /// + /// If `T` is a ZST: + /// + /// - `ptr` must be a dangling, well aligned pointer. + /// + /// Otherwise: + /// + /// - `ptr` must have been allocated with the allocator `A`. + /// - `ptr` must satisfy or exceed the alignment requirements of `T`. + /// - `ptr` must point to memory with a size of at least `size_of::() * capacity`. + /// bytes. + /// - The allocated size in bytes must not be larger than `isize::MAX`. + /// - `length` must be less than or equal to `capacity`. + /// - The first `length` elements must be initialized values of type `T`. + /// + /// It is also valid to create an empty `Vec` passing a dangling pointer for `ptr` and zero for + /// `cap` and `len`. + pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { + let layout = if Self::is_zst() { + ArrayLayout::empty() + } else { + // SAFETY: By the safety requirements of this function, `capacity * size_of::()` is + // smaller than `isize::MAX`. + unsafe { ArrayLayout::new_unchecked(capacity) } + }; + + Self { + // SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid + // memory allocation, allocated with `A`. + ptr: unsafe { NonNull::new_unchecked(ptr) }, + layout, + len: length, + _p: PhantomData::, + } + } + + /// Consumes the `Vec` and returns its raw components `pointer`, `length` and `capacity`. + /// + /// This will not run the destructor of the contained elements and for non-ZSTs the allocation + /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the + /// elements and free the allocation, if any. + pub fn into_raw_parts(self) -> (*mut T, usize, usize) { + let mut me = ManuallyDrop::new(self); + let len = me.len(); + let capacity = me.capacity(); + let ptr = me.as_mut_ptr(); + (ptr, len, capacity) + } + + /// Ensures that the capacity exceeds the length by at least `additional` + /// elements. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let cap = v.capacity(); + /// assert!(cap >= 10); + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let new_cap = v.capacity(); + /// assert_eq!(new_cap, cap); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> { + let len = self.len(); + let cap = self.capacity(); + + if cap - len >= additional { + return Ok(()); + } + + if Self::is_zst() { + // The capacity is already `usize::MAX` for ZSTs, we can't go higher. + return Err(AllocError); + } + + // We know that `cap <= isize::MAX` because of the type invariants of `Self`. So the + // multiplication by two won't overflow. + let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?); + let layout = ArrayLayout::new(new_cap).map_err(|_| AllocError)?; + + // SAFETY: + // - `ptr` is valid because it's either `None` or comes from a previous call to + // `A::realloc`. + // - `self.layout` matches the `ArrayLayout` of the preceeding allocation. + let ptr = unsafe { + A::realloc( + Some(self.ptr.cast()), + layout.into(), + self.layout.into(), + flags, + )? + }; + + self.ptr = ptr.cast(); + self.layout = layout; + + Ok(()) + } +} + +impl Vec { + /// Extend the vector by `n` clones of `value`. + pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> { + if n == 0 { + return Ok(()); + } + + self.reserve(n, flags)?; + + let spare = self.spare_capacity_mut(); + + for item in spare.iter_mut().take(n - 1) { + item.write(value.clone()); + } + + // We can write the last element directly without cloning needlessly. + spare[n - 1].write(value); + + // SAFETY: + // - `self.len() + n < self.capacity()` due to the call to reserve above, + // - the loop and the line above initialized the next `n` elements. + unsafe { self.set_len(self.len() + n) }; + + Ok(()) + } + + /// Pushes clones of the elements of slice into the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v = 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) -> Result<(), AllocError> { + self.reserve(other.len(), flags)?; + for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) { + slot.write(item.clone()); + } + + // SAFETY: + // - `other.len()` spare entries have just been initialized, so it is safe to increase + // the length by the same number. + // - `self.len() + other.len() <= self.capacity()` is guaranteed by the preceding `reserve` + // call. + unsafe { self.set_len(self.len() + other.len()) }; + 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 = 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: `self.as_mut_ptr` is guaranteed to be valid by the type invariant. + unsafe { + ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( + self.as_mut_ptr(), + self.len, + )) + }; + + // SAFETY: + // - `self.ptr` was previously allocated with `A`. + // - `self.layout` matches the `ArrayLayout` of the preceeding allocation. + unsafe { A::free(self.ptr.cast(), self.layout.into()) }; + } +} + +impl From> for Vec +where + A: Allocator, +{ + fn from(b: Box<[T; N], A>) -> Vec { + let len = b.len(); + let ptr = Box::into_raw(b); + + // SAFETY: + // - `b` has been allocated with `A`, + // - `ptr` fulfills the alignment requirements for `T`, + // - `ptr` points to memory with at least a size of `size_of::() * len`, + // - all elements within `b` are initialized values of `T`, + // - `len` does not exceed `isize::MAX`. + unsafe { Vec::from_raw_parts(ptr as _, len, len) } + } +} + +impl Default for KVec { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for Vec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Deref for Vec +where + A: Allocator, +{ + type Target = [T]; + + #[inline] + fn deref(&self) -> &[T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } + } +} + +impl DerefMut for Vec +where + A: Allocator, +{ + #[inline] + fn deref_mut(&mut self) -> &mut [T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } + } +} + +impl Eq for Vec where A: Allocator {} + +impl, A> Index for Vec +where + A: Allocator, +{ + type Output = 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,)*) => { + $( + impl PartialEq<$rhs> for $lhs + where + T: PartialEq, + { + #[inline] + fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } + } + )* + } +} + +impl_slice_eq! { + [A1: Allocator, A2: Allocator] Vec, Vec, + [A: Allocator] Vec, &[U], + [A: Allocator] Vec, &mut [U], + [A: Allocator] &[T], Vec, + [A: Allocator] &mut [T], Vec, + [A: Allocator] Vec, [U], + [A: Allocator] [T], Vec, + [A: Allocator, const N: usize] Vec, [U; N], + [A: Allocator, const N: usize] Vec, &[U; N], +} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index d5f2fe42d093..80223cdaa485 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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}; #[doc(no_inline)] pub use alloc::vec::Vec; From patchwork Tue Oct 1 14:59:52 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818236 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 59ED5CEACD5 for ; Tue, 1 Oct 2024 15:01:56 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id DADF8680014; Tue, 1 Oct 2024 11:01:55 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D34EB280068; Tue, 1 Oct 2024 11:01:55 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BD655680014; Tue, 1 Oct 2024 11:01:55 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 9D0A4280068 for ; Tue, 1 Oct 2024 11:01:55 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 44A86ACC16 for ; Tue, 1 Oct 2024 15:01:55 +0000 (UTC) X-FDA: 82625348190.12.AEA5F5F Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf28.hostedemail.com (Postfix) with ESMTP id 2331CC004B for ; Tue, 1 Oct 2024 15:01:49 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=k+4rDUfw; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794845; a=rsa-sha256; cv=none; b=V1dIowkN9/wnEj4HQ4Tk/zoclnIQKPFJljMOtJzA+fL/Bvji7585ghVfLQ7LrT7X1or7oe jh9thUFbL2ak8E+jftRTyrztxPy9qBX1ZTMzPZzfX2ZzXQpSfn+rnZ5QEcnWNqfyeukCwY BKJyxHPKjUfguSkzCp9ey6h5SDTIRYQ= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=k+4rDUfw; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794845; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=/E1181t6qi/Z0YbUxbEc267BdYuyo2NyzYGplhXduPg=; b=5F0LmR7V3080by/sX/zNeaczydAC2r10/OFNIhFoGbOFQKI6WvtqZbKvbuvJ6oM0yw7EEU 4j1QOHNEzmc+sDwyUunCL5SEwl8prKxOxGjwo6Cunftr3B7WKmfyhBMjwaFN4VaSLBrLR2 2mf1yXjWIM3YoGETsuF6NJqDSRW9MZo= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 17BDD5C4CCF; Tue, 1 Oct 2024 15:01:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DD97FC4CED2; Tue, 1 Oct 2024 15:01:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794908; bh=WU3ilb+F7s6b0hCQthPkZjMBffv2TQREL2Wt+coFn1Y=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=k+4rDUfwl31k9vhU3jqNUMnH4fBOcloRkW7bgFCmZteeG1L7uc8Onk3lICt6F2g7+ LPnLqF6Gnx6shQhayZZV8xFbO7RbPBVcfB3Zc3aigG0yeGTs8z6WVJ0zLwzlAfpX7Z UUDGoOQY6GGxPO8RzrxBJsyacERIK386bw4pVODb33U0ExScCmvhFzNC1OE6fhfuji j3RB4zmU7ne40f5en49QARsqgPATsXh0dlniG0PKwZoOk4iRITv2V2nUPmbue2Zkz9 AC4RjZtjgb0zVt7med1hZfU9dG5GUDo675PpSipEdmGHY37AjT0DYIryY7p2QuOvTC YcmG6MBUkUUKg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 17/29] rust: alloc: implement `IntoIterator` for `Vec` Date: Tue, 1 Oct 2024 16:59:52 +0200 Message-ID: <20241001150008.183102-18-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 8pnhpchgxebzfthrsfgpf8bjawk3kkm3 X-Rspamd-Queue-Id: 2331CC004B X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1727794909-414174 X-HE-Meta: U2FsdGVkX1+tSWXXSiQUBiFFyaGgLg992IgRD7BQvdQVtdOEe6ob4oLTmHtPylgz9oBNrwJKrdbVG2bhJQZMn1N2JMq+Hbb/DI3I4ALS0hOIuuxc0X9HTWBErBy7igFMePWLDw4ye6t5cWWFO/7+bZBnKC624YYxPyWp4P2btxyX/sbiXu8pbgry1NNcETzQ9aqwUeDO1az8NXAJetXh41SVkLmiuX+uup3tXoxBq5t7fqL5l5um9bxg3I0udl3MJdPNn1WSdsRIfyn9YlSUrvOLnR+Ihp6t1gaU5NiN5FW68bzjZjQp6zoGvImfKVVewVjUa1DF2iXtk8S0HH0ZdNy+7chMNk8tIkSHXinLZJw/Qqs3qIxTCT/ACu9m9sC7o99iuP4f9z9FNe92j/2QJmQ7OG/XCXE0bwLUMHq3XVFd+3+ves6zoboh607vgAOvcAMh9i2VIAV11yUEfN/zsF1Yy/1tZcOmQwz8cJnxugRYrRe8SH+sM8JUQqG/bpgpzRtGhE6I+pNc8v77+dAXkfVt28DqEevaymzvT2nMcMctY2iBTK0hWmwBgvd+O+2oPyuB3aMmyo/FGfYAtdTYaZQOaaah8ASfYUlr/VP09diAH4pRvOJkcKyZA4iINNlcVIyoEJ884Is+efeHczcalbL+ZEXVpCLADXLjD58XeGLXnymShLhkgJKb4lg40TbYyOiA0zc2h8kbObAVebhWt/2rnXClbIlFnZ1bnptY/OW1g2vJs7umIKRXNml3ugLpZZlVQ7EwP2D+Elykz7dUAUOg8D31saC4g/38huv/P7UB/m7lbk4Wu+XVXz6XJYZSlo3OdbudyFR5F3nw+h2yb5LQEH0VBkzSsqLR2ujm37gIzbDKJww+ftewboVnkwUJKdNpQyz/zE/3EEIFiGi/xcQq8683ay9HeZR3Soic/970UoEaEmQXmaWhAn91sDKVzW/ek5l0rA6XRPXKl6x poIngHDe 7LR+PmdgG8ks+0LhtN1f14UYi6TUvS3kX2TmDf7o6yOyrqsACABsjZlza04m8n7bEWex4zx9E4CfUhR6C/t0x2YOfGPGjVsFZGCeR2W39qIYkLdQdl+zyBV4ZLFBGdh1Xsy2YeKjXxdpbK5ZJqPZivFBkMUbUFgHUhGnwhJ3RgQRCSMfB4Sfzfnm/sMRUY9D/Yr4os5xDKz5VPzPNpo7lDNXuuHBpUh+Vfb1g9JDWyltGFoLsgL0KmnXvCBfRxjg9cwprIzibHduITOeEVghaf7asxaJeyxKR7yjncwAL5+f2O50mGm98hnBWDs/57jZJj5F6zo4g1xyLV8khNDmCJbdfWZx2eEPJG+M6d2WRsMqf2OabN17O7ug1/eZiMWpUmn4Z X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as `Iterator` for `IntoIter`. `Vec::into_iter` disassembles the `Vec` into its raw parts; additionally, `IntoIter` keeps track of a separate pointer, which is incremented correspondingsly as the iterator advances, while the length, or the count of elements, is decremented. This also means that `IntoIter` takes the ownership of the backing buffer and is responsible to drop the remaining elements and free the backing buffer, if it's dropped. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 170 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 961070daf6db..1d57bfe2acb1 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -20,6 +20,7 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; +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 44aade0a653b..ff1c152d3423 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -635,3 +635,173 @@ fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } [A: Allocator, const N: usize] Vec, [U; N], [A: Allocator, const N: usize] Vec, &[U; N], } + +impl<'a, T, A> IntoIterator for &'a Vec +where + A: Allocator, +{ + type Item = &'a T; + type IntoIter = 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 = &'a mut T; + type IntoIter = slice::IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +/// An [`Iterator`] implementation for [`Vec`] that moves elements out of a vector. +/// +/// This structure is created by the [`Vec::into_iter`] method on [`Vec`] (provided by the +/// [`IntoIterator`] trait). +/// +/// # Examples +/// +/// ``` +/// let v = kernel::kvec![0, 1, 2]?; +/// let iter = v.into_iter(); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub struct IntoIter { + ptr: *mut T, + buf: NonNull, + len: usize, + layout: ArrayLayout, + _p: PhantomData, +} + +impl Iterator for IntoIter +where + A: Allocator, +{ + type Item = T; + + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = 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 == 0 { + return None; + } + + let current = self.ptr; + + // SAFETY: We can't overflow; decreasing `self.len` by one every time we advance `self.ptr` + // by one guarantees that. + unsafe { self.ptr = self.ptr.add(1) }; + + self.len -= 1; + + // SAFETY: `current` is guaranteed to point at a valid element within the buffer. + Some(unsafe { current.read() }) + } + + /// # Examples + /// + /// ``` + /// let v: KVec = kernel::kvec![1, 2, 3]?; + /// let mut iter = v.into_iter(); + /// let size = 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: `self.ptr` is guaranteed to be valid by the type invariant. + unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.ptr, self.len)) }; + + // SAFETY: + // - `self.buf` was previously allocated with `A`. + // - `self.layout` matches the `ArrayLayout` of the preceeding allocation. + unsafe { A::free(self.buf.cast(), self.layout.into()) }; + } +} + +impl IntoIterator for Vec +where + A: Allocator, +{ + type Item = T; + type IntoIter = IntoIter; + + /// Consumes the `Vec` and creates an `Iterator`, which moves each value out of the + /// vector (from start to end). + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2]?; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, Some(1)); + /// assert_eq!(v_iter.next(), Some(2)); + /// assert_eq!(v_iter.next(), None); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// ``` + /// let v = kernel::kvec![]; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, None); + /// + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let buf = self.ptr; + let layout = self.layout; + let (ptr, len, _) = self.into_raw_parts(); + + IntoIter { + ptr, + buf, + len, + layout, + _p: PhantomData::, + } + } +} From patchwork Tue Oct 1 14:59:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818237 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id E8EE3CEACDC for ; Tue, 1 Oct 2024 15:01:58 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 80A07680015; Tue, 1 Oct 2024 11:01:57 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 76894280068; Tue, 1 Oct 2024 11:01:57 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 595C7680015; Tue, 1 Oct 2024 11:01:57 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id 37B61280068 for ; Tue, 1 Oct 2024 11:01:57 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id C64851209B7 for ; Tue, 1 Oct 2024 15:01:56 +0000 (UTC) X-FDA: 82625348232.16.DCE4FAB Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf26.hostedemail.com (Postfix) with ESMTP id 2D18114000E for ; Tue, 1 Oct 2024 15:01:54 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hAVzhdkB; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794774; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=6+isFfEv8NpwPOmMh2hqeoPPB0NtfNAZFG5xltJeSvI=; b=evvwwqktYQRlt6sw6LFAXmZgs+UIENbqa+NtUAE0Ee62hxlyP6os6yA3wOXeAcOslYstPU LF2JShuc01lmwCZRpSACdSVRnfn7gFE8G28YHkg26qg2X78aPW1FgyW8aDILj9Ib0L/4hG KZGfs2xmX1QpZUycz5rVE1MFo3z0RcI= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794774; a=rsa-sha256; cv=none; b=HPzps0TVsQAP5cKXsMUWYuIXunvKeD25pDS8FsqbQHv6zr2AbaB16k1quf7l6R3MYmdiob 22hPNSym9ZAbXs4+yN0XjkHzxiIKNmY1JGoB6e1T8FSW5+/zyTLyA2Pdcvr42MJy0Io5uK gmMMaSle5WI21VAWisxEa4D3vUDFtAY= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hAVzhdkB; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 2B3D1A40104; Tue, 1 Oct 2024 15:01:46 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 40919C4CED4; Tue, 1 Oct 2024 15:01:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794914; bh=MwYQyJaBKHTn8WIWv0eTKw1s4/kooQlsfmpXe9kkPyo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hAVzhdkBlESVit9NBGfGk8d3WQcFwnUF4xU94wv33PIpIpwrVCOYFtxb2ONALejOl dRpEuS817+xztyEb5apQFjgDobbKiPS00hwkbE/bWXtuYtS10wqTTwmc8/uJwWi1wB fIL4SuFy7342DFfdoza/n/8b+cikdtIL+hg44AF9mTZEoFrb4ovaS/6j3K7+kYvLCk eOpDeU6/fKdW0Z0ar5vH4FqT+5hlSoasi+1stEC3470t5xzDOwWDWDJ0Da/WLzwlwr CQSDkMnsEVwfwtLEdV/lvKjhelw8OBZhZcv+o7Mp+sD5S54LR9JkmIEWKaUvked6TO jq9AzXGRUyDYw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 18/29] rust: alloc: implement `collect` for `IntoIter` Date: Tue, 1 Oct 2024 16:59:53 +0200 Message-ID: <20241001150008.183102-19-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 2D18114000E X-Stat-Signature: ro3ias6qq16r7wbkns7xurx1apnwsynb X-Rspam-User: X-HE-Tag: 1727794914-195682 X-HE-Meta: U2FsdGVkX1/Bea/jDM3Vlsp53mC1gUTgQ3Qk714BMEzgL+lUPgB6VsYFjMwyAIP8FMvQNtES1AcuZfGcLuqIfrc8ss3OZasi8Z21QXy8VD0XYbIpvuZf2VQZRYShe1FDBJN/zzm9zJaVj3dGvb56xxfCBY14aLF9WTQ1x7+hG1Nooen7Kv29PdYHElA9Ej2f5edTVxptE4pRDUrcA5s0H4SIGrsLZzfN0CBSCTjO+0RP5lQhHOJjGtYRf8yK9CkRdjZAMYHX6vSqIm3H/lq9f+eFGiwMIrdIzEosUuAIlrChB4MyTUR8YqXJHiR5aU8z3JsiUDv5RYPc2JANMnhBeWHP/u48xouw6o0bUn8SNSluk/2OBSWgYT1u+JoU3QUqhxG3zIXu9uB4uem5uQB+wYXXgiWa+gpVrSczOrvXAYXE1rTUNjigAo/XLR895bb/E+Yuqv1GK9cz62+iZZcx7wVmezU3a0pma59ZKuTX/50QVkMftv+0VVWNG0kQQiwJfVkii2dXvuUVxRQ6x1d3Djkm9ry3QscAarsvDGzT1eL4cWJb6M18lPY0XGuqh8zP9PD3lUpc2TQGVzqUL8j78ajPAncP9iZ3rkAzqIiqAy87kLPkuNRW+1kLE4B/18wbdca4/Hvfhra47oHgfolx3tliL99eK9Mqr7c0jZv6dWePtcVehQHZQ/Xswdr9IcOsTth5LoStkAAZ6svYQ9p5sO0axZQYWpyNNpaQNNkKl0fT0j0UgemnqHeRE+IWYz1OrAyOD6TlcEKYNbw+QJZH6ulwZ0KX7s9UdfBHUzKk8ONXaCHuqD8PSXRD4P6n5eH9yk37GVkR4YhF3YteB6grCy/SrjNPHENqZgxKY1w2Pp9213ESLBTyMWys0aMu73fpSrjh8GBxzzfXqk+fR+9UHaYHEOemvY1rL+At/13IkLaWBa+8doEvIpcrFYRrewKkUrHKUPevgLaiYWDG02P 9brw32XJ GeotbHL/HmUmVWgGmKIOXaB3hr0wa+q6wnRXOHQRRfwjedJpLODFkJ381cQAOeYsJ2YmokE83WiOEy7GhsSfNPkVOO31LZmf9gSrTjN8NpXqZvOZwBjXWK7wKWlHr1CJkYyLEUAJMZ+0GN7IqKOcwbUYeKDhF+F1WGo+v5hE4hPu/PL7JhKbcPnS4J/qRuexgXjGUW7TV7UZajnv4AfDsulE3j+n+YBFj4FuP9n0x87YqBVlLgB0pOePFz+StzjlCZFLJ6ZvMecK+IB1CVlAKldwZAeyuaLSF6kG7AXYk1lkq5QjkjA/JpK0KBeEoZiA0Z11yF+kMs1A8eeU= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Currently, we can't implement `FromIterator`. There are a couple of issues with this trait in the kernel, namely: - Rust's specialization feature is unstable. This prevents us to optimze for the special case where `I::IntoIter` equals `Vec`'s `IntoIter` type. - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` doesn't require this type to be `'static`. - `FromIterator::from_iter` does return `Self` instead of `Result`, hence we can't properly handle allocation failures. - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation flags. Instead, provide `IntoIter::collect`, such that we can at least convert `IntoIter` into a `Vec` again. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 94 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index ff1c152d3423..0ee320ed99a0 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -681,6 +681,100 @@ pub struct IntoIter { _p: PhantomData, } +impl IntoIter +where + A: Allocator, +{ + fn into_raw_parts(self) -> (*mut T, NonNull, usize, usize) { + let me = ManuallyDrop::new(self); + let ptr = me.ptr; + let buf = me.buf; + let len = me.len; + let cap = me.layout.len(); + (ptr, buf, len, cap) + } + + /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`. + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// + /// let v = it.collect(GFP_KERNEL); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// # Implementation Details + /// + /// 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 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 count of elements. + pub fn collect(self, flags: Flags) -> Vec { + let old_layout = self.layout; + let (mut ptr, buf, len, mut cap) = self.into_raw_parts(); + let has_advanced = ptr != buf.as_ptr(); + + if has_advanced { + // Copy the contents we have advanced to at the beginning of the buffer. + // + // SAFETY: + // - `ptr` is valid for reads of `len * size_of::()` bytes, + // - `buf.as_ptr()` is valid for writes of `len * size_of::()` bytes, + // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to + // each other, + // - both `ptr` and `buf.ptr()` are properly aligned. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr = buf.as_ptr(); + + // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()`. + let layout = unsafe { ArrayLayout::::new_unchecked(len) }; + + // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be + // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves + // it as it is. + ptr = match unsafe { + A::realloc(Some(buf.cast()), layout.into(), old_layout.into(), flags) + } { + // If we fail to shrink, which likely can't even happen, continue with the existing + // buffer. + Err(_) => ptr, + Ok(ptr) => { + cap = len; + ptr.as_ptr().cast() + } + }; + } + + // SAFETY: If the iterator has been advanced, the advanced elements have been copied to + // the beginning of the buffer and `len` has been adjusted accordingly. + // + // - `ptr` is guaranteed to point to the start of the backing buffer. + // - `cap` is either the original capacity or, after shrinking the buffer, equal to `len`. + // - `alloc` is guaranteed to be unchanged since `into_iter` has been called on the original + // `Vec`. + unsafe { Vec::from_raw_parts(ptr, len, cap) } + } +} + impl Iterator for IntoIter where A: Allocator, From patchwork Tue Oct 1 14:59:54 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818238 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id DE344CEACDC for ; Tue, 1 Oct 2024 15:02:06 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6F55F680016; Tue, 1 Oct 2024 11:02:06 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6A5EB280068; Tue, 1 Oct 2024 11:02:06 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 54621680016; Tue, 1 Oct 2024 11:02:06 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0012.hostedemail.com [216.40.44.12]) by kanga.kvack.org (Postfix) with ESMTP id 2443A280068 for ; Tue, 1 Oct 2024 11:02:06 -0400 (EDT) Received: from smtpin21.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id D5BDBACC2D for ; Tue, 1 Oct 2024 15:02:04 +0000 (UTC) X-FDA: 82625348568.21.B1649CC Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf14.hostedemail.com (Postfix) with ESMTP id AFC97100009 for ; Tue, 1 Oct 2024 15:02:00 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=q5ac0Azm; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794881; a=rsa-sha256; cv=none; b=X3qQl4xj8z6FNCOCKLpwd91RWWkq/v367u4jgeJUlN5scg3jNl6Zd84T6Y6MV0rF6k+gWa d/dLYAtW2EUHxZfewPOV18n1HqOpmRZHBryiZUw44oHqV+1QOggUbfvdNNtqK9dK/vgcfj fYXxxyKAnrNoegML8Ks41Qj2zvTkapQ= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=q5ac0Azm; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794881; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=UGyZDjyZxhnG6gqrWWDgaefQfQjFJVOj0k4IjyFvnpQ=; b=Q8shB+iJwSmkTQzbMXMiPdNhQebe3VmtLGAry9ACRNfVkmJBIo32my4WTC8Fg7A9c00ga1 rFu11glaGSr7DIpGnZOGs7/dHuWcVPrIMZTIkLz/Cu5PQm7Ll+VuKLipgbs9W9bMXq6RYK fHV9zaQj/s11VD1OEesPxQQShdqpa1I= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 843B3A40279; Tue, 1 Oct 2024 15:01:51 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 95C29C4CECF; Tue, 1 Oct 2024 15:01:54 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794919; bh=L+/LMFOMtE864WvCn41tWWSUMQocDvmfmSNi2WDyR5M=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=q5ac0AzmGV2ElLdhlD4+yTKtDEpfPVAhJdXEM9yuVluSA7ZN4jRVDGY1YCM/imngE laj9dhlSw8k73BtPsXFQEf8MINHpP7+qSMO67XNPHZEv+ugT7IDpeZ0kRb0/DZa1NM j9evXryTLEGDekebVTAcTHDEdfpduYwURpHjQKQCrHT47q/QX0C8B0OfCgi8JtDWbl KrIzUEkBHU7KAg32b1JWyrf6EY6Yw17urRFjHRXgvIWDEWRzdGQ4kqxR9k9TMDDLyt i9kUccDMuGH8Crmzs+G7AVlSu6MlWJ8FZJgFixA6w0wVCD+fFtMk7y0IQxgnqnFQBB mh1RonLnRjoRQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 19/29] rust: treewide: switch to the kernel `Vec` type Date: Tue, 1 Oct 2024 16:59:54 +0200 Message-ID: <20241001150008.183102-20-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: AFC97100009 X-Rspamd-Server: rspam01 X-Stat-Signature: ze3ugar7xi6q669c6wco6db8bhx8rpcm X-HE-Tag: 1727794920-683103 X-HE-Meta: U2FsdGVkX1/jLdhER83pGMzO9EWxDTNrK531ZbWU+ILd4XyicWO9r8dgl605AenDeYDukHDyhRGIwuwVIe9Au9cy4Tn6PxMpcn9xe9gUslNRH9s5uzzri/2aXKts4UVCLkoisTqG+9OaS2Qa0/zR4p2+fvTiESrH1t2IgrHcMTghJ9iSAddk7QBjRAh+luwHqG4xrt87KWefP5Qxe3rthN9qsWTvRRbr3CMgabc9Lwm+ea2HowaYp67N/K+ieFs1cdGTT3Bg1wtmHvbGyvlqwGKuVP1f93WPhwR2LaGxrl7UrWvOA6A7vSGSlmzS9x/ob8oX0z4bASMMzlcpGmH6QNpCi9OicScmbWibER0aL/eYpmre/WQwoFXBAHZOwFj1ZHFWDR7nH45tePqpB0bTDiNeXMXkgXCt/Intx/JTUuaCHVhk2fAk6hOdY1BnhWmCAnzhrnqITES2Gfsg6kAw4eN6oOGQnR6QP+/8sLlIyaPh5pmSmuJtUu7oRdPetqB8Kjx3y8TMkQZKvPQG+AsIFny+xZVtrjZsszgvh5z9EWcmFcNqRO2KY5kWKQbkZkxbY1AyDahxRv2HDLFKZr++KX4JUWDr8+sYz+nc4w2o9jZYs1az7IK4waX455ckAXIAzP/tEA/kGIBdKFyzHtFSaKyxTgtp6axRpgyH+HiSm6aCI9VsfbCmlwwburqkj5UrCSKUL9TfDOWdts9B3XW6clyhUNBhIYpz5y0m1JhLtx3+FfE2ho9ivkpD3rR02Cb7J+QzSRbiGOQjN0B4+wGezRhQYeiEgQ+kt6t764I3jNfgpWcsDpTFanqIIMdA6rAAWOwXpr1X/Z30tKMQesM0UsHK8h6JUhuI4D8jnGUSljHhThBngPcz85m/Qqh/et/ps/yJU/44PKjlmFnBC7wt+Q5vD6sri8wJ6Fbvr8jZEXReYtnxs9RtDupcW/wKrsFmYH0QZoFLHsQ9DhugTOr awnqO6oF 5CtnHbw8gRjNGYTeKzsu2yWEDbVcahOypzjUB3aHsr/4zYOCdIFkIQ7IUYdF8TAPaNaJ1TRAMQfq/Q4nAkZLOTdfQwJXS9CTHrE0aoTDJFHlnbI9Rrw3v6QRga1sJhc+gl3Qwg6N5ELNmlhIhasRACQVFf+pDHpjeq9n5/7PyoKlzIzc0BMU1whu9SmTc64EaBbYs1rN40ZiM6rxV4OncUZ4Nf0/A5ZZGOyLh28QIct4pZ8quOmRHvBD486zMmOo7mlNFvjbwSzWRVES3nto5tZ7Ykjc+koS+lIRsO1ef29I+BgoSfwVCsZ/Aw10o9gIm+DogEUv9dohOCt6z5TTxhEnFe8GWOhsLvt4qVJR/wxtsuSFViyXuQ6flHUobSY7WNmtS X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we got the kernel `Vec` in place, convert all existing `Vec` users to make use of it. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- rust/kernel/uaccess.rs | 17 +++++++---------- rust/macros/lib.rs | 6 +++--- samples/rust/rust_minimal.rs | 4 ++-- 6 files changed, 19 insertions(+), 24 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..209ad1bb1a49 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,8 +2,7 @@ //! String representations. -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}; @@ -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, } impl CString { @@ -803,7 +802,7 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result { let size = f.bytes_written(); // Allocate a vector with the required number of bytes, and write to it. - let mut buf = as VecExt<_>>::with_capacity(size, GFP_KERNEL)?; + let mut buf = KVec::with_capacity(size, GFP_KERNEL)?; // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes. let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; f.write_fmt(args)?; @@ -850,10 +849,9 @@ impl<'a> TryFrom<&'a CStr> for CString { type Error = AllocError; fn try_from(cstr: &'a CStr) -> Result { - let mut buf = Vec::new(); + let mut buf = KVec::new(); - as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KERNEL) - .map_err(|_| AllocError)?; + buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?; // INVARIANT: The `CStr` and `CString` types have the same invariants for // the string data, and we copied it over without changes. diff --git a/rust/kernel/sync/locked_by.rs b/rust/kernel/sync/locked_by.rs index babc731bd5f6..b94517231fcc 100644 --- a/rust/kernel/sync/locked_by.rs +++ b/rust/kernel/sync/locked_by.rs @@ -43,7 +43,7 @@ /// struct InnerDirectory { /// /// The sum of the bytes used by all files. /// bytes_used: u64, -/// _files: Vec, +/// _files: KVec, /// } /// /// struct Directory { diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 53d3ddc0b98c..bf1a96d5e1f8 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -135,7 +135,7 @@ unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {} /// # use kernel::types::ScopeGuard; /// fn example3(arg: bool) -> Result { /// let mut vec = -/// ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len())); +/// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len())); /// /// vec.push(10u8, GFP_KERNEL)?; /// if arg { diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index e9347cff99ab..bc011061de45 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -11,7 +11,6 @@ prelude::*, types::{AsBytes, FromBytes}, }; -use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; use core::mem::{size_of, MaybeUninit}; @@ -46,7 +45,6 @@ /// every byte in the region. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::Result; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -54,7 +52,7 @@ /// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> { /// let (read, mut write) = UserSlice::new(uptr, len).reader_writer(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// for b in &mut buf { @@ -69,7 +67,6 @@ /// Example illustrating a TOCTOU (time-of-check to time-of-use) bug. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::{code::EINVAL, Result}; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -78,21 +75,21 @@ /// fn is_valid(uptr: UserPtr, len: usize) -> Result { /// let read = UserSlice::new(uptr, len).reader(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// todo!() /// } /// /// /// Returns the bytes behind this user pointer if they are valid. -/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { +/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { /// if !is_valid(uptr, len)? { /// return Err(EINVAL); /// } /// /// let read = UserSlice::new(uptr, len).reader(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// // THIS IS A BUG! The bytes could have changed since we checked them. @@ -130,7 +127,7 @@ pub fn new(ptr: UserPtr, length: usize) -> Self { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(self, buf: &mut KVec, flags: Flags) -> Result { self.reader().read_all(buf, flags) } @@ -291,9 +288,9 @@ pub fn read(&mut self) -> Result { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(mut self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(mut self, buf: &mut KVec, flags: Flags) -> Result { let len = self.length; - VecExt::::reserve(buf, len, flags)?; + buf.reserve(len, flags)?; // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes // long. diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index ab93111a048c..8d4ac914b48b 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -242,7 +242,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` @@ -251,7 +251,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } @@ -281,7 +281,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 2a9eaab62d1c..4aaf117bf8e3 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -13,7 +13,7 @@ } struct RustMinimal { - numbers: Vec, + numbers: KVec, } 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)); - let mut numbers = Vec::new(); + let mut numbers = KVec::new(); numbers.push(72, GFP_KERNEL)?; numbers.push(108, GFP_KERNEL)?; numbers.push(200, GFP_KERNEL)?; From patchwork Tue Oct 1 14:59:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818239 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id D914ECEACD5 for ; Tue, 1 Oct 2024 15:02:10 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 71CA1680017; Tue, 1 Oct 2024 11:02:10 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6CCB0280068; Tue, 1 Oct 2024 11:02:10 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5464B680017; Tue, 1 Oct 2024 11:02:10 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 36234280068 for ; Tue, 1 Oct 2024 11:02:10 -0400 (EDT) Received: from smtpin21.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 6B33CC161C for ; Tue, 1 Oct 2024 15:02:09 +0000 (UTC) X-FDA: 82625348778.21.C2B52E0 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf23.hostedemail.com (Postfix) with ESMTP id 01609140029 for ; Tue, 1 Oct 2024 15:02:05 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=nGNHafod; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794886; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=9yF5l6xGiLdefJbiGba5mRr5YQkAiNkzw7N98/YRvog=; b=ayhNnYe9EU9z+bff0g7zzY/RKpaSEBOJ2Ti7n95a7NQPc2CsbCDcKCApGrYKfi6eNxtK4E H14ROYeFrJZdGTILmu1qSGH7Y3gNgQe+xW07ln/JwIvu1hIWi4eugJB2PMYzzD6ygK5Svu J1FT3w5hckOXHZkjNGWSesx73UaGZxg= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=nGNHafod; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794886; a=rsa-sha256; cv=none; b=gK9uFa4by1x5PfPqJ/b2vzi/aSgMICb/dYcWq3Jk+hvI5qwoOtPB5cZT4PG1s4YvDerH5P Mz4aaRNBhDUf6bQAaGyIZBT89Tn272mFSzal+wZVM7RbN4tiCM0BckRu0hPBTFYkS38lye ASU7C/CXZ5sQVsWRmT2bNMzhVHl1Sqo= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id DB9CBA40147; Tue, 1 Oct 2024 15:01:56 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id EC4E8C4CED2; Tue, 1 Oct 2024 15:01:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794924; bh=IBiqOJrVjNjDKaz5y8ARXywOWvCMKwjrfiOMMbLXtzM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=nGNHafodq7XknYv7/i2pTAp25DC5ZK511HvP8XWsqVDW0fljOyMXC2E8Bzk/2SQYw i/fhrcH1+9qNkX7R83YjSk0N0gdFBtaFSKNq6UD/tm71Ysiss2i5Er7l7BYAEUBeyP jmYW04fCdBlEYe7YJVwe0HtA5SCbRtylWdOi59quqtD73JeJqBrPtXHsDwZDOuXEWl sJT4/31+ZdjTn+Ip9nzI91i2NozgNhdbM75CvMk/8KLSMKM7wlRQnm7oA+iZkt2rA/ mAhKhaXNjg/cJPUWSF55SVFmMXVXBfrlGRedL4wBtZ32f52zqRsuIo8YnTzVmdecnB gX/vWBQhQ5oqw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 20/29] rust: alloc: remove `VecExt` extension Date: Tue, 1 Oct 2024 16:59:55 +0200 Message-ID: <20241001150008.183102-21-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: pogqrpgwbypbum4o4bcyhwfdnsbo6ncq X-Rspamd-Queue-Id: 01609140029 X-Rspamd-Server: rspam11 X-HE-Tag: 1727794925-552007 X-HE-Meta: U2FsdGVkX1+62HntWwxD68/yANwBaMa4R05dYrGP3ooLvpRjZ6ByDcgDAYzYX9RcYUglPJBq2S/mp32r1C3lxPDNkEMqvEihg42smM3653T1A1V053jfqsPpUw05FCjUOC0lA+HrLqe+ub1qE73yMkycUEBTHcHN4JmwP68JlTBjMq5z0Yu/fRILOuMTnerjwXlcDqpx13mUnw8S+JOGkIp13wDdRgXVFsWy9zWyDMbee/HUDC59vI9LGhLb+lgz490nY9WXkrWiU5DqFCaHa7duUaOA5ZC5lN5PzaE6xVTjPnsuZQ33t68i89il8DGWpW7xJrSkPMKlqv5ribRWIKfAJBxpETib3I9LOjuDGIMemaDZw8KgR0Oz0iaa93J0LNXXWMYiNk0pu405TG9tOcJ2pwGUa2AqfdN3yrf2X0eGs7qHh3I7jWANmBnbKfn2494J6qQJidOUTTGwhzWTDzRPniv6todLiRSL/31z7fj84vls6nF99K23u5wzt4XHe/eTKA/wcXYgnlzN7VL3BU0e/c/2RaR2gL2I+Oel9Kr7vZDDJ/x8WtXS2YsnJweR9yMqbSh7zBgsMr0EFEOuWbrLsdnw2QKEGDQaBvEuTshaW3RrIh2M37aIzMqj5v4rS9iXI/RO4SsBhPpzxGdKt8xPyEsLhc7HGrCViK8vRZt6y768fVqBSVBNnC6n3j/XFv2+t1jTNtVj1pC70pnA0vxAJTTaeKcEEfcVF11CvsozvkAP1x4vG3CJGOqXJw+gm9CyhxGmnABWbz9BaLY6q1HbFdz78SP8D83uypgNBk0CRPiR8hhU5sI6zQy4x4xwas/QIEoaapZi3ulNP4QjTuBMXH2hLQGC7ftaabv4EDs7lYWSbXxJHPgAcOurPN1yT60IvHNEJbxyjPJDM07IEyiQkg1CERk9Z05e9fqMvsl1LenYVNc+5lzO4C3GOg757SY4i8Eprz4vxApfcJJ DwcXP539 YLXoXMZWWxM6HMDB2g0cjUQCzaYEYLit2kP3YGvXI2K49TlV4rbW5fP4v7i2AJZGjF8duQkJHIjHonSnCABcqTFMCe5iGH89aEC2ozgYD9337RkKPmCtI1KaRa3wpTkVmfAG/NjbjB9vII8bRW6+opDUOJ5pmTI8HazefmAF/wvZvP/dvBHmI/k/hjo7bztPCO+w4sgN7HF7cf0fYsDtF+5J3Qw1ldDJ3aOJScTbbMSrox7XTaeCUD08Vgp7W+aHDaH+ZIFWGqD3cF/JO5KtyrC3i9+8Y/vYERkLG3Cv32hLUAdQzgmG782Tc9hmqJ3wMY1aF2XoS7qAXK5wj8Keg/z6AH8r5thbbzS9MGYXuHeXCPL2NIpRPJn7MWWdDkOUfPUJb X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that all existing `Vec` users were moved to the kernel `Vec` type, remove the `VecExt` extension. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo 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 1d57bfe2acb1..e8955340fe62 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -7,7 +7,6 @@ pub mod kbox; pub mod kvec; pub mod layout; -pub mod vec_ext; #[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 = Vec::::with_capacity(20, GFP_KERNEL)?; - /// - /// assert!(v.capacity() >= 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 = 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 = 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 `additional` elements. - /// - /// # Examples - /// - /// ``` - /// let mut v = Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let cap = v.capacity(); - /// assert!(cap >= 10); - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let new_cap = v.capacity(); - /// assert_eq!(new_cap, cap); - /// - /// # Ok::<(), Error>(()) - /// ``` - fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError>; -} - -impl VecExt for Vec { - fn with_capacity(capacity: usize, flags: Flags) -> Result { - let mut v = 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 = self.spare_capacity_mut(); - s[0].write(v); - - // SAFETY: We just initialised the first spare entry, so it is safe to increase the length - // by 1. We also know that the new length is <= 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(), other) { - 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 <= 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<(), AllocError> { - let len = self.len(); - let cap = self.capacity(); - - if cap - len >= additional { - return Ok(()); - } - - if core::mem::size_of::() == 0 { - // The capacity is already `usize::MAX` for SZTs, we can't go higher. - return Err(AllocError); - } - - // We know cap is <= `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 = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?); - let layout = core::alloc::Layout::array::(new_cap).map_err(|_| AllocError)?; - - let (old_ptr, len, cap) = 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 rely on `Vec`'s capacity - // to be zero if no memory has been allocated yet. - let ptr = if cap == 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 = unsafe { super::allocator::krealloc_aligned(ptr.cast(), layout, flags) }; - if new_ptr.is_null() { - // SAFETY: We are just rebuilding the existing `Vec` with no changes. - 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 >= `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 = Vec::new(); - core::mem::swap(&mut tmp, v); - let mut tmp = core::mem::ManuallyDrop::new(tmp); - let len = tmp.len(); - let cap = 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 = unsafe { Vec::from_raw_parts(ptr, len, cap) }; - core::mem::swap(&mut tmp, v); -} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 80223cdaa485..07daccf6ca8e 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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}; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; From patchwork Tue Oct 1 14:59:56 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818240 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 94100CEACDF for ; Tue, 1 Oct 2024 15:02:14 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E71DA680018; Tue, 1 Oct 2024 11:02:13 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E1FE9280068; Tue, 1 Oct 2024 11:02:13 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C73E9680018; Tue, 1 Oct 2024 11:02:13 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0012.hostedemail.com [216.40.44.12]) by kanga.kvack.org (Postfix) with ESMTP id A6371280068 for ; Tue, 1 Oct 2024 11:02:13 -0400 (EDT) Received: from smtpin15.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 59C25120996 for ; Tue, 1 Oct 2024 15:02:13 +0000 (UTC) X-FDA: 82625348946.15.74BFC74 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf22.hostedemail.com (Postfix) with ESMTP id 8CBB7C0004 for ; Tue, 1 Oct 2024 15:02:11 +0000 (UTC) Authentication-Results: imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=LCAwFDG+; spf=pass (imf22.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794892; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=4Tl1whPfU/nWLhFKdIaDrQ4pPfk7cl2YbpR6IXgDySA=; b=ZK7bdFq7WjJaUGirZTSFvnV4qobJU7O5jGWWXIlPhx6jJFhbw5O0Uxb1ovV82hoZ5m8+jd 1E/4ak8PcGY02frI2TSolVJF9c0G7iDC2cZmtjN0xDN9Y6RdGX8vCQZ9+tKLtpUyHEz5k3 GEcw/sindE6tEeY64IgW0FLitPagg04= ARC-Authentication-Results: i=1; imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=LCAwFDG+; spf=pass (imf22.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794892; a=rsa-sha256; cv=none; b=yOEjFn2w6SEWOvc+k6QveLeGtN6mNZ9y+l9FeDwIM2eyvggVgEa1A7EszAXD9CdwxAqkNn NHYWqu4XMoiy2yZc7RaeoNhLsdNqNLGjvyYQTxW+Zd8DQt5G2H+vhkZ3NE5AzKdlRZuHDi NXvIaSmpP7j/APQHg8IeJfVGfBXD/Dw= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 7AEF55C0114; Tue, 1 Oct 2024 15:02:06 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4FD63C4CECF; Tue, 1 Oct 2024 15:02:05 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794930; bh=ZNs0Dj/ExXP/FTdJ3MujwXiT4/A3eVE5pzPxpi0CaOY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=LCAwFDG+HwF0qdWHedel5sJSUl1FWW7tqFalfSm0hqMw2bBfmu3u+6V3cH4/C4WZL JErQKf4WUj+jDTKVznqwb+sqjnLwkieuky9Rn4ch1aRuadZcapj2Hg22Z70bLeP7Tx YnKWItxw5aNY4RPBSmXkPdzqjjylTr1uiedInV6Ef5uNg16UU2/Et3REwUtK4L+nuo wonyGbDahi8ZM+7wfIviQsGi1EraXFl6u5Y8izDxYSXfyywjf4tfLqv7kNlnZnMeZI NsfyJxEGNT0PmS0sXODuurgMvJ2lujEqDKrkeUyCW/F9lh/nP4wa+UTGtpaFX26aeC aD/Edjh/yuAWA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 21/29] rust: alloc: add `Vec` to prelude Date: Tue, 1 Oct 2024 16:59:56 +0200 Message-ID: <20241001150008.183102-22-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: ia9u51ais3j1tm76aihpdm5r5n5qn4r3 X-Rspamd-Queue-Id: 8CBB7C0004 X-Rspamd-Server: rspam11 X-HE-Tag: 1727794931-528560 X-HE-Meta: U2FsdGVkX1+HBdDEN/M8cvfGo0DqzL8CGjMyIHgv58sc4U8hLh5XOPsjF6KJ5OG/o/pBHiZcmzKCjJgsD8gd4T8LhWxILKpUJ4+Lfv/uCS5L9uU8Dt52D6s/t/eqRvpLOgvFRMIU1++UBGE2lm0e6SvMLRJd9r6Udco9siQBWVuy90kEeinI7smE3TxqLIUVkObWm35GlBz2F4fsQ8wXhv5CU3hRm6nf/QOZb42g+NQmVB19pyJgCSywJ7/8QNLAiLzt8tAIZmHsSwC9DEvu4TUwpOl2RssSEEmH6lRKxlE4K32nvrIWrTAO1op0nWC+ORd3zD6e//dMOCb+MIq29bGwSBISBYaSWHyDulxuuAVI1b2OQmuaM9vYRn/H/aVTOcs2MJeP0DmG1j3W9div0ATzBWYgGNBHKtQtLzfueL7c/6Xf22fVMMwil1o3G71MM5skBFvpst1uclt2bsUmc4samub7T0c0EtdrQ2gRnxAlY6Blu74ppRTHR6imIwO2BFDHbjJKtJXovSUpuX0r55lt9o/WO2xHPLXnmyAjY0xZAJhdytlOahA3e2VnSWkmYiE6uyTBAEFsjJBg5eEDw1LCrz5Ona/H9IBmYqUp6yvfMNVzSi+/Xt7SUl8WcWIcbdvFc8X4iPfnJgIXwU1067nl7lYtMkeK1NxeII10eGCuOYv4Igu+GwMoTQNalv6ozgDYV0+tXpAaudtZ1a5TI0rvs7A4rXyO1hIii5w0X7OBQ/P84bZ6Tioy94tT1EbHxTYcnIcfTr47Y/I0+lu6OM2SCP0osbltYRBV7YOjB6VkywaQtv3wEqIN9Nthayqu/kTTDe53s9hjiCOZ9WxVLSDX4CBZQd5OpaHB2JowR8G/wJY/ETV8loLvXEFUt5eWyZp+JzX3us/zAVTxzlIMe3m/X0lEfThYZv9NPROSmhgpe9zoUfVhWCur44uRUsHvztoa3q4fBJ255/9KCfd NsGXRKAd bAPzmAK9vt0k7QSfzN9YDU8m/+46R3JWVzhk2VVXlgncyn5aVObWcSSmHs5OlOepbpTZBn3J5oxQT68HTHxgQHZCm3zwUwuaONYUT0mKmP+vnJLm++G13AyJBIYEwkd2bcukXflb7OHdZ3ZFhzp9cnuDMXKHunlkBplt7dGKfXd8eDQWsHBN5H3wGwQ3r+xG1I8WH+6gan8Ia/POAobb3O0+oMnk4hP5Du537ztKWPoa4+U0qgixWGlcsjV9rgy6wF4EHLrXd0PBXw3QTy99iEyKXLATqiju6VrTm7bCvbHsKr0ua2x4658U9lBRWqtap2M1+hI2Q3f325Q6pDBZECHu7TdqZ9i6LW/RkKW+9+L2va92GF3TZjaJgWv3dyFlLsa4T X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `VecExt` and the corresponding includes in prelude.rs, add the new kernel `Vec` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo 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 07daccf6ca8e..8bdab9aa0d16 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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}; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; From patchwork Tue Oct 1 14:59:57 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818241 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 65896CEACDC for ; Tue, 1 Oct 2024 15:02:19 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E21CB680019; Tue, 1 Oct 2024 11:02:18 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id DD209280068; Tue, 1 Oct 2024 11:02:18 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C7283680019; Tue, 1 Oct 2024 11:02:18 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 9E788280068 for ; Tue, 1 Oct 2024 11:02:18 -0400 (EDT) Received: from smtpin18.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 55AE11A13F5 for ; Tue, 1 Oct 2024 15:02:18 +0000 (UTC) X-FDA: 82625349156.18.F655CD4 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf19.hostedemail.com (Postfix) with ESMTP id 8B22C1A003B for ; Tue, 1 Oct 2024 15:02:16 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Ymj6w+1U; spf=pass (imf19.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794871; a=rsa-sha256; cv=none; b=ynPXG8pJO37VkJp6aj4vZBT3RlxEAFCyxxsZ1ECvBNpV04A3j8mCY85GKf1IQJwpxEWn1y jJOKZ6Fjn389bPFjwd9Qid8s03M//lvGXJxUJbjvcwVVoUqbMOkgtMDKjW++SI0zclcrqg v+qvjObHYvZpBv512rQkpvL7NwrvzTQ= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Ymj6w+1U; spf=pass (imf19.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794871; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=fvpAqkrAjMlurxJDO8mN3C8w3v5WlXvTigRyvftnEfI=; b=0GXIE99HRXqpEHjka01Co5ku+6w5QPCoVaKoMYKRYTZrDbbSjUDldm1F3BNl53bgzsx/jN kWbijc5l7CVMh+NREVd4C3DICtfszF7LAU1hqYsOFKTqQPmQjuPbmaYmdP/diyhfPpAa3z nsdWQzy3PYZn5fwyyrhBwEB0LnsbY3E= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 9D2B6A40104; Tue, 1 Oct 2024 15:02:07 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A55CAC4CED2; Tue, 1 Oct 2024 15:02:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794935; bh=gQa83BvihiTDUGMuUjx+C5N2mcc2ulb0bOkT9bwH31w=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Ymj6w+1UKRHEv1C2NLx2yMSp7QG95ZSroFgy9ebKi+fVSFbKEOWP7fSIjsCn7efsm xg8Px8wG55oXjnANugoRRHfj3g5G09YA8KvaLpEaP7ZDsM5e+aG+D59j92HK2cfzrq tJ8EZRLegFxti8OwTOwHwSQvdYTodPZB/29XMXL8uuBeV5ao4ssrepqlg63pFVOqLl 4bbq8haqOilgKc+I+p/e0OS/KJ27SEkMXBT9akOFYzi6nNmYLn16+Vb7LNQkhATvpw 5kNIdK5fqOhURPgyhs49XBFzZYh9eI1vJ6MgKBTyRK5l/jZsrEc6yDqcHGMw+pDOHJ UVDj2MdqOT+kQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 22/29] rust: error: use `core::alloc::LayoutError` Date: Tue, 1 Oct 2024 16:59:57 +0200 Message-ID: <20241001150008.183102-23-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: q4tmfo8tqyakq3icddqoydai35nrczjc X-Rspamd-Queue-Id: 8B22C1A003B X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1727794936-763947 X-HE-Meta: U2FsdGVkX1/25m5QJ6YDm82LwJkEc8lOp/K6Q++DRe0XZDdDDZIpub9KKSK2N9MHIfyjItD/GNEbJL+L59n1T3zzLOgLJDORNp1kaZq6bpuCOoUByraxSA0pnV3kbSB+yd745XzdrvTb/AVt7Zugq//x5Va8KGirh8K+Z0Z/LaKe+WZULnM224gmGS/BJrjvF71Y5C3luvCm3T+4BRReTHhS+alVil8lBwAlGUMcHMEo8/mFEMCw0eYoLHMJDVenfMRrVXELTpALbht8DumWnzdyq23kc19aFiJTTSIJZf/S4ZfONH8F89EylWjSj1azIBatXzyd/wo0LdnZ+WZc3m+08IcWuJ55rkL7I41vIABBW9KT0c+qWrdm01G59WsQlPz4JAZQALQlJUwWKI4ZL1tZdpTbC4yqpokfJJWM2fazn3Z3qoXii6dCGjJqtOUn131X1ZT0CleFQMreX3/9NnHsAmz2nT12qHE0oBOXAi6CPYTS7uADmDiry7mPH6NvipXSMR/6pwlYvZQ8v/xt9snQYi3cOkDrkYKmHGykHJibb61mY+koCSqk+dVITWQc/UpQOCvsFFDEfwz5TyneKJgRlYgI8H7Or8Jlc7HcdrX7ZRlDObFVywV4kmA0hNsuIJesRWHv61RyqM7IbGlxEUxHKzQfA1kMgrnUQr6HH/bLXGp6gM2E9EStTKUzkCDR+oY8vAgk4YuwvbXe4clLFuup+WP/ylJ1xrUtcF4aWZM7o4VVtbvesJZj0OzgIjqksFujtUKbbUyEEFyHgreU4kmI+G7CilZf02MX1zRS5UzR63Bt5dIUunVuyplAhR04g1OMTQP8/ZZ0Jgpc0T+d0BYcY7dZg6oiHSbITHZK+kPcT9wfNU/ZdgTFljrWnfqkzbHf7/r6go2qlNaQXvFjb4E3zr3130rKXagU6QpouwCD0nJTfVUT00mY28UJS5JNMWhwHmHi0GXeUDwlEjL 5OeFvm2+ 3V/aVFrHueAFDuAKIVwydueIm7POTUQdbPKdErGIEJsnOGlGCAUR5NVIne4Lxi33YKFe6m28moJfiuNTl5J1+3jkodhtPQ3Op8TFZTB8yLC7LEMBpxE2LEEed+ns3Q0M25tzAVsN7FYSDWzR+XkCEuBb3uEiNCEcFsHPChn9vbj3gxo1mbi/MHnCdKag5FJ7dHBd/anbL9JBhCnfjtL5jujnt2GsegW8M/DJnvHLILN6lEBLqoq1kx0mYNIADnL2uxN/qmvfPVQS7RdnDvj4JrI8iCSgTyk8GblGZdPeZAWZJQnVHKC2YY1JCwRyldGUlphwXUj6qfQaipP97QEKaWYxtDXBaZTjH/sFwHE7C0u8yujJASuAM3mIT4cRlCXTDhW6n X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Use `core::alloc::LayoutError` instead of `alloc::alloc::LayoutError` in preparation to get rid of Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo 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 6f1587a2524e..81b4fc5cf21e 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -6,7 +6,7 @@ use crate::{alloc::AllocError, str::CStr}; -use alloc::alloc::LayoutError; +use core::alloc::LayoutError; use core::fmt; use core::num::TryFromIntError; From patchwork Tue Oct 1 14:59:58 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818242 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id ED65CCEACDC for ; Tue, 1 Oct 2024 15:02:24 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7E1E568001A; Tue, 1 Oct 2024 11:02:24 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 768C1280068; Tue, 1 Oct 2024 11:02:24 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 60A0168001A; Tue, 1 Oct 2024 11:02:24 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id 3B93E280068 for ; Tue, 1 Oct 2024 11:02:24 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id E0550815C7 for ; Tue, 1 Oct 2024 15:02:23 +0000 (UTC) X-FDA: 82625349366.25.404DB0E Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf17.hostedemail.com (Postfix) with ESMTP id 1960540019 for ; Tue, 1 Oct 2024 15:02:21 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=e+vqwI38; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794848; a=rsa-sha256; cv=none; b=2bt4zQ1hhzicMjEVoprLoEg7rjdzJWYqxsCkkdvFZMF+DDDF/gzyVjOkkXKQA+SBfbNEJV Q9LpROVm7T4hmj7KCYRrZxr+lNZwcJd7oQY+VhyjC4D01hJuFPAYhrhlZF/xWDMzlCoBDZ Hj+iQrNlgISoSfqS4xpGiTbwn/Tp+/0= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=e+vqwI38; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794848; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=auLoE+/cqYzLtXpQAXgaycME8ttu88NyJXsTFN2ZvCo=; b=KofLJiM+AYL1euriXECqCh6gGkeauqgBszck7dhyquzGJd3Aa1eWyDybLaykMOsV0uZbfn 0ZG9VJIfNfBJcW1X7E9YPrSEAMlKZY0qwmc1cc1boXMyByYbIc8AbeRDQftKPh+kokgEM2 3oVu+T4/Nu5OjY14utvnUjoasL2m1Bs= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id F3071A40216; Tue, 1 Oct 2024 15:02:12 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 144C8C4CECF; Tue, 1 Oct 2024 15:02:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794941; bh=dcNxqKnnFz5ev8owV03l67WWJcIeV+zuTzyuxUVGedE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=e+vqwI38aUi+XTqVQgdXynPd4BENIOD2o+SC8pUH/21gcJ38Nb+gJ9Plsd8r5vgwV Kn9kpo72MOUkdbIXgIZpJ3qQBORhhLeLArsAJuKam4covn0BAwwsqH05GicpaVFNw1 2GFtDg/GWK84pE3pbS0ECn8byzZ7dGOcM5cO807Ydx84gCrZxp9MCv+mD9H1gFflk4 v4HuwvDxJvtwbjAHu05uNovXhcR0jTBp89Gt6/gzW8KaCOS3nxpF/SVzoCrOoUSd5h IasB3eCjPkSosJoVIiaxIMMoV4bg2+ML4Pefbxkv75mwlHgMDpaPO0cLzGsHJplbe6 Jvzs4ivfCAKtQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 23/29] rust: error: check for config `test` in `Error::name` Date: Tue, 1 Oct 2024 16:59:58 +0200 Message-ID: <20241001150008.183102-24-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 1960540019 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: y8fu9k6qj5gap853tzwn84mrhegws3q6 X-HE-Tag: 1727794941-175232 X-HE-Meta: U2FsdGVkX1+7r09Q9vOm97StsgeyIqOQnEdYOo7Kgbx2GKYFNJFAN+inLgBeK3t1axhvFki5uspVnIDTg740lLyKDlpRuE7u5toC+qlbWAqB/pos7XdHwfhqOSjQov8ivxv/c/pd5nu6eAAwxY3DdwUr0jvmTsl1Z3CeIoY+iTaqf2UomOHmsJfhyGTHrATE2EbYe363hGzNnpxEy61kNaj946Y3sgDztH85iJNlinJKWYbMRzrCGEfoAG7683zgdHZ20ex7yxDd/PIgqCoyFHWGSsH7UMTEqw3WEY5yI9ouy0nqX5F7SEiMreVIOkcYHfSjiRbk72QeKTQpHmiwR2vTsJfGDG6NgUMeTuUchLG1LKNmmnRSDp0Bt9FVCS1ziXG/cC2PogvaGAW8TIctLgf7O8x4vf8rejcZBUnIOac8iFtAMDWOBRVZCv6vB6UE/jukGGslXhlWwS4I9w8wxlyLNeGV2ZMhWm/TyXWlFAD0Zj3wcJAhxg/tCCjEd0E2G1BxHhJCViVCLW5uEO7J9ek+D9/wcPtW25TDJoXyz5Nj3FC4UB+KHeGwcajXflCFEalMZm7fIJ8tzdUByxqQ/Wmu4YJtS+RK1y9fajg/juGXCBv1D+KNvGUU7cqBypLWK/4WptDdrCCyws2FOTAPFhR76n/6+xLojCHmLTTgyTWGm9OzmBXNxT7zq/vC/Jfit1gJAKGzuCeqAxQwfv5r03YR/FF+xCojuayDnVh04fDtqJdlggLUKjO17VPBP/SJS4mPdHm1927sjNX23eTwpoTeQ9VaPDhs6tdG1a5j7lM2GEgOUyUswJyDrASuDKizWN7n1+SciRGUvkNKZMsDGLB0PRfr65KtAi2sbek+OIUzK+6EtJeT8U8GimJY/Dk+oGeVdH6ZV5Rv1QLuMZps+lxXc5414H8hjx8FFRl9EKF0IlO41rmUjrTNlM/QRnPiD0K+2ynfrKLpORRsaHV LJArR4LQ M0dnhXp3V52JZMrdOHynItXZ3m0muJy7++ujl1Ua3ISxlsuY/TZlzTh+GVgCJ1FYLlBbEyGMh9VJu3GnDOLrjyxVM3n28P+TGquTLuBPtqgbNkEO8lY06EJxYD3efs28R2A3Xt6cCiSd1Dm/ydbYrBTwrfLZ7/58EmehsVK4aZnctsOOdwPPTwighKu1554ywmWWCXPAwL5z6MwGRML8LkKh6gCIx6bRpT3IOssfZqgVYLePF1O1ptnU2BHJjsznv/IrL8kpcGyfGPKqYwe3HlZ8bT497pHzDFqMls2qL0P75bK6sPkZfNo3m0kp+NXZRlAN6xr6hMaDp0RlAFKjMPmJ1VFR/jFnI73SeRRobaX64m0+CyiDAktK0yEHy94zb9Z/a X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Additional to `testlib` also check for `test` in `Error::name`. This is required by a subsequent patch that (indirectly) uses `Error` in test cases. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/error.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 81b4fc5cf21e..b71fdd0f54c2 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -143,7 +143,7 @@ pub(crate) fn to_ptr(self) -> *mut T { } /// Returns a string representing the error, if one exists. - #[cfg(not(testlib))] + #[cfg(not(any(test, testlib)))] pub fn name(&self) -> Option<&'static CStr> { // SAFETY: Just an FFI call, there are no extra safety requirements. let ptr = unsafe { bindings::errname(-self.0) }; @@ -160,7 +160,7 @@ pub fn name(&self) -> Option<&'static CStr> { /// When `testlib` is configured, this always returns `None` to avoid the dependency on a /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still /// run in userspace. - #[cfg(testlib)] + #[cfg(any(test, testlib))] pub fn name(&self) -> Option<&'static CStr> { None } From patchwork Tue Oct 1 14:59:59 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818243 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 720BBCEACD5 for ; Tue, 1 Oct 2024 15:02:30 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 04C5668001B; Tue, 1 Oct 2024 11:02:30 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id F09CD280068; Tue, 1 Oct 2024 11:02:29 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id DAAB668001B; Tue, 1 Oct 2024 11:02:29 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id B5096280068 for ; Tue, 1 Oct 2024 11:02:29 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 713B4815F5 for ; Tue, 1 Oct 2024 15:02:29 +0000 (UTC) X-FDA: 82625349618.12.9DB69DF Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf27.hostedemail.com (Postfix) with ESMTP id 8A4D740012 for ; Tue, 1 Oct 2024 15:02:27 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=pGrDvkAu; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794882; a=rsa-sha256; cv=none; b=lqZiagVaPXenBphrrwpx6k8UktDvfP7MANKygyhsIWbjVwxAvczXpO5jSJEpmnHWQqs+EH RJp+DZebBct1RdsoVQl4Ve/aWVl7Rt8kNbIgcF94tfRua3OXhMkL8nEp/TnLKiATMLrDWw rLFa2Urmj3K4UCVqTHOv19W2aBQUSG0= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=pGrDvkAu; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794882; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=IIt0dFxxtEQYosJ5ltIiL6nguC3ESRR0tY9hc3mlrpA=; b=QoCVkZOqd07h8YEumHSPySg2p/8JZi5UyG/osN08TMTvvU03CfUQhrH403MUVreyYVAPA+ /RESj6NQhxWdBdCoULbOROTl+tppJs7nUTvd+6NTB0r5MliQsEq8Byoson4lXod4qU/Gwx r+TqF9qh5ha3PLDZQSrzP6g4ZqJcdgY= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 981BE5C3930; Tue, 1 Oct 2024 15:02:22 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6951AC4CED3; Tue, 1 Oct 2024 15:02:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794946; bh=ZDmHNLUIwFFHS+R3VBXXGD9KVgIi1Tkfsy4gCUrqKAQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=pGrDvkAu7K7mNxFAaWK1ijXKGhH0O55fTL6tlWOoxx7u5L1OfHYlMSDQlcCwRNz+k ZfFhTd9KDHWXs91qO5mF+JtxWNKdZ8HfZ2OODmexqa8PiZa5Vge98pHPs8N+YusiGC j0W418/ImK15iFqWO/ljbxZ02FLdhJSWbxlF0ao15m7KngrJTcRpzeV30jPZKwBryb 3I649ueGfTvclLz2QjX5T0L0dIrCN8B2zh7DX6PQjSg6pHY1axCLT2MR/IUmpT/Xnx EnGt8oLGcYhK0PX6UXV6hq6Ojfe1feUFvjHPV6Rfu+sLIWqe9FE5ToIRC3qH3vz98D r9ucqKGDGPTfA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 24/29] rust: alloc: implement `contains` for `Flags` Date: Tue, 1 Oct 2024 16:59:59 +0200 Message-ID: <20241001150008.183102-25-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: dpccn499jedtjikyi3jiq556kx9u5tw5 X-Rspamd-Queue-Id: 8A4D740012 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1727794947-562340 X-HE-Meta: U2FsdGVkX19sOTuvAk0S300D3OYYDc+F7cR0DzRNdcc1oCYv3uJPqXiC2jSCND1QiBssb7O0LDbu2P6+FDzuMf4qML4yltERIcruqU/aw1UhcFI9F6e9ZDwd5Y1nWPxU06BW3YDIyjX9CV6rovEg0+tUl2WXGnJDF9wJIs2kTX0IdUWCCb0aWN8nlrXPlyeEu8+JsRxoazl9J7jMOpcMCCR+OD+T6IfJwuiMWc1Ykdp1n8K1h7J91ew+phPyMYUNwrby5Dr8UA9ZbgrvGfARARyhc0SzFvgMcAj85zCa4VypAcWg5fZXFRl4+12uDQmo7rzwlHy+/v74870G9oNfyAEIUfrHe80855PgFPW09hjGfHTQbOCcUzDL+4Py2oPuTQxXo96xKncdi3qV2ue2iuigAlN8PVSSeoDASJD8oj4YbV/c4f7HqXSSrvgXztN15eCAHqm1d8HLVbT9kiBqXqnUUxNWOz4fQttXXyTWonf24lzyvN0YRZK71AXd6xT19hnlKGX277owtf+lvNd7j3dy40ieFT8Qh7b9BMgUQwdz1suA/U2zb8cS7O9iDhEGa2XRtlwdKFSmAeszgfNLBThx3nwYY6JxA8ERTaymq0rodhTDV0XU8+3CBVVSKYkvSSUuAP1FSoAn+Fl59KxGEKGpGuyODMD8JuYmObAvx6C32k8VDRPnSF3QCWB/398jWVmaOtTEHHi9vs7mEEyC3UNdjQhq6knCwtvuZijAAxeUWKiCh08K84INkMKFEcBv7V4RHSyji1IbCWsh//ZFjO0q8zQO6X0CfpvY9Q9ok9QhlGD2TfE74n3k54wxMJdG0MWnOxQ9lD6huijsz9TtcRZCOJHLJg+iWiPaRYnr+JAMUSWg6M2KjSYa/LmHPl/x75GT/BdyXb6sKifm6mtiRgEcsLqFVUS+EoZOCoqrQ4YKq+u37PPn4rdGv5kSeAYtcXYSd4/1Hvwm8KJMn9K CjHyd6Ui gwQMGvOg+m7/1L+eJjsC7mV7vxjqp05Sb3xCd7P5nLakqT2ni8dLZlotvXmpicOz2oC3oSVBSn61bonpYlkuWNCK65MCWDC1JcoTLP4oOS3NluT3CHpTr11VBLuC8qQY9GRQOWeQ2OHLhCG1WHUfKCAFNa/C9Ll1gZ2W4T8Anae86qUaGKrX3YC9p4rv9XWVpBvqFL0NnV75FCN3Fp5uVL2iiF5+tB8l7e63MDgRj2G3XNaw7tR8U8vsQD1IzGv+UTCo3NtGwlCXug0oh1IUkzs80hKdoUh5Mmd6PPSq2RngQDnDNYDvXRiJ1HHmCY5V/RiE3NpHe5boqWobgaPCDOs/GgsjOwcrdGmDaiogji68nBDP0mr67y1qdk1lp+8P4Q5cy X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Provide a simple helper function to check whether given flags do contain one or multiple other flags. This is used by a subsequent patch implementing the Cmalloc `Allocator` to check for __GFP_ZERO. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index e8955340fe62..8acaa24a8f1f 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -35,7 +35,7 @@ /// They can be combined with the operators `|`, `&`, and `!`. /// /// Values can be used from the [`flags`] module. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq)] pub struct Flags(u32); impl Flags { @@ -43,6 +43,11 @@ impl Flags { pub(crate) fn as_raw(self) -> u32 { self.0 } + + /// Check whether `flags` is contained in `self`. + pub fn contains(self, flags: Flags) -> bool { + (self & flags) == flags + } } impl core::ops::BitOr for Flags { From patchwork Tue Oct 1 15:00:00 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818244 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 5120ECEACD5 for ; Tue, 1 Oct 2024 15:02:35 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id DAF0A68001C; Tue, 1 Oct 2024 11:02:34 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D5C2C280068; Tue, 1 Oct 2024 11:02:34 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C23B168001C; Tue, 1 Oct 2024 11:02:34 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id A218C280068 for ; Tue, 1 Oct 2024 11:02:34 -0400 (EDT) Received: from smtpin09.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 543871A15D8 for ; Tue, 1 Oct 2024 15:02:34 +0000 (UTC) X-FDA: 82625349828.09.D69AB38 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf13.hostedemail.com (Postfix) with ESMTP id A5E7520013 for ; Tue, 1 Oct 2024 15:02:32 +0000 (UTC) Authentication-Results: imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="PXHOT/Rl"; spf=pass (imf13.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794826; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=3AYZbO3il7IMjj6UU6a8G8k9T1mEpgQVoLLNur0v6rk=; b=cSVatM7tRU+BalYi/DZBW0ntEXMqvkfhdFSto5kkBSjEr8AKhirad7dYvv+n3qJVqV54ps 5yKoTM+cGs2bs6Tl0B2zkMC82lh5ts9jjLSl2AVqM5Cz822SbVG2363NONT/VAaiAbiFxj meZzZwt3XW4dR+sIUdEMuX6oA33cHlU= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794826; a=rsa-sha256; cv=none; b=WV0OhfahyX3MZCTVXZxIQU1WjV/D9bTgM1LT5YjzNMbrrSDx1sjbdtvsSXd46IOcmS9OX6 J48JJ+pasaDMp5/np4dlpjsoWPWBN5ZA6P9uoK3OyD9cdPTw0BJMVmts/OZKISg577+Tqp YvsaMwLe02DqTxXCnntpw9ZIQ8DUK0Q= ARC-Authentication-Results: i=1; imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="PXHOT/Rl"; spf=pass (imf13.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id A9CC7A40104; Tue, 1 Oct 2024 15:02:23 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C10B0C4CED2; Tue, 1 Oct 2024 15:02:26 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794951; bh=MnOa0U7RkKOR0+keHOw6H4AlceJPUYq3oyu7nzf0U7Q=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=PXHOT/Rl3F/gV5bzZmYoMj3Lj6bB+QWZ6CFnpagPAn4v3r5fesP9NRdvhyI+8c02G A7Hodb3ILKzIyl9YxMN9XhaINWLBHyJSZMLuJe7cZyor3wU6X8G0XiIPJJKcM3hllg 5vyYjdWQ4IWw6JFP9SGBGgr3q0XUwwcBkBg1EgVi8BU0uNJusT02tHclobkE0WTLXI 30fSduTv7LTnmP4yCapuQQlkJmxjxZ+HQmSdztcNFGU08Nr/s+jK8TLoKKaGlp9y5F 6nXxVYZOI2pLAD4Kx5XyY0xppBDwA+jf1rWm/Qz6wjHkeSTWSuFMHWpq6ihUBbBYxH vRBmarcEnJD2g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 25/29] rust: alloc: implement `Cmalloc` in module allocator_test Date: Tue, 1 Oct 2024 17:00:00 +0200 Message-ID: <20241001150008.183102-26-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: A5E7520013 X-Stat-Signature: 9cjk6cineiwisjwkqk3gq4ysyqzbbnzk X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1727794952-68869 X-HE-Meta: U2FsdGVkX19FZScmcXEAZoMdYCg1Ridu7d9dUIP4kuGDYHeEISwWJvcI5Lgu8zgbSILHCDnh3hDXzPzWpCjKVJ1nK6yvRI1Z/bI768qPfa75OI6uML+zUdav/e1Fl2w1kVdKv43fil4VDKR33O6M4y0+wk+Q004U6iZz1eKPffgFO8ULh3WlS+SM2qQPbvwdeeQ6QbKeOR8nMrbQfZXgg4+MTmdZ8cT4kGNamkaiehy4Iq/bZt/+zF8HRswqaUXwIlO8DyCRXU+8cWUocUIHt2WgQy3Duqggn1v4rlRF6q2aQgizNTfibIHbyr0e6uzzOr9h13Q1GSkkQfXYol59DpSVJxi7bCAnqjdZXBP+d2YJp4jqyNMgDUraHWzOiWhB2a05HsPD7RJhQtHqAElhovqrC8tUD8/mEctMIE4QKJbd5iKHZeT7fdymcVBXKTX1XjrCDPDL2AK1Pb4LqWFEZxU8CVG0ZlJN+WyXBa1W1WNIZYfhiWXDeWN/WeOWbBTjIimhzF1kfN5fzPgJDNcIX2DOlnJq1Brz7SNqvBSvK0APKdFsYe+G7Vn+RdiXT4Ip2MGCgNs7qdx76rqJFOY2S6Yv2zS33n3qf6TIMouwxwo1U9ikUuCvwkGMDlZ5tVCOwRuA3IU7/TwEqmtRb6l3x5fOCXrsdjjrlZrlaI4c2Vzya+8J/Ez4DxKR7VhMulE2F/L4cKozChwfEqHNQmhi2bbsWXu81pYVBk6MSiNd5KfUGNWm/gDMx/xBXXVg6A4zTFLFNKxZ7+6sQwdx5X+r3pnUgSMEOJVeHscvDnXlX2BjnmcJ0I/qorlYW4vuWLqIycZ+yM/qJflplE3K4pzIiHIBS0AfJcLq3b6Yu3Cl1b34Hyz095l+T5PdFXoKGPXlVSxqH2EZW/YVxYvmW0lDIqKMTP/tQ7cS996SAZ6mgx11DTFnyBclvvaX28pEhrcUH+HHaMo6JSfnH65JCrz 24+YYM9d 0wZjgaqNZvEWrvFer0m7ENVVM/923Ib+JSc+jwYtQK4JZHqhsIEiwkITJXucAz1CxTU/sEtYk5/Eru8EPq6rpmZER1Yipuyw8u9nTjXAkLtj4UzMSTFHK8edLdl6suRV1AE/xVNPPV9NuOpL+R9jhYRGOl+ngcPr3WebMQ/dB98tU7LOZiYle+ZA9iuJxq9lQCanWUN7jiWaUXE8XXQHB1C+a+IPv6rwZxJxiJruIr1/tfqwVPSo8XJbfK63RP0dTcf0EXFMMLmkveI0+PGZ61W3uP1Tg9U5BTnwj1MFLj7gMyRBaSC1wysky2RucGPw6jpB0W19ZqZP3PcUuobQ9C/7nzaRlRZmSZutF X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users of those types (e.g. `CString`) use kernel allocators for instantiation. In order to allow userspace test cases to make use of such types as well, implement the `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as allocator backend. Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin Reviewed-by: Gary Guo --- rust/kernel/alloc/allocator_test.rs | 88 ++++++++++++++++++++++++++--- 1 file changed, 81 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 1b2642c547ec..47c2b509898e 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -1,21 +1,95 @@ // SPDX-License-Identifier: GPL-2.0 +//! So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users +//! of those types (e.g. `CString`) use kernel allocators for instantiation. +//! +//! In order to allow userspace test cases to make use of such types as well, implement the +//! `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to +//! `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as allocator backend. + #![allow(missing_docs)] -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use core::alloc::Layout; +use core::cmp; +use core::ptr; use core::ptr::NonNull; -pub struct Kmalloc; +/// The userspace allocator based on libc. +pub struct Cmalloc; + +pub type Kmalloc = Cmalloc; pub type Vmalloc = Kmalloc; pub type KVmalloc = Kmalloc; -unsafe impl Allocator for Kmalloc { +extern "C" { + #[link_name = "aligned_alloc"] + fn libc_aligned_alloc(align: usize, size: usize) -> *mut core::ffi::c_void; + + #[link_name = "free"] + fn libc_free(ptr: *mut core::ffi::c_void); +} + +// SAFETY: +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation created by this `Allocator` is always OK, +// - `realloc` provides the guarantees as provided in the `# Guarantees` section. +unsafe impl Allocator for Cmalloc { unsafe fn realloc( - _ptr: Option>, - _layout: Layout, - _flags: Flags, + ptr: Option>, + layout: Layout, + old_layout: Layout, + flags: Flags, ) -> Result, AllocError> { - panic!(); + let src = match ptr { + Some(src) => { + if old_layout.size() == 0 { + ptr::null_mut() + } else { + src.as_ptr() + } + } + None => ptr::null_mut(), + }; + + if layout.size() == 0 { + // SAFETY: `src` is either NULL or was previously allocated with this `Allocator` + unsafe { libc_free(src.cast()) }; + + return Ok(NonNull::slice_from_raw_parts( + crate::alloc::dangling_from_layout(layout), + 0, + )); + } + + // SAFETY: Returns either NULL or a pointer to a memory allocation that satisfies or + // exceeds the given size and alignment requirements. + let dst = unsafe { libc_aligned_alloc(layout.align(), layout.size()) } as *mut u8; + let dst = NonNull::new(dst).ok_or(AllocError)?; + + if flags.contains(__GFP_ZERO) { + // SAFETY: The preceeding calls to `libc_aligned_alloc` and `NonNull::new` + // guarantee that `dst` points to memory of at least `layout.size()` bytes. + unsafe { dst.as_ptr().write_bytes(0, layout.size()) }; + } + + if !src.is_null() { + // SAFETY: + // - `src` has previously been allocated with this `Allocator`; `dst` has just been + // newly allocated, hence the memory regions do not overlap. + // - both` src` and `dst` are properly aligned and valid for reads and writes + unsafe { + ptr::copy_nonoverlapping( + src, + dst.as_ptr(), + cmp::min(layout.size(), old_layout.size()), + ) + }; + } + + // SAFETY: `src` is either NULL or was previously allocated with this `Allocator` + unsafe { libc_free(src.cast()) }; + + Ok(NonNull::slice_from_raw_parts(dst, layout.size())) } } From patchwork Tue Oct 1 15:00:01 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818245 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id AE97CCEACDC for ; Tue, 1 Oct 2024 15:02:40 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 40FFE68001D; Tue, 1 Oct 2024 11:02:40 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 3BFDB280068; Tue, 1 Oct 2024 11:02:40 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 238E568001D; Tue, 1 Oct 2024 11:02:40 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id F3A80280068 for ; Tue, 1 Oct 2024 11:02:39 -0400 (EDT) Received: from smtpin21.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id A979F1614FB for ; Tue, 1 Oct 2024 15:02:39 +0000 (UTC) X-FDA: 82625350038.21.D0DB53C Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf26.hostedemail.com (Postfix) with ESMTP id 040D9140018 for ; Tue, 1 Oct 2024 15:02:37 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=r1xNcO7w; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794831; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=qBdAA1MHAXxVW3QJV82szD4rRVx9kb1ZWjIJ/ELeRdY=; b=uPoApdHa2CLrI3DXS1hdctQqa7XufPfkT9AgZi0nJ1UBFy4FqFrhM7tcECnHdIAQ7hEnay wNqS6VoiQV7Pg7K6F3prh+1PokM7OR7xXrQStG9xTFbij0ATJiRyWWjriGwI3J7yx9hzgO aWBhzF13DLKTVcK5IUS469jbvafdvVU= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794831; a=rsa-sha256; cv=none; b=zsGNRFqm5PfbS98RSTBkpTy0aMQYqfFS50SgAY3oJv9gCzWdmYJzLUXaoC1D5SarRyj4nU YIKEowgPNhoGwzNXfQ8tEPMEY9/oDzIfohiD+vSWogDLsSf6hpI6HrT69LPcNfZvHSc2r9 huPpYnDNWMbOza13j5htSbZJ6yFxrvg= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=r1xNcO7w; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 14D83A400EF; Tue, 1 Oct 2024 15:02:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 226F6C4CECD; Tue, 1 Oct 2024 15:02:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794957; bh=rMRoTLbwJY/KNbnwZeqVlUvQeXlcU9VSnqsWXV9nz8g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=r1xNcO7wmDj+pX9zXKSF5zGwWUM4O85kJZ5cWPAxgO9+xb910r5UXJlLXxC1BXTUT zzBp0tTw/b1CeJHxrZy8zQ/bdjKcIOnTq8eOvJIpeXw1cMsIqUvNt3L7SIRSn61PTl ULpwj3RBaA4YjI5NczO3MZgxSOju7nslA/iHjIWPgpSrQwMOvY7je1ZvCyoage2RRw DsL33UucQCuqwoMwJtQaQmGtNWSnzyiAGCJPNjlAEeuoZGEE8Di3jHuGZ+YB5HwTSW 2uu10sTfzzqUOW5Can8mKlVOL3Q76hTPPjmlVHG5LSSsr9tPb5YkMuuza15LjJbHWB hsHNBft18qx1A== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 26/29] rust: str: test: replace `alloc::format` Date: Tue, 1 Oct 2024 17:00:01 +0200 Message-ID: <20241001150008.183102-27-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 040D9140018 X-Stat-Signature: ufiawbenk3a6rth77w914spk16y46h35 X-HE-Tag: 1727794957-301708 X-HE-Meta: U2FsdGVkX1870f0p/ACZqRS4yF74AKbG9IeA4s0Zd+IWVYqtptHTpw8YM17+Xj+TeTsbmhh9sOLhxjPXwj3YrM/FvHh65IK79z5WN3JBItH2qqO64vOMX27GrlXVSRsH115PymMFUXWJck1OZJaJNuU9BO8YfvIYPXaIwvWAHz47j0YR8mtDDrwkaZ4C8CAKXiHOVKAfeKDCKyzim+4gmpg1Dn6PFuO2HXeudO9cUdRRH33fmT3mtU5sdvfj7yKaQoWxx3+dYMJevc7UXKLXYyYPmI0LCgX/v+5dLv5L+3tXROBwBWMyDl7ExRJOvtPwOb9LIgr+oQdC4db/n8l93KSBX1alv5Cbrw0KZJOdk0byektEkDPAPErxfXU9uAFKxY4J7mNqN5BbjvcqvLJsbT2MkTIlnepX0yZ/ylup070+iDSm7LS+nWzPWRzEM7dbJIqL49s1FwgmwrEXVpqZPobbAIt86Q2jISGcO9wzHwglJxKaerIkLnf6MSLsvKKfu5Pu0Iu3Stauq6VhffzlEIBU3Ls6/8g9rTWxE/7abWDJajcYbx3JlWU7YM6bhXbQNJVAbZs0v51Nsmu9ghr38h9krZAu/fzGmogfzyeKiAfjthPgMQ7XD4hqZVgHixduHNRz3s62/gh/XaZcz2OGslo3pMCdWhnsn0LzYoHMM1Fkzou2vQtQ+gZeQmV2cQTHRNO9sZfiIgIqsg9hz1S6Pju00B8jutzY5zgkay6B68lFVS5U0rYcmNFjRki5z5GUN5ZuZGiciWLH+zeGOX1UA2dAodOmO53dGQZ8ztNLmfhBWdZabIu21M3k00ULq0Skd9Nm10TqiFFAohR/X1WsuKUl5KB9qzcfllQbSGSGWHkcX6Qd5XzfqipZJTnX+Qddz1cpbepMWpWzwQ5zEdlfcB0DQINosNRI9KUe/AQQL7c74bInx1NNfo584eb59GDAggOISMM0PCYfgsKouO9 6viB+Uxi xP0sN7LCiiEAcoPDf4lLkxDlXoNuIYStqCaAHiu3z+OUWsd7ybWPiN4NhmXTCKEStJ2uxQLfWgPdXvh7bP+53lLqp5nFWFlvcqhl9+AOa950CrFPomV/oEkBl2J53d6wHaEBGiawQSvNqew2kQxvJL3BkN+uqIPgybmPR1yUIz5tsa/xaQ4wjLi1552Rqf3Ehcg6yWNYAgHaqyomFBUbn5mwRxuoTslUrEBnhSyXMOziTIvlgU9C6WeeG8PbqrFjGMo7HMHXEx+wLmG/24kyzwUs5plWyJBAOu+2GErs2bQW/fCIM4LCdrsNW/VJV7A+Y9ZeIk9f61nV/HlgV/eX4216eqHMmSNewnZWlrm3f/Jkz46aCLVj0WfuNxYGx1I8f7TSg X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: The current implementation of tests in str.rs use `format!` to format strings for comparison, which, internally, creates a new `String`. In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement `format!` for `CString`. Note that for userspace tests, `Kmalloc`, which is backing `CString`'s memory, is just a type alias to `Cmalloc`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 209ad1bb1a49..726329530338 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,28 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; + + struct String(CString); + + impl String { + fn from_fmt(args: fmt::Arguments<'_>) -> Self { + String(CString::try_from_fmt(args).unwrap()) + } + } + + impl Deref for String { + type Target = str; + + fn deref(&self) -> &str { + self.0.to_str().unwrap() + } + } + + macro_rules! format { + ($($f:tt)*) => ({ + &*String::from_fmt(kernel::fmt!($($f)*)) + }) + } const ALL_ASCII_CHARS: &'static str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ From patchwork Tue Oct 1 15:00:02 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818246 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 16332CEACD5 for ; Tue, 1 Oct 2024 15:02:46 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9DC6D68001E; Tue, 1 Oct 2024 11:02:45 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 98C5F280068; Tue, 1 Oct 2024 11:02:45 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 82D5168001E; Tue, 1 Oct 2024 11:02:45 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 592D6280068 for ; Tue, 1 Oct 2024 11:02:45 -0400 (EDT) Received: from smtpin09.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 14D601A15D4 for ; Tue, 1 Oct 2024 15:02:45 +0000 (UTC) X-FDA: 82625350290.09.0BBFDA9 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf25.hostedemail.com (Postfix) with ESMTP id 46B6FA000B for ; Tue, 1 Oct 2024 15:02:43 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RiY4Oaov; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf25.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794924; a=rsa-sha256; cv=none; b=EDgFXqsEauRFQ7myQ74CzpwZ3iGlAm+Rs+uqyMtztvlUVgjq4PiYbxGOjmVPbgw79WYn/V zVVCMqpPdYW67eMAwkp/ksnjrvPmxhJAoYUC9pmn4ylLLOPn9PGlHFNELF0dmtGz9kGbzk UPFQit6XQhT5WUoNzPiRN6WPq/qSLu0= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RiY4Oaov; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf25.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794924; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=JfRFCry7Fv1TL6pLtnF0DeZFoojQ37yEliOD1ikMPAI=; b=ScRiuRMdN3vqiTKkx76BBdL4gnyjqGdSATxw/oGR6TxDE/Iix6VjlOWryoOAGFRzOOOZIu Na6xnnBPHsFDgOMvAD9xpMOFrx/TwIZ+q4li7IFSkjvSQ5p71m6+OCNBcdQp0rXYeHll67 RJku82SkYuMKsGtV7Yw/rDHXWeFvxho= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 670E5A40104; Tue, 1 Oct 2024 15:02:34 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 797E0C4CED2; Tue, 1 Oct 2024 15:02:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794962; bh=GR6bCjuYYHRgHCOsPDduyYPPq8CvkGfa1JPMMj7rInU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RiY4OaovolUIHId/CXZBG0mQjFVvQQSFisqfSuxUkQ+pN72OVWhKoCUGsyYc7eWjQ fMjOsCDz64SUKC49XOzYlAlqlaq9i60haj+28VfMnRZFE3pLjRL//NlfzaO+QrnpE5 2JYP7EWnlBFn2jIJQ4PCXxFlGGFUIJT8zckMtKty5wH/Tcyk0LqzclUt4j1O7DRN3p oGGPbiWCWdVFXIuo06u9dWeBTqlNeEjkfyzmGEtAZv/JFP6S0zufuKo/KAj7O85ZjL j+j0srmtkCgDk/w+wE9D+/lP4XJN2dMBCqPF0lSjHZ9FEku65xjRhMeIatGqPuXP0r 6YQ5YuzdJwIvg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 27/29] rust: alloc: update module comment of alloc.rs Date: Tue, 1 Oct 2024 17:00:02 +0200 Message-ID: <20241001150008.183102-28-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 46B6FA000B X-Rspamd-Server: rspam01 X-Stat-Signature: giixtb6as3qrxj8ksob1io3n4wwig7e9 X-HE-Tag: 1727794963-431158 X-HE-Meta: U2FsdGVkX1+c4KuqgKDsj40jZzDaXS01KKuGT6bAAbUkHo97/qvGMvHdkBxxjfkk47EjSdaPCNTFPRD62Qq5AkQMK1tmJUZmy72e5rOxr/gyYgxZCXJhDKtL1E9QxoG/5rM78i2A6Y+8iY6ct9iMRd/VYwFk7L76VkTZQF38LiolNtMTggTESfG0d1PgjjeJqJg/UA5lYhkUKbh3LLg6cJJaUfZUlbN6EqJDePYpo9TJ3imHGVbbi54qidCeTfatBHe+ZmjXe01gT9VNrrNFIG/0Nyt4WNR5vd/yfdq+ZMD4DQOGdMS2UWUktZjjR+ACphbQUJatpY88zz9rG8KVFt3KJWF7RZ7/3h9zDqctZyiun5m6b4N7GjKqNbW0n16Ysc2NGc1kkjWucM/RI7wAnuQtwK0+u8u4gd9X3t5K1raLQrqWtM47mdxRUDELA4WMNyJD+AZ4D/rZf6oM/JGW3Da575eXjTa/3oBSH3jTxN9GKAr5jkvXE/f5LYEfZrN6bIvYhBuKi7LPZw+yxiJmMEGYEMdN94LmSyVzwYH3M/W+dvcE81p41BFklnItybpZ+8Uj9B8oEPVvfh2K2zbXKXaKJRSsuMArwHYLILv+CUuBjXilrs2VAnDccY9ieARgEAdC75gYHIulAQ9oKZtKSw+NOMN/VVZxqDSRyjCmMUlU7UZDIAvnBqNgKXCTczBG6miP2h2ScEkGwjCdloiVwaQAlJAs4LMzD8y2QwG35sLhi6tntoU8knobAwY5Kzl2nabxKDBBXrMxjh43jgoBy/HIbxPp3twUIhMjFk/VrwYl4cnstDjbzPN7lSJWH3DdaF3ouPuFSCm3qcOoaXWxNVgKL4GROrxjGBdQssqmHyC3ajy1P2JO9mlQyF4D3ZTPk0inUkQ0Nhs8UF+iLTXxSuGu1aeyUeih7H0o4CfFsKCS5RRPacyVhTXPyoJ5QPVMgq+vx7fNrODQb0RZRfs tgdkoAbv J7bSfbRL5rl8DV6ZoaDAQ9fdPpjt9KCv8Vuj45yqSa/wWrLnnmow/lAA9JYlgMRfWy1L6sM73ASNTUaI7cn23MFA+XpAjqg2J7AC9n4xjQpksftufK2HrycDlBdx7a/ms9hlFH1in66QHqUekYH7yxJ6N4VgXaJE/pUDrf3ItzcFS8LB7BL9YzgmleBhgqO6I52jMkXW5xQd9scLPLlZH1vavr/wnZghxD0A1e1gRWbLSgge0J6Y5v3aeQzX4MjCYVige15k3EJxCAjRuz6Vgg3TKQcCEyQt30j2wtgcoDsmYf8WVd+ZNiYe0YK3TSSjPGLGnAL+Gcz7t0mkQgNqCR4NdCf2dvyhM2nIe8HoFnPELLLeDiFfXpvdwxGMGngq2yJAVGrURu5VUyr+fQ+P69UzCdjU0ChSOjGjG X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Before we remove Rust's alloc crate, rewrite the module comment in alloc.rs to avoid a rustdoc warning. Besides that, the module comment in alloc.rs isn't correct anymore, we're no longer extending Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 8acaa24a8f1f..b4e65454e695 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 -//! Extensions to the [`alloc`] crate. +//! Implementation of the kernel's memory allocation infrastructure. #[cfg(not(any(test, testlib)))] pub mod allocator; From patchwork Tue Oct 1 15:00:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818247 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 93E56CEACDC for ; Tue, 1 Oct 2024 15:02:54 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 215E068001F; Tue, 1 Oct 2024 11:02:54 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 1298D280068; Tue, 1 Oct 2024 11:02:54 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id F0BE068001F; Tue, 1 Oct 2024 11:02:53 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id D152F280068 for ; Tue, 1 Oct 2024 11:02:53 -0400 (EDT) Received: from smtpin09.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 107BAACC51 for ; Tue, 1 Oct 2024 15:02:53 +0000 (UTC) X-FDA: 82625350626.09.0126311 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf24.hostedemail.com (Postfix) with ESMTP id 34A0818003B for ; Tue, 1 Oct 2024 15:02:48 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=bzOWDfCW; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794841; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=gIhVsTrGU/ORPizyGXvLQjU0wTWQhsdezv/biwyjGOE=; b=cjREwRzQZzr42tfBG3dMrbAgCAzePn0MiP6Vygx87DjiK0gEDCfV7jPkpb77QTZ//g61dU p5e/7rn2DYWrVxnP2rPgeSg0FL6lCScWUrjhZ3qXs+vqj2ldDuIEvfWOXm5N4CxzDRH/N4 SVH6oRI1LkPGWG6K8xM34zuW7GRiW0A= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794841; a=rsa-sha256; cv=none; b=f/ocIahyj5I6YgQwkW83Du4ZoNV4Wb/AQapj7TODzsN+qCw70wiWV2O6hoWB042rZvU29J WcLGmFIRqlM+VrFYsYq757DdBQ4MBbG1YVHztSWyz6RDVLEtKwZRfU4R0cWVO1QgrH6Eev 8CspPtY0/c0UBD60Qf08sgLcdmrge1I= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=bzOWDfCW; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id CF5B9A40098; Tue, 1 Oct 2024 15:02:39 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D1CA3C4CED3; Tue, 1 Oct 2024 15:02:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794967; bh=cVm78aZuB5Rz7RoLW+2cZZaDXtknlbwGruXhodnZH1E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bzOWDfCW2+EZ4g+xEC78TbeRCoi7uyLf19fSSO5sQwaUUYrMnKtdjkPGkumh1gSKw cd3sLk7VDVsJdTXwoLpqaYCpqyHSdj35acqM3O7gfSaOeJyvCiwPHd3vX6Mf+pSaii dH0I9VjV5I8PfPQa6vqBYCecxTYPxK/MnyVfhkJsqsbgmod9eYL1EuH025um+nlSEj 6dYPnaueasYavw3VJX+cF7YBXsaTlC/HGjq4+ZH9S0RQwHb037UB9UfM+8sWisnswF ypDgJIJSYfaBOnPGFB2qAquXsHCB85CnftkjfG6pIzfVPMSFG7EzZOuSqlxu0lOuRV mkQQ+Dlx5jB7A== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 28/29] kbuild: rust: remove the `alloc` crate and `GlobalAlloc` Date: Tue, 1 Oct 2024 17:00:03 +0200 Message-ID: <20241001150008.183102-29-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: wduroqrcgcrac8bkhm91np8je5xqfy5f X-Rspamd-Queue-Id: 34A0818003B X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1727794968-9166 X-HE-Meta: U2FsdGVkX1+DREnQunzaEE5w9BRICaqoyAsouUt1c0aV4LBpRiKN/j56tobpyi27mgGPTxRUKQyjBjqBRLpWg7bJbGd1T/HnUsSyixF4uurhPYcNxkkS/4HayqZOJMGIyMajVU2A2Vb8XcXJMxEYil4Ttp25/Wm0/fm5G5hLNn3H9ONTy6grGs9uQIJEDuQcoGf43/1MwROzGYWxAqWdy6RkfrHu71JnR+XyOVyYiJidCyuJS5UgA4kaRzX1Hnd254IM/rEzpWfOEqWbWZ55HJMxBsH23XA3u1YhF4WIHQOczakrQlbx6EmQ931RKTCQFmG2+c8NkSWpQi6Qnt6dR93D4WeDBw8Hn2hmGme+J4UP65EjxJLTqPVD1bkXPmv1UhKV/jC4cBf/S9WzOwCZfRDPF9ptKfF0lH82/7nRv+/YDrZWL8e9DcfM68gOIJ4cRzQ5T2Qq5VzpJePddBrLJNBOO10roNttFcrMIX77UabGhQnLBEtg+VL9YKqZ5pRomPy2kFQYSJe+nWxOc2NphyNEb/L04uh1LT4TYB1F2qkByNg6K9Q6WwCIs1EeDx6E8VOKDrfSg717fotEscO5W2Hkgo6zoVWvRJg2YgkmuFAk0sLuf8/PqFhPhBO/Ni8zj6i3A0ibQzFfDGcnVtsWBKkW/UJJObDcwq95GDWsr97t0l3vVatiZIMU+Rp0SAPV2/Vufk0z50sMxsxBUVYa9YJjjFqgORIlIWrWxmcQjfwH9gJjO9D5L5ybZNDdvTVxUm+Vrp37FvdtRQAvqGLxmYKIhnAD62F+/UaRIXynrlDiUTIUrQ1gh5Yo64EMF71lcKWfYvO7c7PGswDjY1Mac6C5AMStx49buFJGhFi5vXQTaR3eki8FLslERru/BhNycduCyBNwCpZ1w0famEp0OqP8IHqynryHgDwzbWIBYMzrN4h5rHlj/cmnQ4Ftd80JBtHDtoWZIEakgy8d3BX IiOOrPsL JcphbaQjlemxy9FpGLUbwW/fbySAj1aKi/wN7fBKDL29M6uhI5/alAcA4g5VRcQ//E9JWHAMqpYkKwsPd9lAMr7lALjBFlGqlzBjDrMB+ujBCFKR9UWaGajpmRwKcI5EbtrTktrNYg4yWgGrJFGlXBwcFnvYTq3OCyjSrIwlx32JtL4RIwe9K2vLc8rPPI54rls/0FFIJc4xvS50/h0ojfHtbjeRbzDVFa6y6VJ6BCq5/Cvq1D/Le4G7uLLyPlPhRjfH67M+nOVZvGnT8gPnMEtY2uigWZUCKybOrcep7JRKxZiI6vMjNs41ANyTnZi4Cr7HgN4Sw9Xiamd959tNgZqhbuNeHdhHY4/DV X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we have our own `Allocator`, `Box` and `Vec` types we can remove Rust's `alloc` crate and the `new_uninit` unstable feature. Also remove `Kmalloc`'s `GlobalAlloc` implementation -- we can't remove this in a separate patch, since the `alloc` crate requires a `#[global_allocator]` to set, that implements `GlobalAlloc`. Signed-off-by: Danilo Krummrich --- rust/Makefile | 43 +++++---------------- rust/exports.c | 1 - rust/kernel/alloc/allocator.rs | 63 +------------------------------ scripts/Makefile.build | 7 +--- scripts/generate_rust_analyzer.py | 11 +----- 5 files changed, 15 insertions(+), 110 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index b5e0a73b78f3..16ea0087ce71 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -15,8 +15,8 @@ always-$(CONFIG_RUST) += libmacros.so no-clean-files += libmacros.so always-$(CONFIG_RUST) += bindings/bindings_generated.rs bindings/bindings_helpers_generated.rs -obj-$(CONFIG_RUST) += alloc.o bindings.o kernel.o -always-$(CONFIG_RUST) += exports_alloc_generated.h exports_helpers_generated.h \ +obj-$(CONFIG_RUST) += bindings.o kernel.o +always-$(CONFIG_RUST) += exports_helpers_generated.h \ exports_bindings_generated.h exports_kernel_generated.h always-$(CONFIG_RUST) += uapi/uapi_generated.rs @@ -53,11 +53,6 @@ endif core-cfgs = \ --cfg no_fp_fmt_parse -alloc-cfgs = \ - --cfg no_global_oom_handling \ - --cfg no_rc \ - --cfg no_sync - quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< cmd_rustdoc = \ OBJTREE=$(abspath $(objtree)) \ @@ -81,7 +76,7 @@ quiet_cmd_rustdoc = 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)/static.files/ $(Q)find $(rustdoc_output) -name '*.html' -type f -print0 | xargs -0 sed -Ei \ @@ -105,20 +100,11 @@ rustdoc-core: $(RUST_LIB_SRC)/core/src/lib.rs FORCE rustdoc-compiler_builtins: $(src)/compiler_builtins.rs rustdoc-core FORCE +$(call if_changed,rustdoc) -# 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 = $(alloc-cfgs) \ - -Arustdoc::broken_intra_doc_links -rustdoc-alloc: $(RUST_LIB_SRC)/alloc/src/lib.rs rustdoc-core rustdoc-compiler_builtins FORCE - +$(call if_changed,rustdoc) - -rustdoc-kernel: private rustc_target_flags = --extern alloc \ +rustdoc-kernel: private rustc_target_flags = \ --extern build_error --extern macros=$(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) @@ -162,7 +148,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $< mkdir -p $(objtree)/$(obj)/test/doctests/kernel; \ OBJTREE=$(abspath $(objtree)) \ $(RUSTDOC) --test $(rust_flags) \ - -L$(objtree)/$(obj) --extern alloc --extern kernel \ + -L$(objtree)/$(obj) --extern kernel \ --extern build_error --extern macros \ --extern bindings --extern uapi \ --no-run --crate-name kernel -Zunstable-options \ @@ -198,7 +184,7 @@ rusttest-macros: $(src)/macros/lib.rs FORCE +$(call if_changed,rustc_test) +$(call if_changed,rustdoc_test) -rusttest-kernel: private rustc_target_flags = --extern alloc \ +rusttest-kernel: private rustc_target_flags = \ --extern build_error --extern macros --extern bindings --extern uapi rusttest-kernel: $(src)/kernel/lib.rs \ rusttestlib-build_error rusttestlib-macros rusttestlib-bindings \ @@ -311,9 +297,6 @@ quiet_cmd_exports = EXPORTS $@ $(obj)/exports_core_generated.h: $(obj)/core.o FORCE $(call if_changed,exports) -$(obj)/exports_alloc_generated.h: $(obj)/alloc.o FORCE - $(call if_changed,exports) - # Even though Rust kernel modules should never use the bindings directly, # symbols from the `bindings` crate and the C helpers need to be exported # because Rust generics and inlined functions may not get their code generated @@ -360,7 +343,7 @@ quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L rust-analyzer: $(Q)$(srctree)/scripts/generate_rust_analyzer.py \ - --cfgs='core=$(core-cfgs)' --cfgs='alloc=$(alloc-cfgs)' \ + --cfgs='core=$(core-cfgs)' \ $(realpath $(srctree)) $(realpath $(objtree)) \ $(rustc_sysroot) $(RUST_LIB_SRC) $(KBUILD_EXTMOD) > \ $(if $(KBUILD_EXTMOD),$(extmod_prefix),$(objtree))/rust-project.json @@ -398,12 +381,6 @@ $(obj)/compiler_builtins.o: private rustc_objcopy = -w -W '__*' $(obj)/compiler_builtins.o: $(src)/compiler_builtins.rs $(obj)/core.o FORCE +$(call if_changed_rule,rustc_library) -$(obj)/alloc.o: private skip_clippy = 1 -$(obj)/alloc.o: private skip_flags = -Wunreachable_pub -$(obj)/alloc.o: private rustc_target_flags = $(alloc-cfgs) -$(obj)/alloc.o: $(RUST_LIB_SRC)/alloc/src/lib.rs $(obj)/compiler_builtins.o FORCE - +$(call if_changed_rule,rustc_library) - $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE +$(call if_changed_rule,rustc_library) @@ -418,9 +395,9 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_rule,rustc_library) -$(obj)/kernel.o: private rustc_target_flags = --extern alloc \ +$(obj)/kernel.o: private rustc_target_flags = \ --extern build_error --extern macros --extern bindings --extern uapi -$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/alloc.o $(obj)/build_error.o \ +$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/build_error.o \ $(obj)/libmacros.so $(obj)/bindings.o $(obj)/uapi.o FORCE +$(call if_changed_rule,rustc_library) diff --git a/rust/exports.c b/rust/exports.c index e5695f3b45b7..82a037381798 100644 --- a/rust/exports.c +++ b/rust/exports.c @@ -16,7 +16,6 @@ #define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym) #include "exports_core_generated.h" -#include "exports_alloc_generated.h" #include "exports_helpers_generated.h" #include "exports_bindings_generated.h" #include "exports_kernel_generated.h" diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index d0a8819c6741..067719f11d13 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,8 +8,8 @@ //! //! Reference: -use super::{flags::*, Flags}; -use core::alloc::{GlobalAlloc, Layout}; +use super::Flags; +use core::alloc::Layout; use core::ptr; use core::ptr::NonNull; @@ -54,23 +54,6 @@ fn aligned_size(new_layout: Layout) -> usize { layout.size() } -/// 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 this allocator. -/// - `new_layout` must have a non-zero size. -pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - let size = aligned_size(new_layout); - - // SAFETY: - // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the - // function safety requirement. - // - `size` is greater than 0 since it's from `layout.size()` (which cannot be zero according - // to the function safety requirement) - unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } -} - /// # Invariants /// /// One of the following `krealloc`, `vrealloc`, `kvrealloc`. @@ -156,41 +139,6 @@ unsafe fn realloc( } } -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 size 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 `layout.align()`, will not - // overflow `isize` by the function safety requirement. - // - `layout.align()` is a proper alignment (i.e. not zero and must be a power of two). - let layout = 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 zero 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 size by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL | __GFP_ZERO) } - } -} - // SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that // - memory remains valid until it is explicitly freed, // - passing a pointer to a valid memory allocation is OK, @@ -238,10 +186,3 @@ unsafe fn realloc( unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, old_layout, flags) } } } - -#[global_allocator] -static ALLOCATOR: Kmalloc = Kmalloc; - -// See . -#[no_mangle] -static __rust_no_alloc_shim_is_unstable: u8 = 0; diff --git a/scripts/Makefile.build b/scripts/Makefile.build index 8f423a1faf50..68c605049b87 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -247,18 +247,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- - -rust_allowed_features := 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 = \ RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \ - -Zallow-features=$(rust_allowed_features) \ -Zcrate-attr=no_std \ - -Zcrate-attr='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=/dev/null \ diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py index d2bc63cde8c6..09e1d166d8d2 100755 --- a/scripts/generate_rust_analyzer.py +++ b/scripts/generate_rust_analyzer.py @@ -64,13 +64,6 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): [], ) - append_crate( - "alloc", - sysroot_src / "alloc" / "src" / "lib.rs", - ["core", "compiler_builtins"], - cfg=crates_cfgs.get("alloc", []), - ) - append_crate( "macros", srctree / "rust" / "macros" / "lib.rs", @@ -96,7 +89,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): append_crate( "kernel", srctree / "rust" / "kernel" / "lib.rs", - ["core", "alloc", "macros", "build_error", "bindings"], + ["core", "macros", "build_error", "bindings"], cfg=cfg, ) crates[-1]["source"] = { @@ -133,7 +126,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): append_crate( name, path, - ["core", "alloc", "kernel"], + ["core", "kernel"], cfg=cfg, ) From patchwork Tue Oct 1 15:00:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818248 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 907D4CEACD5 for ; Tue, 1 Oct 2024 15:02:58 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 1EDCB680020; Tue, 1 Oct 2024 11:02:58 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 176C6280068; Tue, 1 Oct 2024 11:02:58 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id F3330680020; Tue, 1 Oct 2024 11:02:57 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0017.hostedemail.com [216.40.44.17]) by kanga.kvack.org (Postfix) with ESMTP id CC963280068 for ; Tue, 1 Oct 2024 11:02:57 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 77865AC2D0 for ; Tue, 1 Oct 2024 15:02:57 +0000 (UTC) X-FDA: 82625350794.16.A690BFA Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf30.hostedemail.com (Postfix) with ESMTP id 531EA80028 for ; Tue, 1 Oct 2024 15:02:54 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DRxFv1vq; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794935; a=rsa-sha256; cv=none; b=ej4TwchqNW1xs05yWZGr0VR/pvgY/+3I6rPkgVQRmLmXz9fYQECpBTco8PEUEhODmgRdFe pLRSCNYCPGMf7VEZImOAm3/uNMPZArA7s+wAK1l1LMAD6cmDXclmQNAiatsZdEANDGVSbu 8x79pteJMt4h9E2z2QXPuMVSgifeZwI= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DRxFv1vq; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1727794935; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=ih9T82L7iCqATFe3BRPKOsvLUNMtsha1mn/ly8JWdlM=; b=x8rdDsJxR7Kef5YJ3C1RTNyWCl/2MjJ8QwkUYhp+ysIbF8e3dY4yam8mK+cxAKZhPnaXDf V4BzKaUoFkM8DJLaQRqt5aiG4gcrH8rAAgusXVabZMjKlRG8A7aIvuhwIaxGVlXgXV2eHZ xGl/DWRumkWqcaSiR/78h8c7PdwEaPk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 1A576A40104; Tue, 1 Oct 2024 15:02:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 31880C4CEC7; Tue, 1 Oct 2024 15:02:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794973; bh=5WhXHbdkvCvx2BiDbC2YGf2YH6m+QGC4hgOdP8LRL/M=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DRxFv1vqGJmKwc0Q+OIGBKJ0n6aReQHI1G1uiAx7R6CXZwLUZPy2wVbtreTtE9euP s2dT/+RMLyEDr5f1mMvCLIXqOD5fTE9yPmQ3P+YyEvgU9LqT6BWom5bOCJuJVmkqaX deV3L9KHhHe2mCYzEJm78GcPT4+SA3tpuhSA4KkpNoVGTZDBm5oyHHBx0HeRZqxzHH w2SQ20rvlgK+0zjc/KLTAT+j87VPRmflRjp/DBZOvoiK9Ga7tBWLfBfjNYdfbOdezn HUI+FcZp70AWKd2rMAgloTnBYbFwNjA8SEywnUslSnmpMpb/B5ha2lDkirXXmrk6jZ 0B9TDthI3f/Ww== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v8 29/29] MAINTAINERS: add entry for the Rust `alloc` module Date: Tue, 1 Oct 2024 17:00:04 +0200 Message-ID: <20241001150008.183102-30-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 531EA80028 X-Rspamd-Server: rspam01 X-Stat-Signature: 7eqg8n3ohqri7z79hncec4f1arbss781 X-HE-Tag: 1727794974-569373 X-HE-Meta: U2FsdGVkX18ia9KDQnO+sU0SpNE/JeGEz9iTO2mmRYr2ip7uiffSVcnoA2543ydP5tI6thn/gDh6lBze3eWfZFFTfxjUdDqNaCmOWfdR6i7nuwd/yCLR0kH18tZnXyzY/dPqgtSzuagz8usFTd+i3wPOts0GvcwphB7y2UWNU1uTrYgWo9FocJb5lg2+dmWvQcfl/japBhxl5B+OfBa4uYVGovJlHcxggYWSjM9koStY5sqQmWbWab5vq67DLGH/d0BXoUtsxv0goCbZ4r1ztHNCEBy847K6dc4RhzcdNSGBuPDo0H54wZQP2N8o1OMo1HEy+EvEZgR7Vg+NdmGQ6elEbi6gEjlea982XzTf1K83mRhhENaC1oaJDix+6JqjtiRUwcysFBOSrpRLY0QHQP+YqZIYPMTPiIos4O1S/TjfZSFhBGNVNKNp94S9PM9rD5O1X7Ld+71XdzdJteM9I/CMX4kssYb87tMUFgr/qeGCDkstchviQ2tnKKnMp/cC6ZSr23KwrOjny7RoRRAkkiMIg86tTUL4rc9XvzsZJE1ndvbEHiGV4vbzuI42aIS6SewnHrj8qIDtFKVkohLpo3en4E+fyoslYaKqSepdkvm/6k1OVUPdWnbrHbtsLeRmfk+amfs/9nGK7hnP1SO/22f8kAjEQSuvvm88Gb4p+Qdd5O/4OirmjxWbz5Ok0qKF3PqYJQdYEum6Lgreh4/tZGa71j/tgudoVoP85tUvChVShQh5PLrfaeS163386HhV70ezukFPQ8lzq4ebvFmAMUbJfXGcbF9tLdQ+r2jIRc4livRYDaHCuGxtJg/U66CakFmOTzfLCqZSKGjwKTn5gmx9uGaBltufPKeYD4c1j1P57/krrFX4wdltHt8ZhnIWodY14jVUeiAr8TOUWEJNRz1Kby2c/xFgj2fFuf0U/2aqBqrduRcyFkAZBgIZmYW8iTOmSrhAANtsXycAzXF njuCe7ta 581EIw68PaLbAP7r2HTCpwrB8VS1jGwCQVp+TRrHwv0K1ZQJunyeaNnMJbGSRTvlSqgtyEPMmoFaS9wO/htr765l5ueiqogcRA3nCKqUpXBp8t8/m8wGGgLdb3wxKhZAFMhQcDC+GK97VBZdXXKZkxqEI3iu3R4ju0Q8oTS1BS/8VJPPfdkBnFQlaOpW1zRB1O4oIY91P+93pUd8TrDbd3+aqr4nzw32Gaf5CpyR5xeuCVXbzQZtx8nIm7DB1dom8dFbvQaOJHlOfVLOHJ2VVFjML7k8OY0irQoILYZyuTl6oagKuQMYT5ABOarwAbmrAbRcksCKzJ2KlrSzmA3dw2RSQ1D6t7rdXDMtm7tgX5L+lZEQwDRkSXdOx43qndULe0pPB X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Add maintainers entry for the Rust `alloc` module. Currently, this includes the `Allocator` API itself, `Allocator` implementations, such as `Kmalloc` or `Vmalloc`, as well as the kernel's implementation of the primary memory allocation data structures, `Box` and `Vec`. Signed-off-by: Danilo Krummrich --- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index c27f3190737f..3091ea621b5e 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -20225,6 +20225,13 @@ F: scripts/*rust* F: tools/testing/selftests/rust/ K: \b(?i:rust)\b +RUST [ALLOC] +M: Danilo Krummrich +L: rust-for-linux@vger.kernel.org +S: Maintained +F: rust/kernel/alloc.rs +F: rust/kernel/alloc/ + RXRPC SOCKETS (AF_RXRPC) M: David Howells M: Marc Dionne