From patchwork Fri Oct 4 15:41:05 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822612 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 96BBECF8849 for ; Fri, 4 Oct 2024 15:42:15 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 27EB96B034B; Fri, 4 Oct 2024 11:42:15 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 22DFE6B034D; Fri, 4 Oct 2024 11:42:15 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0AA436B034C; Fri, 4 Oct 2024 11:42:15 -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 DF0416B034A for ; Fri, 4 Oct 2024 11:42:14 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 7A9E7C097A for ; Fri, 4 Oct 2024 15:42:14 +0000 (UTC) X-FDA: 82636336188.26.3763885 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf10.hostedemail.com (Postfix) with ESMTP id E6D0BC0004 for ; Fri, 4 Oct 2024 15:42:11 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RAW1ky8v; spf=pass (imf10.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=1728056465; a=rsa-sha256; cv=none; b=VNCCpCAtUFthVtY9wrBlc1c/VDZv7Sb2ks+zOOns46vD9lBCiXBLEzyOcw2W/0jkRnNkFm CJbgonvvtrX1jHkfLxGUpo2i/ConTHu/HhMohiTzCnZRGbHHY3CZ96ZbJBHkt0coRFy6L+ FJOPjml3tP5NZe7G621CwYMoZ52DBOI= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RAW1ky8v; spf=pass (imf10.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=1728056465; 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=RKMmtNo9urhHvDtbd0MpCpamYZk0193g4yAiVJA91us=; b=B9/dMnLymDZH0VBbbQjrfOvP41GLkyHsd/ufAHSX1/SeWMjC8VpSh4/z8m4mWRB599K6rM 68naku/4/+wk7uNqfnYLuy81wwG8NUX1egXEO5qnvhbIK0fwt3JP0ms4CQB++raPZG/xlM OFMwxwfOR8Fzy1I/ETP2Pdqa/Qmp1zk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id D02C4A44B83; Fri, 4 Oct 2024 15:42:02 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 01F96C4CECF; Fri, 4 Oct 2024 15:42:05 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056530; bh=o9fTnK5hDeL2M1Gfsa2jfEjky3P6Jc8p9pXGxlscHLY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RAW1ky8v40yQnljYx1biN48PIk0ApY4J635Fj6cnMGkG86MNyra/loqlO2s+zH+ge HvnR6t1PEzGwWaD3RYS+E0Z4Ur6dNVxfI0JtDUIkPbXfZnS7l8g35iNhuaoUM0GdbD B/ywyJ5atXiiYow9VJFJCeetohINI3hbGhKZcIt92FBQBSFt2n6bb9W6k6X+ydxD+X k0L4x7kU17neqJDvrAxNE26LuXeI55q02amzcu6HpucIujT7a8BgE/kJbcXbuO7Rhd VufrwlMnPdbR8gnGDIUXl24001WgLhqYUHtiW+KvoHHC2OXo9mL6syokthlkVXz8/n MNZlQVYgzrjXw== 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 v9 01/29] rust: alloc: add `Allocator` trait Date: Fri, 4 Oct 2024 17:41:05 +0200 Message-ID: <20241004154149.93856-2-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: w5r5jfqemr7now6bmeqrekjmbna9srzh X-Rspamd-Queue-Id: E6D0BC0004 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1728056531-413242 X-HE-Meta: U2FsdGVkX19KKThFx/d58s/cSITlwkFaTFBJnYA6c4YEFDxr3O748TsK1qKP+vXfydI6K2ZTmWSXvztc83Gvo7ALW0qrSLu6LxjUFDaNgdhgKduIg6xyUJaQns86A3MQ7FJG8CPw2QjSHNbp7eYHcgtg2QOqpBs/YWWqeFnOmIGBvTyhg5d1+mmJhSNl2Z0hsBm7SX8Dlb6fr0XHY8iaXuNwxtjbFvQO/GSgluo5KOgfXqFfsmVfeh5sVZFTaOjmdVZb7N1NluOTejyRwVOi/hguQc3Zby7p1E1oqyHIsnwPCPAghgg+X+u9dUe0/hGXDpi0CdBe9NmGmHjZ07xGP+nBlr8TVIfbhGLvcip/XFHhkm2g8F6mkrXfSfRUaKaMSrB9JJAAPcLubnpb0qfWiBdKuSKjPjcaXvoI+3Hq+MMndAIQ6PuKCBMiyGWuX7KJuMlpdrO5e2LL1ewducxuc58LOC5z0wUleVDGjfcemSgpnyLUyvaeHztD/CR2yyWCHqQhQEeXQ9RAUExtHCVkmBT/pImCG7+X5T74AlMr/QT+EuXjc+2Vf8ZBM4lFs9e5xXM4s7tJXla7NcEHzGzb5CIpkrZ3GZBf5ARAy+XGkVjMl0F5Qyj9fM5pSqTuL4ojz4ct1wK5TkIKjaHYbV9Pg54dYBYoHd4LidBBUHsHBjdu/yVqiYNHRR0rDT6i8moF+T+PXa9/Ljc0Wf852Pn7RcLGPzdn4Xp6hyBWYldY51LjS/EK0nePpBpxXbcksox3pQUfs3ajvHHkfuF4YcdlRIJmBd1pGhYfRXq3sNqF6XvIazRENdfozVJNWXTRP9sp0soV9yUndC89JoN7Mm6JqGtSVemNDijJg4gFSERyO2AimNpG5Gduc35RUzvkV02/CtJybrSeUWtsYe9DpoxJyf8kPXvNG/opUV0FGLmlce0eAYEzgYN0ya+4jB99jpAbd34L6Gdj90znKANvsmB a/BwnHkT ppjHRtZDvESHLIOrgc1ACi6bB4z59ZN7o7cIs1FL0LaSN2Iszkt3SfJqeHeKkkG1njJQltje8Xd08shEoyircGKYINR7+4hmToSyTFEOBr0ygPdXRF5eq9g9jGTbH5vRchFgm1tBzvftZZuEuMh9nO04r7SChAqeD9DLZ8k47PYiMxkKrjucLp3PG17gMuzBL60InDh7mLfJodXCnPLp0sttzUJ2KnCm0re8HW/cFlGIeW96Kw1rcL3RQuPvCH1JrgrCgbV6e93ACpxdWsG/8AlnUiADdQ2s7hHqN7ExlTAZz7J2dgI2jWvFYgG57PCnFOQzvvdI8BOsYXsAdtPFUzeFAR/b27NnQFYx2Db50P1FKC8yvTcLXVGBImk5dVc71a7ZLBwZas1DlABifiv0FwhfRo0gMf/IlzneA 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 Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- 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 Fri Oct 4 15:41:06 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822613 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 EB467CF8849 for ; Fri, 4 Oct 2024 15:42:19 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7B0CE6B00A8; Fri, 4 Oct 2024 11:42:19 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 75ED46B00B0; Fri, 4 Oct 2024 11:42:19 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 600886B00B2; Fri, 4 Oct 2024 11:42:19 -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 43F0E6B00A8 for ; Fri, 4 Oct 2024 11:42:19 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 07EB2A1748 for ; Fri, 4 Oct 2024 15:42:19 +0000 (UTC) X-FDA: 82636336398.01.DAA2B13 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf04.hostedemail.com (Postfix) with ESMTP id 6D88140018 for ; Fri, 4 Oct 2024 15:42:17 +0000 (UTC) Authentication-Results: imf04.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f4eAqOAq; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf04.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=1728056393; 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=Qy8KxCIgBtvqnNj4RqFDbh6uuhL//IY30twfovya/Q4=; b=C3psw9Qb2GPRSySqeFui84SVK9eSXii94iMEer9uQOtrE/Rt+uZ3QkkECVBGQ1Ea7Dz5E0 SXzWCvRV3hDxeMfmlyay2P6t4axj4M2QDRGSKvfHtHk1vvd4eMApWmo34qAtYhSvfSRe2Q P2aGCAR53OBc2gtr6HgNuwxTbpnWWGY= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056393; a=rsa-sha256; cv=none; b=IE/iaRBldYpMOOTBNw6DfSdb6U09styhOY+vcqSYVjvkG+2XryuG1oUlrQiWiGkwgugxUK QZnE21hfDjLC1d+utaiIKu2Ljjr8nl/VH7qaJwTdhPTitjQEGvM8HE/smWLBVuDb7x4KRO ZXUBaIrSO0lhzD4pH2Yw7ormf8M/zkQ= ARC-Authentication-Results: i=1; imf04.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f4eAqOAq; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf04.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 47F5FA44C2A; Fri, 4 Oct 2024 15:42:08 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 66D15C4CED0; Fri, 4 Oct 2024 15:42:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056536; bh=RKYOxaZlfRNBRkHBIioYvHfe6spLUu1mZk00Wam8Has=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=f4eAqOAq1FX1Ya1okjVZkz82mLxBGix6bkOeHOi5qGpTXizdIdI1HGcng3ZO30+Su 1ibtaobqiZMH2mWJtOhI2E22BuQcm7mIPwwS5ULuccazCkaUDYJw+2hT711xDBX7Ey 2oeYgJ2/Kmu3UizrBDNvRBFrFbYJ2zlcfPxejGlYIRW7zYvSuqi9yZcmfyaXj97ykj 3g0kRigDy/sekuNsh9ECtUeQiQxI41drqNILzFdrd1NaAbk/ATarkl7sM3abOV40da 892mB3SXd74TS2mDLL/LLHLP1h9PKePh79zBPjVLoVaqcxEfPsIOcDe7UlJaWr47Tu 9+LAnKXkQLjWA== 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 v9 02/29] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Fri, 4 Oct 2024 17:41:06 +0200 Message-ID: <20241004154149.93856-3-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 6D88140018 X-Stat-Signature: 1f1tjpnotsusud844zxmh5ndo8yr6mku X-Rspam-User: X-HE-Tag: 1728056537-245034 X-HE-Meta: U2FsdGVkX1/1URFYnp62o17bPPcolZfNXoMLHpW93xF1JNhivr2z5pDsgsK7fydHVu35O6jXQWG5GIG5x8AbisVWmXLhehdTiM7e2dKVrHtElIdJxob5jaT8H8oYD8b5jZ3chzmVIcySp2R5Q36AmbaiSW70D1EUlpkKNH9DZy3yjg0OWdo+JCjMkJ45ZyxKlDMDtKVISzrzcNoBwJFzkx3qL+BMx6DsvpV31+A6Qpj3CUVKn3OatbcYW5CZbr5ip1PRu5wW4TSNFlkEqwpvj1xv6b8WfgICCg3y1UIGyXxiW2dW66I/Z9Xw0dgBNalt/ZyXlRlEudavX2RbtGN012Xuk9D8hO5uSHA5w9gZXEHiLAPNgI+SwHPfE6cx81gpZYmyij/gLuZS6avbTd2XVhneAwWAup2I8fiVZ/uoWVgjXkVy5jo0OTQZZBzs0QtnfHJxWQPMnjFYtmh/SNa1HyGs48Sb3wH6W18bQ0pUsEzM/oQ8yyyuiOMOyc/6J0UgQ4bm8fJQNcX55K4LqqB5g8MX/gJtaFi9ReicSRpivgJXWB5xIwUdVA2Vmp4VOGbfE/hL7da5uZjrJNwQgz8y5ieXxWb/l+dEYp7ZzUCAAkdE0Hr4Ha2UCWUvLVdyjsdQK+ro/ebQYEUppTFHG1UmBDMrZLw19LV7XCwZN66IfghEyou/nuUtFpUhsHmrIEeZpMquYyL25Ab1lio2Nox2P26H4yfJXWXHHJB3/nqrNCrLySsOeJMdz4cTP+qZ28C2kOxpW1+mtU03Wk4XyOVbJixvwOJHN4+8GDZ1H+IZfcDflLls9/3MAebTA5aSuZNYVWfirNvHNDuMR8ENJhDKfSonpplBVXhd/givPuFVouYbeOo6/aydPAX9uicOywBVUQBBjD3dt7+ypE+PIjgJv/iPPhMn+47eqWG/H44zaxBottGDqEBnbalT+aeCd2d2AvZil2pefeCld20Na8m qaLNR6yR iNzPInwEYkij+efwvGBjTAqyRG7XUNbal0b3pJQSsmQmGTaSBvJiDmrd7c62bvRb41dk5BV4qWnWbx/lvB7xZWF6sgfWB4OI2K4P/1rAOc4P0roQI3U0F81k3PVSQcE7ROGO/j2up3O5chz9BWmYiQXgH5mnzJzvTn5Cb9g1Uc9zKK5CBzZ0DhNKoCfkoWT/dH2I5pUOdzNgd5ln0shbnkHjCOIdKy8g7t+c8RZWrVQhFO4cWJ47vP6yf4d3AMCcu/1aTPV/0a2XzkY24A9H409jBmkPstmQXaIGBDua8JEv7eS19E2uMdYWR6WYzCJhLTvkmDqxIB5UCcBJGYqsMSNYwLWYv05NxeQy1wRCuAuVC7WAjuBjAhlm1B9DFAVMEOd3gp8xoGD77ZPHoHPhiUQ1DF86LRbdN7dwuEV5NUhrE/yyfU0eEqr1xIQ== 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 91216b36af69..765f72d5bc21 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 Fri Oct 4 15:41:07 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822614 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 787E8CF8849 for ; Fri, 4 Oct 2024 15:42:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 0F7BC6B0401; Fri, 4 Oct 2024 11:42:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0AB566B0402; Fri, 4 Oct 2024 11:42:25 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E8B5C6B0404; Fri, 4 Oct 2024 11:42:24 -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 CA1506B0401 for ; Fri, 4 Oct 2024 11:42:24 -0400 (EDT) Received: from smtpin27.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 5CC4540BD5 for ; Fri, 4 Oct 2024 15:42:24 +0000 (UTC) X-FDA: 82636336608.27.E3681D7 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf16.hostedemail.com (Postfix) with ESMTP id C41BA180002 for ; Fri, 4 Oct 2024 15:42:22 +0000 (UTC) Authentication-Results: imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=iLntNC5G; spf=pass (imf16.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=1728056501; 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=nFu/Jo/LyNG0lCAqYTcrwUZmY2ZbXoi+1/wExRdrQs0=; b=NIHek5N16tg7LAUFabmyDPZShVMbT9DVIoQbdfodRTtH1xDgyekXtXWhBdZrn8QVZK+k1i bsTAcFPaYIZMFihiXjNILrp/IazQ4hvn6/NPq8aUzfmrVgnb/wvkbCe1+F8nApBI1JpZ81 XrZS0AlmdPTK9eY0rEij3z2JsIB2PpQ= ARC-Authentication-Results: i=1; imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=iLntNC5G; spf=pass (imf16.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=1728056501; a=rsa-sha256; cv=none; b=ibh1Du/MGFCRdZeH9+e90vfOdYrR0sdzUKRjwR2ixFhKtmLM3GmFOUGlKI8BQ2Bovj7/t+ SuSrkddd1ifv8wZ89Nqagkgg1yg0yrIaY2dn+SOtgVkVRbGPnaGN6E4UINBOUEaCEgbusk cYOkCjC5W0NLROvOomyhsHFceIlSWB0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id AAC38A44C44; Fri, 4 Oct 2024 15:42:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CFD86C4CED1; Fri, 4 Oct 2024 15:42:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056541; bh=axTTg7SsxXZNqW4CxUpwgLYR5awaQab7skyekwlvxHA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=iLntNC5GMO+JfUfJ8T+RToF/Q6zkfE7Zbk6QFUt/YDBi5fmDfvLnGjdsh/MmTD6nx JdHKLGahSiq+PTzPUi+dCZGcIHqfbnVbuAcjTZ+PuzemKlxbCcLs3jiVBtSFySOR3+ YqyOojHVpAFhUvR2z+/RUrIhKXbEnBB/mHKYMZp2SO2cs2APgp5zQiiPWue5mVIFyE aXhBqMr1Qbv9cGHI8RT7aaniTTWQL2W5hf5PlOIoHmtFHf/g+m6yLGcWsbhLsOqzOa RDJy4UgSrxf0zlREhw+BujKjRga7rESHFswoiVECMil4ZVX2lXo4rTVqzM2W0zOmeH EILZDqjGCWlUw== 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 v9 03/29] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Fri, 4 Oct 2024 17:41:07 +0200 Message-ID: <20241004154149.93856-4-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: zarbox1qxanibjn691echpz7cca6858a X-Rspamd-Queue-Id: C41BA180002 X-Rspamd-Server: rspam11 X-HE-Tag: 1728056542-381945 X-HE-Meta: U2FsdGVkX184hloB1xSdzYHrWvJPFXp9cOeMIv0z3GTJMOsqXliTZtwEgkUlOOoP1H/Ehzla31vWWaHsjqOO2g1S6lXwA4qQOGbxSkAzAQJKoS1zm9S/coPziMqZ1xQx8gjE/wPAz4s1Eh7c4WqyqpFjPMGMF8SMxg36taM9CbVCzwQsceM3CVcMlCvKOY5tylyw5mHb759aG9omh0paWofAT71WehefPUYednsOF/b6kEsPjk3+Cmxxo2nTfUIl9o3TPIMbw3OWLvuFwa2gm5Xy73cL9VQ80B6q5v0l2SxzRvGG2H6dDmVAXTOvB86HcLKB6BWomdnGIKDECWnuO9Rjv/T4m5/eydVQtbYkOjO5A5DzMWlsRBDEcsnkV2SR9ZFe/KoIvdq0JWXCWYqZo6ZiK1A4RcOj8Sd0odR736ejXO11Qmub2BtG0axMbQ0uytJ3Q7iELE/uT8N1zY8S6qltGu7F3tasBCRrUz15axgfNdGIOhvo3Rl3fX/0F2Wj06MY+0iRRiTSzUxV4Rw2EH04WfHHbSZSTXQDnO0q69ueZTrQx6s3hm8179ARWA6OV2WC5AjB/DTIAEv/HSuNexuGRM9amqnr4Lk0yZkIaQk+V1E31c0tzALiviMCt+GDDJBukhMAlxFw+QukYN4A1P5Jqd7UXtbmB5aCzgyUG27hVxfR1bJGRiqMTAdVxz1pH7E1CAKpt7olQATlC+luIaesXWzI1cvls59/B4WqBcJgY9RA1KwISumKPqTuKpKki8Fp0S2W4qYXYH6HzdhPZxH/mKnXAXIQ05Jwwz0XZEoRf0DInazo13f+zskvKE4zMOGargoYtERz1fafg3juM60AF4ApkHg0KDNfKpt/FpO2XFFPTYBdXJozRyRHqamP0hxhEiCe2Z9hqUZW/4Uty4eqSMBv4QCLZvfa9dd4OXrnZH7FH6L9rq7eDC6JQgesbDlhd75BFaZMSSlkTyb IKuwZKL5 e2B/M58a/K+luPkL+f0ofrEF1gfzEZwUey5zYXf41csDHuSTxoBTTteg+zJaDeJsqsDqxEsa7UShPyvWUNRb7dQ9jd2m1YZEv5hHz+mhnxKLwjsPyMtaSSssOAxlkTGLWoQ9l3Ss5vGh7muULPws0L4dBlx9PRTwLkNM8eUAc47E7TwJr5khD9GCiVYnpabz/jA4qIW9M3oC0tuOgumXvnT64vOspnxId/12x4jBKW7beDUavqc3Za50xT4OQYRJS53/Sl6XjPFkAC9xcTUA17/yKK6pfx88RPctFTIws3QCHANjVbyvUdZj2AfoCHeJMUYuWqP7MV4yxnQ6VpA74omwF+0SfM/sdCa9O2T3uyPHIxPYhR8tN9YY90ZdXrw7spwgAc1FHMseR66+HOn74n5SUpyKQF0aVVn0y 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 765f72d5bc21..3b1c735ba409 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 { @@ -37,7 +37,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F } // SAFETY: TODO. -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. @@ -74,7 +74,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 Fri Oct 4 15:41:08 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822615 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 6F0C8CF884C for ; Fri, 4 Oct 2024 15:42:31 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 0834F6B0404; Fri, 4 Oct 2024 11:42:31 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 00B406B0405; Fri, 4 Oct 2024 11:42:30 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E15886B0407; Fri, 4 Oct 2024 11:42: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 C3B426B0404 for ; Fri, 4 Oct 2024 11:42:30 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 430F481824 for ; Fri, 4 Oct 2024 15:42:30 +0000 (UTC) X-FDA: 82636336860.10.C846BD2 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf25.hostedemail.com (Postfix) with ESMTP id 9C9B1A001A for ; Fri, 4 Oct 2024 15:42:28 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="QVUR/08O"; 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=1728056507; a=rsa-sha256; cv=none; b=Dc0Ey03+82xn3CL6Q1oGialu8EKNc52ELEkyd4Ng4d7Hlhkyv9XpagUQo1utYbbZB5toJC 8Wmx9WkhbuBMcjSyTN4r82KvHcRehLRsoZd/BBPwvI3nDzZ/euPpO0+I86OjYPNq0Heo1x YgMS5UNhnIfzeR9NpshlDZrfxrYAyYE= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="QVUR/08O"; 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=1728056507; 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=Y8afrj5fwsE8kPj55OEkbECCJFcjKz8tGCPXOPqYD/A=; b=WCBMT93cvjL5dM+uKcOheZmK9m9oe6gMtrRGn5yPwMfPZFLZSAPuQ38STa7nawszRe3ez8 crMSroSF+/sALQsaT7JleH/1ZOKCQ1N17E0ySzYqeFNQwGFtpRcOf8GcrWYMbZQpFQF/U1 aKYeZhgEa90W8Z0oBOa1Im79QwmhigI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 57371A44C48; Fri, 4 Oct 2024 15:42:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 41F86C4CEC7; Fri, 4 Oct 2024 15:42:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056547; bh=FjNpQ7WplEuJvZRXB9OKv92SNKAtpq7ActsyiT3/uto=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QVUR/08O9+E1CNbbgPERgJT5Kwjss1sEY4YsIYtAHtUWpluZl24F8r65XdahkgBbQ KqsJ+pcUshMVHutDmTwYlUonLQLcUfNl0AiCnazXFGf5qr5JpfCGDIwiJ6KsyGztRX iQ3m3d/gWQT517HOJkSJcM4RfkInPGO+pW6mf3AjXK49jOp5beuavcWBoODmsUgU34 0PGUzUgE+v+RuLOz6Fk71tEy5IFx3IW1U+B6bVzWR6AjgLdjB9HMIuHFI+1N1mTxYn LQgA3F8cbXRDpAqi9uZyXziN5ChX3v8E2XeIQS2IbA78gm/hlC+0097YdthT8KcV56 rpe/FpWijamSA== 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 v9 04/29] rust: alloc: implement `ReallocFunc` Date: Fri, 4 Oct 2024 17:41:08 +0200 Message-ID: <20241004154149.93856-5-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 9C9B1A001A X-Rspamd-Server: rspam01 X-Stat-Signature: o4k7i1pqzq1wxft8npyhjt4pgqpu5y5u X-HE-Tag: 1728056548-40352 X-HE-Meta: U2FsdGVkX18k5Hf5L+osykvvYdL+KF0ynfGmg7jjVtAN2B/c/s4jHahjX/VHIDZq4AWiB50VrsxCKo0u6oKxxU8TBPE8yMyJmiTJ7J1MB7GroJRfgNFpZbRna2GfWPetRg/hB4yq5IHiwtnddUQ84iXHLxOywnhVrQZ77EeMP84Zjk+JUJbWdTRFgeb95FlyhALBZupCRroU5iAz728vZ4W7yQR1icvYGELS/Dm08Ik7FDPK9S2g8p9MWx89ZvAVKpBfx7JS/bxR7wlU53a0C75x273SuARpVlI8hrzNasvfN59NCoQgsaEpViLpUF27HNa3YK1DxhcJaH8snPCXjIeL1jjwpjH4JgD3K6qW9OpnMPhnYEo5oW33VfKjJOX1jMASnchzm8eX6NkUFoiIKHBuaaPdBN/hulnCYE2AUNbF2pnAaCtqQIJM6eKJIcixB/CxpwfTy75ar3CDgDpSM7fr4hEkuCXvHn2hDi0cn73CtjrrYANoDrrs6nIa/eS9W+zQ4oZc9bj5SRZZB4/IYfOQNh1GMBORyy04oF+fiMd6EP1qXlPoHnNzBAUhBsrpLYfOR72XIbZ7D+SKHIJ4zRlGAb1yE4IvZJ/qc2Q81U4dZ1hOMrlLMaNy3vqB+2ZRIkjnQCPum2F2E18dPjIpWqDOD7sZ8L8cYynxznG4OPIdg0bt7l/anpRDr0TCrfhVCOYTx+cNLeQyzWbYjAdmjjpeFch7A0m3lu0H90dS/mylEceJyxp+jqRMu5YstsTM6aJTdQp701uEu6+gsuCIdDVjdm3BVMXkDKVp9fWbXtTzNq5jZpE/Ez0LA9j67Mvhxvxo2rJYSe1RvYh+GOUsLzZaRu/vKdofkaW843l/PJWCCYTmIYs9EGz4hot6PD7ntnfd0jH1WiEogbb4hscJHjERNRpjKvrjF7NzIqfOy5Zzk/7B/ib8IfNDDXGCoeDNqYLuxUS4kF8kMCwerlq gDi1qKM/ 7UrlU13Xy2+A0PYeK2RY1s50bqKqXCGiIudj6jfkTX7VX3NcUPvv8fEU5D47AmWEYe9SKr4zk0N7zHc04Tr1ArMpITlCLbI1G1gYAtZhoed/2AYIQ/2ojejzxPqtuIb9ltlqQ9/5qyof9WUh8tXi0JfOhG5tPl+7Svexw6JIcXN6iwtMszbHLMW1JxoWCj9zJKF44n4cPnPFjfnT761PNG7bIChSAGjUXu6xNmaYAZa/3ZzplnG6jnlQ1sv5y/aHkxmuOL99x82QOuDEfdLbfWnCGXAyjV5aputyAQvMsQCZTzpPzRN68irQb73tcdAAA1HU0Al3kFn14181p5yt7mxi/b3rLfpNWv00Jeuw3SQxFv9etkeVwece8YjsJIBNUE3C5 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: `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. Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- 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 3b1c735ba409..e5bac90046a4 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)) + } +} + // SAFETY: TODO. unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { From patchwork Fri Oct 4 15:41:09 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822616 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 56ADFCF884B for ; Fri, 4 Oct 2024 15:42:36 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 983E66B0407; Fri, 4 Oct 2024 11:42:35 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 90D4D6B0408; Fri, 4 Oct 2024 11:42:35 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7D43F6B0409; Fri, 4 Oct 2024 11:42:35 -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 659F56B0407 for ; Fri, 4 Oct 2024 11:42:35 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 20079417CA for ; Fri, 4 Oct 2024 15:42:35 +0000 (UTC) X-FDA: 82636337070.06.AB00993 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf02.hostedemail.com (Postfix) with ESMTP id 8636B80012 for ; Fri, 4 Oct 2024 15:42:33 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qhlqp3tx; spf=pass (imf02.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=1728056422; 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=6UnhpAH95JK0fnXZvtx86bZbvepH5HOY6OJin7RgYyI=; b=IUrYolMRGki9Fr4nv8HvcgNxutCS9xIDTDy6OnLnGyip2bOBFRT3QONcMu3uUs0YAOLBcy E0k6ICjcGu/Lh+aEL5Z0jm3odCpfNPZrpx5AQ+CQlFtvlmhl7777Jt/m/e9RFYZcZaasCt Jiy+BVm95FXNXIgsyvKqUqFITnpToJ4= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056422; a=rsa-sha256; cv=none; b=NYO6ByCAehM+IDdvUyOdiE08PxhfFgR0BqePTZnNn/RituxSHT/P7nsh6r0ZP0jAjpgk8C sqyQ07NL1qcA9mvDPAokgciFS/VY1iPaUuoRqXkWqsTo1S3xhjttBrXNadjH5oeULvQIqC Xh03lWf1xsivyqRaFBlOEwzq1BItJN8= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qhlqp3tx; spf=pass (imf02.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 89629A44BB9; Fri, 4 Oct 2024 15:42:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A6BF7C4CECF; Fri, 4 Oct 2024 15:42:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056552; bh=sxl4tea78ipgv1w2ubiPdzaMlUQIlFJyy3VgFb/Bypk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qhlqp3txx5UGYepN445qb5tXqTXeQZscm663Ynhm+Ohg5Gwb+YVM0+JFs4NeKJ7+e YjiwFn7VhR7EHqC7Rba9eJU72m5sfpDiClPFKuEm+e09je3P9p4gWDRrGa9vJFbgWY 4JO9Syp6zwKtSI6lK//JJIlOkI9bX0GO2xSl3SyP8QORp4kG4SPToZatXFUjixyfiz gbNXh9FypFs1rNE5Tii93wyf785+4u28rNKxnnLbYqF0858HQzd3VVzcRTg8eiZnmY 4BoNHc0U9uIVEI1K90JWeHeoSgUJIt8kC8liAXfbHmhM1ZUuPD2V80f/ZYse2X0Iiu vFzgR5K95nw2g== 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 v9 05/29] rust: alloc: make `allocator` module public Date: Fri, 4 Oct 2024 17:41:09 +0200 Message-ID: <20241004154149.93856-6-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: jhiatfn7xwu59brpt6d8rqy8f5snnoar X-Rspamd-Queue-Id: 8636B80012 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1728056553-283000 X-HE-Meta: U2FsdGVkX18bVTmQsxSouny2ba/G2BZZHdWh+SLOTccGNtTpAFcRTfWjuebSVrgGGPXE7Lrp81DJ6lTl+fXrMP19b0UzZj+XHzKJun+XnIMvRgJR2sDgB8e8dHF/Tk9dXuZZXrHpU9CXACFjl6MuouB0T6SaMPAig1qnZV96y6rKgGG5CU08oCgtFzIZL/5z5h/mluAG2O9zF5PqB7cicN2Sl0+jCdCOhct2Dq2aA9lPHQdGnS7yyqxE43oqOf07Rp3JXt6Hzapz7Tzp1swoYj6taHed/GH7cXRdEHw1P91ueRAwVsMyqscPu2KSBRueO4XYL0+ADoBtLWnQ1ZRBz1XNhsb9pSI4/CSPRfmwNn3Pm0KeI5zY4spbQ2/j05qkW/OD/t4TwEwcdyF9VhteUaZdDiZ3sXK4CxmfKuZdFiW1OpS0JfV0ry64Qo5D5fCE29ZQ7PJu9BLacg0oIlw6Qk4hByzI99tv9qMIGXPNCPvcWEcv7Shhg21pQLhK8sYBpTY33kUAvf8+YyZ6vByXQU0yApYGoOdowCqfOQyUTzRg5eVaPDD4eTBs1QXfS9Vjt6SrbuuDs0s1SZbmzpRfrDsnFnfDoNsIBFjA0zIgf5pNRn0y3SxTXnPtGULQiHLLCMvIm+pG0+W+sG5dp58QpS4tKuFvDqCWc0EMcgbEJ8ea1ZZpHcUjdqWmnUiJQj97kUGAQafi3aoLOYi5URHeL8swqSofItqir9nfrAgxnu6pukt22hRiDZJs2RlyGpj4QVP5BqIKSVJ9oh5Ij/rHQGsuPXaghcfoYkXomVM/34IWbNV6DpP+5ZXaeufpn5Kh7pq9Vdei8r8t4mcX6keNJHI0NvJ2LaGkHvriDYpJqMeDxZyzYgKBMZ+GIykh8duJNon7dPbPlnKPcpRIm64iwpQJg3uyAVJtEc0W9ofKH6igV3fpTVrFPLX3aZoYdMUovQu9hRQwgxZtjyzqpug jBhKUOrm 1nj3aRNRhrPQS3CnywQsHR5LWOTXe2FCfgUeABaDHhfL6AyhRZGEp7LdQlFdYL4y+BjfXwP+VIs4QdnFrZ/kJX5fL40op7HB8pK3Kn9Fboh4i80ISb9t85OfqJHHByf0nNU/wytruyU8I/Ei6Qs5aE0r6zoTDPxQ7PjJYhLk+2RQn0jirdoWRyGPHhCLZmk9llyDCMNQeWS7cJxtr/TDZrbEHjuANKxQbNXqliQHJfgxOJmEPqWPZVRF1yWkMlhFtiNPggjy8dAyMPZ4n5rDwtGlTOMrBwWLZYOoTD2LUmbK1TPXqKqgay6UWaJm9BOAUxRFYhdEaHMTDxkrWQIJdEveOUBvcNCVY3gJEeoT9DQS+PAU= 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 allocators such as `Kmalloc`, `Vmalloc`, `KVmalloc`; we need them to be available outside of the kernel crate as well. 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 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 Fri Oct 4 15:41:10 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822617 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 2A9BFCF8849 for ; Fri, 4 Oct 2024 15:42:42 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B33C06B0395; Fri, 4 Oct 2024 11:42:41 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id A6BC76B038F; Fri, 4 Oct 2024 11:42:41 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8C2ED6B0395; Fri, 4 Oct 2024 11:42:41 -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 666626B017F for ; Fri, 4 Oct 2024 11:42:41 -0400 (EDT) Received: from smtpin18.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 1E839161975 for ; Fri, 4 Oct 2024 15:42:41 +0000 (UTC) X-FDA: 82636337322.18.73964A8 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf27.hostedemail.com (Postfix) with ESMTP id 7AEF74001C for ; Fri, 4 Oct 2024 15:42:39 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qgIP+fTy; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf27.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=1728056518; a=rsa-sha256; cv=none; b=qQSokQLjsAtipvCMJqNh6DI9zRpc5QoFNwAIHCUfi7BCTfFRzdLQIwSA2W5NGBgLBXSPDG /5pcgPG0Ga3dEdq5aZK6MXwXmbV727bnagSyi0FyP5gCb4Vyhjx3bF/iBtz41dbkJqF82S RQbA/fW6GxRvj4JmpqlBUZgqCGGRiHU= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qgIP+fTy; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf27.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=1728056518; 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=OXbb9vuIJZW1uNrX76L0wqPxeeMp2MxaDSrDlseTL58=; b=rH0tVByMrlFlm68V7NVhsz5pgt/+GRPcZHWHNm9cZQyNEZm4d+oPPAykP3W9eH3mvV0iJY 3TB4Wq6WExaT8MlAxNvkWME4iWWiBUcmEsmYESqjiZ3hihMDpQTw3JKkQKxKY8WNOEfDmn MRAeHwRUkosdmoY2vKfnJ5URZMJsfvE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 339085C5A2A; Fri, 4 Oct 2024 15:42:34 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1D46EC4CEC6; Fri, 4 Oct 2024 15:42:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056558; bh=WMfOs4LG4FcoFF7HvER0kneu0SsNLoPkbGbTFCvgLjw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qgIP+fTyX7lwjVlnpmUyGjOJZynK9iiYrJ1weIGyEyn4HIs0F5TN1pp1cwK2jj/oJ 41Rd3fxoq7eW1KKElQYZRH6QXoHEfGl8QtcapXpTVKm4+FaSiP5QIg2njJwHir2YsH jfTO1eTd6sZUn+4rporGAsUPmMVD75txon7Bk5OBZ5mTQDBCx9jfdeQ7pR/a5ED45e Q3GTVUw0R/LGjBm/hUASbRIBRsypT3vGThTkUmrnuwfbPMU5p+qV/hAc496btDURlO i5zN3rdjaPsfxoOGzu0yjs7POkDsibjNx9eySUuTBaPSC2bWajwdVUKDyosIU+4Wov ci7cEGqNZPRDA== 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 v9 06/29] rust: alloc: implement `Allocator` for `Kmalloc` Date: Fri, 4 Oct 2024 17:41:10 +0200 Message-ID: <20241004154149.93856-7-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 7AEF74001C X-Rspamd-Server: rspam01 X-Stat-Signature: o7cc4th7uqsmeix81ououocngfn5e3dj X-HE-Tag: 1728056559-916173 X-HE-Meta: U2FsdGVkX194t1iXuIDBQRj7t6myM/lZl1T3nYF9+IgTtnR79jGltWSBgw4LvPBxMr92kJqSePIu3DFMIzt03wh81pd4NODBYsxl2ra8fxxpfSqwY7Sf7bSnDLft+liLftcqTc6tFBN1crtV9N/ErzjWM9NdJqsDrbWaHl4SZUzSz+snKf4WTNumy50SJtWgHgXS0nAtL6aZyVjkJwiC0UzDKE/X0i4o0oY08GvrmmJER2Jm0/qeN7RkWce6VqcDubAv5zR2pBgWjQW2Pd6CdhrzZtCUS85IEgcyWmC7ayyiHSJrA4CFL4GqYV6RdZoQ6g56Cc8FvfveavtF7VUQJtFxPHslp+mo8kGiWtMCGPdNoOOAMBrgsqzn66BmZC5+vuf1tVW6EaXh9zsQhrS1DAEqRg2FxW+IPm7gpaUa5zoWch8bwPu2tXumtyWI7hNTrmPm/Ak044YsdOVa0m4XOWHeDWlTyyPIIOvz54byCJpP+c5PM1zk11/XNBRNto74GAjU1XeFk7PbyLrnHEAJRIsObDnf9AxxHMtQsBVAfwizwYBzGf6HldsziXFp0bAmnCDUK1Wh0KSdKeK2zqn4Ube5xi3pr6Cq/53vJKFWjpMlZUzdSxF6N8F7BlcB7/0rNRh8D5NOiI/9Q2Rj7i0en2kS9U+s0qxagIy9ikjJE/noLOXJ7ToBltyg7mb9nOdj55tVMKu8pw+L1YnPrYVoEt7+gDskxNRxKeumI/Oh5CSyibNqcU94nlYLCDE/GJoE8iOKkKxd1V8ZlyTVZ/PhE4+DB+rcVXm0ReH5NHFLRjqYp0E0zLoWQVfwax7mLEbgLxdt0QFDQa/29fi6/gc45SUdxFVViq4TNiuPg6mx13qgWFXz9hmDDpzpySS31EKRpKuPpDvhOHb17Y1nr9B8GZGYor5icIicU+I/gaC4sulNGuhpMnv7CC9WWVmIxGC0zWl4i4Lj3xJK5FjWcxK rBH5ER/Y JNWwWgo+56PnnTzqbThMZ5nsc2Gdf1T721N/ggc91pAFsctF4hjJvOsoXb4SmNLN39YKUHwTThnz34Ec65+xD+5tDgABycWpVEBmOi3zCg0X3M9d2H0bgrWsq7+K+xE0y4sNSSJR4PzNwrWNt4ZR3V/ZtdYCTLUoyNc3b68QJnCayI4g8EFOMei/ex6TtV0bXvR+eAJ+4EO9Krj2X3uzxmAFFnOzz4RkPhFR4Z+xg6QiLhKDAlbyQbKJdSBSqOS8JiiYuWmkn2dsf1aS0Z9EL3scQLDgKlzp+yA//e0Mpa7/DdCNb7QUSxSW7OPnFEc8PNP/c8b8AXS0GD99tbI2jmhPWRjAVB7xvkLE6AAuISQT7MHk= 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`. Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- 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 e5bac90046a4..b1894c800448 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) } + } +} + // SAFETY: TODO. unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { From patchwork Fri Oct 4 15:41:11 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822618 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 DAD0CCF8849 for ; Fri, 4 Oct 2024 15:42:46 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6ED406B040B; Fri, 4 Oct 2024 11:42:46 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 64ECE6B040C; Fri, 4 Oct 2024 11:42:46 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 453576B040D; Fri, 4 Oct 2024 11:42:46 -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 1FBAA6B040B for ; Fri, 4 Oct 2024 11:42:46 -0400 (EDT) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id D1F931A19BF for ; Fri, 4 Oct 2024 15:42:45 +0000 (UTC) X-FDA: 82636337490.05.D4D8A0D Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf02.hostedemail.com (Postfix) with ESMTP id 5232180012 for ; Fri, 4 Oct 2024 15:42:44 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RT8MltSI; spf=pass (imf02.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=1728056433; 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=r5EBzkSzbJdfj1xqq7k5dIZNTKerfdRx8BBRjqcBIO0c8QETg8bhP9bJb8IGsP5DI89q20 2ijkx9e8KPz3TinAPo+0txV2yaJlvX41BRy6OdkT6B4KJEl1AbtWp5IS6xieC/1BbrMcM4 hSGPPX0CZmsXRdG3M0wzW9hEQBUdWpw= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056433; a=rsa-sha256; cv=none; b=3l005CEseGoIs5MKkgPJmDvCX4JTikBT+vOjDql0vXQf0OYDc91GRE7h/syf/pswgCYXss o4CIUviyp4DcjadK9NPR1U2RQe29Zdo+65nPM5wfgsxzG7dIfeEf8mog95Nb1M2Y+Umphl W1hrKrP1IZv/uoacBtSi4gtWOmybNjw= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RT8MltSI; spf=pass (imf02.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 565AFA44C4F; Fri, 4 Oct 2024 15:42:35 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7FCE4C4CEC7; Fri, 4 Oct 2024 15:42:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056563; bh=qlNC8elt2DUs+OwvKv1BnkmPQ4QqoPQad7Orfyq3Sws=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RT8MltSIAOaKHQso1eT6Z3mUjfi5RIvInL1mxMQG2SL1evErcWA4qcx+604Orhc0L KUqXykgrTTXpuWLEQAxwd3FKpElA8xCNwM/1ZapjJMEWlLcNT9oPJvY89Xk1XMyPky Fak8WyV30MuRnMLZyWdMaMh9ivSoAujvNZ1VyuDQm40yXjm2BM6dAPJAryWCYSjc7o D+OV1bXzZJm27Yox5GFTb45b2DsjWT/U64k4XrJvC4ATcbKOZKLfnY1H9RP8Fd5BVL KQ4swMp90bxNA+VGWSmMkRnrqZG8QzStP40GSzB2CILS6gTbVkSnXcQPKjiYwpl9mk b/VuM9UUxUjaw== 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 v9 07/29] rust: alloc: add module `allocator_test` Date: Fri, 4 Oct 2024 17:41:11 +0200 Message-ID: <20241004154149.93856-8-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: jeffcgksydozy9bm8d6cokb3snkrbd4n X-Rspamd-Queue-Id: 5232180012 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1728056564-825568 X-HE-Meta: U2FsdGVkX18LBYqsnUCOZxRjTh+zjGbemRVBdHs6xrLrOMXdtJkozHkQ+NVmQKmdmsdmsyVk0Tj6iQE490A439ENPOOgfI6nhfJW3A66EWQ/MypMjO5rabWXxj07DBcjl7SLDgzgsqtTySRa1BTx+3C1OS49L6kkKFgG2rNbC5vD3j2s9G4F4Yx3VQfTFId5qtyePc3f2Tb1V4Sl51UC/+VmxBQOQieduhTwYFTBl0Dnl6IG120bBOoGWY/al9xLjniqPhwwOMY0wnNuj5SWqYwaerWGI4EHWIXTyYlqtrm6VbyT5CtIAmZmlm9sbTc2JAXE0n0THb3kHbI6eh8J5T8n/mtFhEgpNVa/N16hdJfwXUdvq8u2y7nfGGUeMrMqz91VLnH/iy7GR3RrASS1ZxN2S8HF/adFbNQx3rSymZIGIINjXBvY82xfZ3Gwc57j0v30dM9A01qxhDyw9IqAb64UEMlYwE14L62+x3h+neizwD6jXaNO7iZu1lntszY1zPWIBBT0hk1hB/dvWFHloQKQtI7/20slg/hekTWdFObacuj7afteqhz2YxlqAzI6/sENNVZ1azLXgacEFATGYK0VuDBPgSt3HJoBCHQYDfE0d8+xYeYo3E2oO3/W4IqqFOBnUDMxhvkdzLbg1uatVXDi12Bme5PbZuSdFhgj2vYhgrCc86vofHCGRaV76XjzBRBXhGMxf1kZ9oWNKEnChRnSw6imdIUhUmnkq2N0IG5jqZqk7477rsb2Epf93BYsbAwdSytuA+OHRcqgGCe/jor+L1aO7MnW7roPb+va/hVYItMJyEUTZXzdU+jQG4xm2T/L0gsB9cD4psXsbuUlHLSInxutFOZS4U7Y/y3WyWLoqCH++gLpOio5PodV8B+6l3sguihHnl1ltTBjXADqB3XBCRiOw/5etTAYfIY221EhB7k14jTNdcMcaom3DvqVipjN1xy2XF4CdoWMO8R w4mYQy2X NkmztiYqRHj0k4yBm+ABIslsvs0PwtddMJdcf3huUaciQS2D/aRvHtfEGmobHGGDVVmcw9YhBFhie79CZccXUj3WE6qYmnkvUVGYa3wLcDE18OrrMpyn77onnnTT5v3BoE88dQK9MXNcG95LRxWca/hneF8KNSd9+aj/60XCIoSyhMcjhZFp2vskq6BBn4t3P0MARkAv0l0vFV2Kin2+U5xn5SkVYo36TIAyeQcj/c4QHPwWAtpeLEfugZCIx5xKV9kcf9HSodfCeKbEYz+bPJDQCjs4X/itbOWzhX8+aScovQfuMy/YtymbZHKNoyONAljNKyRWMMvIzUL/KtaQB+OeNdgXHKSV53MfABFvH3Ev7xyRhKv85XusaZtOgqC466dX0R0NxCUjRQPS+sQAeHhI+DxMDxPtX9azvYcbgIqCaE2DTJwOEXdG0ig== 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: `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 Fri Oct 4 15:41:12 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822619 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 AC179CF884B for ; Fri, 4 Oct 2024 15:42:52 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 36BB56B0201; Fri, 4 Oct 2024 11:42:52 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 2F2F96B040D; Fri, 4 Oct 2024 11:42:52 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 11F476B0391; Fri, 4 Oct 2024 11:42:52 -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 DCB246B01FB for ; Fri, 4 Oct 2024 11:42:51 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 59B29121A19 for ; Fri, 4 Oct 2024 15:42:51 +0000 (UTC) X-FDA: 82636337742.08.70F5CD2 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf08.hostedemail.com (Postfix) with ESMTP id BF3E216001B for ; Fri, 4 Oct 2024 15:42:49 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cSA2K6ze; spf=pass (imf08.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=1728056503; 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=kEHbOceUJnP8Ubhpcd93+jphAnizfaIlpTbGHAUwJ0E=; b=lYVOdswX0kmZ7KyW+xeJoVIJwLDyN6amv0tboMePIWfr+nLHVIjJ6rZhyq5FAfSCchSDuN mk5Iaa7P7J3n8fz8BOSW6ewwpQsXDSsqM0zL4W93jcInMraDjRh4bh4zpViSP2IVSvfQh0 nww5bdvaisUrfNvUR5pL4nislTw2LV4= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cSA2K6ze; spf=pass (imf08.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=1728056503; a=rsa-sha256; cv=none; b=GS9Em6JCgl2RggwHNp7i3pled9VR/LioJ7SRpb05sdv5mCPnPkMxafsWLlWOcplk8Dzn8g 8c9mbWBaypju49FCZM9yS07VXc8l8JTs0tcrY/pjiIJJGae+ydyoirFnyXf2MjROFE/y3m 9nD5iz9ToQtJ3qVrfQR1OdGWPaNJwTw= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id CAF4DA44C5A; Fri, 4 Oct 2024 15:42:40 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E1B5EC4CECE; Fri, 4 Oct 2024 15:42:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056568; bh=ivWwJFghp2EePOEDw8b0kSPMmrO/dnpTdtxjr1CLz4w=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cSA2K6zeVv53uZz9bvEnG58rmYxYWwi8m+G32sOaGwu7Rcjut8ag2DdcqHYX3Ft6G 1AtbO67RWiG43g1FNUdnf+HuXevV+6dbqHC9FSpn7vgyHsL7w6bYwpz5/a0+dc8nK9 ZwsbLcjfvaDAjSAIHEY3Rj8G3eZmoKFtGM25jukwyFLHVWS5VZvXg6tP8WYPLj1EhO ziQ1MnRkf9Az6ai+7ryVXTuCErMWEuVbtJTMthTpoMjRB/gSl6VKSpxAoCeyZeYbkE q5mIHNIx/0B2PM4AdS81GXikoT4rc4qjb6o+EOkO23+/TEmCWd/aupZx3/hET+9KpY /2UPc0f/gl1oA== 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 v9 08/29] rust: alloc: implement `Vmalloc` allocator Date: Fri, 4 Oct 2024 17:41:12 +0200 Message-ID: <20241004154149.93856-9-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: BF3E216001B X-Stat-Signature: o3g3zrnex3wumobttt1jzwu5onob4jhz X-HE-Tag: 1728056569-205109 X-HE-Meta: U2FsdGVkX1+X/Ze/1VY0vZvPKtq8q9NWhkEzEL+wQS96qzQ+Z8KMUN+g52zScSrGtzzd+A7kvvYUktAK/TtFOgJ+v9fKYF/D+gdcWm8Dmg1bTaSTm4MiOJkRkUf8G4NpCm4gF6ZEQgmDDUJxedqr2JBi85ZKHqvhq+YEU/dA+TOOK5GvKYaH9g4OsSukcb3jhzOJ2ZD9TfDZ4L1jvawLpMQFU9z5NyMWgnYOvR8Du9xhPYHqvOy/G0cRq5Hz4EjRtsHEKhsb62dTfv4pi3HEPgLCNh7SwkVrPMope4qd1C2B2uwp5CADyXFEtjJPZf8lklLkAxEgMjK/BDDS618mId3aP6T6e5PneiMEMPLuE2mTxk/43/k1NmPd4Ld4/s/DyXlu6Aa3iZ33cgQoSEx4SglEIgathNyXCRwHX4GG66wMcEky8glJf5iE9yVrI9UUSeXufM5pNuw+T8mxN2BJGW6NrTUxvA2fTn7W6zMBzs0hYnZI1xA/szMyAcNlZfmnlW2SWx3e8CCG3v6P1AHCeQCByN8IrrZps5nAuLHemgkVAO5J3RFUm4BAU5x6qDJPEf1IReNMsnBDp4urO9g+njpPwNC0I2sL59cKoMyjmTXW3j8lCBwDChG7sHGxFgAJIkhZQbTTw+tgHdG4dkWDGTXwTMyjqLhCnHS2GywZ6XUebUnW18LIY8b7+kiXEYRqSWpIvS/PcuC04sUnc5LoaOPEvkFQoGgPePzERPuJRzv4wBC6UZ6m2Ndw31lbpPcRZG0s2WVtdm9lYXZBG8AivS/xOkGrr973xu1GoBCrKU9xHVvmSJhruU2dfZnBzxXS36+MRIzullMSe+hi3ycQz1ahF9AbHSMYopWYbfM8C6xsFwnH8Mz9q2VtDsNESUkldgRkOX2dCrQ4c6MKGn3c39Pp1XKTr/wAMBbaJWYtMruR9N6K/MHFojfOBGc/Bo99ifGo/ckSDXVwsUYyl5c vRiR28jm IUDDmYZuDvgqEOYXiHd0kXup2Bx9Wfa2p1PIoErHh1j4xQhJALxDEGBoshGHPetMaLuGgBvfRVASAa29RI4WEVvnwmxE1qTzCRjtX50mVK6diy3fkPUzBNTtMAen960VAE2izM7PBtyMwEIZDcrPE7TrNXS4uzlKu8Qi6Wh5L/hUtlOKIh/vzyu7x01S43TcfpGT4ChKUlv+kL7fzB22V2zq15RJU9XXGE0Y2UUOR2CZzjGeQCczzs4NuX3WQ1gmcgKueji1dsfKShEA6QfHmM21hL+44BsjfCYzjTm6ZvBlSIUOtv8Ixdy0AQ4N64lUAowJA0jsY5Uj7++6V+Dsfw8agTiP+stkI+ugxtFVn+WSQvuuIkUU/voJie/FRNkiE5qqd 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 Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- 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 b1894c800448..5742ce7d0453 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`]. @@ -168,6 +181,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 Fri Oct 4 15:41:13 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822620 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 E2264CF884B for ; Fri, 4 Oct 2024 15:42:57 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6ECEF6B040E; Fri, 4 Oct 2024 11:42:57 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 627AD6B040F; Fri, 4 Oct 2024 11:42:57 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 483046B0410; Fri, 4 Oct 2024 11:42: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 22D526B040E for ; Fri, 4 Oct 2024 11:42:57 -0400 (EDT) Received: from smtpin22.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id D8FA01C7183 for ; Fri, 4 Oct 2024 15:42:56 +0000 (UTC) X-FDA: 82636337952.22.A1067E1 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf13.hostedemail.com (Postfix) with ESMTP id 3084620008 for ; Fri, 4 Oct 2024 15:42:55 +0000 (UTC) Authentication-Results: imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qKjQ8ZPm; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf13.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=1728056552; a=rsa-sha256; cv=none; b=jA+rrdyTXRv6p7MGOy19N3mHMVaolY/GByIsqoNtAdjUXd7co2eKD05PMgZJb2yXs6oT+E mskGwNe1swk4itwGyNStd97+nzK2jMiarTLuWXBHt3O9iWv9v+S6FZJx/0VfTBTffFmfZg 5WNI5JP17gjZ/A64BSUXxs8c0Bni0so= ARC-Authentication-Results: i=1; imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qKjQ8ZPm; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf13.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=1728056552; 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=JvtvDlqgKJZ9179cz0r9Y+742zJolVW4Wz6RejfGigs=; b=cwQbU/+AcSibsJgRFhfsGBmaaonkfrHR9k09IL8AUH9cAzfdbwF6I1oH2H1HHszfAE84MX M7BjGuDzM80oeCF3I/aDxFnwE4yUt+VfI90I67S7oCnCDxrSnOYdsd7v3U0R4volhxThns S10w4CVFmQuOkANaFK5Olw4gBim2ZDM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 5B64A5C5E95; Fri, 4 Oct 2024 15:42:50 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4CD91C4CEC7; Fri, 4 Oct 2024 15:42:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056574; bh=bmN7ni692A736mVNYrpUELQFpNi/F1V47sEOIzb2Zxc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qKjQ8ZPmnVtLHqr4nor207d5+lle0HUgclARf5EncF5XP8/iOOzpJ08rCz3Zf3K/q K+XtuJ8Un3vl+Adb3MVI6prusot2SL+Z/UwzTKQLoqlt68BtrM+123fOkwQXTrMhjH 89pD77I6HL94tZs/5aC52cRVLNRIILom+coxCtCDk1R+Aa19I135JJNEoC1pJr39Ar jOyml3k76DlaNKTwO6U9mfO1p/9EVrZug5sZopte54z/yzrBOhwDmvAnReyaZ8g4K/ VepMZe3eyDzdjg5iHBnqXzIHbrRBxVCc7ia98DqMjjvONZjKWXFbGZjnCfAsNdrKVh f/C5KfKLN6ySQ== 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 v9 09/29] rust: alloc: implement `KVmalloc` allocator Date: Fri, 4 Oct 2024 17:41:13 +0200 Message-ID: <20241004154149.93856-10-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: ss5se6y1rpspmqxfu9jhuewwz89hason X-Rspamd-Queue-Id: 3084620008 X-Rspamd-Server: rspam02 X-HE-Tag: 1728056575-307366 X-HE-Meta: U2FsdGVkX1/Cd5NgbiYy6nqpmy4YXh4pCHPk3SNlWH2L/jvzuGETcwFl8ks5jjEMFHbc29VxUW2X/J2OeKbjXoeWKUqYXA1exrv1eOiJ/4yY1fuG55Qs3nhefWWeOycPOjflamXwTSPKPGzuMOGMDBsECYDDlkovlbViG4xQO8GIcktKDYg1ThcHHz2o/S07OFG783ZMGoF6PVFRXf527YFJj6sXi+AQ8gT91XqZucXVJvmpyAXClcBj1dpqvbmqa1JLHUxXs6S1uvuHpRgDC/cTulSL1IhQGs3mt7nX1jJv6CTe3ueJ3QyBh4hwC+yUgVCpiuqOW2q5zrqt8dxbPMtEnbuypNVK6P1oXv0a52ENJBfmcfuR4OYZErWM3nLijKoSz/npKBfmICk8BppZJszVWPd9m3Y4GBUTcRXh0mY0fymEOsRgFVZbAgslInsWRugJE1WcBX2Q1hS8fyzpPwjlVHdJ/gkdEoaMQh8CmAbqpBuqjLz/tTFuvNglUpJ/U7QYXDgcT3Fk07/6Yc+36dvfuVlBPS2LELn7zlOuRUMiPuxTa3vxbJrG8DHOQg3bB/0NbaP2Fj8pZ1Pb9kQ8539wEbq9EWattZ9GnyB6iuf2hHlxYUeAdLO1psPzKez/4g1N5OZli4NLbbW/CFl81gXTdRp1Z9W2aGQUOgl9y31towxXDkY39XQmDv0oPM4TL1S5WSAEltuSfH8Q11CdxzVrgUrJDYjvlodQOO784Jf8/tJKvjCh+r/MHcCUMi63dASNudzCeX4BhOrjV9ssOq/K3YtasX8oDMaYCGunZV/dk5hgoU8aKQxSY0mBY588tj0QJlL/WnQf7f6AiNUPsfdKxsIJap6Z0H/p/jkA+91+88avOJyB+ygvY5PaqwLa5VOPHoxEoDrB/emo0/z846yFVKjO9x3AxZagBDVAdMbNzqhHKd6C6O8q7TkAghNBHrd17DNl3XEBSOq+A8E bDRzixfW nAbSXfEoy/SpDBB84qp0FhsAawfRtB/+hXvx0JBNPfX7tKmsaAiMeXXFA0Wu2pZ94S0CLEHkLbVslOCy1WuE1Tuf7+5BsMLCEtjZOiCCmASnKmJF/XoJfti7qGlztgmurhUlaon+mN0mxPLuSrnrXlBm9sYC7dJlG475baKMRdyqlGiVWXKPAxYPAptn7143igzqhBp4JcXlaFHie1n2EXwz4aFVj/mfhLp3NDT+7utpIdizD6rglQEXAFV9/9ieev6/n3G8GH34kZHg0V3Pce1tRdSYAzSTNg6CP0DKTfYnWu2w7r4PgV9yhm6P2Vbt3ETX4SfVwwls7/99hwX7ScS3QQO1T7RAmnMGSL/p3FlM9JmtOICi0S9SynIdfwCpofnbz 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 Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- 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 5742ce7d0453..d9043ca42ce5 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`]. @@ -205,6 +217,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 Fri Oct 4 15:41:14 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822621 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 26B29CF8849 for ; Fri, 4 Oct 2024 15:43:03 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B5A728D0005; Fri, 4 Oct 2024 11:43:02 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id AE2188D0003; Fri, 4 Oct 2024 11:43:02 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9355C8D0005; Fri, 4 Oct 2024 11:43:02 -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 736218D0003 for ; Fri, 4 Oct 2024 11:43:02 -0400 (EDT) Received: from smtpin27.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 22FE5A195D for ; Fri, 4 Oct 2024 15:43:02 +0000 (UTC) X-FDA: 82636338204.27.D5E6F17 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf23.hostedemail.com (Postfix) with ESMTP id 8A7A5140018 for ; Fri, 4 Oct 2024 15:43:00 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=G0SZdVWM; 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=1728056449; 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=CGdcv0s/Xbh/ZnJ2CiuBGK/B5aTTHTJyqukIkMNd694xyuT9t+6fRm4TBWGPKwVPXNmGhz bMeEwWMqR1drybe013ThOrAdHKpLTzAc7kUGN4WeMEBXVLH36rqKIxI5a/LbY1AgrYgCMp x9oh1/0AoIzb92QZ7AxAN708HkxLX5s= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056449; a=rsa-sha256; cv=none; b=baSUeQDjBSO6X1XX/MIJtdn63lsHM+JHh7LK3PelslmhoXl03zC0ksLQ8murKqUyZwRiv9 qRxkGKDx2JmqW12EkYwTq2hYMavMXazUPANVj2CdaeVbvoXR5RNeFbhieztR0CFApOy3CM UKKttA7umZNAv4ULgOyLCZ5otRnuNCs= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=G0SZdVWM; 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 86F72A44B76; Fri, 4 Oct 2024 15:42:51 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id AEA1DC4CEC7; Fri, 4 Oct 2024 15:42:54 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056579; bh=k3fbnNVumq3p6Zkau+316hxp1LWKMWboxrOE8MJqOiY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=G0SZdVWM49uPjrTKdSFLLtEup1HwgkGeO9v9ZDDnn5aHOC/i/t7QB+rI7DTTt8Uhq QGpzMmjDSv5/Qv/j/7F92bzQpromwD9bU8z7/bweJ/CYCoVL41kbiK/SbygAqIxBqN ibze+ncGEHEUljEJDwBQobzEi4pp4I/Pns6sFjuwbCew0cB3cspYtq0kXvPTFLk78v Aeb6O8+lSbL51Amuo3xpUiptRKKfFv4hWnWZuI711Rj8/Jweg3w+7pIusrhns+Cf39 Y6cq0XQxjySmgv72xnyort+/t+OcltdJQA1mHzJ2oDHuSaE7N3SLbHuRI5O+FZnjPk 4TnpYuFKDci8A== 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 v9 10/29] rust: alloc: add __GFP_NOWARN to `Flags` Date: Fri, 4 Oct 2024 17:41:14 +0200 Message-ID: <20241004154149.93856-11-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: fdo95c69ojtrymbk74mco9yr3qxu5ign X-Rspamd-Queue-Id: 8A7A5140018 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1728056580-415347 X-HE-Meta: U2FsdGVkX19Yxt6UCbsYCegbLL6Epx9ECHHotzdnFIJHMk1Suxuultvjd8iE7e1BKyJ37aKGuGgGiRB5RgD64A6OZba+e+ghdZAM9dnHrQ3aLdGHOnWZQ+/V8Ai0zoUMqpb3WeUYpaKxBigrGHruLSJkhsFZNAXhBJzb0DIHQcQB6keNyY6/dPezoXhsGyIJYsBJzHqoBrwI4RI7nHlaRjwrxL+7gCui1md+TxMRthOlfObetExecQFXm3e26uESa/hrjCNS2nDBfY3NDSXblpA9ThYw33aDr8J238zbffcpBNNgTPXwJc2zc09uAn5JuZXwAuAQKx4UL4ejajiZICIP27+JoS1QrE0kgVEvVQPWvoEbEWbal/Y9SkzTSfl1fgliLqbBmjnuGhNcek3VOXUItvQCu2DMY1Gnotv0FvtcbnlAEx79jBl5SpM5lJTbWSoD4TONwpEpFGaBcs/1epzqoMm1+IByGWr4tyGjQpgsfN27E4b/ru3jRtPl1ZHTTnQ4UeKL1k8sS9gs+IsoHgskNH/laW9uV3I1v984kJoJyzYwmnTrlxKRkt6XbSr0fyJosy3Z0YslhmmZpC/Uw+arl91NG54XOe5txv7Vt5HpoOL+iPUPCsCPbpLEKRoG9xxo7MzexI7lmiyQ3mEi6ANrVHBYcZ/gwjfzjZUBp2q7SliuPQLoBR7mi3Puo8z/29DhMbdpH/dQ+9/fyN1kExuDPyI/N0BYiI7ivpVUrnYPVIPZ8rhlU/qlprOwZGeKsbwZilqzSN1cpo084Ck0JKfwtpIHo2OVN/dMFsjlmScRgkb+X25ExsTTe+N76U9DyjFv4daJI7iOmIyhAgkQ2XqAfIa9m9Pu5suKRBgwbtLpSZmhbYoWjJR13TQEBcL9RhF84WKDPj6zO1nBRSHfYyGupRKMo80qufAfonxlPIqJtCieVTgCOrAKBXJEPahGGQN8iGQsFRUB5ip+Wb7 JixnnlpP UJgIFc7D9rj74EY6puIUWFvgkju6x1rbWofB3buLAJI1Rsmihxh3SobCWETkzC9b3xviUUSeC3Ljmd0v0gFdIBVvOGs/ZHlAx9VFKzyhtF9ybfKlp0DNkMVOQwV6iQaeD1R+3cjzEBCTlFTvujoRbU6m05DrVN2lwze8eNqaYYO+IgSBOY1GeSjniqS8lEy4F4uHG8r2xtm+XAA5nAKsQbUUZrKb2oXxHD8UTWgkz5szwMs8vOfjbzfv5RicQEYhC1Ofgk5hJL6+sP7C4zt9e5ZLJtk5XcIEOjRy1bHU6tCamokXu4lCCAydn/ehw5KUS9ackajC/H8r8srWjXMKURcm6xaq19MOl1lKRvpXZlNvuN10cXLoX7bbUEqACXK7tcQB1z9sZKejLLlj0qOv4U454i+ayZf5Bi1WOpAMxU3cCb2mufRonJZx0IA== 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 Fri Oct 4 15:41:15 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822622 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 69EFCCF884B for ; Fri, 4 Oct 2024 15:43:09 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id F2A0B6B00B5; Fri, 4 Oct 2024 11:43:08 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id EB31D8D0003; Fri, 4 Oct 2024 11:43:08 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D04F86B00CB; Fri, 4 Oct 2024 11:43:08 -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 A59016B00B5 for ; Fri, 4 Oct 2024 11:43:08 -0400 (EDT) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 2E6CAA19DF for ; Fri, 4 Oct 2024 15:43:08 +0000 (UTC) X-FDA: 82636338456.05.6550B6D Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf17.hostedemail.com (Postfix) with ESMTP id 5847140005 for ; Fri, 4 Oct 2024 15:43:06 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aXA4MbT3; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf17.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=1728056480; a=rsa-sha256; cv=none; b=wjSo8YzGqeGUHeCbm7qKb9i/eEmcTytHR0tYtXnqM63R9eM8dZxPhQVMtQCYRE0sgqqvqd ZR19VWoa+uET14r1W3aS/1Z5oypNkhs+u8On3+5ewR13mYKskl+DOdojo+srRsW7pXIbiF 9xMxqzOs2CBmP9oBAje+2r/vt5x5BSU= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aXA4MbT3; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf17.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=1728056480; 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=iczPogmx9SfiVs1HO3FYcYq9L3/IO/tP24BFQYkSHl0=; b=GePWAuxUby8VOAA9p0b6Ng41GtU2olWT6ozhVu0WXG78DtXWm1FRhvrXHAdquPVErSSm02 zqD63SwpAeVB61B7SdlHV8FwlJezClV/72qtvuP5Efjr21uIehu+xMsEr9U+7yvy5/SPF7 4JfM+RJxs0lKE7go9JG2kL7mbE9iHbE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 3E26F5C5EE3; Fri, 4 Oct 2024 15:43:01 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1D188C4CECE; Fri, 4 Oct 2024 15:42:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056585; bh=0VH0Qd/HgPfKYpikkjjp9Q6BxVtxq41nH7v/a9brP/A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=aXA4MbT3+vVTICINEc9lDElprcdefwnCKhj/v+Eph+7Txy08rabYZrIGdmcT7v/oi aLfx9CCe5vmQsMu4kMz/uGqPQ519vVq/Gls5n7o5vjSgrjrL17ftAjiS1D7dsbyHUh 6m52CIzWX33re0t+/vcDtBGJZMI6sjIWBROmVSGwHf6T+NmLtQV01BErg3WIDEmQUS vc17rSTGNBbLlk2rII/72OrZeaHSDZBkGeNNJrZv+Oauigo38u0FOLsR7SLqqxdnNF DSuJC0OCu61f+AoEV2jzt4nWceDsNRruQJehH4wFUs/6HbOD5plWnQJF7GbwZ1NoIc tAJI1sXLBpXaw== 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 v9 11/29] rust: alloc: implement kernel `Box` Date: Fri, 4 Oct 2024 17:41:15 +0200 Message-ID: <20241004154149.93856-12-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 5847140005 X-Stat-Signature: f9fcwkg61pfmcq4aoqudkbtqy8xntwia X-Rspam-User: X-HE-Tag: 1728056586-482666 X-HE-Meta: U2FsdGVkX18b9D7cv6xUtFcOIDIg0rwCoUKLbSa32eQkzbitjiJ74CJmMEYs8heVUSeVB7IbgOc+xSarhJ7gQka+pUZMeaU30Xpfq4KyErcEF+sm8uLIIyeQ2xQDjXohHkfAgGlqffsptCFcdLm9Toz6HNsffnU6pBEGxp3evNXzlK+B6KoOTV0YOigMma7h1EszxIZ6gdMnZibzakOL55bG/cxGEhepqLZExayxhSGfFjQnEKMFVgY2t61xNvOIWCvzLYy7ZTI2F/VFTeG3cQc1y/fbj+O4mZSNjwStNcaJeNpCrkYThIQYxJnD4aQnDtq4qe+y8rLkEJq75ReczkaRPu8UW2l2OsRFNjXLEJLk+ab+X4+mqQuTYacIIMjBvpJGi12ge0kacmjZrYyG6STOw54PdLlNr0+CK13d/wIi89nJzaewUDR4JEO2dBF57VQzorjwyPYY7rMEAMLD26WpphytEyDparP5+G15UQ+sTiIPPOWioZCBRhR2K3EObxZSOhBwVtbfwH1rk/HotalMC64njtPQa6vQcS+wBYAb7MKPHsw1sf6rPrqA39TGoNF9niCedYESXR564KDklLuEUpFtGUoPNhvwi/klEsgJQURWMm1apXZl4XhxJ0ZERohareHiigjt/DJ5P5lGrrFD8dLtO2hnyS0IPcOdAeVHqbWtWCg/D+Cq4BphCigcc1SCcDdoL9n7VSXN5kdqVsiCuamK2z/k051KnCQVSYPPZF9VlopaBhjeFx1Ee6CYhE2y/rhWiZRIyW4gFYUzW5/qhYF8hZG31kG85VTsruEyGJe+oTlRurkoK59c5RDQL18bIfL7g/B2gK5CZvfNxpC/NTBAWy4p2bw122/UMi4QfsO3jzTKTSTzzPdG7GdeojJrl0Vt8i+ebZ3hS5aGUcQIaaE7IKdzarmBxkj/VUl1SGsKlT8J2/sjQFkrG+pbp0SUe8U1lHW6M2vAMez 6Omx7BAl j/ZUhULOEC3QaT45de+wwfHCuPCh1688jGOlA5gmcG/3uv5srDuGFWXV0m553o7ghrkWfqxywOdwNhY3TGB/FiOEPwrAZt9wlOUChx81YvxNDiBCrmTUuv0OxnC4LnOFAf6mgtXTMp8V/86AMGejYSIa78jGB3CyEn5XuyzT8l6hbMrU3jeh2n28RdPlCathk35vtTCzZjJqToiNjB4tcYHWEpNthC9J2tuVj1YTVvtCrKnJxYshIAYsgLK2FgTgBgiyrrxyvDmtCtXiGANkFyYdo5ifxeYs03zzcBqeO2rPeuo5fD4WnDIMfocSoe6mm4usHtWRSprpALtRP7UabZ8YOLLk/fPpQDGFsjyjEO8ELu3viS54a807fn80ckMQY6FyMYZyrRwn3RONnnXSIGp33PQ== 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 Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 456 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 463 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..ef1add933f60 --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,456 @@ +// 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); + /// // SAFETY: `ptr` comes from a previous call to `KBox::into_raw`. + /// 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 Fri Oct 4 15:41:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822623 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 C4F4CCF884B for ; Fri, 4 Oct 2024 15:43:14 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 567898D0006; Fri, 4 Oct 2024 11:43:14 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 4EE4D8D0003; Fri, 4 Oct 2024 11:43:14 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 31A788D0006; Fri, 4 Oct 2024 11:43:14 -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 0890C8D0003 for ; Fri, 4 Oct 2024 11:43:14 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id B9EC4A1962 for ; Fri, 4 Oct 2024 15:43:13 +0000 (UTC) X-FDA: 82636338666.10.2FB6A16 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf25.hostedemail.com (Postfix) with ESMTP id 17865A0004 for ; Fri, 4 Oct 2024 15:43:11 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QaWoBAj5; spf=pass (imf25.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=1728056461; 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=eSfKL4CEvmQFWcVJ/XfZy40ehG68p6OW8x4Twe2BgHs=; b=mxpLVBc1IRC4x7uPBh4Toe7L5jwBZrjoZQCJL72UkxkD5Hxnp/G91rqIGfP08wJXYJcypO c8djzO7Ts0Jf6QI8sUtZ8tS7vzMuhcJEdoR+UmUAwlXPQ68VseieVlqpaYG2+rBpoBndHa KymwlPstpzFVJEX79Sm/bEhJPXWwrJY= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056461; a=rsa-sha256; cv=none; b=RW7/JESRsVNfc8zu0a8sQp6Kp+QlA/E3s1HZfyTBwH5UBgQCn3NK0UGxup65DkX5FM+SZQ kttM4r0sQjzcfSJuvAB/g++4VC6jdwUKBmFJW5KNJjKSH3jKR/CT56s810pdetL3oT4QB2 bTewwvB0jnPhvl6t3pvKC5pE6nKCz3M= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QaWoBAj5; spf=pass (imf25.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 E9C725C5EC5; Fri, 4 Oct 2024 15:43:06 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 81019C4CED0; Fri, 4 Oct 2024 15:43:05 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056590; bh=32n8JgdHO+8eRlSHJI2uTCIWYY9WmRtXv+48HzSp4yQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QaWoBAj51CQQulLDgA+/1MISUmvSh6Lszi6gA5SuasW+PWmiOg2R9e4i0TjlqZKPE kiGKnr7Pc67AN/+909EVZ7/eLP3PZ7Hc8FJRqCdJLFzPVSm4TcbIW2K5RVBNPZIUfL m2jOcLFvFvPT3LyaRrTAszT2bISGm1L6NXqXgfWEBIVl+yLTSzvstMhkCt9j5DnHxs hwoGmxEIis6kbSj0TZG3Q9s1DjD+dAA5HgZjKJzM3aX8cNfZqdyqQXJk5MuYqKGpyl 6kWEM51LjQPa2W+nlbigu22gAeyOylhyrEmMG04mIYdrgkkd2R6Y0r0NwLHnU8Yn3M pWO4486P0b82A== 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 v9 12/29] rust: treewide: switch to our kernel `Box` type Date: Fri, 4 Oct 2024 17:41:16 +0200 Message-ID: <20241004154149.93856-13-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 17865A0004 X-Stat-Signature: joz1cj9cxoeg1s7n6pwutg7rxn15epkc X-HE-Tag: 1728056591-790456 X-HE-Meta: U2FsdGVkX18N5NTR6MMPvs4cswlAPRtfZBWqv3TsVq35W+nSvh5fF0Wkk/7IOm1BiG8UkAY2T+bTd+mi7qxe4nWwRJ4KDsvN/BoodsvDr/GS9uoU6zpJ+SUbVk2LaZexRQJLqA3x4AGlOshISgYH2Tj6c/CEe0pC29BY2OVAA4GqgU2qxIr+TEWc1tiMPrab7kWrlB952mWrkE4J3ivsupCJc+fs6Zvh8hQvt6xMRCo24THAphZUDR5hwuuajDbVQny8qPxm6N+MqU93npVP0BfLMCjGXJ7LJdRg22QnZIuzEVYn4L9i6Hv68qI0jGP1zYrC/VUO9UaLzbwaduRtkJlylVGkuxcYTjG+Y5mtHZmnPezR9xqTA9eDgymqPUlpUqVIcFzChsTE5gKiCg/WWXy+b8x2/dxAwkHHyJcD/sYOYqvkf8cDh9z8hHNdSBubRxCTbWvZ2xrnwYZF5H2bH+lkPTB3T1MOSvXNSruMcRJg0ua2FpkhJY1O21Z3XVOEAeTylYS7GLxD3nnBDYSpeWri1BLHLxWXrCyWWibq86rJlP2T1DXZIO9BdP7zyCLhrr4JfPdYa46S7XPaXODf4fvzEm5bJvHJ/X/j1VQSYxzDJCjYXmEWiCHIWybV2yDUK1+Ax9DxuSueUfWCVOlEcYg4IVCuBUAtYk2ZobidWuUZvn+RhjpCaqGSlmTZBJYkcOIriCDrpDhM5M2bIRJUtoI86h4DzHrXX7qOzQkR1XxXh3QVRkKVvP5+rHwbE2ojEk25rr4ep5+t8R1uDgnjGDVbSmEXy0lcWT1qLDkhhdlOOE0vqwP1pYybLGpjJch2OTHHI33Y5e022dYApdg0RfMnm0QbHlbzQ0kSRf2MRTEPnnkm6nhNgO4eolnobHb7by+l47V4Pe9rTgGKvavEaM9vPxBHXoLdn1yXWnR+MqBkpypCRXs63nP0aphTwAsJpVxvLUsDBkCl0nt6aSK Qdjh3Vox 2mTlSQFGzS6JUMipe4rfxlo2J2XGIf0ykn+dvpy+J9XA4K5LHHfp/xmVrdjN54nOsRlB4bg0tsqfCmy7Iq+n3U3l+HADJ7C7khFcr9x4SLRIXyDLaxEOlys1LDHDBr+sfTawlZNW0IwcqoV9TGysgoEz3kD2D9VejKH2xY6Y+OocRBW3paj7FiNsAAGIGz97w/9wimIAA+Hkzd2rmkZ1bnvHynwVz2G+iE07BLsxGkfdhCbjq+xYwJBYUdEH+8LFExKPY+Gnufy/7fdXtCnA1TAIiyyws1vy37q37JmSv3bez1fyWrRaSgtqnYnfS6m0sPBt46cC59cjqQ2UfNDkPy9xEUe5veuzfN5Q0wqR+MhGFVlFHFrysudxVWCScDY6o3G62EoDqbCf4t14CPnbxREbc5l+rTGGa9xbr9P1lFe/6hCCtYTexHrbCkz6iRr8qMp1sBSc6zuQkUrMFrytTszJkTFm0SJGJgbjbiNBTbboAblph3vNCLi9RQw== 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 25057cbed40b..c889f2640b56 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. @@ -92,14 +92,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)?, /// })); @@ -391,7 +391,7 @@ macro_rules! stack_try_pin_init { /// }, /// }); /// # initializer } -/// # Box::pin_init(demo(), GFP_KERNEL).unwrap(); +/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap(); /// ``` /// /// Arbitrary Rust expressions can be used to set the value of a variable. @@ -460,7 +460,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: @@ -592,7 +592,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, /// } @@ -600,7 +600,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) @@ -692,16 +692,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) /// } @@ -812,8 +812,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). /// @@ -893,7 +893,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, @@ -919,8 +919,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). @@ -992,7 +992,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, @@ -1076,8 +1076,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( @@ -1453,7 +1454,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 44431fba7aab..74329cc3262c 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -105,7 +105,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 d03e4aa1f481..cb4415a12258 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 @@ -1038,7 +1037,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 { @@ -1046,7 +1045,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)?, }) } } @@ -1062,14 +1061,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 } } } @@ -1079,7 +1079,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 { @@ -1091,7 +1091,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) } } @@ -1113,7 +1115,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), } } } @@ -1164,7 +1166,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. @@ -1238,21 +1240,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. @@ -1268,7 +1273,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 9325cc5a16a4..db9da352d588 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, @@ -201,11 +200,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()) }) } } @@ -398,8 +397,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())) }; } } } @@ -641,7 +640,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) }), @@ -651,8 +650,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 dec2e5ffc919..a1a29c0bdb3a 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 10d2bc62e2cf..4d1d2062f6eb 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. @@ -567,7 +567,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput } // SAFETY: TODO. -unsafe impl WorkItemPointer for Pin> +unsafe impl WorkItemPointer for Pin> where T: WorkItem, T: HasWork, @@ -578,7 +578,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) }; @@ -587,7 +587,7 @@ unsafe impl WorkItemPointer for Pin> } // SAFETY: TODO. -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -601,9 +601,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 Fri Oct 4 15:41:17 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822624 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 103D4CF8849 for ; Fri, 4 Oct 2024 15:43:20 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 936978D0007; Fri, 4 Oct 2024 11:43:19 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8BFFC8D0003; Fri, 4 Oct 2024 11:43:19 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7122E8D0007; Fri, 4 Oct 2024 11:43:19 -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 4FC498D0003 for ; Fri, 4 Oct 2024 11:43:19 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 05560818FE for ; Fri, 4 Oct 2024 15:43:19 +0000 (UTC) X-FDA: 82636338918.11.3C77B42 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf09.hostedemail.com (Postfix) with ESMTP id 5BA6314001B for ; Fri, 4 Oct 2024 15:43:17 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=PY60yaBL; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf09.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=1728056491; a=rsa-sha256; cv=none; b=0AXK84sg+JnLHmXw7VsVM/3yAKlWau/Y5181ud5hGNvLtl6Ot9b7waK0P6nSCOh9Uon144 eVV4NXdhgWwFdLgEPeW/fTF0f9vTEYB41TFKCAfhDuViK7WMTpWqQZ48ZAK3E84xO2CSja NjtCnnUeuonYVe6Q2n8SmDmGYq3EOok= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=PY60yaBL; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf09.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=1728056491; 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=Avx44lqLlghmMnrQ7zImAACZ2o6BLxj5HsFNLQgxe1A=; b=u1yFZUILMx317hXRe1GW3SCQLL4DXVXNsAszJ9k0CdpBSudN9kkckwu5G+yadmH6dlkRm7 HBIz3dGj9G7TL398+BwghPT3Ix3wvsNdP0/5kQsavp5Ra0hPXUCGlt8Qf3nFUv4ZPMNG4o gJOnwWUXt3ZXYh3bbXJRdqxFrA5HnK4= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 263D6A44BFB; Fri, 4 Oct 2024 15:43:08 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4582BC4CECE; Fri, 4 Oct 2024 15:43:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056596; bh=kazRakNrpHOowneaJN4zcTb6ci/LaZH4uk5yeLlVimc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=PY60yaBLX5FkWroGne2wbiRf3YOduSZVZm5AHgfyk3WHkfWbM3EuOrVqXycz4PQq+ L7kLm6ETYxc6+1xIy6vIEplED3xtKssri1U63By0v6Aprb3PO7CD48G/KQPD32sgtJ vci/dSKvPyxY601jRKNuA/LQ03a7e2hPiAZLWPQqRQUms6VALZyIA9L5y8jP4wxwV7 O+XD4vvvKldAUaErm99zXSSYqGHqSfxaJm+IqSE2EyH5k/x7lOfsO7Gdrk0RwSzZXs UZB3fpr7e5dFB5csBMAGxrOWgFIN4xCvRqYtAUB2d6YvLLzFf1UgIPk0KrpdD0lUdG 7FqY3nKH27GTg== 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 v9 13/29] rust: alloc: remove extension of std's `Box` Date: Fri, 4 Oct 2024 17:41:17 +0200 Message-ID: <20241004154149.93856-14-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 5BA6314001B X-Stat-Signature: te4657a751jsab5scrbm8s8suhehdo3z X-Rspam-User: X-HE-Tag: 1728056597-654842 X-HE-Meta: U2FsdGVkX1+a9TQtVybx+DW8EaRIJy5S6Lofzi8p0KJIbXdML6sFu82AkJIV+Y8jI5w4mklFcWN4OuZqTFAeOk4+0CtWBBDmqnwD0r3VUB7o0xMM93ImK/dd8VL8pE0ZviQ1x2CScMaZ5ZprMyiG72sJFI+/5KaQw3OD+fYCB1Btle0iwn+iCJPp/+6DyOhOjHhNS7tjNRIr+aTfICEETh8wO7h98rjujgc2xFOMmZmqg2cGmXMPuCrXlf9KRkMzUUHeuUeJAj86Vb9O82rD25+vRTusjbzjMMjU5nT19JByTXxAfzegd2pnRJJsGcjz4QXXZiKOSmrz1MR1FM7s203C2tUAXUHTdEygnXCH37tvGgk/YYMQSNtRQQh8jJ3yVzX9coOIk4ePPU/qlwTuyB1oumKGOTc5wPGElmxanBnxF1I3MUgHa0rp8S7VxlsYy4Z3hZXjdkp9CPUgQfNwatthvdVPabcRT8020Y1yYH20azRvYrm78SFP/Q3T7QLANE2+WZbw/MZO0RY65NMHb47SuE2zdBU8SNnzDCMJSdjfJ7nE5n7JdIXIUNEnZjRiRIIFsAw2QZueK6I3vE/xodyRua48/VZeF2H4FqMCVnCGr631uUkC1Wv1XA8gDUfdxzmgSzM7yPWyg+BgzcJ2igZlWcI15W/ZxnSOjTA8pHlJuPIU2OKmZRs4UBIJNCGDsgMZJS3cKOA0Gfdqv4/YKdBJwkRntv4+QeJoqu9MsietPrOVAZN5PBByuQ/PVh+AGQ8pLD14wtvwt/EEvZflYBIP3ZBTVaaeBHS+OqNHUMiidVXcN/GqfcH8abjYZntL9+wITLINIqKBfOBny182/iYaKDbvL2/qps2y4fjNy5qHD7gsSxAMOHdMoUCyA240Ahjk2JyD/7k7stzk4x9zH1nFzAxvcvh50+pu8oGBDDvn9dsOdppcrlfC1P9G7XqgQ9rANLTYqbqBODEsxk5 tudvzKud pUsjn985fIWySKkXLmf2fGZLPsGacI5H2c0JKkWpGmE1iPQtvBr42F20/Oy5wb8GcfOZgTpO6rJuzlvPm0Qa7bJA1Ut3nJXFJ9xsBvfFeD2qd+IAjnPrP00MzDYKJFZ0/GfwsR0Y5wLwJgKAWy0Pb/66YZDgapjCxV8ftBKVEecSKZl47vgzM5c1TxtuIYVi4inodvPCRJU2MZLIQodZ9Mjf7WSk/zpd24259FBeFMJpNTOOxkqNT9rcdRSslhRzDmESnDZ2N5rWNTxUUNLJYEDWrSd3efPZfM5dZ5qQHUIcz13EHid396PlgGWQ1R1OSuEKkYMoc0+Z/PgB+ixm34IUaz/xFgLJ4EIHDxKRjBm2yAqmnwiS+R899Jgm47+YWb36m 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 c889f2640b56..c9919ba0b683 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, @@ -588,7 +587,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1245,26 +1243,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; @@ -1301,28 +1279,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 d59639e36db5..c9fb478f03b2 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -16,7 +16,6 @@ #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] #![feature(lint_reasons)] -#![feature(new_uninit)] #![feature(unsize)] // Ensure conditional compilation based on the kernel configuration works; 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 28d9e5ea3df4..f567494d4e54 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 Fri Oct 4 15:41:18 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822625 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 D8CD4CF884B for ; Fri, 4 Oct 2024 15:43:26 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5B4956B0204; Fri, 4 Oct 2024 11:43:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5151C8D0003; Fri, 4 Oct 2024 11:43:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3426F6B0209; Fri, 4 Oct 2024 11:43:26 -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 139426B0204 for ; Fri, 4 Oct 2024 11:43:26 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id C7B9B1C6CC5 for ; Fri, 4 Oct 2024 15:43:25 +0000 (UTC) X-FDA: 82636339170.02.CC27340 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf12.hostedemail.com (Postfix) with ESMTP id 463AE40012 for ; Fri, 4 Oct 2024 15:43:24 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RAX5Fxuo; spf=pass (imf12.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=1728056537; a=rsa-sha256; cv=none; b=iFAAzNUj2W+E61sOVWRK+Yvrcclz8vu3m2F5vF/EX8xrHtTBKGpYiBCY2h1yxUQ3I/eO8L /Ce5UErWlkIIxqsmAu2lfopqiftQO3O7k4bwVFxkWnM6KWx/5RmzDEd15s++mMi4q4ic8I EVq6CIHXmeoH4elv/2iE6zLxzqV/3RM= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RAX5Fxuo; spf=pass (imf12.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=1728056537; 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=WSmHIApohYb7KxIZ9sLzer5t+mAW/c1s7riaLqsLXAj3cK+MSF6VyysEXhpjdkcPELP3MZ SwTtAeoYHngJGXRD8Y/bJtLmcuH1gBhFiWmBK2cW4mssCR4GyXK7ioKyGZlMBCTUHgnKo3 /zjFyWKc/99NsyuPwz6oYZNubWnF3sM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 0B0415C5EE5; Fri, 4 Oct 2024 15:43:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A84BBC4CED1; Fri, 4 Oct 2024 15:43:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056601; bh=83eAnIr1D5O9vSM1uHBUzB+eFQ2uxXd/+rUZl+c6k2o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RAX5FxuocB81c4eS/xKda7a1vgBAAor7uSqS3MWtBwA7kw+xQ3UyS2nA03SKUGH+Q pLhGAhPALTKoIQleAVL6AR3hqdHJEbrttt9mfwcZoRRbnLsIcq88/xrOL+IzCR8kPo YoNd6gYwsTQek/s0Z3T91AK3r9l/HO1hxOshZy3AsZJV5ba1DNcxjoEs1hit3lWLa+ ELkhPNrbPYlJQwcYLil7DckqarR2yCx59JC0TBqlq5eFefw8zweVV+nq8t2aQy1syn gBBaFWaEfo3J/eWy1zAi5mY80aDTblQfk8AXC2fYIo4PGhj7rGBd0WvvcBTMP2kCB2 uwabeVJOIAXxw== 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 v9 14/29] rust: alloc: add `Box` to prelude Date: Fri, 4 Oct 2024 17:41:18 +0200 Message-ID: <20241004154149.93856-15-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: nmbcd49nt5uuigq4k9urjck6j3zpkxbm X-Rspamd-Queue-Id: 463AE40012 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1728056604-669896 X-HE-Meta: U2FsdGVkX196pCvzW6lat7/l0Johz2TGNrZqOa1vDS/+xtuQNCO6ua7B+h9y1LPPY85I7Jke+rg0/4GBON5bveJ6lrKOkRxyOhrnF0cU94fN8GVft1X/fVTgTMPmblXJaHlOKw++Xu9+w4M0jNuKRE7ufEiV57izfo2ROgE4aaoA3xmyIyIvHVCwQ9DE3C9z7slmiFSGKyw3SCY9fEs6CwI2mgTcM4j3RM4+Hmpit5cBa902mgUKk4wRL4p4ne1imtqRKgtjTcmCgVtJMb7n7dET9DdpYHxynMnSgEKGuQ1C553flGJaAwKx0jgh7+PrRYhodH0YIea3RyGYS7NbGeSK/OnWH38AIUr02dpxw5V3BCy9bO6/wqsk6v4GgMzfqXFSu5yo6kNlpbcij5rYgvmc6Sl8tsEIiU5sllP9n9krCcrk5U61fPEr3VVxhXDqQf56Xlneiwy9iphWf7q2UdbTmFpm9jZmRKGsysbbowPdpDWaQvixXTJdeRzD/VqzipngB8ih93zBvVXhpCnQatW6MrUO3XgtKdR8RNrfo5qnZ0JKyD67qZfL6yNR17BZLu3C6BukvHxVX9gOAQlep0DN13uIJjdbbXdQ0d6AN9IrARVtrmwBm/+eHTc3TjFrqsoDycZqeE+cik/PIX/PJAH9UXD3Lf4VIaJATFe9CRnJAH5YtIbMgig6+lDWct8yuKXKcmVtgTdgOX7dVDXFM2bOlMGFnz+2cqf+R1Oq5IFGghUrI+k1uZJQ59ptvNfl1+NUjSlLfh3rIz9FraFsMLsx4kjOe+wmkcS6FMA3JX3SduC5Ol32naEDNiS+6/VCzQS/fiMKyS88jw/9EwBwFAf5g+zGo3TlZSxubuXpbS1qH/W7QKgujSe0LWA3TyXGUhA082V9/YBqQrDTeH9TPCZtIaU+zu6IAUriI7WeGnX8qtiPDWvbixQa6MDbbIfvOJXUrKuHIUly5FBMhH5 Gxrx6U1x 62J61UmvsubLj/0hvjmIovh7T9GVZyZRS6sRGP4/8XQx5u6M3G4r2/i+XRp3pjYY7FA5FqmU6kxF97dKHatIBD/+4PLrvgeT2UolhcVsED9F4gMHhP6fXkYZreDZteGTGXrHsk3FJXUD1r4/tJCvH2O1b8iT1hzgrN688Oz6DjbdiWQQGZeokM8Uqhxumt90RaLhi1mrTN8w7KjnFHJUuMV8x1n6DqIe60OEfsMsSUXg8y1yZT+hqMo683qO7KAm+i7k7j2rdsnexU0xIhBQOrmXGQ6fujirUHsVBylgl16eUS2DwLq7Ljy+1CUNetgn4KUe5zwdS2SGKdA8s4PETtgasqiHP1kSggjdSayDZRCvqen9bFjAosUDDi4O2i58RXcrU 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 Fri Oct 4 15:41:19 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822626 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 AFBB0CF8849 for ; Fri, 4 Oct 2024 15:43:30 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 343146B0209; Fri, 4 Oct 2024 11:43:30 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 2CBFB8D0003; Fri, 4 Oct 2024 11:43:30 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 11F6F6B020B; Fri, 4 Oct 2024 11:43:30 -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 E2AD36B0209 for ; Fri, 4 Oct 2024 11:43:29 -0400 (EDT) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id ACA4D1A19A0 for ; Fri, 4 Oct 2024 15:43:29 +0000 (UTC) X-FDA: 82636339338.13.6D856FB Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf11.hostedemail.com (Postfix) with ESMTP id 195ED4001A for ; Fri, 4 Oct 2024 15:43:27 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mM3Uexz0; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf11.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=1728056511; a=rsa-sha256; cv=none; b=ubpAOqVJDrFFgXwZgQFUYcSL9l/vU8f7uU3Jcme7ygGMm2NEvsm+BUXrlhLe4wHXhXOMic UzUH7ptm2DdyoAtYT8sjgEVioj3WUsp619TKOx08OAYAwClrtalPa6ULyLcBUGVqNnMi7+ 6Vi61bjqx2TyIKg/sbXNIY1wgjYzV+s= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mM3Uexz0; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf11.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=1728056511; 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=rfJQZ8IAzrBqzZr2bhLVn+f/o+Ju2bukwEf4wCpSnsY=; b=DVRNcbD0kcxnp5E+zy5HClXmsXBgvTJJxcNlZlbLmR+PuElWOKjcWI2YqAsJWPPSGKoDZL nePrZfOlG5yiQfKIT2XnoC/YPrRnVIIQN0X5yVR+vKD8LotQKyUAwG3Qea2gLKqhkQJU7q /TRlnOQHNeBil1sVUJ5w3ZAaz4Fu6uE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 01A6DA44BF9; Fri, 4 Oct 2024 15:43:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 18E9FC4CEC6; Fri, 4 Oct 2024 15:43:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056607; bh=Q+ML1ibWYAYZGeFhUyhzJzIY+ZOBQOky3D240qlJo4Y=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mM3Uexz0BDtA61JTp90r4hhfmffR8zBUbDJS9Gck2GzwPkQJWdqGF2kXRaGcmrWMN 4Y8NSqhOW8sicnvOmy7Ak7+p+pdc6kyeteR2Cbv7utjnJkv7Gyl0gCgA3FSJbUhGz9 kORuqJ0DrEuV9XfjA6LDLbtV/iZ1GKQO4h4zfXR4goB+P+w/rg5I0gqUDQAoVLsLnw cercRS/hZcyU4baHwPeYm3rhtRMVvDUZZrXbG1O8+gULiTC2ecYEGj18pizpQ1g7qQ kSFtD72R8ROVqH7OsEpN3dXlKW13qg6430qMwWMIZ+nEeZEQvAcEz4dylkb/jGbzWs 5j4auh5MnXLQA== 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 v9 15/29] rust: alloc: introduce `ArrayLayout` Date: Fri, 4 Oct 2024 17:41:19 +0200 Message-ID: <20241004154149.93856-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 195ED4001A X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: pg54kkr53acs16uqx8pidg7qsx91y7bt X-HE-Tag: 1728056607-700792 X-HE-Meta: U2FsdGVkX194wkOiCT+jAs6UB+OrjNREMyVO+/JU8kQ98kHoak9eiBZw0tHdjhI1LmDGlw6AGtNoMQXcUKjEsoLPYp7AriymcZHWoVzz20K5c4DrOepnjxAoT/s1v5x0dU3D70EWntdhMtO+ffmqzGyN7z4G6zG++z2N9ADnZa0t0Eax/jeIHTZ19CiBWVm9CBivNsgMiu5G1nnZ8qK7jEXChH5FhZcxgov8m5TlnxMeDoYnau9n2fM4wASTVCFxpW0RQkIwcqfg0ep9mlLGb0wrcDwwQjSrkJrfnR5GXFa1cg2FVw6kaZklNihKyf9ETHNze+gEo5ICO1LbSjCOZQugaF77q+B5f6QvrcOKpTP6orR8Le5HfYcqz5lDpLxZRGAcfs0a71PVu8oCvCBHs9C6OuXZFFkqrC1SfC3bGoXcONgsIlzD2HIxlMsyOdpKPTU9dEa9i8P/7nUeW4Zz0VV01r/rqkg+3rozN2JrwqelOgkg+6erPguQe48rS1IIXU75C9/JhvmHLW4QCKwr2jC0e6+sm1HOJgMtvHfRANT+AynOPSOMW48X6Nkaoslk9CP5xV6APQzFHU/j0HYfCtgBf8xgW72iRkee6Q+yZGsnqsO/jj9FFQUksW18tuUrJOdwnpuj9+CDMIeC6ZY8QcQYII/N8s6PhmGjm9GvB6a67AnynsDtMXk3tWJwIW/gmWuI/v/d570ud7VXPMG3bjHnLIrhYSzPafXzGHoY9TlRMLytaY3u9glEzF+kKnfJdJPJNbHrkS6vR1OPAvRR3OrGMG1Lx5q1ffpGG0DEI/L8SemNKae6ysAEcCP72GwkZuBKQ8n0kWNDEokgf4THAcr8KLX0UXSaUSbcm3vLRa0Z3xBGxq6YIKY8DUQPC7e8JYmsxWYoKzZwsgthe9Hwgrki9oZKg08hqIqEGkAm+1B+PByVhXcqmkFjW5TiCuV+hmB0ZgyjH8xppHVQzJi UswrMOIh ypO46ksqaIxO7fPIQQUJdoDbnbCoG4YWt3bFPOl6bDXNPRZRwZbFJALJcq8GqweDOG30lwXBFkhZo7OU7Jw2PdSW/v5u2sCa/exjzQyy8MImbp8/nKy246/SG1jhe/UsJ9LZKNmkMhvI+/Ndw1GE1sCwQKQNMzRyROJAWYDzNlDgCN1dodR89AoruDW9m5/AsPGTotR67l4Hc7aICQpoRNZKWu9TYScQDI6KfMeILqfUw/ORLBqRgbscKLjVj0jbP7o5bP2PPIL03MZ/0MbrFK4fE1otnixfpuTEjgLBhGNcyYlnheBycGbHvS7kE7qet7jytQmWWs0E3ffObG/Yq4tKZ/w1Gzcav32Orz+lEHybBFNM= 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. Reviewed-by: Gary Guo Signed-off-by: Benno Lossin Signed-off-by: Danilo Krummrich --- 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..7f0427a4d3d8 --- /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(core::mem::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 Fri Oct 4 15:41:20 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822627 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 90724CF884B for ; Fri, 4 Oct 2024 15:43:36 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 231856B0088; Fri, 4 Oct 2024 11:43:36 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 1BB246B0089; Fri, 4 Oct 2024 11:43:36 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id ED9EE8E0001; Fri, 4 Oct 2024 11:43:35 -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 C191F8D0003 for ; Fri, 4 Oct 2024 11:43:35 -0400 (EDT) Received: from smtpin18.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 6E54D121A85 for ; Fri, 4 Oct 2024 15:43:35 +0000 (UTC) X-FDA: 82636339590.18.CCCA1E9 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf09.hostedemail.com (Postfix) with ESMTP id C43EA140023 for ; Fri, 4 Oct 2024 15:43:33 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=UBhbEufK; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf09.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=1728056573; a=rsa-sha256; cv=none; b=qnnb+jDXzr3Ej2gZFrStMjeWrHJ2tCmwMDeiqCwUSkZHLWaapvHSbQxvJdAQ3vLdg02lqr CQJh0EAPSszxUUZY/soy2fCZFgM0Z22brqU1ewPv72ko+GQfnzMPhzpl7Gi1h14CyFtiwl zrNRlf0o/ayQnkhqsCnE3YX7D5o3KKU= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=UBhbEufK; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf09.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=1728056573; 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=fCFoZeZpep5TXV2s6LFNmJ8fJeDzgTzpaU6I78gsKPk=; b=gVqTV1zzirIoWgCT49hZbqWM/EBfqxXdYOzBVAnfzc1aN+q5SGA1NXBd3RSxHzgSLPnbY8 0RQV7+ncPIyFrPKc+GAt5NuWJxSX/SZm/HH+od41maBHCsYRDrATN9VCpc2vRaXYzvYnQ5 zTd0RgL1m22THmCia3jcOd/g8rU9M9s= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 7078BA44BEC; Fri, 4 Oct 2024 15:43:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 84324C4CED1; Fri, 4 Oct 2024 15:43:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056612; bh=urUND/M4698IVjZumaKDfSVmB/eKfMiMjzbdlOGJcEY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=UBhbEufKcxuCRY00KyIbVslslxEMIsPk9WUsIs783OrEc0mZ18t20DCCioLwVd1CR 1UfTUeTTIUP9ShwsQ1d0sNBf/KCN+Rpnp+XQO33XJXDfKl1p+xscG4TmrESRWPDaOs JeWwYHnhGA5YhAQq20eXafHKYRzFyPBANORhWwpaT3MZvyf+6k7Mmj+PC0+8d/9vot x3lNwP0/1k2vNG1CKBomy3RqW7liDAYigkC1beVZ+EqPRy6RbMqFgldSl0q7A5djNa yilRx8s7MuFSciJUyH/m/yxjvMfjwN0sfLHB9gaPHgNBOTuL08qmT6VFlccK3Bd8Ot MtvXCVnihQyxQ== 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 v9 16/29] rust: alloc: implement kernel `Vec` type Date: Fri, 4 Oct 2024 17:41:20 +0200 Message-ID: <20241004154149.93856-17-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: C43EA140023 X-Rspamd-Server: rspam01 X-Stat-Signature: 338szfb73fr6yq3cnhabyncfp6bujcyf X-HE-Tag: 1728056613-555850 X-HE-Meta: U2FsdGVkX184soTZVDmwMUlGBtvW5zFAvDP/kzdC507TMMAKtsCteSDtTGOBZpWjIcNh+Du3bOLoXIp2guNV1TVvTzsiwG8BWrm5rHsrUeMi70uldzjtab6VAGj0LLK4fuMzHEh/uw3i1QYBFVbo5DPG81qlyOA8zVf/Blq1zcpT6LszCWQgd39Ph/EWWn3kQ9fNmKBgDZNw7dw/wplEW/zYugqAYfGbluXIMQYPBGllMuCnHBPK2VC+lzLQE9InQF563LvgciHSk8UrnDqxwAZrBntpuqoprVFWdrRhKkqBECFyajBiulDs4Qt1Mp3wOaVYxX47bcyl3/XnTzCVSvGHgEr1dVQFuebaHctDjQKxj9KHBlPqdGe0EYFt8xZGduYMrZm/nYJngyl8dGC1jmdwKGAhuO0PzNAcz24+vje4xbeWjA3VuLgafVrokFQqqoUV16krdJ9Qm0CRII17rhazx4eimzjq4M2Ss7yBS2x8xZLrWzgFtC5xJqZV6UmZLNJIbGrK8IVFy5jH4pB/2BBWgrOK3Wi7FncLRDaaTcHDx76HkRBzFdPIBvv3hm3caxtO0cNf+XGSc3lvJtmwiT88AsZ7j2wKuNDfFfBpy2Ad+yysgPTUxb5L0mk0fdZGprw+ny5l8wX6hrNbdmy6ed4X7t+DMPbE3mlyyXDAwrJLftzwf/g+yKxB/L3rP+69+hJdBzuER4Vrf1LJHO3Yg/s7aRQ/UimWQovJKIFWRRVr6rRlz59IUBP4uVblxKaJKcyTyz+f9EIAI+v4SeMBFKup2NhoDtY0g0cl2s0X4kjCtqzR1uDNIrE7EmJhKfmH/e/7O9WfQZxTamPQNK1mU4jWJGl9EAHSZhr7n6FVpY5r04OBqksqESYVhAymCHuWw8WZ9setxNXnmW6nZeHh4+Y3nzB6GidVGTaTr8+U38dHjUfat8iAsvUK6k08F0sortEelCK85vS6BjFo4JD iF+Ce2mG A+ctP/I+a/P3PMIcA7YD6ctqOzsMl9O08jWhmrdhyOT5LSdADggP9ECtBN22VMTlGdzX/hQeLomeuBe+jQQlKu2hQSh/cuG97GC4q2or+zc1xObABuOcxgs4vxq6q1C8hEsYWznoa9weIgPIn9GVXySP5CISQGvv8DSKh8r3FDhvx7EbfWlpQwNv6l/U3klTq82gTfwnl6a3H/k1T6s/Yoam+yyDHd0t36v6EHkkBfoDvPnkrDHyJ85U8Hf8TwYaNNDE05JDbEUZ8Ro+bJL7DjoD99mmnrMk6oNBIVq8EJdjnUQwxFeuVGYc2r0I5TL8L1iN0w5vXl5r6jnMHgn4v6JPF+px/hi22j+aic4zfpVLskPc= 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. Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kvec.rs | 650 ++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + rust/kernel/prelude.rs | 2 +- 4 files changed, 658 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..d41353b7653d --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,650 @@ +// 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. +/// +/// New memory is allocated with `GFP_KERNEL`. +/// +/// # 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. For ZSTs `self.layout`'s capacity is zero. 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 { + // INVARIANT: Since this is a new, empty `Vec` with no backing memory yet, + // - `ptr` is a properly aligned dangling pointer for type `T`, + // - `layout` is an empty `ArrayLayout` (zero capacity) + // - `len` is zero, since no elements can be or have been stored, + // - `A` is always valid. + 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) } + }; + + // INVARIANT: For ZSTs, we store an empty `ArrayLayout`, all other type invariants are + // covered by the safety requirements of this function. + 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, + )? + }; + + // INVARIANT: + // - `layout` is some `ArrayLayout::`, + // - `ptr` has been created by `A::realloc` from `layout`. + 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/lib.rs b/rust/kernel/lib.rs index c9fb478f03b2..01f40729810b 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -17,6 +17,7 @@ #![feature(dispatch_from_dyn)] #![feature(lint_reasons)] #![feature(unsize)] +#![feature(inline_const)] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. 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 Fri Oct 4 15:41:21 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822628 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 C4292CF8849 for ; Fri, 4 Oct 2024 15:43:41 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4F1EA8D0008; Fri, 4 Oct 2024 11:43:41 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 479B28D0003; Fri, 4 Oct 2024 11:43:41 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 31A438D0008; Fri, 4 Oct 2024 11:43:41 -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 12E6B8D0003 for ; Fri, 4 Oct 2024 11:43:41 -0400 (EDT) Received: from smtpin04.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id C7EDF8172F for ; Fri, 4 Oct 2024 15:43:40 +0000 (UTC) X-FDA: 82636339800.04.CF9BBEC Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf21.hostedemail.com (Postfix) with ESMTP id 27E091C001F for ; Fri, 4 Oct 2024 15:43:38 +0000 (UTC) Authentication-Results: imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fRSbsK68; spf=pass (imf21.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=1728056552; a=rsa-sha256; cv=none; b=cd6gzKVoBXvWmMaV0EUkg/oBD8ZAYmig3e7JhAyZbvl6uf8HzimiJi0K8ygt8dCywlqW+l /JJxpQ5yquQQV+XFrPhAIo6drEg5UYyPfzUX4y69xGmyQD8kt+EiUAZvDXaJoZAU4DHPhu sAsepV2+uMS8E1VlUoX1x0myvqIRnGU= ARC-Authentication-Results: i=1; imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fRSbsK68; spf=pass (imf21.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=1728056552; 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=zrsUQ5pwUz/vazzPp45FlAvaa5wnBJGNPbE2OH5ymJc=; b=G4pQ0vjq1rnzGfTwBK5rbFw04RrmRPTh47VplNkR4v+ht/nK+f/irbV6UQVOPVbhoCzOXt R/cjg5GMhTD9Gn7KfcIdW4SZ2s2BxHOD8ZbbBn8ZPiMyxG5jbAr09MpGhNc7cvI0BhJnhE IWuN0Rb/PEvcLJaSk//rrFxJxvbw/+U= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 39BD15C5DBF; Fri, 4 Oct 2024 15:43:34 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E9DECC4CEC6; Fri, 4 Oct 2024 15:43:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056617; bh=2sSsIzdACzoPnqvUhervrAOknVeczgrx1816hyZSkw4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fRSbsK68TywYDweAzJmxnLHP52gywwuHTd3U0HBB6jz5L0XkmeuGK4tHtivRhzfHJ jA/tut0+mI3ZgS9I32hAcnIeJrDvWZXp5isJ+RWfbfvPkN32+uBawoWrYL5nou+Blx zdERRBRrfBllOMd5yv5grsEB8zrKexPjR5CqqIyHs7l2pwgJoe+dj7z+IHiIckZ4B7 3qmwiwXJ/Wztcs0M/fjlblqz/vkLqkD+leaiAjL8U625qPXa6hk8QJWo+9ZwzMPSuj CGPuU/nWAZqCth6223YP+dYTee+RT/rQb7ZPVKcaijxzCLHRAkVEolLhArocmgLuTg Fc9D2RN9mHdVA== 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 v9 17/29] rust: alloc: implement `IntoIterator` for `Vec` Date: Fri, 4 Oct 2024 17:41:21 +0200 Message-ID: <20241004154149.93856-18-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: ghgjfz7p4afiuawfwcjq4k5bb67h7acz X-Rspamd-Queue-Id: 27E091C001F X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1728056618-267329 X-HE-Meta: U2FsdGVkX1/gHIVsvHC6rOuwFFuywknb7/1RCklmJ33ImKQgudlO0VkLOCSKwl/FUms0Ml/35UzQfYU1DGofF2oJZGiBIWQyHa/Ssc1E1WWKWrPTLQ0v1FEvlKIInibDPdaqB69X0YMZ8yizTLr/QmLqiCZc3hvWAI48+EBsEBlGQCa/urAx3zXYgd7vtk6ibFUKfl91+/PiMqOEzE1Etmqw3Ye2oBNe0NB31/uD0+CVXPrbOXGwkGvkTD39r1+70TGqIJPSm4XVy07IS6pLa8D/VIJULMvGBOpAxHiVRhbFccEuTHY6GWxFK0HQJIZ93HYFDTu6jwMNifAUlkTBD8fKlRd/1JRTeyDI45MvpQ9K6/Fb9vaDCooIVhM0P7hB6yKc842S76TfF+Vlex9A5kjrVy6S8RQs1okxRq5dzp8kNF9LNxJ2L8HJgI7/KwoJXK+LUYHrsfniTmPTUEV1DazxaFUwm+9I2M4rFQ51Zb9NssuQjc6K3M+3hOiR9QJYpTkjUWlMCEJ4xjlpUO2yMgCqrAR6G6PrYQ8mevPTE9/0zGI3b4Hcqx1JHBvU1MTIYQKmntfUWaC6KBc1C+wGfIcjLIUJlMr+3QO6jab1cRcLs8u3g5ZV7+llo07AhJn/dyypoQPiBm/d3sTfV2nySeSxy2rR97J1yN4x1lvt8qY1Q8QqeKawD8NOmG/IlFDUqbc5g8saDaav+/CCxOSSW6cN8fKG5+78vBGPGGtYWICMA5d5fqZexTTZaG81YhFfXXhf7SkZamvgiriKq9LXKRy3OMXimyugGeefA/pGnATd/o6nxViPQ54jG2VkJ0y19gdXNCFeSetq+7iYY5lZp9hkrNmGw72BwVls2e1KVgAQE4Gz50cBN1yx53hVRmmQh+s0WFta2Fqr/9N+XL4c4E7wMVo8pMyxXwOoCdEFu6DkQVFfKLXCTjkR/KDxYAdVmRgavtlsCCsLddLqmg7 6bEEcBBp 1H0EC0n0OrHzAoEHy93R2re6qaYnLFrXZULvzVQF3bvU4dHeDEUUiTUy12ZMezG8rfqJ2LxEJ5IGdftO6H+b3H6x4h5UfnlG7uOfa5U7aRP3laFh69/yWgnObUn57DNmAG4m6ADW9dni9wXzARiAXJMsM5CeRozexh9RBxr+6G5REvUhzXRu1gPHZHAbFIdfnn2Jtgf6z2NC3yw3oMbrpgvgSvwaA7j3QHlgJrUnMVuKAUldOuZPDs/NK42F+FFkxRY2Kx825fpq0v1D4u1/bMuNBiMyVR2yjSPJAfnrzOOs6tOs4sU+neAhdG/ZfLr7ausSTB+PpcFX45kwuQlQA2NZZhpHCYgjb5QrsaWmiKJN2ZbtwrjOMsedlwZj5jNPytD+j 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 d41353b7653d..86382827f576 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -648,3 +648,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 Fri Oct 4 15:41:22 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822629 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 7C82CCF884B for ; Fri, 4 Oct 2024 15:43:50 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 120C16B0096; Fri, 4 Oct 2024 11:43:50 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0826D6B0098; Fri, 4 Oct 2024 11:43:50 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E3E406B00A2; Fri, 4 Oct 2024 11:43:49 -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 C26526B0096 for ; Fri, 4 Oct 2024 11:43:49 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 7B952C10AD for ; Fri, 4 Oct 2024 15:43:49 +0000 (UTC) X-FDA: 82636340178.06.1AFA0F2 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf07.hostedemail.com (Postfix) with ESMTP id D4D9240010 for ; Fri, 4 Oct 2024 15:43:47 +0000 (UTC) Authentication-Results: imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qHqXPqqt; spf=pass (imf07.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=1728056587; 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=SaaR12E+gQuJeSgI5+LDALCaKYVQL5s+x2o4IDO480I=; b=1w/NbdABDxs5xR4+ob7FUSagVLaD90HNtG5h+cMTa4uKGD2q5C1Ig+JpvvFKTNbbRPrOGT zyeORXaO+U4G9HtxkbnbbzCFmHmVzx2etuZEXjaWoqI1DaI4osFDfMvC+vkhzlqk/OcqR9 5Z3H+xRUsCcq1mf1K6O3iYytzacwWgc= ARC-Authentication-Results: i=1; imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qHqXPqqt; spf=pass (imf07.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=1728056587; a=rsa-sha256; cv=none; b=M8WL+QzkUwswhsyMYqKh/Mr3xw72H7AJZxEWe47dmDjH3TOK3DoX0G4+ZZ9osMoHMA5NNz haxj0JvWRfBwbxpKlAidTD/wsHHB1PKM8GxNRKaznfpfkd4CAAvsqNdOHskZ9ohM6rTNkX HVvIc+mkndq+EN4g7WQi3ao8AfJRbhM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id DADAF5C5EB3; Fri, 4 Oct 2024 15:43:40 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 56752C4CECE; Fri, 4 Oct 2024 15:43:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056623; bh=AaRhWJzhXeNmb7koJrUIhcIZp+NJ7YnTtkDq/65dn0w=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qHqXPqqtK505FnU3TTT6/Ji6dpr2PBjGmIlIN7KTNr7b/n8nmzyALSiHSoiLUQoNb KtUvqcut7lfST4w7g9rLwKr9uH386s/XGHuPMY2lMezaoM/i4dPAolBGABBTcYq/hk uDdhPGfUf8SR858gmtd9UZlfuO3ndAZchUHfRPwFdZwQk5LoRnsBB1xcrrGre3MkD8 gaYPhS97lcGwbRYMOC6v+jXUJ5WydyEO/G0w69lm2Xx9WcRshRlUVHLnRS8moapyaA YnuBVVZiJT+mwr1eLbJM/5tuGkT/xjhcDrKa38LRZxLVzsEouk1asvDeB6WXKelqZ2 brqZEsq6FxgXw== 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 v9 18/29] rust: alloc: implement `collect` for `IntoIter` Date: Fri, 4 Oct 2024 17:41:22 +0200 Message-ID: <20241004154149.93856-19-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: tq6y8ce356fatwbi8fio6qhb15xkyiiq X-Rspamd-Queue-Id: D4D9240010 X-Rspamd-Server: rspam11 X-HE-Tag: 1728056627-361367 X-HE-Meta: U2FsdGVkX185S+fOb5q7f/gMn5SJ4Enp7D1zNwpv3PPDiHODqc3D6nUAcCi9JtRW0/CG8Cj1S0uvJHokUIhcQXyLq+y2b9XEZbjNWlNM0rqQB773fSrQr48+enPv0pLQa/LFDQH6U7xXkflVZLdJDY2FrokKa4dr1Al9ZTFad1g7bG4oYb94mScuHe/RVsq/TyK/YxZOJ+hP08H5tYwxvQ1Igcb9OcPVBnIjd3WR3eY33/HwpIaDD6jmQXWzN8q7wpT7GSy33fIMlXCSN567fstrGY0jZ6dkN9TCVwviEjjzw/IVgVe78Crbqrbmny7xPKKe1uzDd67anGFTIMnrTSZdunMlSnEwBGxIqG5k0CpMCaKwR8tuGbrWrrxkMZUziaVO1Tt3DI8c4BqbCGhkWArqDoqQn14cWis3aHhBiKCCx8qq7VGdEwUvyPLHAUejLZQIrBb2/cSGlfYThxIQarhmFGr3UUI3ms9m/PqznqN9hgZBI/w8YfjdLNko9hZxbfRvkfMPhHeV95A33XuPJa2y9vzZQxbZsvGP8iq1zx7mTNgHc92tSn4xq0KuoPmjeMSreiU56EmhfsFfLnp4EaVYpgRR6DoRPB5n7/ft5iQB1pvrDLaTkGQfPSAE1Jqne/T1jUPMB8rri0nLvFJdrLCmzIJh/fq6i9PMpvSy5nZtKjan8LWIXsrvqJlVdf8ael5oCkYqEozyNhemdGfMCm0QOpbYaKVLopcDvEnt3sZORxKgvXIfjwXIDJfEovnflwhVyzYvH7I8GpjWcOhNOckHOfnFXrXfUcaz2ObEdaceqcNnqLP41hz1OKQcSq2wCBjmDysuGZ8iv9Pb8EqI4eYQjzhrhx2NouIk0tNTNr3BeQ8h4K+BO6NnNQvh6vVlq43aC/VF2pm9TKEVkIAhy3xkNNYBdeqEa/JxQOzcobyqluVHhDgwvcBu+sg+zAfABWVigsdJ2pcycWZCVEc cSc/SsuY eQ2opFN6LMQA9x3BGGPQF4PmV+dfHiHroO6mMRoIcnyZHEPIr2OhdOQw8J+YJqi46zaZlwaSYLGnnCWgPkJ74Ul8esNdRkCHz97OGhzMQswOsTo9GdCFEkqSFojjEikRie1Vpv8iu98WZ4CsN2qAxrciG/x7Rgnl/nnx0PUdNXwQlfXgXWC5wLadyTQSkey7UH6+sYV7PiJBOFMMZoGtqPtQ16otXsgnvV9eT6H7V1Zuz+VnkT0voKAaya7fyPNqHjvl9wgbf3H4+bXhEuXkRQWZaaQkH8ZX7knEtHUDy8AT/c3XfCXygplfGOA/B4ECiDfcuOJ8Pd+2/f08= 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 86382827f576..119b5a4dbf77 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -694,6 +694,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 Fri Oct 4 15:41:23 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822630 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 8E3DBCF8849 for ; Fri, 4 Oct 2024 15:43:53 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 010B26B0098; Fri, 4 Oct 2024 11:43:53 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id ED9FB6B00B8; Fri, 4 Oct 2024 11:43:52 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D534F6B00C3; Fri, 4 Oct 2024 11:43:52 -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 B348A6B0098 for ; Fri, 4 Oct 2024 11:43:52 -0400 (EDT) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 41402410FC for ; Fri, 4 Oct 2024 15:43:52 +0000 (UTC) X-FDA: 82636340304.05.5797563 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf25.hostedemail.com (Postfix) with ESMTP id 8EC10A001D for ; Fri, 4 Oct 2024 15:43:50 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=PB6q1555; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf25.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=1728056607; a=rsa-sha256; cv=none; b=ghBhQr5uwsWcbQoBsUg3x5lf54Ce/00D3raUNbEp3exwW4Vk/UzwPr64x8z5+sT8LX8yIU /WAkyzl3z2MpTZUvJUzIU1l8Tde4WYPm9clmZkfsFNG/TWAOs/PkwQt6yw3xlqnQuICYdr +7VEQfDnSXrqxoMEWYJMkrnLFc3cV7g= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=PB6q1555; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf25.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=1728056607; 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=R5wbbA+JMXwhnkLrkpSjvWCmUBJwpyeDM6nMwjhb5dM=; b=tkeKVkQA92pRHtO/cNcg8ANWibioQnx56fjBqo8GnzEGgnietXbZ47GoVJTDmgZgVFJ9JZ geCUYsD04QrIH/fVKACppEdTmYdLCmWRIgyfTUCci80fESWo6qBI8CLJpouZHIy57v8Twg QWtmVOaG1GE/tQxbHpOZ6wHSsYN4RMU= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 0A45A5C5EB7; Fri, 4 Oct 2024 15:43:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BBDE7C4CEC7; Fri, 4 Oct 2024 15:43:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056628; bh=X/Is4V205f6dqcKBfBpL0xDEX/xfJQD4IPyW6qzXB1A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=PB6q1555s6lkEk59Szp9aC/Xt1Y+gF8vd8klrAs1++eyPrEsFCqzYFDQitAQlo8Kk j64FUARo1KpIdN9UO0vAxPH1DWO224hAptzgZN9vgpJ1gNwHSiwOVbNe57Mswryi+/ ffnZOuw96WvWU+hN4o3GQI2/L8rXWTzN6kkwiQ4rjkKhH6VAV9mIzMaQG29nhBATPx XYFWpRjvc588kQqqac/P4wDrICCA4DNVRsjkjWU7/d1UkVdB3fykoGljTDJiEPKYQ6 N9WUr7aTSolBX59wQNlhqAr9lz3zIUu7p3LGU0RD67SqLSVjtSY8FBX16xoOKk4kFh 8XAi7qjDlV+Hw== 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 v9 19/29] rust: treewide: switch to the kernel `Vec` type Date: Fri, 4 Oct 2024 17:41:23 +0200 Message-ID: <20241004154149.93856-20-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: wa3enbwhb4t7onssqro6ce3tazy75hx7 X-Rspamd-Queue-Id: 8EC10A001D X-Rspamd-Server: rspam02 X-HE-Tag: 1728056630-120333 X-HE-Meta: U2FsdGVkX1/LgiyGJ2gaJrUSb8kg4dZK+I7bwvsbd0wpqH0CX0zRZYc6TP9HaxcCkpy73aRXt8XY5dFsl5q40+V8Gky6micPA1vVRahAKcUHn4+CBmKC6xJISMPsmFjEuocRHc+nT89QXU3eCFfZukGRqx+X43D+l/8rtZSALqoGggtFaajdujmO39JGhhjS8PyvtmZ4qLnUN4wxUiwf0AbhEtPeNsokqoRhaGh3bFnJbe6rDNNTPfMT2Ylb5kDZ5uk7yGMXjm2ZNc04d/bCutpLT4d/j1lhedtSQb1hFaMMT/pDJZjoyw91lSAvUpXZGPZVFoNjTquGeRja8CTOxLzPWWYaFS8rlkUy3DSShHaCcmnyn6oxmE3lFbSZjhSUsZjavD88tPJZF5b5zEEKNNzdHeZtg9A9+ozgNYmTUAvNk6NRZ0/HaVitMyuEbgBQDwXO3uzvab+zbKhX8IqmbqW3DzVyeVLK9h93aMggLMk7nBbBRIlSp+B+f8YYKNi5r3Eh6TXnZl5mGJ2u/Dzm5s0PGgzkE86mzdUaXcP/zG47WCQQ8MynncLRXoMEXk3GFbWGb+OcLDG/H6tP9XTzyqEctJdgIXRVO9+oEJWWCsQjLjltMDVBNwOAvIlzzXa3wofOEa/52XyuQeSGuTR1QHfZpigOMj0D4Drt4JqIDV7qkVdkMVhWwzWHXgAxmxbJct2qxqDWAmno2s9bmaJHuRpSN+oFTG5UfsQVSQ19pegf7cKsOAfieCLsOsTy3KH2euPPx/gPcWIvcgm9qn7g1IW2LaY0BxVBXd/ZLaNkvHomXvWSzS6T6IRtq5fMUMzQI8Lem7psY04Yusgll81zmwfc14yXXudFGRe9YRLyIXyB7fRBlknZOxdgkpsCSUoIwuT7g2/VBcmHR32U+1pr76ohkfVRxwf3GgeyYMbrY3yiHtQjvO0IGDCIbkXwcSV3HIEMD68EcrkrPds+g7b JVVj9/y6 co1yiaIHNd9IPpUMb88mUuHX1kzXLyI0XIziEQAhovRTO/2EwCGxn/rcCDKSX3DfoEL65XtQwwERdKDyowuPbXtcIT2lBaE3z8yR5aWdB3ZUU/TNKsjVkoK26hsJjrgwulV8qBBv2LBw8/q81g2hfbKcOLnDhPYK4d95HuomGhY9D1pR9tOVbUlMTMaEOJGHCt457EEIfA7I2of71+5xTk9nluaim8IdGri2VCN3sFrUCvnvv56a6Qc5qB1icL6DUw+QOX59AHlIWWZPS4mWV/341bmCwC1hyyppiXs4UeWLN1lzFfi7gY0TE4lNj1TNIR89SjREXfoBOvQaQm035TDRZVmMO95V2cdtxfpkN3yr2tMN6NepTootiMzVH1jX7zDM0 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 66d4527f6c6f..6053bc7a98d1 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}; @@ -791,7 +790,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 { @@ -804,7 +803,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)?; @@ -851,10 +850,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 f567494d4e54..40e39161fd7a 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 Fri Oct 4 15:41:24 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822631 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 37B6BCF884B for ; Fri, 4 Oct 2024 15:43:59 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BA8526B00F2; Fri, 4 Oct 2024 11:43:58 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id B322C6B00FE; Fri, 4 Oct 2024 11:43:58 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9AA586B00FF; Fri, 4 Oct 2024 11:43:58 -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 75F2F6B00F2 for ; Fri, 4 Oct 2024 11:43:58 -0400 (EDT) Received: from smtpin22.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 2BBD01C6BE7 for ; Fri, 4 Oct 2024 15:43:58 +0000 (UTC) X-FDA: 82636340556.22.E88CFF9 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf06.hostedemail.com (Postfix) with ESMTP id 5BD61180014 for ; Fri, 4 Oct 2024 15:43:56 +0000 (UTC) Authentication-Results: imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Eoyarmk2; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf06.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=1728056540; a=rsa-sha256; cv=none; b=6+93JcTX5WyDzqjKaRZCTEVbe0rs+clHYqr08WJsIfue+FixYbFt7L/YZ/Bi+OHbpoQ7YK gFMRJyv0/EjUQenPdrUA0bw8NqMRIzbpgFP9WaRpAPA7HB+vZ2ouOZSEOxwYXiyK5Bqr+b YRrsdyocxls8PWvnmB38Q+argAX3OPk= ARC-Authentication-Results: i=1; imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Eoyarmk2; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf06.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=1728056540; 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=eXywVDQqUoJh+jrjGxVCUXxWKywT+4KbbxBrexmrT6xQ1kt4ZCEL8bNJ3nBRLbLeUqk27T 0f4F9wK0lVV3ad6XUzt1ozz2GidrfkUcnUOUSxJexVXAnzXqrJG7+qQLwtTgGiQrP607kj 0mws+NQbq+ft8L/VQROY79YzfwYmpPs= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 20DFA5C5DBF; Fri, 4 Oct 2024 15:43:51 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4F8FEC4CEC6; Fri, 4 Oct 2024 15:43:49 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056634; bh=IBiqOJrVjNjDKaz5y8ARXywOWvCMKwjrfiOMMbLXtzM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Eoyarmk2KG+SUowJp1Ym3nmczdQguqMr0OdYG7jPc+BocVKELOy8LxEfTgsE0tCkr vQFSiX5Al0/2nZGX+YX/CN2ALD6iKOcaMI+jhF/QaqftyRR3HgtKeGIa66ouPwtc9l xj8JDKWOH+votd53/VlKzJkOFMBTM0uIIqIl/SJQZphZ4WYMTg8O12Uv6gfc/96l0U 61hS72Nae9c1eBYKHK89CtolEehenOPW9u6JhYWCIZKD0mRbEPTzWf6mI7SWxAN6no sEJq5k938MgzzxC465odYDYyPopbvfh1vYZXbO3wEBq9QCvpvpVtvIJIziKW2cTq5J uEsB/gO7OfdZg== 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 v9 20/29] rust: alloc: remove `VecExt` extension Date: Fri, 4 Oct 2024 17:41:24 +0200 Message-ID: <20241004154149.93856-21-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 5BD61180014 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: w7t8ctwjw3irk1ee5nd8974b6x8km7nh X-HE-Tag: 1728056636-435250 X-HE-Meta: U2FsdGVkX19MpIjH9+sMMZUXRC7hEqpcOiTPP3z3XMyFRxXPhAfyN8OFkwxceWmzQwyhXb7tBgHTC+Tgiv0Vf2qkx9sfHHofVZO+aSfta6VGTOxYEqqBpyDpF53HSVzl0BEQjUF0LqazfPiuKLUoPtpja1RFIuTyEaG6tG+bCLOX7NG/RuVfGhR7Py1MzUMPp4wvGY8lsP5ZsdiBUjqpvHQJ3XYoPx/jDO4JW/4Z5T4M1Ufu0rY/6lpkAhezYNEniE1w/y4RwheUu3o3ypZo1TcAvdOH4I5J+/E4lIbkJqaWXHceVLDZkwKI3baET+n5YDT0ctKkY/NxtilcrI720GYLkf3QNgyM1qy9ZocUMJ0qzUOvjAqVQspsIQgezhv/Kd8QgEDLe7ZmFojBOGoLyEHFYWYKXPKD459tYzwv/ar83fewK8+1fyl/8HR1T6X/76fvb18yEeArIn1QL4M+Bd5CJWWKtMU0Nx9nynbhoCYhyq0eaGzo7gNo668RcfyMqPCFUuLgGS+HPOOzANeCxb+7b5VNAG6liaX5893IERr5jLUIt8Uaonbej1rV9/xJsXRKVQ3FX95y8S0xQqIklf4xzT46k3zyea5CM+Iatxr/uvbsz04e75nfRWFR3iAGssIDvR8vExXGDLY5sCCre4CD0sm/u8nGAZFK5A937OwVc6cGjSU9a5NNZ3FHScWP8hZ4YwLlplGd0tnT34dW2wFgeKoxxHvWO9+n8qIj/HaJ3xKGdpowl3WMqGyLJbQl61+n5EuD0O/ehX9+GzuDqu+gOOPGmunZLh+lJRJrtsvW4r1xCfxmjYbItsUL36vVTJtwGWKawf8GXnk9cEOkF04Q5VTx21uQJOKvlJUKLD8clizGrUsl6DUAX0Sxt0U+EZPI/ej6oYil1Sv7blKHA3WYqgajIGWSRaYtDXm9DEGUvQvJhWBdxGWZepA0sdLlXWMnmGQwScq/ff2E44a jJr5BPsX 0E8PHGz7fRiaECQJADHOAj+ZAdBneWk6/iMVFOuFhHlEwGYmzvA0mIkuSJCwfGXuINjaNIEuursuSFQhHqCR+260g3mFdLU4tY5Tk+DAo8g4DZ/1NfrXpeMK6ftZzHVUiX01UyReghY031r/JbzWScV5YsFivTxo5dXt9At1CElsemgjMklPhhhu3shw3Vf8GuZO75PSTGjr+nWKMFJp6uQMSahUEc3diWuFOSbDZpzYI9wU2VR3HmMIFybqZzwuxG1KUPMl1S4+YVDKFOMuRRws6G3Mli0I6xMUS/DvwyvvKlZ0ouQrTaU2w16Yl5ljRFWsLOrIJ/nKI3iYrtwJ+/4ugP7zkc3KOS4Vj/WjW09EHvLX0umVlHApvjjPgNIUDdk5E 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 Fri Oct 4 15:41:25 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822632 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 CBF6FCF884B for ; Fri, 4 Oct 2024 15:44:06 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 569FE6B0134; Fri, 4 Oct 2024 11:44:06 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 4EE8A6B0135; Fri, 4 Oct 2024 11:44:06 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3413D6B0136; Fri, 4 Oct 2024 11:44:06 -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 134486B0134 for ; Fri, 4 Oct 2024 11:44:06 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id C28D01209B8 for ; Fri, 4 Oct 2024 15:44:05 +0000 (UTC) X-FDA: 82636340850.10.CCAB63F Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf24.hostedemail.com (Postfix) with ESMTP id 2BAE3180021 for ; Fri, 4 Oct 2024 15:44:03 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=naxFRuUs; spf=pass (imf24.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=1728056513; 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=1sR5NCGsLJsI0oa09B/8LmaiLCW32F5gtFl9bK7SbrU2VOlbBk2CojCBRl92FJTM0q4RC9 ndAnqOQIcrVX5TX1Eh6jhVugoigvX1o1AOI4gbdj/lMETVqk+2wrP+jmJgtFDBCJ5upsqt i97BAA37EeLk9DmeQY5HgiWMFQ0B9v0= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056513; a=rsa-sha256; cv=none; b=lm6EMynesfW6voffhB+C1kxW5n7/noJ2KAcAUnH2k2VYcULXb+EIxCD8uTGiUoNxVGGldv 2ju6RDeBN7p4JMy/IbDnomoYxFbUGJkjW/a94LEC0uadzvcP0XJLeDQEEJ/WPdS3n5xW7Z On2Xba5EnQpfZfK/rmPdqXYdjifDHEc= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=naxFRuUs; spf=pass (imf24.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 E81515C5EB7; Fri, 4 Oct 2024 15:43:57 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 12092C4CED4; Fri, 4 Oct 2024 15:43:54 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056640; bh=ZNs0Dj/ExXP/FTdJ3MujwXiT4/A3eVE5pzPxpi0CaOY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=naxFRuUsVrevYd57QkeZy71i1FomL2fbRGU99i6Eh4OdJhiBcD++cCd7C4lZZ6t6l J13m9IC9seV1XcxefMzLNy6XnqX5JtRiasb1Lxflmkb359reiUagWZUxFke+M9Jhag rITOiBJu/rhFJ+UBXkRFf4Jy900Sw2dU/yYly44Pgh1bm1fJ0h/fmvBTYHcIg69vA7 oCDZqjN6iNov7iYvNUiLF3rgYhcXkRdzrVLT3i0o2jI3oyohGXhXO5VzVo/Ggq+eCU jdOl5SBpFNmasg7O04LxeChbme/vLh8PcoLmClEUB6EZwAvt1gI1+VeBQFe4prdEn/ GtHC+mUKMSV1A== 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 v9 21/29] rust: alloc: add `Vec` to prelude Date: Fri, 4 Oct 2024 17:41:25 +0200 Message-ID: <20241004154149.93856-22-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: ehfuu4y3z38ktqpi8dwhcs1nsegoeazq X-Rspamd-Queue-Id: 2BAE3180021 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1728056643-108862 X-HE-Meta: U2FsdGVkX1+7IpXJXemLAR2CeCvQ3b6YFlBt16reSx+9iapERBdQuXME3ackcMAP29viUfJ77EYnn6muKwQa3+zAPnC3uWPmmELWhgo8AVjhCJ7KkMxaP0/amo07bxE849KG+78IeYDzEF2+K70BqYg4eKs51UoAI/8DtzE0nDyFo2QEFB9SHQ15y/CiwMykh8ScU5z4FlgkVlxOZ/h9FCognXClsRrwza5NJsX+IwVwAohmGB7SWHW0JXwkCM794EibJhy7UQ9GOykyQf2LXRZUuFs80ixsCmA2nUZqNSuF21j1amHBPvUsTyXDoL6z9YWP1llsPhpU09sLvKQvGunJCHUYtZQIKUwBTrAC6atKHbgDiJsIC9aWIGKvX4kNncpqSmGiXazcdvPF9Lm1flrEI9Y9TGmmQcNTfmH54i7eHy1lQXAKYCEhfily3w3pZSzMdNatf2p0mpYwtYxlU6hi36M1Tn3N9pgXbMVk267gi/IESJKRcIJ+9xRJ5eRMqGdkwWzhYjrhjExyRySM6dGbPzFkN8DsTA0kIDDCeaS4NJZpEjonuBTxQAxTOKzgzHYuUA/wGAxmJERgFuUOEVRTmNy8O1KwJHShrq57HuptlyM2R7cR+G9Zj6+AgKbXmQ7EAAimJF7nN5oNsYsRbeB9iFokLgbm49TGCcQPV+anbQ543D5J1lueiOLyoYwXmtIOgX2I70pkRL1eYWl1lKh9//UbjNpdC3dNImE2HqZjXQkdqAZmntxxbLIVzz5n5giVLCnb/hnsf4utfqpJd9jU6AN9vrF+Sf+mpqaLo9SKddqaQvj50mH2HslUO9P+kdFqXWOoW9OdbX/qZr6Tc6yagKlLDiVnIypaLsHKMjRusC4onOkXw+iqDEgAnyDRX2qYHKvureIeh/Vb8Da6EhZrthGAYxjckqHZ1xgU28rmdS1BNrIMYcdfgu1ZY4oIZIVgR/pQ08qLmH1DG0e LgClBFY0 caZlB2w1Acka/sd0SjofQIZ6ACSB6XgNgpFrQBGVsBUiPgpfHFiY8EScP25AjXUiJXKYsiNtKKA8FXT9FdAFLH1U2I2UiS14sYSk9q11Eo4iBk2mCIy4PuFbbUQkGliRR4D52Tq3Oa+L7rom8SVlUXqv+94Kvr0toO9WvkIAzqMO6eiAk5oxhPXQnkoZiHwGfb5KSykirHRmrHLT3D7U7MkeK/buTLidgM4uN3X6M7MryS9+YIHn0pyKSg6SNRK5TwTV8c4ql4Jwxm3Jqd5yPNevUpzf6TP/RxG7lb1A6EUCNnUhmqkgq3vF2gamtC2n/jqFtbqravAgkDXSiyDZYEKa+C65Cdx5ieBFo6XRzjAPVdO+Oxhg9i3kpxQ+QA+D/qogv 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 Fri Oct 4 15:41:26 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822633 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 EEF9ACF884B for ; Fri, 4 Oct 2024 15:44:10 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 825116B020B; Fri, 4 Oct 2024 11:44:10 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 7B0246B020C; Fri, 4 Oct 2024 11:44:10 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 628846B020D; Fri, 4 Oct 2024 11:44:10 -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 424566B020B for ; Fri, 4 Oct 2024 11:44:10 -0400 (EDT) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id ED8D91C74B8 for ; Fri, 4 Oct 2024 15:44:09 +0000 (UTC) X-FDA: 82636341018.05.6E689DF Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf09.hostedemail.com (Postfix) with ESMTP id 544E1140004 for ; Fri, 4 Oct 2024 15:44:07 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=VtrLQqOW; spf=pass (imf09.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=1728056516; 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=zLSSiaHrGfKpcg9itzgMpGD7UQhnR7DW3SCMaaCjk4Q=; b=k/tayVJb1m26MnqPczykv6xnc4ZYH+RS8KMXMg/uHSAk4CHKiTYxEZJFj4uTOqV4S2Szcj /O23jW2IDnioWcPZp6E6atB+mGcpC/R8mSb30WFS+d+hfYz/yASzcaWURShMsqFbH6qwhP CyhEr4zqJfoiByVrqjGYtNI6dLPXyP4= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056516; a=rsa-sha256; cv=none; b=SBs5Ob8JzHPwfajZ/o2nG+ZPFevYQFWC+Zhp2bVDCTF87zp51KAtUWVrZdGz29qcifYAkK hu8PcpjxhYrQ04PFuvY1QYoJ7GJKyP7AvWlg/HVrPxh13C8bUpcIvalFVpORcPN++JguyY 2LhMwefY9jhamLzx5Q8h82w/8ZDEAQM= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=VtrLQqOW; spf=pass (imf09.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 55F4EA44BEC; Fri, 4 Oct 2024 15:43:58 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DD494C4CEC6; Fri, 4 Oct 2024 15:44:00 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056646; bh=qja4/b6sVnAwfQIKsU5lFy64XWyVYKZfs5Hg8rSPng8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=VtrLQqOWPhsua2MiiwHzfBRPtDZBUM4nukUln7OZcH+uO8VGfzl9qTUcUMQ8O8sHx /ZQ5pQgnEhXA9wmaNudiiSJoWSZOzdV/+hTQzbtIStWz7jbFltFtR+/T8VpzqtMh4Z 7QdhrRnqgG6sQDDwPVnGcLPxpGi3oDjR3OJ7ZYZIt13f6QS5wu2uMEWRqKhPucUtZn tRGYA0j1FyATkN+gUk6kfxXg9ZfLOHlGinUq2UQGUNDm6zqb9P5qFkgTvECWlClxXK 6Us3ipus/DIagEIP8Gb5Lx2uB2nRZSnjTNhIBJmwB/LNx8kmOFSUz7C5ONTyktziYJ bX6v3bR1AVziA== 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 v9 22/29] rust: error: use `core::alloc::LayoutError` Date: Fri, 4 Oct 2024 17:41:26 +0200 Message-ID: <20241004154149.93856-23-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 544E1140004 X-Stat-Signature: j393t1tco67otcdh5wbgzstp76gge38p X-HE-Tag: 1728056647-820884 X-HE-Meta: U2FsdGVkX18X7lbKmEKhTzaJKsPJxPZvt3ewHYhYBTwewE4dtt9aba3NX6LsQBn5JrKY5Dos4e5F2ZtHhrbdEm5SspFhPYQ70CvJyrOnwo7mtN5PEAYTC+fOOD4FqdYcy9ceeB2ikYzpBtAdyyNjDmIN9+PIQkBsn+21WdGbZgYeByaEMaFohSTx2t1At7TcjldQOZDWGm4MejvhaRsAVPTUJVDJs2er9TDW9f/qjdDw9zD/iJb1OWXit8L5WZufNlTYqroJixVnd7uovInSiv4nosYOJdfJ3spMhebOC/fHZH6iKDOPEYbox+YBTD70uNj7hKl3dFwGkr6asupnhz/rJ98M6Cxxcx6Ej1vFH0vWM663+33h1HdN3xehDe9q+reYB5ZXlCZCj7THSP8BIFvrH1jmQQ2rRFjX5jgqAMdtQj4m0rPah/H2zmhy8j5sprzbYxukQvI4AbeIJDWqboxh+1MSlQelrGSJz/usACiTDOB6oL2ywZvjp4/Eh0jG3r3jjpbf54BLKaHsmwv9HPSH6hqQ+etJ0ayi1P0O0WmXMJO98wH5R6RScNMLqvXczYcLOHfYtCr1OHMAtBZznRVzhdyV9UKRpMHipvZZZNne6ck/NH0T3hnNP17ZQw+ADix4NUzS5B0loBXjwuMAb7k9yr7NR4S8NPgG0b2cxQ3uNrDhPEFsIenuzBtcUgVe4MINpzupuwAVLSXh3vhT7wBLo/lTp6JJpD81Tctj9AFSdCc+jFesDjdluqgu8nXZJBfYk57J61ixYRNqfKkTX4N8zppaa8MQtNY+a6xiTM4OPhZ/Xq1lMZmWumvEPNYx12UEx1OOZHAgBW5XAoLJeJoRSGsebbLBaqOcIaM0ERvkdbhEufcakT5TNk/BIdu+AZCmK7L9nu31Mf1oZi+2QF7EaE/YA5DNP/iwfsdseI1B71eviWf7VYguYjCORpDayfGLd9GpgxJjgt1lxiu SVSvmRW6 0H919Vae7TmD8A9n0EC2SM3Twp3qD72XQRbU8cRpyM/zn7gA0e8Wzi+vbj+N6wgPt0mL8yD3J0UaRe7gc5U7eG3eDgzEX2zOezWIgOS4EoJTA9aYHVtaVu1mQyQvM1EUypMFQqQpL4r+9DriI4CCvxIF9NlwME/Xd3uProcRje9YOmSiIAuRf3tyGND8U0FokOzaw3ONKWVDeq+ab1j6FPuamDqhzDzcfe46MWWZXVjpZv0QlVe9Zh53MAiyjJOGczbHkI0WsgtaUDgBAgfdpq3iYoGaTSxRmnDC3Mcu6kKpIW/z3XQ01fG1kbhrDoLum/40abvhPbNA0WAE4kvx8luWYtdB4cOmw2KEb0R5JFh01Bor9mphhYFVr6urs4Au4oDW6 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 2f1e4b783bfb..ca957bd262df 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 Fri Oct 4 15:41:27 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822634 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 4A177CF8849 for ; Fri, 4 Oct 2024 15:44:16 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id CE0C86B024A; Fri, 4 Oct 2024 11:44:15 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C68BD6B024B; Fri, 4 Oct 2024 11:44:15 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AE3476B024C; Fri, 4 Oct 2024 11:44:15 -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 8D5476B024A for ; Fri, 4 Oct 2024 11:44:15 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 482AF120F6F for ; Fri, 4 Oct 2024 15:44:15 +0000 (UTC) X-FDA: 82636341270.08.E4CE948 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf23.hostedemail.com (Postfix) with ESMTP id AC55F14000E for ; Fri, 4 Oct 2024 15:44:13 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HPfYaikd; 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=1728056480; 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=rvuxmdAa0A06Kpb9ppECcGQiLr3jw00IXuf8wnagVf8=; b=3UZPFypRmg+/2PpAG9jd5YLsIkudZhbHtrz941nfs8pgCkORkA+/hvaWPBDGNon+0JB5AH nczKr2KOnqiYIWfrjrbuJvYLgTo6pwF88+NyqG15KDWP3tEN8VBObLMBamDZkDMeEzBTtX VKKmMMvvzx5NA/e1uiQqftCyqWddGZE= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HPfYaikd; 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=1728056480; a=rsa-sha256; cv=none; b=Uv4RCX5L3l368d96AOJr0KDJAHzJCuWZ1WZCV93MQz5ExbXYnXwkwKaT7Abc1mQj3sJbdR qQue59Y5tRiudtt2O6/VRwFf+xNemuHgkG773MC9swSXNDFcKf3yW99QVfpYjEE70PIp80 B0/8No3S0oJ61dU4ygkbou2t2uMSAcM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 7819FA44C00; Fri, 4 Oct 2024 15:44:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DFC5DC4CECF; Fri, 4 Oct 2024 15:44:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056652; bh=VajjPpTKjd92I7r04pL25dRwn4WQWZ1yOCCgBSYIXyw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HPfYaikd0L/Vx+JqKeDTWx4hMoyf5HUOadWTknz+gONqrexWgDlw1ZuDMy1brwY88 GtyfW1b2JKLCI1bQN6crBsF7amgUYsB1MNPSbPzIToO8N7xZ1iB+tvWogaPb/pis6E 7scY361XwbntTfDE+WcJS9wSd62G0hKmXzmkaiwFcfelOZfj16trTfEETlcaW6nxSt pi2ABhYIO9QggEAtYzZheUDGuPHsVMqacsseRUGKmHuUhUtOIwS4Vh+jS+0AujyAo+ JR8dVh76tKj5pcblkzaTkc2uvj6D97PC3eLEf5hAmjPyZjlN9YJTXlwMcQQvmjWyMf P/hOEN+8Mty6Q== 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 v9 23/29] rust: error: check for config `test` in `Error::name` Date: Fri, 4 Oct 2024 17:41:27 +0200 Message-ID: <20241004154149.93856-24-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: AC55F14000E X-Stat-Signature: 818aud76achf94zxz6gx7o7om8w1q116 X-Rspam-User: X-HE-Tag: 1728056653-456820 X-HE-Meta: U2FsdGVkX1+wdQ/XLpfhhMAyqy9t5ST1mxqHhZhDzTSoPbhFV9HJmBU8Tm5eq1zCpCo26/QpgV2F93QmhUwMLoqqgjlIwtLynOhPU7XXbqh5unc9cwFPCYPhFlXHGmV99vwJ4kbKqyhEJhRBLpb0ABl9TdcdFTOP6AeWluGasy5e2hOVZRQ2fU+zBUznvdrp7H18n/nHqNYGBcdYxpO5+nFKvO+S486C+Bp0fmjKCQEL4eiQjBkkUlBGeAURoF6XhAkDBiJdmuZ7OjBWn3UugRZ5EvWivbYDI67GtVSsdTtKpkHOJ4ztMEt38tqzo5IL+pzCr1bQcHXfFgpMC+t/Qa5QL/sRrpuSJovNUBsGkeMiIkJItOm+v/NV9Zu5B7PwRO39eTcYEPnWTaX/ESRzEQRpVMPWb94W0Ks4CkgT8MMUo3rFSvZehX7lg/nR9PLiISteAuBNGOoK6RRBfyGlQbiB0aYUYqsSMh2d8T+1qARGUTGcQHMRbi/bB7b3q8ZbDmdrIrLfC2hvdj72thhSsvNkTtgb1ZTzYcxEA8X8ZnJNOSZttZH3sLStMlsMBQQnDEUqmli9Uj98usu3S3WvisBMarNjsLk/meuUw2oZM3Gyf5Apa+tElly+HRALPp9v0O8MzrXJCHx0B1ZLTaP95qIL9LvdpT9sW0jpdJjk7tBZS8FvfxKdlcq6n2+/hzOccnWpWydQuPHYNmDNWuxPzkjkGbirlyeZINXmk519OEWq4lzwid/VywlnXpLZ12nHZdRV4kPqvEZ4mUgkTC65gEC0RSeqYaqAw6YhZ/FALADpjOEPXS/iCYfPN8cqm2Jk4LQ5NNT4lu3b/T+b90ZigoxCfoU412Svo0N4ZLgHHVq1KATaxQiFle532BL1pA6UUzik5GxuoqlbhTjmbZcOwNyJNbhjxGBssidsbkNdF6FTQN3SrKDzlScgRxXNIoNhh0YDeReNVGVbpyC1aaX GNAAE78X CZ1B4/X2ryU88+vy6jrMKJtjJo5Z29aZUiH9B0Z29unwjPB5bRKZL0gFFdBuZ3OQKvulHoG48UuqDOZ+uDWPoAYWr3ieWW3dK/I0nbKO9VTSRs4KiRY3QV0K+IvB//MI5neelgHnhkwgQi9KQ509LmQypxeDyCdI9g4wbMfZJ9oQR9qA7aYSa60/GwD4ezmjXvSOiE2GhIkNQb6B3juSSvEunLY0xYZjoeFMVdZRJOu4ecKO2o9ggzokQFj2VjbVvzRcLuPUij83exslevmf1bD01MHQ0iliBKNZ2b245R1WwHSDlr1zmQ6aaAJn/jSPwRpnaKeu2Tb2kF6/LE7BtkIAL3xl4zZu1UvHS/AVvk361hPOM8bBDVxJebbZWn2omPK9m 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 ca957bd262df..99d505cd5ae1 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -142,7 +142,7 @@ pub 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) }; @@ -159,7 +159,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 Fri Oct 4 15:41:28 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822635 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 E3F93CF884B for ; Fri, 4 Oct 2024 15:44:21 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6C63A6B0253; Fri, 4 Oct 2024 11:44:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 64F266B0255; Fri, 4 Oct 2024 11:44:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 4CB136B0254; Fri, 4 Oct 2024 11:44:21 -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 EDA8E6B0251 for ; Fri, 4 Oct 2024 11:44:20 -0400 (EDT) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id B7B81AD034 for ; Fri, 4 Oct 2024 15:44:20 +0000 (UTC) X-FDA: 82636341480.13.74D451D Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf18.hostedemail.com (Postfix) with ESMTP id 2BBCF1C001D for ; Fri, 4 Oct 2024 15:44:18 +0000 (UTC) Authentication-Results: imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="m/1oasy2"; spf=pass (imf18.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=1728056485; 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=6/bYlXUy97hm1pTw7ih2Bz886ECRdOtszOFuqpaSItYni0TLwtnHv9Vm76c5Q5XcJytCza CrkUNgUY+nIv0eaVsdm53ddprqWtpDb1vsQPWpycLyJStIH0b9eZpVkR8uOHprmeG8vI27 FUqoY5rLo0hGB2nXfQZsaGvZWGd7leY= ARC-Authentication-Results: i=1; imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="m/1oasy2"; spf=pass (imf18.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=1728056486; a=rsa-sha256; cv=none; b=mpXxCsvGKD7h1g7Ru4CLmpYiZYIFvziT8kqKfB2EPeGQOWtgNrQeRR/iss1uUEzwR3UX6q oksaZwlSTZOgQoLNGY4WvpxrLAzS/o1gRIuqqrQ7ltgwlfSKHi26CSd9rTNA8830qMxW5z XBO7cTepo3D+a8U46nK92p+zv7GzX1E= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id C99A3A44C02; Fri, 4 Oct 2024 15:44:09 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C6F94C4CED0; Fri, 4 Oct 2024 15:44:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056657; bh=ZDmHNLUIwFFHS+R3VBXXGD9KVgIi1Tkfsy4gCUrqKAQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=m/1oasy24Cg4tn73r5ay0ehOqtkvBqrOSpcYKK3cBYeqKnDuemnNCxap5ZpiTC1ky 8yY41UMuGwH4SHMAt8L9/bkl2mU0Ldiq36xAcZn9oRXdGrODP0ctZdz2E9s9RzL/As ffZt9RiMcsOvJtoIM59/Dxhh3g2xGB37pDSiyRQnGsBXXL8ov+s4SBV8+gpxYUo0aE I8sshYOkrsW+17NczK26zO1xu4nFjgyWR4HzbZCOm8vIG8kdCPsYnJ90J1n1p94kte OAwnDbfF9i/+9HC+bSZBHW12/Tlw88mUSlnfcwluRSpKXQYq2sSEFyJke/ZCPEY6ra 1PuZUwr/XS+1w== 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 v9 24/29] rust: alloc: implement `contains` for `Flags` Date: Fri, 4 Oct 2024 17:41:28 +0200 Message-ID: <20241004154149.93856-25-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 2BBCF1C001D X-Stat-Signature: o73jk4kubaagxhy6rsdbnn58uz1rec5c X-Rspam-User: X-HE-Tag: 1728056658-403323 X-HE-Meta: U2FsdGVkX1+WzMEdRvtVdOroyYstMHPwBaFXfSj6rUrW6yzP/Oo2Gn3p9pWJy0m3oEXvCv+0e3Jva5SY93PhW+w47sKGwjCVZYaOUCAfcMoWgqawi/YWFAj82dS8D5iGi9JMKQNPsKRL5bl4ddA1LwxoOfctcnkvezUvTREOqAwT8UUax9ENM/TvrdLFA2etTW7I0DmeCHgNX2rqRzIYyQoz4SFq83Xri4nMOpjyOVFpyW+oCgWZ5usuq6+V6zpptruAssihcboslj/fcrlwbwjF4NtXFU1F7dFny6EI0EQqhs0qgh56FRcRzVvJLS2SbwUkW2QQ2iixC9/+KGQiW1W063wwcNnTZjMGTFDBGXjpfuENpfKvC39dchIUyEueE2T6+TPN9CsJ6bjNrLMJGT2cgt7uNISs8AKfeJGJCUSqQWSxQFdN2ufTF3ocGCzaxfudGK5PU0WeM+fM5HLBt8Mdckz//5qLCyZM+vEHhYC6UOM6zrFSxtS4dCDFIg0ph//sZOpwy0qPawrrOgqvjPryEnBBkjd5oCKg2bvcchGGaH9Wzurwcq/KB6vDZbYe5EpKY1Qvu66lEgdq8Np983qaLTi9nJz/hf1qYlYpvFQiu0HO1nOCZidU6b9Nxc+lPMiEzN2wh7giOgZB75/RsW/SxX4AZysGM0jWmDtXWOmSbMnvZsu474i5kNx1UbV+jYs+/vtWM7ZcRkUPvJOL/1601hTJDZy8X1wnR9MClRJ75XdUpY8CzdFeBBS45Kn12WQDZ2P3YTLcjVbYrWJZrijbvsLs/rAqxp6xE1AC75yW2Gqd+DFgw+tBCjqPYLtyMU/QsXLr587yjzxfVryak2i1FxOA/W0CPH5TMTWtHa8zZJD3ELUi65vlByhoTh1QqX8jFKuaLz03ZViRBwg0npGfsfedmizDMNlEChCT2KpsRVlGZnErTnyTCcbPJLUWpSnKEAfe/r6o4lDrCRd YTqAZlsr M/U1O0uJZxGB7EmC7c7xqfOy1WXyZFZ/9m1PFvUrtUOvEs2Qmh13q36wvfXZDUvhlnN89w0N5AknZnE0fr9ZoPIE3KelAjcTlMFImyX5p6qaDe+wmRB/L9l5keZzIyNXJm7mwRWTvJcFnkxzx3L8ppnUWGMmEEz+Zn8h7qAHJ/TVQ1RNBtnSjJIHlGCYLDH68jjxCxNgnsaaIjb6YQW6hFlQopQcbHdfqtf8NtdJB9t4Zc/VCAkigmza3o+HRdiLcCxpJsbQrhjUfp8im+33MUpRod7ibdoxvt6DRcblC6zAo6UFxr4YaSwf68fh6Xo8YthiLgrONin6ppKs+bhNLVANXWKckkjAuPbHJBeII2n1z79xto6nD3gzzUwgwFBYWdL9I 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 Fri Oct 4 15:41:29 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822636 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 22C0CCF8849 for ; Fri, 4 Oct 2024 15:44:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A70986B0288; Fri, 4 Oct 2024 11:44:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 9F8486B028A; Fri, 4 Oct 2024 11:44:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 84A316B028B; Fri, 4 Oct 2024 11:44:26 -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 5FA386B0288 for ; Fri, 4 Oct 2024 11:44:26 -0400 (EDT) Received: from smtpin09.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 0F183AD01F for ; Fri, 4 Oct 2024 15:44:26 +0000 (UTC) X-FDA: 82636341732.09.8392CD2 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf02.hostedemail.com (Postfix) with ESMTP id 64ED28000E for ; Fri, 4 Oct 2024 15:44:24 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=isdAQEK+; spf=pass (imf02.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=1728056533; 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=gcf7tZTchPpa/lU6Zbk3oD92pRIDja+Eus09/GqFcYk=; b=xnRqJPRUS2xFqimV7lwEU2KK1HcSnzHr+Y3tYrc1vIJwy1TwVPnS6PYPkXz9wlm3iY9gjr q+DRIm7F5+uVQAPn7Bq6SR77KDQHuHSLPyPy6YjponhNGsg4Tt2HYZNAkXWierV1YlW2cL lQx7u1oyMtpqFSDA6JqdJ0jlnWI9LwI= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056533; a=rsa-sha256; cv=none; b=vmZbmMxl910lmNsXPKBCj6pQAlXlFRLZatgkhkar+CnBU8kHxX22tHEr2eADjk4SotT5G4 q2dcaemmw8lTGrjwmHZozSLBfq+AWKl9idjmoluQQwTXIPCQtnPfaN3frgCa1pjbx4Fs3/ gByu/a8Z3Jr5HOad8M/az5zNHe64gmA= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=isdAQEK+; spf=pass (imf02.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 692485C5EED; Fri, 4 Oct 2024 15:44:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5594AC4CEC6; Fri, 4 Oct 2024 15:44:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056663; bh=co+B+qJ8g94Julx8Nci+IYL+QVSNE672qLhlTjw/JNg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=isdAQEK+fyU9LQiPmikCYp+he+tsGnTfNWAcIIkeyh6V5XNcGEHFQYit/ZlRDcAa2 IOa1mMRJ6iOotZftnaTIpKf1+8I1A3Hg/20Da19AY13ysIGSwD2d6wdd9//ouP18cz y0vK4k+8CyjavjrnlM+d4IT9RtcikiE1zAT01ZjYBvp2LjtiMNLnYUBi+tMpu9okhH 5o0W0NG6ln3yvuNyu4svUcpGRnWXsdthSUKYBLl5LxTgriaBcAVdVYh1O90kT6E8zM 5+MyZjCtVE8HQAt0w4vXmUNmEaGCrcmgt79gmeSW+lbC0PhJyxa1jKO7Uuym76dtZO rkkHlrWKeoMAg== 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 v9 25/29] rust: alloc: implement `Cmalloc` in module allocator_test Date: Fri, 4 Oct 2024 17:41:29 +0200 Message-ID: <20241004154149.93856-26-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 64ED28000E X-Stat-Signature: nfyg17f7nrn98fpru81b6syj655qhg6y X-HE-Tag: 1728056664-357243 X-HE-Meta: U2FsdGVkX1+4MV21tClDiRa6B0hUoZhDloBo3PMK/Qenzjd0EKqbbP/ew0DjnjKQk325hL450JIf7aU5EYJvpuUefxOua7j9omcOp+J+Qm17eYSAMmxZIq8IRAxfcDlwOU4oL5wDylDMAoWcL5ja5W9LHCP2Q1w1+YwY0XnvAz83TVer6TvtN4Qdg6BSaNp3b2jyfAZPdQx+xeoIYMKfDMf69nbeJu/rsCfyIE+f6t/+//JnHg7qR1Q00VJQw3tRFCzy4rYmyPdBQ8OY/g7KakMeBn2uL09OUD4RpzQimfA4TcQ2R/WAIkwgoK8AjvkCn1d70Y9fLCv4rtyNEnLfL9x3GjARe9AkUEzElCJGFwyzKXiBBYVMkiuX66QpKsCEcwJQUdbBss5vy0mRg6eRg+CtnFYFUQa+3EKOWZI0t4M/mc7L2EOMz3EfqVS2wjS2RypZJzFkwHpLsZL6FRJQci2aILXtUlUmzBYdEIz8BG1Kf7LKdsc6bPYFeCd20RGA7hn+nnjfZwsy600lCRrdoOiG5TS/nArdc7XvByirj81VoyIgMpozlnrc32sW+TRokrSzFnOiW4yZXO7ItaETNKni+y8G0Pw02X9h29zoaY70L487KWUpEAlnKqx/WeQg+4Jht70ke6N6E7yZqBTGXjPJTN3ZfTN0abERX4PjPRa3k8zGNO01nGTbYMsuZ9BVQrcj73zaGEcBpoRdzXF7ZnWdWO2IrdD46yh6WrM/8koHgSn1qStdXaD+R7xAfYtFdA2VCtkV4Dn7TACVN8L4ghQMgE+3wfq7Cqi8YSeXzMezBLw3m2J6FVTgWe9/W7ZLcZmTogIoTQP8prWhUpLj4JNQ9LHw6WWAD593n7UpTNspqlxYbGxhSxXSGMc3kwlPLrXSeeA0DFjdmHxPlRakDH4W7vm6hFWLnQZUOKTc8yMQJB3MtHfluC9W8rieIUeCPdlmNgz+YohscFx0ztg yU7nlNdL 3E9kBffZxkLDfrt7S8IC7vGGOVSodrhIuz2j5wnw3PtiJwLZ6jIivyhi6NWkuMswl+WDL2Y1Qg1qNjyBCK0n3yfxDOAVG7KEb5D2d5j7++oK4KGo44OtsDcZltNV5x6Yh+XA5KLMDwP+jqxm3u67Y9uFsdzxmglvuTWpb0etw5YAuCqLDgiNSk6zFA5NMM+1S0O8JzPAcUHB8jxN+lML88MCAIljMkbMB4+ePKzIbbXzkTMobRiXx7vTEJPN5qqBzbi0U5FPHJjRZesF3JRj0zf8EJyy/pHhKwjmVYBTAWBSKXrjvfKVE9MjX0m1DXFlJ5+g6p1hPOIlIWgPpj+Ook4w53CBSYKxDBiyi5xc9rdGBXQv8Ay4bP3+TsBrogdCOIe0I+sjUgTVS1x/OWmQMfPtT0SE6AyCAPk51 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. Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- 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 Fri Oct 4 15:41:30 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822637 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 70541CF8849 for ; Fri, 4 Oct 2024 15:44:32 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id F039E8D0009; Fri, 4 Oct 2024 11:44:31 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E8C9D8D0003; Fri, 4 Oct 2024 11:44:31 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CE0D68D0009; Fri, 4 Oct 2024 11:44:31 -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 A726E8D0003 for ; Fri, 4 Oct 2024 11:44:31 -0400 (EDT) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 6D8524197E for ; Fri, 4 Oct 2024 15:44:31 +0000 (UTC) X-FDA: 82636341942.13.2619571 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id C75E040023 for ; Fri, 4 Oct 2024 15:44:29 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fnNeEXxR; spf=pass (imf01.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=1728056538; 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=ASRYhw9Dg3IAmGN8c5WgCpAoZPW6j+dg/YVKcwHcBmk=; b=xHWvJFbBjAyAGWTcFGjFiWTqJkqmCjhYgPOVett1bcuwp/CHn8ANiZAvZ1qt7VfwXNVdJt ebQej2XqB1YTgcgsQltXYU9AV/GJkNyJjmt0t7fkTGEkTHaD+aV1odQedqn3b9MM6oSNLL VDcJ1bvKdoiD+SYn9y0qItwKbYRcEyM= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056538; a=rsa-sha256; cv=none; b=aCCGSuBrNVMVVxJ2DO/SMht3gOOiv7jfyZ13ZBbp3iUoPzZl6d9daMkPL1IvLKQDg3zVrH 6chscM4apax7V5ohSeZXp3pH9eJhVO5G7SozhOZ+W+3BPG2DGwwucfOSf+8stOvcjd8DPn vI0MXPLNaypAh1WICa1y630E7MvDcm0= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fnNeEXxR; spf=pass (imf01.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 D7FA25C5F07; Fri, 4 Oct 2024 15:44:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B8C23C4CEC7; Fri, 4 Oct 2024 15:44:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056668; bh=+flMXZQfIhSSa3rmdG7sm/b2ESf50jZzxj0uBuhzVdQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fnNeEXxR7mvP92yIfBbZLKQgeMPUx20LLtjjEtRpZbG5b21h9I1Q266YhULU7we5G nIKnt7Ig2nVe5gPYYo/WacZZO+8P/BkpLtAFIfmf5m6S5lMNkXsZJ4yTPSmqgK7scw /kUUR7mXbJJ8XXO3LP2dNem62eLLl2KpL1XH3Xle8t6v18Drlsi691bL1jeRJWyQR7 4cxmM1JClD1M0QJ2FXgsJ/ZrZEQRzaQYn9D+5MrpBEY9ABXsinpdgYKX9rn2EjyRUz pNO82/M6amgupFvVov/hqqXNHS/+rEi1aMJOiy/7d+sQYdu0oHywrQ7+1ynfWF9luu TmZWjk4vJOhrA== 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 v9 26/29] rust: str: test: replace `alloc::format` Date: Fri, 4 Oct 2024 17:41:30 +0200 Message-ID: <20241004154149.93856-27-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 5u4puxeec4qq4qpdfs4rfsaisqd51qs1 X-Rspamd-Queue-Id: C75E040023 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1728056669-279359 X-HE-Meta: U2FsdGVkX1/NDppRz4cZRCKVczD98TQD4NjMYwB1VPgdtB/n5XU9aq71SY7ahIxksl/6w1AWZp7y2cJBZjIBNq1dktJIMYjjkUbFNb+JfqHpF8MIO8lP+RJcB1uv7HMfexUf2zPH5ObH81SxFITlcsIY770OelzwVpngLywZeNgMZ4/BX1YF0MCp/PUS5u+//+H9+EFUU/G6iKzpkHAyXcStp8IB2b2mhT6fBIa4yhO6/++NqonHAm0aKkQo1T2D188Wnt6P50lPLiyEiwaX7WSNNXgFGESus563yj2MPd0E+jhIUIFVA2HTDUOHPX9COKm91H7URW3CWWYW7FVx3XPuINJskYBlT+IO3SK6kfdSjiJcY0WaMh+29NGbed8WB3MsXsy2UV1vY98+ugisvnVuiS5MI1+JjBEas3CgXnT7HDuoEF7lYXqlhNhdJcWNcGhD8oR1Jjasg8F+Ylmg3hv5wOy8qEjdJ21bERPyhp/eEF98pkqLKJhccfdeuGRQF0rEYEj3pJjB6i4/8g9IS2kcawmxvpjG/S/3m+ht0MM2yRXhqq1OovWW/qAQpuNzhApJpDE7Y206CwyJ+/+GgJg4DcpxLcTtduMOB60/c7x0Xipq71pT3kgKNLthG5/mJT1YaRmnMMHUzAUHvDfRsTxeA4EcGu2HOWfXJkOX8yzMpcj7v7GPSJ1v4plKycy2/bH163mdVRd5L+YezrZzyXiKWCZC/crhuCs7NPropIGIqivT0JMX6NfByqLW5LpfAwOGg6Ha4Oz5yT9JQ/zo3gw7xDfod9uK2ud4Q7QjSS8jT6VQFBt40aPqJt4Kp/VO7mn+HTPGjy8X/5hTFuPO7YrbbG/fnLk/ZRHiopDzOjHWSZN104Duwy8xAqEweT39U69duRFmxmhCd+JQRTuBb/9l7XaT379P9/dj9U+Y4rj6AsRKx7phjInW1QbYMkXnuhnWh45xoZIaOaCJ8lo OQJFVwI+ Q7eqKCcY8Ue/Xagi38ul/SHfEtWwe4ILyfB8ObBoOGS+kGSgZvENlRHc1ygNVV7VGK6Z84BgYN5JwE/a1zLuWwlLj3EN2SXtdhW+rvnBuuk9uKadI7GRRWxAEpjIJMmXumaH584DUe7e4N9Iweu7HT75X3NjOnaCveVJy0TtJU5NEydbl//phnnQ5p2sqWSkXODuRyha0MZmZWk4qJUKectGAXHEzeNyQJrKE1g4BP5IegfGLBGIE1FcNL4YgNedtt7DgeoaSTh57XTeeHdbvK2ts6xuaYoR/nLGi6RjWXV7y3WZEXxMOYB4jYSEdAN4gwD9PKI8JKtGsm/DqEWxtrMX1XvLuPTJtRfnhzkW20O5DGmwHIkT7RdQs2k1SxrfZw606qrMS5y4t3Pc= 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 6053bc7a98d1..aff6baa521d4 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -524,7 +524,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 Fri Oct 4 15:41:31 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822638 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 AC7B9CF884B for ; Fri, 4 Oct 2024 15:44:37 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4CC546B0293; Fri, 4 Oct 2024 11:44:37 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 453926B0296; Fri, 4 Oct 2024 11:44:37 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 2CC6A6B0297; Fri, 4 Oct 2024 11:44:37 -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 094836B0293 for ; Fri, 4 Oct 2024 11:44:37 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id B20FD121ABE for ; Fri, 4 Oct 2024 15:44:36 +0000 (UTC) X-FDA: 82636342152.12.5847E75 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf08.hostedemail.com (Postfix) with ESMTP id 2DC8A160014 for ; Fri, 4 Oct 2024 15:44:34 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HInwzaMg; 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=1728056652; a=rsa-sha256; cv=none; b=ugkugUHuLz2ePUjtkgjFWDswRFNu9wseDUMNq7/J79fw5Ly2NpiAFJo0HoXsHprFolnqgv yT8IIF4LmRAXKdgQGz6WhHZH66vjMjYjFB2pI+dCVEf1sWX1lIruAxP+UqpxgRKPLf97ZY RGa/DaFfNUfE6qTc9Pr/5wZGEJikXvM= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HInwzaMg; 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=1728056652; 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=e65sXPSzs/wExdsiWFWrUuB0l/sZUA+mSfY3vuDEqmPyA6xm2juHWRnUJR5L+yFDtrSByD HMr0vchBRv+8Zy60Pz0H/Z8J1hhBk3w+wfCM8Zp+swoeWpccyvBiWC19zx2juU+4zUdp5Y 4UbnUsitNfPeZGSU3Ml7DHp2pGLfQ6U= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 04C0FA44B76; Fri, 4 Oct 2024 15:44:26 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2632AC4CEC6; Fri, 4 Oct 2024 15:44:28 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056674; bh=GR6bCjuYYHRgHCOsPDduyYPPq8CvkGfa1JPMMj7rInU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HInwzaMg4J2W7s1jrkgNdeeywo/XEmyb9ionzx1z7DF543TSyLE5cmftSnOF4QSj+ 6r9x5wDRez306psxF3BKCgCH96wCu1MU5YU4GygFh36+FmUef6U8xv+b9V0tcKM7Eu OUpq6xZDzJz63Jili2hXOHV1eiGiWCy/G/aL4dTfnTmhn+Dcjx0ERts9kBPhDSQhNK pOC1l7WQ3f1YFq6tblCtZQi82nJa3DCrdQDfXLlgx3MwcwdIbtfOJbyNYnGoNXnyKp MGU5BspVs3/hpEf7o65ljYnzndSi7AIqY86E00RcksQQPufiCG9hhsJPdrbelIAMOA EWy2hs58e3Cyg== 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 v9 27/29] rust: alloc: update module comment of alloc.rs Date: Fri, 4 Oct 2024 17:41:31 +0200 Message-ID: <20241004154149.93856-28-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: 7c9kx9x1ewfc4r8ep3gwzctd9zr4yktz X-Rspamd-Queue-Id: 2DC8A160014 X-Rspamd-Server: rspam02 X-HE-Tag: 1728056674-605274 X-HE-Meta: U2FsdGVkX19xorbhssknskdPeTm5cLU452cdJHjrpb4gLrLOHBrVCqFsKJvphE5dXC05304779cnoZl9n41RC3OtPN1zeqLd93pxKwR/A5KYhgU8QIh4CWHpHxyAJI6hy33HFAXQFjK8m298fjxrpuoKFnQVwCITkCIh7ce0jGy99dPXH5JVsLZMNU7diAEJmDTQbsckhboYDVsR39nut8wm1oySeWQglfrlOvbpk4O+5z7akeIAwLlos4Yt/KLplk5fBuhtj4kLrfaWzlnEoLuQEFTzjC56N2YOTMOTAJwFV9wiYqvYkk9cgyASJmeHycEMfG8RVWF256cPlkEgYJ+karjzo06QDPTHo0kNaxXUGmoOSM8+OpqYZzg4Jqc3R24vkRGtlZz1qBMIdLoW++0SDGA7vivS92Bah2af/GRqwmM7gjPFxm4k4veT9HqpW7/BpdNBwoVxx6Y5Zi9fxPD6L2Sn9wTYUOkkqvZHBU4xIe633lNYJvlHFwmUej4SL2JR4e/qzDYEXaHImXV3EWwu3zTkg2rsjzRqTfbh1vz5MSBl1WHYWbMOnx6HT5kWAoM86pEnnyGsLSUF/mgqAS68prHYBf0jg+bQFZTtMUn+7X3PjxYL/DO5xlNpvj47wqXYI9Bb3tmrkBOXdQbNdStLWgetcpfElYh3B083n+nNjPF1R6nNAk3TZgdZ8rRBPYdFN39SVWLHHo388ayQNXs2Tn1AIYtim8qoNbeJYW2/AaMkP878HsEOE6rBDEpo/ScEYFxxYuCKUiCJr7rYy2qdrIck5q4fyl16ihqiDWNTy1YbYeM4bYcGGFJqOpBWlUiGGKOcTaKn6giyratgW3MHhxYnwxHj+bWEfkzDt2q0Ho3RbrLng9xf58wwvf77nJqKXVN33RK9mVXBZTPs20NCOen8hOFmeqRG8GeEZYQVY7VG1bc436fUzlk7g6XZQ3G3o+A8DDruyby8vc2 rRyBjLib CEKMfbqftqfpGKH9+XkBM8qVOzZFlzzmoCSd5z6xyNuicmQP+0B3fT/vHftQGT5pfN7AicrKv2uynHukBmMjZxJXrwEblccbVTr4hgO+OHs3U5OsEsNCDzaW3arEw4zpGNoiR+H7tw+Mpg9o592tQy3RSX7AJBBfBCFws0wAe5gczwgA4hsyflmPQzdoratlYePxjE9hN0VjvHymZdVMBJDm5jCFqIkYUA3vVJlqe9W+qLmUzLhiZwoZNQQQErAbSwESXHlNGs6xZ6UQZLuspOj+PswXzJmO+DyxCiZE4Rj7bsA6iFxJ62yY/YigiRKi9zDw/mkc8JEVlwhR08Khve/nf6c29nfB+dk77rVwOwjxu/T6wTcX6CRgOeI4nH7P3D6ge0sSHpMVKmV3n4L+eWRoFcstK1L9WlTq0 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 Fri Oct 4 15:41:32 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822639 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 52773CF8849 for ; Fri, 4 Oct 2024 15:44:43 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id DA5A08E0001; Fri, 4 Oct 2024 11:44:42 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D2CE48D0003; Fri, 4 Oct 2024 11:44:42 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B7F138E0001; Fri, 4 Oct 2024 11:44:42 -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 918348D0003 for ; Fri, 4 Oct 2024 11:44:42 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 5632F1A0F31 for ; Fri, 4 Oct 2024 15:44:42 +0000 (UTC) X-FDA: 82636342404.12.1BE2514 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf19.hostedemail.com (Postfix) with ESMTP id B01721A0013 for ; Fri, 4 Oct 2024 15:44:40 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=idrN8R3f; 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=1728056507; 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=opWBf80luK0VgoxqykYGArMe6QikwREanQ7fe7aAKjM=; b=1q+Rqb6DrLxsJMMpFsCbVbKuM+7Opc4PxtTSck7LKUt/frxFJUbhG2cbU1/rj9iYzZwq+c Q3fD4XoBTQBNDdPDDwyz7z433k+6+/Inkm9MvQA5mimnQgywOGyCQXAH2Ebxam4UQKUMUh SoEau3klj0d2Q6YarjuII0TbvfiLhvk= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=idrN8R3f; 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=1728056507; a=rsa-sha256; cv=none; b=dH8D1Vfd8zdveNC6aD/+tGqdmpRxOY4iPRjx7cl813RO8WoMOB40YQCMyVFdqOJYXYFlio IzzcPPgU/tDAC4OG+zOvE2uHHOSI9KZYwAOe0xc08GbRqX3jf4odtVuxl4Ocb4i5JPqhNO NHAyCCtzEgS6i2e0ydWYz94ih+r6l2Q= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 94DB8A44BEC; Fri, 4 Oct 2024 15:44:31 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8B9FFC4CECE; Fri, 4 Oct 2024 15:44:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056679; bh=o672VVH3AmvwpLuEYS8c++RfA9LDqdgouc73MUW9aPw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=idrN8R3fHUStsOpR9WkFppMYshHLSeMsQMDZRS0zWz9IL3jb+lWGY4FL+g86NT39B cHqWMrkYi89dyJSJR4/GhDW7SO5wD5DxiJMv/yMXTbtoC4gnJKzJX85o0EsaxdHEm0 Kcfx/mAmf9LY7Jq6TS9OO44DX+bj97zNgInmTu3VLuCMQBK2JCu3mGc1SAamIikoHK WP4ouzpb5w+ZzfeQSpu7CoSMId6JBZtW7yMQd0FSmVqgrYznD8PZopFfV3XlIrupnH MN6mfhlLfg6qFzRZZSke/8jk6OUq3pJQR0t31VcNzeIf4oP3vatHFuyY8VZTLblFyM bzEcjkvWs0DdA== 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 v9 28/29] kbuild: rust: remove the `alloc` crate and `GlobalAlloc` Date: Fri, 4 Oct 2024 17:41:32 +0200 Message-ID: <20241004154149.93856-29-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: B01721A0013 X-Stat-Signature: 3da4bxg7anjx3btoydrw53yaphkzw3in X-Rspam-User: X-HE-Tag: 1728056680-678279 X-HE-Meta: U2FsdGVkX1+0twsSnvQobbbnSlOPjNBG8sVGxUZrQ7IQc9qdmyvK3t7gWshX0rBge4lCAD/iZg2mEOGB7RccwJVl56+YEov6DK8VK/q43BhjQmdBTIZy9kHPdwKJU7WJTenNmTOeQLUWjvwSwm96RA7oAifg4r7klbsq2EoUnJ7rnQHSzOVpNfa28XxQVWKyuX7fT8g0fNhxB8VOegQffxf5c9+RyRsMvi0LsGhB3rhEFAsD+boTHgFsg75wMoLPA0TUOiMQAgwjsazAtRR93EpU1ZRVZzWhFIBMSQpTTD/EsfydZlXSuwG9ANn4QqK4glRuUcRDQ/ByaEIwm9o1vVJxpVoUSHqFKs/FRbnssPyUq4immjk6UoScsswQzzeTJMyiw8QV1EKvB3MHmaFPSY4CRCqx3IkgJMawTY5N8g90IN/xPXd3RlcAUtQfinq6HC5zHA3Hg/7tF01jkCXrJnntk/cCcadfSnJYTIJyhV+/td3jRD549ZI1/ZrpwfprVfZm9h6/RGiy15oWauCKlbu3coB/1aYi+em0QxrZ8BWOVCwcDrvh67VPUjlp4/JHeBY7WXEM3y2t/3JF5BW20HTrHQF71kOd7Ogfe4F6m9hX1YFbPePMLbuHDAhdiSQocgIatSBkXrxW+bdqazHGQWa28lkyJzf52TveG7HqsdayvZL7nzLYMyLX9S+YtyeVBrAREFlYCZSl5hmQ0mC5vbFxzX3d+JrhDD8WKxVd3uZ0y/4q8a1C3Pbq/Q9VkHpuXd4G9AFSmsacaAMQQV+PzvtD9T5D/MegjzKLog65RCjGieTjhDwwqWfZdQG1gulysBd3ewHwQ3DcyeXQZCwIaIHgGoUn/z2G9dIWxZZdCqE5LoUuF7hFaNMqKCqIicGRUzAMYBzNBwAbdP/7j90Wi3eJIAyDwiHt5HHPo1K/IdY/jkFCBLTQC99msuakGudmuiftcAeYWcbnwogLpTz iBgcG4Mu rxVasIb8VIkmi2Bt3LuO9Ia7fHrmSJjxZxoDp2VZKiqb/kWUqn4kzFt5/ksLp0ErNDdE0BbDAe7B4Bu8H6CqgtwDmkivtp+Sj5Bexns16hClD8EIkcRW6VaIZ9u2elFAMGDmv4SA2pc5r+5172cDwmfzsD+8FBENLGyLR/vLjOExMa9jETrvt6MCeUA9WS0kjo4JbnWay7poRRg7UMhsq9e4+At5NZzZi/NOWUnjnQqUFkG2/bxi/8snB6HoFklsPv8cKDusSCE4j42F3J96TGhk8KAuey3K0zmxoJU5F9TSO2QY4GPSCSI9mY/CY4h6zUQXWgbLAbSQGK1jMGd+XB4KVWvhVm9ykwkqr 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 | 65 +------------------------------ scripts/Makefile.build | 4 +- scripts/generate_rust_analyzer.py | 11 +----- 5 files changed, 16 insertions(+), 108 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 0856fd6bc610..3678e79317f1 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 \ @@ -108,20 +103,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) @@ -165,7 +151,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 \ @@ -201,7 +187,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 \ @@ -314,9 +300,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 @@ -363,7 +346,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 @@ -401,12 +384,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) @@ -421,9 +398,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 d9043ca42ce5..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,43 +139,6 @@ unsafe fn realloc( } } -// SAFETY: TODO. -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) { - // SAFETY: TODO. - 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, @@ -240,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 64518c2f3d9c..2bba59e790b8 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -248,7 +248,7 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- -rust_allowed_features := arbitrary_self_types,lint_reasons,new_uninit +rust_allowed_features := arbitrary_self_types,lint_reasons # `--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 @@ -258,7 +258,7 @@ rust_common_cmd = \ -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 Fri Oct 4 15:41:33 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822640 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 BB30ECF8849 for ; Fri, 4 Oct 2024 15:44:48 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 53F708E0002; Fri, 4 Oct 2024 11:44:48 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 4C86C8D0003; Fri, 4 Oct 2024 11:44:48 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 31BF68E0002; Fri, 4 Oct 2024 11:44:48 -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 0E3338D0003 for ; Fri, 4 Oct 2024 11:44:48 -0400 (EDT) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 6E0271C751C for ; Fri, 4 Oct 2024 15:44:47 +0000 (UTC) X-FDA: 82636342614.07.2B40D55 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf13.hostedemail.com (Postfix) with ESMTP id C1DF92001B for ; Fri, 4 Oct 2024 15:44:45 +0000 (UTC) Authentication-Results: imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=BwEfrzFA; 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=1728056554; 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=s4LR6pATznTAxKNQJhJJpRiH36m1oEaj0WQdKwoDHvw=; b=tKA+0RG3V3B9Q6YdsDleuMt9nwNEirfSO7yan1XHxx5+cymzhOk6ib/94XKS/dd4rT3Jpu gAmXmwbahl+B6Gh5DhSh2M1Uq+GGbrTix4bMXahSHnZhfhuFQ0DcJTjEVqc45UC3AKEQtb oDohl5v/stfUm3k3GOaGzRKmkN2miPg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056554; a=rsa-sha256; cv=none; b=2JwoPIaf3BRgtlyXnReLqGzMBte+4v7YEYv1L1emDyWt254rpGG1XG8d997UfhxXNBwXrj GsiZvSErq7pQrHGFxr/HZo8F4RXfc6MJGdi/UubxN3Om6spLJWqKctv4f/Z86C8JQRVnPe Sg0q7OhnfgYyibsOtUeh3s1BHn53C8g= ARC-Authentication-Results: i=1; imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=BwEfrzFA; 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 C795DA44BF9; Fri, 4 Oct 2024 15:44:36 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id EC34AC4CEC6; Fri, 4 Oct 2024 15:44:39 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056684; bh=LdzqPbgEKI128eCZYKb03oyNMyTA/dv0Gv7wqQmMX2Y=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=BwEfrzFAPdp4OWI26Vyob0+ciU7heTInmH5hXtmwaC+7O3Pvo6QP8pRMhkfZCUh7W qmx00+qBV+Vk3YE6eIiTiigQRtr8Ur069zHII6bJEp3a8+jVrhgVnfTd9zPrxPkO6v HoTXtL/Nv1k5wa5fUd7csJhRgcIUbaVIwm4yn93X8bVoBDlb0DgISPoJ1HaRDCUOhj iW05DEBQo1hiA3F8fKTiHU0PnFbMTDK5XwV7RxHVY/oX0mEgu77q7Af+/t6NyoNW2W wviRjO1xkrf0ZonCjFrg84ILr1fRTAoOjyyyUslrzz7UDVekl42NGaiT0eHD7EZj9q SvMT1iEUYNPIQ== 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 v9 29/29] MAINTAINERS: add entry for the Rust `alloc` module Date: Fri, 4 Oct 2024 17:41:33 +0200 Message-ID: <20241004154149.93856-30-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: i1dieka44gtm9jq4ankdotzafs6qrqie X-Rspamd-Queue-Id: C1DF92001B X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1728056685-116325 X-HE-Meta: U2FsdGVkX1+Sh6zlYg+9ytUI8qTKnipGzGnKe7w1H5yjoqs1kktPxBEhGwQBiuFQ0KHMgm5Txg6crVad/UgPHr7RZ+TEcfKxKxq9nukRUQx+PTJXLcI0jXIiZhi+5chH0vqskDhN0CF+ZOWUC7FGK3KgANlIX88U6OBGVfgHN43D6Nz711i5PFlqJoZTZjF82AGBqOY5ndHsTMhrcXWQJy3wq4+dNEEzLNpHheIr8pHzOntMqmf3dx1pPYetgC6o3GQ9p8o7as6QVzc/J2qnpJRzlCkJ0zFk887LVbv/0fkGkbxr+pDsfvXP6g01UjaCZAI2ZCas05ZXM7WwWIcmaPg7MQRM55LCI+d4eqANpOD88hwPfuMc69L9PXcxWFo57L9i4UcYDZ0nuS1XIf7ic9zB9SLx/MwwPZdrLraCx2hsVLvaoQOc32iJLTGAnxxpXsQGBxLvQesRzjy57pJmr3et1tL8zN/aRBJnRYeZueD5Sobzv46wuJpHpv6EZgJx7ylSdnIbMwsjt7590iD5XY2kzUiPeW3RjR3JQIJqcQ5Nuc9oey5DMTEi3jt6PP+aQA8vklziBP657TSJLhHjWKc82jLpKyST0GSiAViTIaL1OOlLK10ghwtBGwn/OmWv+e4RROoOfDH0Rl2r7LDfVIDVb+LNEDeJAHp3/bQF5gCgD66aWyKM5UUhIfR8HIVwsOpt6d0VtjXb2F3agAxGo13qSBJSCxjRu0jM3ooY9IY/m8Vv+oKelhq2tFRfJ8VoTa17fMpZLsSaBa2yLmD0rmfnGkBalB6h9+g0ZU0iUW7Fp6yCVxDmBVa7M6BDov6DPNWVrVZc3Vj6IpaEqcJv72j14GSAFQhr3Nb3MmyGKnBYDO7DZlBUMw8Y1nzZtA/9YIUmQ2oqzdxxJEgI8mLQ6h6PJaG1eDGfOlOIB+tUxEF2N4KmLch4p0wQoNXf5QA0F0zt3ywL88a/9V1UkkW +lo5s3ko ootOKQIkD/AUf4/7ALzzQKdtfwrZ87uwTH0L6SLKAzXnbdgRvKFiEsJTqioPGt+LHKAWsl3vKGbsJqVv7ZGHIfYk70Zg1IFDdjr0hotQbVJHswO0LmV5qR2Nv5LrO9R4rysXQm/LClrK7fSCwzFCu37AReV38+/FA3mIqDKq3YEUbtR2t05I/jekn+kLd/4KW+r1Pp87a+FMvsKAJGcfNUUDWvAoZXoU2XbIiKQtSDhh43N9D4cWvbii8fBW3fKajeFtuYJ3dONNZOC9UawmYdzADXdd52Qh7gAX87SW5tK/SHwbgX7d93Thziz/iO+QfTQ37Cx5DiIj4e1VGq+caCKl67v3YKG9o+wKoyWMvxUxSfwHh7qarsklCYrcm8WcDDWUz 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 67f9f2b8bb50..aa3b124e4989 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -20226,6 +20226,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