From patchwork Fri Aug 16 00:10:43 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765282 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 190FCC52D7F for ; Fri, 16 Aug 2024 00:12:35 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E6E176B027B; Thu, 15 Aug 2024 20:12:33 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E1DB46B027C; Thu, 15 Aug 2024 20:12:33 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CBD0C6B027D; Thu, 15 Aug 2024 20:12:33 -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 B08CF6B027B for ; Thu, 15 Aug 2024 20:12:33 -0400 (EDT) Received: from smtpin30.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 66A34419B9 for ; Fri, 16 Aug 2024 00:12:33 +0000 (UTC) X-FDA: 82456182186.30.2FD1E3E Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf17.hostedemail.com (Postfix) with ESMTP id BA77040003 for ; Fri, 16 Aug 2024 00:12:31 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ZHAELe33; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767114; a=rsa-sha256; cv=none; b=mw79gSV7+sxySe2Fz1/fiQpg9DXO/W3k05VgxSH7SKvFq0PZ3kFDAIoy5ELlVrU5ozzNtz 2NvdCDHH+s/PNV7pkNReIg4OO/33JvnCapFqwmbonraMP4wRvnCaENw04S9M1p0CUu7/+Z 7EH1oKIRZNqMF8EOlqg6ftc2idK5fWU= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ZHAELe33; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767114; 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=izPWcm+31T2WE8RFh7WL04RuSNp+LqqNmQu4RAuN+t0=; b=NnrlQ2kWFSL0AXwxbjGljnA7c3t840E8lVmoaGPqLiriBgTxZsb4B50jF6mjgKr/w9/Ta7 kTf3kQd0WRII7XE+XC+aBTMgGZypCFaoMSAZR8F2vAC8g6wCDjcgrpOcH/8ONdxx36Gyk5 abuoZXX2ZeCRZsqUhcadQsO0EKJL3Kk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 9674262061; Fri, 16 Aug 2024 00:12:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6DA4AC4AF09; Fri, 16 Aug 2024 00:12:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767150; bh=q5RlNxfkOyLhc4BgL6waKEiGm6mWXft+//KdK2R27M4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ZHAELe33Ua3jRDxbSxhvloXmYD45gcH+zzoE+3wSpdYojUyPsqnnjpsXyLQkCnZmw qGXEbtqFSDD21/hS1rLaCDCOuJw15Z6EmLmJYatnBupG26mWIPTi+IUQ9XGCHwsZhp x74Y0Ztdeq95QwupMO+oJ5J1C39IeowFODY0W3se/2naWCjnnkwbtTWNpzH7etTewP ihJTjiLb/YVxcXbbMegBv55uvc2wJ1RuxeA5ssNQbkZogN25k3YRe9xluyiSfM0rSg jHhNCqJUc6HDriX5Ie9m21BpHGt2u1C1lC6lAQGGsiI5e2ZGRIHoiHVRAiDJ/12mC1 L+RaFrjKBhfgw== 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 v6 01/26] rust: alloc: add `Allocator` trait Date: Fri, 16 Aug 2024 02:10:43 +0200 Message-ID: <20240816001216.26575-2-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: jfcshw9nftighit5rt9x9yrr4rg3hb3b X-Rspamd-Queue-Id: BA77040003 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723767151-419121 X-HE-Meta: U2FsdGVkX19or+FDZfc8UPXWamtn87YuChi2Tjc/PmkpBKDNh9m3hbgKPiBATf2Glrv5HkxvSGJzWyAKUNUIvCf6wjBBI/gD+VI4HEvCQ1Vt09irwvS94judJr2nhbgAPpF4gkJ6e57wKSRxm7w03D0sTAssvyo+50rssVuC473LFvzzFJSsVTxvokWVSKKUYekIwZdDgOUQt3+8VcUhf9WLvZqWe5/kAR1hbU17X3HZkQY+OHKvBmS5j1jRsIADkUyanpl7VzsAzX5JmfR2h21KHTrD9bgzrmWsQrSYuKG7QL3X+yUlkgFnRsD9+eotO7s/c2FkEEhWCahsNmIFXt6OwuvHTDqRci966EhGFVLCOAiOn6hYM1dLlUnaucI3mH0WKzJVLD+CWPLVZw9JJfcLUFoUGBncuQBw/AnW2sW5wPBVjZc9DC9UGH15AvFd0dbK/wdZ8M+O/9njSIDbPStGtTl7cIcIJNhH87BKXvyQ640GWoiwSLuO/gzQpM+LKA2m++iCp3Pwvh/T1RYtDWuYoBQ5vFqH26IVp9tZt8IGBYNSHfEnocrvGnudMCKb79igX9+bmbOXebQcsGdzvkcy4aN2i70NS8l4KUGn8ObLw9qDDC3jNI+RzHBq1DBpU++pTUqeBeIkZ/6tt/lS/uAuPmLcRxX/Jtu0aCu+7zCcqDYCVwy6ZByNwh0xirm1qew6y4NB/JFZitdcfU8X+G2eEZrmXNmVeJz0E23R7BrBv9l0RLdX/4AZIA9xKrD/+2Me9okx/Fgh8j/hVCogN1KyozVybWw5L45T5T8QxhCHD3joaJ7bf3C5L/5cjzhL6F15WEilDAIVT2e0pqMiyctJkKB3I3SaxPbr9TUY+oS8e8TQT0FPZpeCJU5zZqk29bKFcSwuto8SW1vlgy1EX/koS4MAH8dAnP8oXRBDq6h95WsjZGjxafq+074k2YHhKiZFsYIWwazrgYMsFdE /GHNoPyD cJRoIeoWISIm06D5AdUfC65r0Xfhf0mbfmm6x0GeW9MeFLD6OhctCBbKdCukfb1n23ZpI/6b7yEMHHOsan1f9dg6ApxBlVopzX3ywblZOOTssn++NDD1caWQl8SzXifFOvCZO//EEIm7ANs+MaBpAwa4Bf2z1XMPfjowM7WhfrdfCF8fwIm3cOwoM1LemOy6CXgnzl0BpTOXQVumHhuwkLEpTTKbb/Vap1WGW9qjjdvQLZ3PO/2wT+e+gOvY5cZgsEW0Lbv+YVbMTZDaje+Es/I7gKCizrwCQZzW1j3UlsKA4B6EXniYwOs9XePQwvAbzQRcLBT7+xbOE/yKSW4jDWEtFneDeiQ51fRlIhHF8iDbLy2Q= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Add a kernel specific `Allocator` trait, that in contrast to the one in Rust's core library doesn't require unstable features and supports GFP flags. Subsequent patches add the following trait implementors: `Kmalloc`, `Vmalloc` and `KVmalloc`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 102 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..9932f21b0539 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,104 @@ 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 buffer 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, 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. The alignment encoded in `layout` must be smaller than or equal to the + /// alignment requested in the previous `alloc` or `realloc` call of the same allocation. + /// + /// Additionally, `ptr` is allowed to be `None`; in this case a new memory allocation is + /// created. + /// + /// # 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, + /// and old size, i.e. + /// `ret_ptr[0..min(layout.size(), old_size)] == p[0..min(layout.size(), old_size)]`, where + /// `old_size` is the size of the allocation that `p` points at. + + /// - when the return value is `Err(AllocError)`, then `p` is still valid. + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError>; + + /// Free an existing memory allocation. + /// + /// # Safety + /// + /// `ptr` must point to an existing and valid memory allocation created by this `Allocator` and + /// must not be a dangling pointer. + /// + /// The memory allocation at `ptr` must never again be read from or written to. + unsafe fn free(ptr: NonNull) { + // 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::<()>(), Flags(0)) }; + } +} From patchwork Fri Aug 16 00:10:44 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765283 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 96AB9C52D7D for ; Fri, 16 Aug 2024 00:12:39 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 2388B6B027E; Thu, 15 Aug 2024 20:12:39 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 1E8E76B027F; Thu, 15 Aug 2024 20:12:39 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0897B6B0280; Thu, 15 Aug 2024 20:12:39 -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 DBB936B027E for ; Thu, 15 Aug 2024 20:12:38 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 56BA84193E for ; Fri, 16 Aug 2024 00:12:38 +0000 (UTC) X-FDA: 82456182396.16.B8C3D49 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf10.hostedemail.com (Postfix) with ESMTP id B1F27C0016 for ; Fri, 16 Aug 2024 00:12:36 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GAnPVWFa; spf=pass (imf10.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767143; 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=w6+8tdY4TLtLsqtHG92YkQOgq074S9VZCBc3fF0+vIk=; b=pTt+WFtJC2GRSycL49Qt3kA69rGxmYBOnUUJovWDmZE83CCAejF+MAjAmr9QimielAcBSj ZqCaO1EKYCpuxXOUe1Xam6DznuexylsBWi9dOOnlOwx/qCRAys9r0EBr7hXUsKObCBz3GS cnC9KeDkweCiQl5YyVHEhOT+4abew3E= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GAnPVWFa; spf=pass (imf10.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767143; a=rsa-sha256; cv=none; b=laQ8ifkzSaSPRWCfJJ+SNkA9QUdZi5qJFkdF+nXYNb29f4cXJcReP6FI4eeZrv+rfmsm99 iHSnDO2xVUdER16tsEnKUaPnyqUAfbCEnUhj5Oi6Dg2YL8Hx5Rm+buRz85VtSJ/+RmBmoc LaMixJ7IasLCSC+ZEG2lRBDBUZG4/0A= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id DF53162065; Fri, 16 Aug 2024 00:12:35 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B7B7FC4AF0C; Fri, 16 Aug 2024 00:12:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767155; bh=7ZQlD+OTbqqlfuCqgP0DzO8fypflRQev63uVtG65Y8g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GAnPVWFalHNdYwWYd3lbE6b3W6p6ZwKVuxqnVgvpj9tEBAPTdFpARBsEqVS554dCY x0NhR+80UCX503tsN/Zl4/5G8uk/MKNgqcFT4kWeEu9VLnfV06EaQhZKUAjwt3YzO8 vzu91NxYDN+XFsqD5RCW5KkUiqljpYr1hJ4u1Gw6lvWT7yR21vtHY503Aipp8Yn2bJ e6eagH4QRRJwFA8Rj2WOeKezAP0hVOu5hguQmpfKLWUaEpZcSo/xOSJO8NsfsICceo DP86xC/KOTAyZM1b6xPeL3iy5L8iqk0m5Fi74PkNr01jms09tq4gemNVH3g3Wj5BhF b+Pk0RFEyXfBg== 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 v6 02/26] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Fri, 16 Aug 2024 02:10:44 +0200 Message-ID: <20240816001216.26575-3-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: xe87npreiqs3brrt4kzxg7s165tcfdck X-Rspamd-Queue-Id: B1F27C0016 X-Rspamd-Server: rspam11 X-HE-Tag: 1723767156-387557 X-HE-Meta: U2FsdGVkX1+mLiPSYl3OjDXSX0MdezPmhDLvnuszPzJj6y36dhwTHCFvE0zJ1Dn6EuIURkfJc+6ecly4LuH8e8lVJQsYowHDAZwgOrXJX6p8vT/ZjoMNFfrwWsUa981Da5AXnP1yRnVe6pNRuq6rWeKbCPZfSjiM2X73osq7Jf0IAY25upG/24v0Z46IPkjfAjKmK99mLWz7WEnZLTzDA6hN4WYTVxwSP+klIzBOphsixLfKCal/2Tq1/JU3BNAyzLPNnyfFuAOqDToAKPTyc5snUx/Thqk6sbbhE6REHMXr7PvgFbvS8AxoCvfE/N7qa2C0aYf4eo7H4ftl0Cfyo9Fo986xdFzqQ0mggovAAhhDmt7WQIoO4jJM1pposlGNmoKrIkoPQrpzfBrTeaYax8ag971DKLaL01kzZ4BaPWOjXY7o7fzeHSqeQoIVFhR/7oLakBmWcA0zYH/3A02ex2NfWg77RZadEKBO9Xw2YIZB8J8R7+4A4GVdFuCITrI6tb8Ku2w4tcV+ZdgFHEbsf+Plls8ic9Gv12JVAGPSSgwsu8QXeEJ8jQiBEom03OSPeyjTxmAcjCdNnUvYWNWDheXbb0ZQCRVJ3OrJUKHzMYEvrusEThk5ykSo0U+GAAptic7LnTU0poy9GEskDk6fylnjw2Jiu4upgffq9dHfZapZ/8flSYSimpW6z63VJ/skCyxu2dot3p4mrkT7qBqus2fQuX8Ki8VhTZhwjka9Y5f5OObqtQbu8Yq38jMIbJ+zh5sEUhMRwC0C3Gb+WYHkqhUvkcgGGg0zEJdw+jus0H+QrUa1ecCsxtfZ+t1/OnJ1HgruKhlS6QndqQB1BlTOnCVRjHNo89ZDchleX+bc14UGopyInRb7fwppus8pjUEK7kJsonB760GD1ErVR883YWlT4s15SmvChfWyGBe2xYE6uyWbMOY1NgzLr1IU0l/dvWgvV0+xzXTPyuuI7oo B6iiQYqS BK6q4TA0qIkm00jHmThwT52WobMkqx8bFtx/6WvhHludDMj4WsX1lx4OABq1FPav1wqlLsSIwxVrUocVlqpT5uzQAh9I137Gliiz/o6zBCm/iR7Y3z8NGghgmduVd4mlLCmRoHgfzhpq7Uz/VvdtKSMKkuL1dJEPTnoScKOic3W3CKOPozvURmUw1L8Fp1GyoiktYs+RmnxqgFZ/Z8sItJ+R4+qP4s7LYPWQ7V7+J/W48YFADYhRkRL5z2pIi1EEmGk95lgWpghqyW33lGuqLGCm5QHysYPxD34QBi5i7VNPCnlDY4tj8U80XV0mBdJV68Epqk/UGeBbj7YJtaOPBQgg39aqNadYpkhm+pLsc1rWtnxkkTqMvSgQKwEUjhmCZtXBn 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 Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- rust/kernel/alloc/allocator.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..c83b6dff896d 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,6 +8,17 @@ struct KernelAllocator; +/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. +fn aligned_size(new_layout: Layout) -> usize { + // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. + let layout = new_layout.pad_to_align(); + + // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` + // which together with the slab guarantees means the `krealloc` will return a properly aligned + // object (see comments in `kmalloc()` for more information). + layout.size() +} + /// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment. /// /// # Safety @@ -15,13 +26,7 @@ /// - `ptr` can be either null or a pointer which has been allocated by this allocator. /// - `new_layout` must have a non-zero size. pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. - let layout = new_layout.pad_to_align(); - - // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` - // which together with the slab guarantees means the `krealloc` will return a properly aligned - // object (see comments in `kmalloc()` for more information). - let size = layout.size(); + let size = aligned_size(new_layout); // SAFETY: // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the From patchwork Fri Aug 16 00:10:45 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765284 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 EBC6AC531DE for ; Fri, 16 Aug 2024 00:12:44 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 769576B0280; Thu, 15 Aug 2024 20:12:44 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 718846B0281; Thu, 15 Aug 2024 20:12:44 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5E0AC6B0282; Thu, 15 Aug 2024 20:12:44 -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 405DB6B0280 for ; Thu, 15 Aug 2024 20:12:44 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id C0C4B161807 for ; Fri, 16 Aug 2024 00:12:43 +0000 (UTC) X-FDA: 82456182606.16.15F9D97 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf14.hostedemail.com (Postfix) with ESMTP id 0CE3B100022 for ; Fri, 16 Aug 2024 00:12:41 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ne94WL1V; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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=1723767102; a=rsa-sha256; cv=none; b=Tkbk3sJZMLZSxbLMfrCmpTKJc17z8U+42F9+dk+J6KNtLC/eGY9F30bXxkJUQUhjCwJhUV XPUfc9s+SQEWMWuro/UCiJBjQTiP+Mvl446uAI1uKoAjhjCGUx9ZMqxMRCY/CZcd75Uadf 2ikEc1Ml8tY7lCRD6n7hZID87owU6Ew= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ne94WL1V; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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=1723767102; 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=mTEK4ewxpHHdTJ0KIUOEQy2oIL8O9c+6dlpP59lW2IM=; b=0Gw8WJBuxzKH1UfCqCKPYOMqr7ulesyg9AyrHQ8R/0T/V1yis+i0zh4Z9rJd39QlL2b1Qd SZHrA1E3jT5nkA/w2qj6zoDh6brjQ8+IK9T319yz6uSW/yh/+CE7IKs68SuXuvae7He0aP UM2VIJPU1vQpOfcOtpbKZold2+Vw37M= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 34B4862061; Fri, 16 Aug 2024 00:12:41 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0E4ACC4AF0E; Fri, 16 Aug 2024 00:12:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767160; bh=Ul5b1CTJ9tob+sYMI0uOwgqpbhRR4cA87hpBjRrp3KM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ne94WL1V890QjFloYBA4pmcsK1kTJW/b0HtCFvQl+YVAByoQSFc2VMznmdoDkS4D0 0EfR5GYsJQkhnF+Avj43Zq9zmRhhmVXGfC2IxoB7jmCgB3fx/sqJIwFjNUh6dwj6DN e9KBqyqVWRqVra2FOjv9Sx1BWS+kLGvDCeIlYaWcMphAOgXKsZhEr5eav53HRgxYwR dmSOkJtgf28m/KgG4IRnRdj36p59EFR4iSzIHQSP6IjGAUZpojWgFiMYTUp+Tt5jhh od0smleLkl310st+/eWgw2HoN5ArGPO+Wm+Rz3lZc3rdQ382Lq95vqZSudTx3FJT7w zQL4UXHY0emqQ== 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 v6 03/26] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Fri, 16 Aug 2024 02:10:45 +0200 Message-ID: <20240816001216.26575-4-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 0CE3B100022 X-Stat-Signature: s5xitce8knut5exjkiu3wj1mk3yucs93 X-Rspam-User: X-HE-Tag: 1723767161-103163 X-HE-Meta: U2FsdGVkX1/jyjunghDkJ/VBazVAxhRlqJYfWZf5IX1+HooQvrLhUrm3nEfTm0zEwOGmz2w9kyXzDqGFGfHNAQzZyWXmB+i8aXDNrb5q/LKGZVsWAuWQ2e/K46A6nf0XDRnPvEOsIudS6jElpPToryh3GaBf+SsXokn74U9HBkuoi4xuCFsebxTfJKFsljouBxWuGzFNzc2XF1hXQuFnJTgEx68K72yMPT/blzKOdDnzAbVDtn5s35SWnYV5Un5rMxErHoOmOZGcj1by8s6IFl4/qhlUKsDVmPVV6bRWqGr0QYnVa/B2+7Y2DQvd2Zp9M3D1OZkWbHPf4MUCmTOuMg2yqyvsKYOV8ccqNeOmPwJu+Yu2Pld5bA9qYqX0UMBh3iWZj3e5aumcpqaLIesDieuSSv/vGVy8d0Jt1y+X3BgXMMyVv9a+qRqwJ29niIQ4E2dx++bXYjVb98eeWVISu6KzFkaz52uzPpmlGiRgLjn8gMq9/ow7tAAnlSYZHeeG5oHy0ju3rl3keNzs+ySzt4qXr/CvXl0fu/Z9b+c88XJPBjyT7At3Zhs4Pdqd9mVsxZkVPvs3qMxwO5WpGZxqCIiEyJE5uVVT5jTuDlOm29h94a6awzXDoLFRz+54grm+GOVzqAm5B3dRhVQWs2AAvBwuPO//hfh7DZlFK+M1LkYPFqVcdBXbjpOhKX9JXJgAzyomMiFeKkkUgOkAv8FxXZwpBT7nrWrgkYQX9v0/KEzdozldXvFx8GAGaWaj7OEZIaR+gP8FSw+3YNFDwQbHvZ1zLWOxeFZyu8L0ikNd6mJd3nAdWSl+8aTk4uF86Jldd9Fm0/QvQlUOYY1qlr396FeSyIwQcwqKoqaAuVBM40z32VV6BgsAHhzLIZDasgKhA5wgfAyGUVoy6h0yv7AuCD5V/1Yzs67JTXpL++dAsY/kxWu4N/8U30Q2KfaVTLjrOhPACvBykhWlowMsIPk RDsM+z/B f2HHiscoS99Gaua30XbFtZBAkbAxQ7VT4VXqLQuwUbcvkvaHm8m4X+EvPgy1DtdUamf0aoK9HqB/86Q+KzFfFbxkF5LPgx5O+WcTyYqweZ/jR2yT1J1/ochTJweXJk9lXGkimu2H8XMh48SRVgNigrpkUTiVVNRjBP+nO96K4vGbN27yEyRUeidviDkI80iyOMsMWsGfxnk+2lL/vMtxgzqOPWVisnCecOtTDznu1R3RSCTDMk9SStFAYLs1kQXPz315G5R0/T6ZmD/ZOyNjdtz3wSCEKblLs3Ack/zm7XXWtLX3b67Gx9gKXVH1rCeMPnO4pJdz6RVwnua61LmxV3DoeTmZGIeAAE53Q25IAaH/51NJwAdefDEc9JH3GMMyBQwEX487M6KVdmHCbxUodHLS05a4ataVY5Ogn X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Subsequent patches implement `Vmalloc` and `KVmalloc` allocators, hence align `KernelAllocator` to this naming scheme. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index c83b6dff896d..e32182f91167 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -6,7 +6,7 @@ use core::alloc::{GlobalAlloc, Layout}; use core::ptr; -struct KernelAllocator; +struct Kmalloc; /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -36,7 +36,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } } -unsafe impl GlobalAlloc for KernelAllocator { +unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety // requirement. @@ -72,7 +72,7 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } #[global_allocator] -static ALLOCATOR: KernelAllocator = KernelAllocator; +static ALLOCATOR: Kmalloc = Kmalloc; // See . #[no_mangle] From patchwork Fri Aug 16 00:10:46 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765285 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 DB8B2C52D7F for ; Fri, 16 Aug 2024 00:12:52 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5E18C8D0014; Thu, 15 Aug 2024 20:12:52 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 591E58D0002; Thu, 15 Aug 2024 20:12:52 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 432848D0014; Thu, 15 Aug 2024 20:12:52 -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 2636E8D0002 for ; Thu, 15 Aug 2024 20:12:52 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id D87ECA886D for ; Fri, 16 Aug 2024 00:12:51 +0000 (UTC) X-FDA: 82456182942.16.CC4891D Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf18.hostedemail.com (Postfix) with ESMTP id 93AFD1C0019 for ; Fri, 16 Aug 2024 00:12:49 +0000 (UTC) Authentication-Results: imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="t/wdDl6u"; spf=pass (imf18.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767134; 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=CjoFBg6FjyKuFUDXBdN8jKXJtYkPUu1fNu2pQTTGwLQ=; b=NVcgVz8DPOZiYP+QXxYSpp/U+juey0ILoGTL7/XPfzDuflR6iWEudbMyjadqK1KO+bTSFP STt0XIxMkBLwNpB1HKtxRZSclP6XXc+rKqZUMdHpFn70L79LBI0LIJR6BficP0m2L7zeen hv/BdtvWhSppEdgKD7QloRc1lt2D4L0= ARC-Authentication-Results: i=1; imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="t/wdDl6u"; spf=pass (imf18.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767134; a=rsa-sha256; cv=none; b=D8ORACF/LT2k5BiBMVAOzf7ya1Q6SfBsEsTbXvqdcFqMqf5caNqKL1WyGxvSbPioUJQcnI eHIF6xPS6KZECVQhZ6Bcp5+oAgxNWKXeSL9rsQYTxDkSRquk0yrzYreeij2oWE5/uKWWca LPvyj/EH9LKuTEoDr0SM9HC4mg/c3qM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 022D7CE1E96; Fri, 16 Aug 2024 00:12:47 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 57C8DC32786; Fri, 16 Aug 2024 00:12:41 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767166; bh=COuk7znl+HjiX4xGBpCWDPtlc/E5h9xKKHzNxA7pQHE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=t/wdDl6uEHh61aUhmM3qE0AxoF1wgEbdP+4ptANWSkk1u38xN8evOIHWgEeI3nd2k tqS5HoiMPXj2sd5aVUM8bk2eGVGRqBDQMRP/oYxY4rgzOnB793kd+luf0I/aiTnSZA WC/5YorGjI50ujd+LVTKYlHJs4jMSps/fPte5nv3Zx+ByzEAiSwGM4EPFobVWqCJe0 dihBbG/9rKwLNVETLKf8FGzBVGhY3j8N6ohKceKLKqVzBZmd2VdD7lXrLJ5cTq/LIu tjLrDnQLA4u/3d3edKAS0z+1Ysqntk+BHKBaRMAQ7eHquxYbgBycvFfPaimtG6DXp5 ESpHgA2rgRSfA== 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 v6 04/26] rust: alloc: implement `Allocator` for `Kmalloc` Date: Fri, 16 Aug 2024 02:10:46 +0200 Message-ID: <20240816001216.26575-5-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 93AFD1C0019 X-Stat-Signature: dreommz18m4syiajx365eirijpumhgp1 X-HE-Tag: 1723767169-581620 X-HE-Meta: U2FsdGVkX1/QztLmvX2zU7ZSxu6MkUbPvYnLcX7tnu66/BA35iE2+UTFHu9XoUOF5f0fp+9J6EPzHHpQR5DfQTPo5p/tT00rqU92A9ggB0QLmuitovR/Mya777EAyTvfGMJm7O6vVyoqS2lCLTiIP7XyIbn7Qgi4ybys0coZOkmJHTYS+U93TrOPxGQ1UsmXauNRIHwoHTmZCvn0z0FokhTnhA2JLzeexvcs5zDzY7ugnCFVyCHRNkcBXeq/JYntOoGF4YCbed9IwXxYtMyTMNAWivsmxt2WJtdp1hcKm8LyGZMw20Ns84q2dOOFz1Ygkna9j0OOCdkd6i25gkSgC1w9zs9fDKishiIJs2EuhrwARtlqkFrFcxquf840XmLI3tMG96VHES8Y+hKpiEY+42sPD8H0ZjZUdCNqgWcV+42ij7oCtDgsk4yMk7ewOhv+sVCv9/nrNRphNuB5ajA40Pzzm/GXVLlJeFje8PSOncxG9Myn2BYuUvy1w49fCNxWpLLEqhnYsSU2UHGwtUZT21pTAB3icnWlL5OKckFC7VXqvLT0NlO3Xv0DEpkJb++uz3vNpHjMQFxtLGvrgEkzFLByyQTAG+YpMoCD3mDskTSie9Eo99jttTFRYbaaXZqicewLAKmIJKwmGxvVclQyOM+5+K7maOLdADtszf8HzWZR/+ij0hHDXfD0y0yHR+9m8sibDgcO/PmaX9Zej5qrpQblB8M80m6H5mPn8fCtzhlWDjqm01XwpeWC02wNE9JZWh/fzU9dYCp4/5J5eXBvngCgQwH+FHJpRakpSsWxSQB3pdb3EPSpACJGHRx049lH6HI2hXjZg0ElM+Bktx2wY2gVV4HmN+mZfq7DNzhFeB6VL41R3YqefoOPZqNDrVgOiBRdpbDz2sPKH5wsYgGEpLs2cdmwVS+a99xK2PUSPyUml8/GTNNAaMd1ROXyYfHYFsIcGqW5K8U9S7Uuo75 w3U0efwh Z7O5lHbxFV3nBhuxBoo9BQ/ZljL82o7+CL+zJyW1WPuvfypaNS94TH0cI+HBk9kHDg2DEu0YY4GabeaUvn/4iRdEzkTCwyqvfNDGP+KE8qBK0AzfXrstz/lioRXcRRXLi8BocupTPejyIZ3Tz0cv/S7UK4PerH7piw9uaBEu7zxYBZUAkmuUiHKEAJ8Y2MtZwlaXgNGuyzfA51t3eUlZ4GrR2I0lRIldY+XK1Kt2HXxURXFKZiiUZHfMGNWaNM6qa9vMS4ioqphW7i+y6cJ1FeGtFqeAn1dVV6F5VP/w3P+M9WtqpAOyS7/Z36PzfQDNJBK12cz5HHRwbduY= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000002, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `Allocator` for `Kmalloc`, the kernel's default allocator, typically used for objects smaller than page size. All memory allocations made with `Kmalloc` end up in `krealloc()`. It serves as allocator for the subsequently introduced types `KBox` and `KVec`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 72 +++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 9932f21b0539..477dbe3c5a2f 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; diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e32182f91167..78e7d5488843 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -1,12 +1,28 @@ // 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; -struct Kmalloc; +use crate::alloc::{AllocError, Allocator}; +use crate::bindings; + +/// 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 { @@ -36,6 +52,60 @@ 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, +); + +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`]. + unsafe fn call( + &self, + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let size = aligned_size(layout); + let ptr = match ptr { + Some(ptr) => ptr.as_ptr(), + None => ptr::null(), + }; + + // SAFETY: `ptr` is either NULL or valid by the safety requirements 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 { + NonNull::dangling() + } else { + NonNull::new(raw_ptr).ok_or(AllocError)? + }; + + Ok(NonNull::slice_from_raw_parts(ptr, size)) + } +} + +unsafe impl Allocator for Kmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // SAFETY: `ReallocFunc::call` has the same safety requirements as `Allocator::realloc`. + unsafe { ReallocFunc::KREALLOC.call(ptr, layout, flags) } + } +} + unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety From patchwork Fri Aug 16 00:10:47 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765286 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 8CA78C52D7D for ; Fri, 16 Aug 2024 00:12:55 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D34B28D0015; Thu, 15 Aug 2024 20:12:54 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id CE5CE8D0002; Thu, 15 Aug 2024 20:12:54 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B38688D0015; Thu, 15 Aug 2024 20:12:54 -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 988EF8D0002 for ; Thu, 15 Aug 2024 20:12:54 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 4A56C14187D for ; Fri, 16 Aug 2024 00:12:54 +0000 (UTC) X-FDA: 82456183068.11.0BE7DF0 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf03.hostedemail.com (Postfix) with ESMTP id A3B9420005 for ; Fri, 16 Aug 2024 00:12:52 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Mptd4JKJ; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767136; 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=NctXb/9T9ONoA/cLwLRShaTVahD2/X5m2M9L3dXU834=; b=Bc7Ez6OJkuCwa2jLtMzQ/f19F5Bg2CPAkKpDTNRHuc820un2z/NIKDB/tlbrrmN4uXiOOT 1YiPsocwdFUL7PR8xdQZHq2GUdMdQ5EJtPj48p7GHtk5kshpHaFHldL7RT2v9e09gKeY92 tKEWfHiynaU1jvRaKAxhlmcOXG9+J9o= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Mptd4JKJ; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767136; a=rsa-sha256; cv=none; b=rojqPKGkgpfvqVBY8UM0071rWV3cKbjJC5QN4WTsqtUaHSo6zq9xekpiSBz8re/YFZ6c1t DcuCd/UDyAGrU0I4C3MzpjvVYpgNzRl3oH+ifghPRd3UvpgCTxuZpiUoCY4G1WLLsz/dt7 KTO++unrbGpMtOOmmdtYgXBnjAN7FAE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id CE74262058; Fri, 16 Aug 2024 00:12:51 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A4F9EC4AF09; Fri, 16 Aug 2024 00:12:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767171; bh=xS2F4hvF8mQiKszeCLTojdsU+ekVrYxlxLHbB2WYsV8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Mptd4JKJ0SXQrCoV8gnzgZkaEtUMDY/zq8KAdqLxmuHAr+VEXXfnxdn07L95hCM67 SWTm9DEjWk0wyzn0DbQqZl5Na9O0xmMlVfXgNkToVSCWEHS1EINnBk4LdgsAIKwa5q BDVi5OFRjMsFLkqHYLpL+GSWXpkRTCtq0PtHFFmg8dIVl+VVwAJJ0abKIGiFzTSMN3 KGVHzEBANNSiKdAuP4Vpwj+rf6PycMC11jrBydPUox2Q77Fn2WNmU0ATOeSDqls5vr DuFr1l/NjUXF4gUitfym1UN5IUlYiFYaU3JHjG0plvJYkIXzTV5K0roUB1hNS0/c3b kgJza8BKjQlnQ== 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 v6 05/26] rust: alloc: add module `allocator_test` Date: Fri, 16 Aug 2024 02:10:47 +0200 Message-ID: <20240816001216.26575-6-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: A3B9420005 X-Stat-Signature: uf1cpjdoyeuskrab5z5k8aau36oq65q3 X-HE-Tag: 1723767172-581567 X-HE-Meta: U2FsdGVkX19OQBAaSJ3WDfgl+0i9NV4xr3WPHIIRwB3CFeAUT/LUcoV8/ShnIQAntLNup0Z9vYbDKAPICcbG5fHj9NBaODvVVkeBVImG6mBJHIIQijCktxVwP77Ao60XR9TNMzsjOCs0pHU/nvQ/PFJD785oQCph3Su2UZV9jioJIzAD+5VtLsLEE1C4ET3Co+AJ9dxSV4Wlaj0h7ZJYg8I0/F+2hB0LyKb/rWBkDNZCmax9iZ+hxLc/1+DA1KXHfMWJWSMguULKNycDowza9kHxPbhyT3WWKfI6uENFpkmqosYDLXRFaR3kRI46ei7qdLl+AClNvzy+4fhsfN91cfkXovjfaedvUbFZDktCVWB76y2FehLsX32c7U6aDQGxWArYaLnZYDwxEEUCMBmKTjZ9ybGuo6G7SQrqJyKSbb7A+DtK1fckpmuHY+G7PdhsqBzyvtWKKKu+nigKy59L7PdFwmi0kwnhyuvSekpFHc7MDTVptfYvQma/3gn07dXZR/Vm5gztdbkfz5JSTJuWmCj1ck+Ie4lTY+ZH9PVzKJOtf+yPP+zdgwxRz/FKWy226GQYDFkLsV1yGlS9h7fuqLiJ+nDVXCmoW9hFK3pGwDSXByLiYTWUtnpjwmhHjjyXpxRGbJtG0RgP4fZZzJ3KHj9a+kQnk5qKTC37BS9U4lPQctjKWhoz9NLuU7jblH2hwhc1kXL9E3xck1NmlLcf9fKVWrKclQNlMlefw9kfgW+1t+Wm3KiVn3/DOO5uvKZ8D19PmabdqFuPpI+ujuFs/OiC+HGpOa2r0gzRy5sFCtHMfx6IEkR5jlKDt7fLxdp/2ANY/arWj108DD76Aoc203Xhu0wB+bQvFi+ezEHN3a1QpA1Nz+tnBA6UVi9VP9ca5o+p/bEugFGR3PEUN3o3lgjnvsNYMfExicb2m8vBfJR5gHBCcUFv53Mb3YLQ1RSPYzOtqyz8bWJeU/Jedlb g1u5/xhF 2UwI3ZapHWWTODapd94prmrazTTVjUnjpelg1IpwzKey3ciNpIY8HM+e2OkFpcTBI/vMsJYHftaWoIML23K2H+AQyWIA/EUEgJb59QfWdXjp73TKSC3PEkcNrpqNzG6xk+WqZnrVlg+lr9m/NVB4L8j7aUS8/ie29dtDkKmqyHzPo8chvLEC9O60YqDT4HHsthbNAspzWbkDez6uW61BF0hjg7E3xVnmQE77o40+HiT6ZRf9DiZ07sTHMk2WRJxgm9eNaMJq8agOxZpmeRp5+XPR73U9trmlf+nw+FGS4dM6kVLRGFKYOq9C0K4jPIryWoVikmrjAq2+CMQvkVKafr5aoCxb+saByB6rFA9zSIA8IlzQFeZYYwJpyyeAcFmoIPuqr 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 Signed-off-by: Danilo Krummrich Reviewed-by: Gary Guo --- 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 477dbe3c5a2f..91a367a58f36 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 Aug 16 00:10:48 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765287 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 A3682C52D7D for ; Fri, 16 Aug 2024 00:13:00 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3982A8D0016; Thu, 15 Aug 2024 20:13:00 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 348278D0002; Thu, 15 Aug 2024 20:13:00 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1EA068D0016; Thu, 15 Aug 2024 20:13:00 -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 F3D498D0002 for ; Thu, 15 Aug 2024 20:12:59 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 94273C18B4 for ; Fri, 16 Aug 2024 00:12:59 +0000 (UTC) X-FDA: 82456183278.10.671C177 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf15.hostedemail.com (Postfix) with ESMTP id DF3A1A0013 for ; Fri, 16 Aug 2024 00:12:57 +0000 (UTC) Authentication-Results: imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ivbEzzrL; spf=pass (imf15.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767141; a=rsa-sha256; cv=none; b=1sgiKJIWeK+EJyDdZ3SEory/jsVsPRSzBGz3kVWlKZq3ZgOYydVYJ77iXMFCniHe8dn87D 7ADNslu/xjyWA1QDB2xSKzA/eltNK/ZKx79YuNiGZ6YXPuQwI+8Zpah8sho+4Ly0Be6UY9 +r9JjL664nMnDguypjJJaGIuvvMMIS0= ARC-Authentication-Results: i=1; imf15.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ivbEzzrL; spf=pass (imf15.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767141; 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=NAdps/r0odAShDVfs7UjImCjLgMSC6fLOI+bzykHcRg=; b=k3I4R4lkYd63Mle5iMGJChUJQ5stZjO2/ZxuzLA9I8C652uX/07c3ulfZOZrHVuswVXN5t scM9Zsm1esK+ALuHlMIHzRCFQaVVSI4gMwB7lMDHbA2sCGFjmWQujyvOmN6P8YDrrU6dIW WNS1rwh4yPTidn5C84CuSgagJn/7AGU= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 26E6E62064; Fri, 16 Aug 2024 00:12:57 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id F230AC32786; Fri, 16 Aug 2024 00:12:51 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767176; bh=hX4ulOq19dU7ZAikDhvlf8QJavajKpr4Y1F7LrLQguk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ivbEzzrL5ZD6557M5uq0jSgcjAt5wWYtmCbIQ9K7oSjxLS807foNstdYN4j+jMGpP lSwcGuFd6VKoIx0D3B/gSvm3oc582Z6pZRPv+S80DVcnUvzIlmM4YKWx39BMgSzj6D dMOLVSiWZJBF3w2cu5cgWBghkp8xwFSWkr0HKatrCBRK+S20NXI8Y6ovt29z/BYZhx /ZgS/fANOeqkwB8g+kl175jYA+jQf8rGp5C0G1/4w3805JTs39UyDfPmK2t28nPuFV UVutHfCih2dJpohwcLfc/JOYLznPNMIJvo7XMk60wrDDhIsPGogxBLJ3n8D0wpaXTA s4ye2rlW5fzYw== 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 v6 06/26] rust: alloc: implement `Vmalloc` allocator Date: Fri, 16 Aug 2024 02:10:48 +0200 Message-ID: <20240816001216.26575-7-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: ppu585ifuequxo13au69ytoec8gdtmiu X-Rspamd-Queue-Id: DF3A1A0013 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723767177-550032 X-HE-Meta: U2FsdGVkX18laI46UKqNC+g1ibLTd+O4qMj/eN+wXJOmBQHRd5+rj8nUncJ0P/PZu2g38xUzSrzEMR99M2beTKJbvNo2BCq/m9nftPmkjDuPD1aqx8F/Iq+IG4Fnh9oEUFhbDnyldqKTA8Sj81ogEiel7jOhqdqrfRfhNAz+N8J2D2Xv7a4svxQmpUt965tjkneJ4RA2GyI2hgcf0/dx6iuBWvfkKsEzlw2ObWhjxSGe/Py+1IyAdv8eBg7/2KrZcPrFzOwEGkU22dmJZyV4TrC6/7Lw+y4YbiHcowWrm8prIbjLkp3J8JBtbU6lNVVLHf5hszrQhB1ukARKkLVl7+c3jjvZI4wrAA9+IZPsdGLTeec74rtc8J7yl+epHlvObVFlQa8MV6k7kPvF74+634qA9e9mC6zRqhLaOJ+Cht8ucB3pil5gMtjrhETN9M1J/hi6FdYM46wUoQQFdGvoocIuRpX7P/vtbp8YNXpqWDYzoOpxkkAUkEZQtSzAayTsP93qkDRxajeXIytJvoeXIBkmZ+szLt+FH1KqUxfBKG4pLv8392zeW9pA3+GhwF3V3HrSxWJbzQjmRYdlwBb+MGr7Gu+rCQTM7cz0T62GTPwfjqfQITsX8SXG5YVEVEEYuvD9xgPIY47H12XUtibJJc6f+bDK7Vir9k7fDZWIH5bresfcTR8kkCnzGtEw8R6k0CDMvqlltBFJ7HBSWZTCtGbhO++eGOB9WaVy6/OHCpq5k402eamckpppR9I3HgHTVtyZ4ayFl3lsJEFqFkAQLhWi1uJyfeLksAt6e7/31a1r4/Vuf8n2U7060vXeEoKDBCgk/OY6eMxDH581reWai8QTTS2lFWyL63y/m5LPi054fLFMj30GMdd2Q76MhPqB7/Na7EPTO6hYeaSQmnszycSqevs0QAozMRa8l07lrgb8lNJ6JuwdDUk/CaO3Bn+Ahqr8arzu5wrFWMsPMpD IJ7WdL47 yNF11dtDDqZvsoo8519TF0v30IHJwxgO5h5FC/3KmrSiMt0dxVU7MufoDzMcdG1c4AxQcVgM3NYxgGsRwLrO+WEzOqN2h84Dj3dUtzBHFGI/+e7VPKOwQ74+gexkLSW/6K5RjyYIAXUwfWWsaLBdWHO2JL9uuX//7wlOAE8dW9MOgjDlhuGXhBvtjnEIr77EPGFD+/JafAL8IdqM4mYITI68T82FzBWuPo++JOYM/B5rFg4QX5uPid72ENuEiGQ9xCBG9wESe4knPx6ktTUnRnGx5YWuzwYrgV2oowT/onRr0kIyg7g9jMf/WYnMW5iFWYb3/0uk8KyhtxOI= 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 Signed-off-by: Danilo Krummrich --- rust/helpers.c | 8 ++++++++ rust/kernel/alloc/allocator.rs | 32 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 41 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 41df5b1a6de6..96f8b37a668b 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -36,6 +36,7 @@ #include #include #include +#include #include #include @@ -248,6 +249,13 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); +void * __must_check __realloc_size(2) +rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) +{ + return vrealloc(p, size, flags); +} +EXPORT_SYMBOL_GPL(rust_helper_vrealloc); + void rust_helper_rb_link_node(struct rb_node *node, struct rb_node *parent, struct rb_node **rb_link) { diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 78e7d5488843..09a322e9168d 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`]. @@ -141,6 +154,25 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } } +unsafe impl Allocator for Vmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::VREALLOC.call(ptr, 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 Aug 16 00:10:49 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765288 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 D377AC52D7F for ; Fri, 16 Aug 2024 00:13:05 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6F36A8D0017; Thu, 15 Aug 2024 20:13:05 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6A45E8D0002; Thu, 15 Aug 2024 20:13:05 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 56C638D0017; Thu, 15 Aug 2024 20:13:05 -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 38CBB8D0002 for ; Thu, 15 Aug 2024 20:13:05 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id EE6D741926 for ; Fri, 16 Aug 2024 00:13:04 +0000 (UTC) X-FDA: 82456183488.14.E48869D Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf26.hostedemail.com (Postfix) with ESMTP id 482C6140012 for ; Fri, 16 Aug 2024 00:13:03 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=SQZzPoe9; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf26.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=1723767123; a=rsa-sha256; cv=none; b=YxFdiOAGkpT6GegCsRIcH4W6PZ3zLdGKbfV2KouLlL8YyTs/R0Ps0YA9NzRB5k/GkxrXEg gsT8tzmwr5BZxkGXoIpW313OAOdneKbtRNujOPQU3hdx4QG4VPBNrhokWOYKOKH/BYIQRz 3kqb4WagmKFJx9KFg3zAXBtNDW1DDmk= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=SQZzPoe9; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf26.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=1723767123; 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=yzoXiTotH678Qkh+dnu8Yqkf00zerUhFlQXr98AF0V8=; b=RQ8gE5BM37yTSw4vQeNHGzF2Z6rMASE0YjSnq3/CtNYvq76Obo8uhkVmUcqB4pCpPx66yy 8M6G10i7QqzNLAfLo7aOALKK1G0YB4Sca4b+LMlE+7haOxk0/4LQE1e482+UXQ7/A7kdfc 1dUMq1uC2KYOVA8xUDS37nz6YGaNrhA= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 7777F62066; Fri, 16 Aug 2024 00:13:02 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 48C41C32786; Fri, 16 Aug 2024 00:12:57 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767182; bh=aTI9CEsgYyrzlstHqemFJKjddMy0vpbtXP30W2anE+I=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=SQZzPoe97D+j/WBU1u+3YngiwpWqgLo/aAIXWVe+iB8QGj1vygnofidHkGK6NnMD7 BVS4b9/lkbFii1pXNCEfa8Z2jbz2iaRVZvV1KOdGF2uhpj906RfBaFhIoF2IV14pPP tE2k4VDoEtGSx4xwS5O+8O7H7ScuoGirsRIyNoVp7mqmymOEOQ2TCA244+StOBxnau lkbE7M70hQtDF/cOKYr3eVKg+5KAa1lSq9yRbRQMO0kIItZHqYJ8eEMfxmw9FONO42 4xIdX1eEodyTFZ/kkx9/L/EExQ19aqDlS+3hqOFnUB2C73KrT/RUqrxLLWGunTmEGi utML9JoiTM+dQ== 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 v6 07/26] rust: alloc: implement `KVmalloc` allocator Date: Fri, 16 Aug 2024 02:10:49 +0200 Message-ID: <20240816001216.26575-8-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 482C6140012 X-Stat-Signature: 7bh8m38ypyhokoxppoe8neeh7yp7f6qe X-Rspam-User: X-HE-Tag: 1723767183-275317 X-HE-Meta: U2FsdGVkX18yNALrVO4d/+Ga/WcrBRtKGYQ4UWZZ+5mfLi0d8j0Cv2tGG41zRVUutSV+RfjgPuNRQ8NpFhOCF91lxVuluHFlzO8t4Wui5rbFwBGMeqOIYaBrI40Sv6Rak+B0gmkV8eJ9OOcc8vDaTmthwoiFRsklEaWJkYYOcYyPG5aF17MLGT2rvUoY4AwFWQCyP+HbwH2bCbDowwRnfAHLJzrm7t2xDBLdo0OFyw4laOATQzfCvfFYgNarVkIHIdM5cMKMASvQAUuYktkhdbJaiYYaIpTImSF1qWKfmVHgegiOY6TTfXy5B1sgNJaYaNHHuXvIOPib4QjDKxaeQUspwsY3wZWQAuKpN5aYhvKp4kC4+9ghePvmv7qnWopSDf2C7P6qsOAr/6Y9OPcZZbvlZO8eZX1c8gYnT7ZGwOx4JeHla46XszmVpTvFzNihl0eil62QN9ShDoGpSF6eXF5UGI+yPUlsmXizwoRJCd9+62wSU7X8ylc3MnZinCyjLZXs/97hnK2dIoBWzw2BLso3zORv1Dp7msh/9x0RHYS5x39zek/goTp7xLHbxguFBzd/KsA1f2kfm+BuGw9EsZlwgLNks/YSM0gZo+XBBGctr9qOoDquFwYpZ4HA6ItQYDeenJx6WAbFm4ALBqINyD2djyCf+G9FH8bjFlqqNmqu3DDwrfDE7kSs7wPX0eks/jeBZBqVM2mYaqh5TVfx/ksq8M/sepThifBXc9QZQ386fW2Sonrm5io3iufuCxkWA2S0MyQP6CByXEJlEsfVPy+mLbjqTQH0HapIkQ/wlCFXUqM7pZwoQ1K6jvK5j8mYLASq5pLUoU5dMY8w+lclIYpU89W6saOtWb0Dbr/LYLLkPKL5XON6yRPD/xWuGtZY1c/XFrAW+TfpWmFmSbZfBMVc2qQSYTHSA8b/UOgnuBY6ADm8mWDjTJ2HsRYrL+Ith6kDx0xDRIzdN4WYfkL rHDHmPdN Bs1KFKXfDbHvwm6xAYPOv8ZicSXKAXauaVuZLl0DB1tPbBD+kXQ4g/IjuBpYBELEtBixMldtRrtmHxjAASmDgk6UQ6gR4cVkF2X80j2NZRaEfuoyoVo4qNCJmwC92zACjPThWYUYNT0x3GiJinj/zncAGOxW/89raW7u2pygjcxL4YMh+OhktjtK5jsLd3fbDZpJ/8ZO/7gaNcQikwhxvJ3KHcB25cdgAkmEGol8J2znRmdSDvWqJqfdvEJyP6mCx2dqd2znbC3U9zVKysJUFJi8xtt4q++Y4Xe/SBFK8VkRn560fRXGisYI4CwROe+8Ivk8cGEVZge8QQNg= 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 Signed-off-by: Danilo Krummrich --- rust/helpers.c | 7 +++++++ rust/kernel/alloc/allocator.rs | 31 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 39 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 96f8b37a668b..9a7604e3a749 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -256,6 +256,13 @@ rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_vrealloc); +void * __must_check __realloc_size(2) +rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags) +{ + return kvrealloc(p, size, flags); +} +EXPORT_SYMBOL_GPL(rust_helper_kvrealloc); + void rust_helper_rb_link_node(struct rb_node *node, struct rb_node *parent, struct rb_node **rb_link) { diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 09a322e9168d..0183fbac1ada 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 requsted 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`]. @@ -173,6 +185,25 @@ unsafe fn realloc( } } +unsafe impl Allocator for KVmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("KVmalloc does not support alignments larger than 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, 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 Aug 16 00:10:50 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765289 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 221F6C52D7D for ; Fri, 16 Aug 2024 00:13:14 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A4E7C8D0018; Thu, 15 Aug 2024 20:13:13 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 9FEF28D0002; Thu, 15 Aug 2024 20:13:13 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8C6A88D0018; Thu, 15 Aug 2024 20:13:13 -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 6F74D8D0002 for ; Thu, 15 Aug 2024 20:13:13 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 25602818AD for ; Fri, 16 Aug 2024 00:13:13 +0000 (UTC) X-FDA: 82456183866.17.B5D4CA8 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf01.hostedemail.com (Postfix) with ESMTP id 2A6E640015 for ; Fri, 16 Aug 2024 00:13:10 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=SEO7hcjA; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767094; 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=xY2q6TvN5yPmUZeWZDEd6ys9gSCkNIy8fcuOjgTyz0c=; b=3J8Dp8hCIOhhyMrG4/NlYpOoWV1Uy2BLMcxpcU/PZo1noi0r94tLXw6oBRQClzcqCQeT77 O1YM3jRRRNGX2v6SWxCT2V9RAGJhwia5RiO26Ylgl1PciEGOrVgBVcQ1WLStIK+NSVzcQ0 9kz4TKmjJ6h/iNgzmDEkgidu9G3n55g= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=SEO7hcjA; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767094; a=rsa-sha256; cv=none; b=yG2cOSCnDsZCh5U4ksfoTX7TJajJtrlf45Trw4uV0D2KWfS8xX+fZEv1nl7GkUaZILxEdX l/tvFt2+UaZdcnw4Yxbk3Uy8KPYxR2D1CrvicHNRloKIH+MIlK0fprbMPqj1pV4A8E4SCx WdhnafppEXQzCsKeqV10H7BFFb/T8Kk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 4F36ACE1EA1; Fri, 16 Aug 2024 00:13:08 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 983CDC32786; Fri, 16 Aug 2024 00:13:02 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767187; bh=+Q2tfhai1Eb3pcjdgIQSFOSo90TRqwwdVLlFVhO/a9w=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=SEO7hcjAZYf/irob5D8Xw7gx/QKeDkU6wXpp9wkrJJsPCfb9CjhnaFsZ5HNsBgSDE irKx2T7ipVZQrSJqixDZslXSvkuJz0aXVX7zN/9ex7LjN3/siJjE0uNCThMuBNPlLg BcKzkZBkEM20+7krNm2Vg4Befyih+8/cnV1r0nT/+bIfvzyiPA6hAjeK9jHds0Qxq4 KZOvf7wrDkmxjBx1HjqZd9GTUKy72/AiJzmuGJogJjUvUQQF+Tap3uTQDP0sfCNJKv K6jmZhLMqiHZv2JTAz6oo3AxoE70dkyO7U9B/32lJJJz2WAIZNGlnuIsLNOecf2QO2 o8IKcWJdImKlw== 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 v6 08/26] rust: alloc: add __GFP_NOWARN to `Flags` Date: Fri, 16 Aug 2024 02:10:50 +0200 Message-ID: <20240816001216.26575-9-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 2A6E640015 X-Stat-Signature: siwupr7syzbu5cxcggnda5ewai8tmh3b X-Rspam-User: X-HE-Tag: 1723767190-912545 X-HE-Meta: U2FsdGVkX1+4GSqGmoEZ+0b/fhlVtDnIzA5TDKnsGcfEdSzlWBZiJ/BfYyxPEtGe8eqhlPoTILNsVuVCp1IxnyvyCq19wgGiiNE2NTI3TV61hsDoPVTKuTfTWAIroa6/mzq9lvN2F+zIHGIowYVs/74lVThwwxOgpXeGLIIqK/6qUbma5dU9Xtk50uaFeDBWP1Tz2O6m9N8CmblULZkgNANJ+XeLjp8DbR7eieQEQqrs9ypLpk1n271dspv3PLrxNuTVsSgZ34hGMNxdIhaYWMhjrr/YRgRxAIxqZq4R5XJRjJePBaLguEbtAt5o1SOeOLY+sFYkjIjp7KFXmI6Btbt+EYr+gfUfLbd/R6VTpxbo38FzJa8/0cJiwzYsBRGnsfEc7cEDHIZE9Ui2hIsOLkO8wZfO3kJMZ7k+lnCh0TTO+DgCw9L1CqfVkmFJIldpMPKicUbuy2msJoqz5MHmmBle7yJrxKSIY2ZvZUOAe4i8xRdsi/Zf01k7Y+K2rqbRsQ9MSvBDRZBLpECMsUqlkEIMwKx3bpvicTlp3nCAnCJE/XDG8bzTkvkAdsVtirvpu5WQ5akbl/F1Gb8XS2IgofdFJ2PxNT1HB8RfkmNAjsZldFR0Vi8ij9ifrX+GHnPESbly/KuJD6zugYVf9wd8o7/gAh/A2A7Sv+iT4MprAZR6IGUac5wPMd+Ijm/NglfjaWGgbwBhWw85qWkzd4PTpdKn6/rFix1qOMIg3PJfi/sJzKbt/OuFWSAebxPoMbP2eiqXnvIda2G0FI1xhJfHHQI/lcM/SWdeekgSosaV/wYOeeTZZvbr8YdLsJttPSG0qrPRnAeZjFdwHFD2ml43L/P53yZ/pcIwjUjSomVSqGL+ATReOASTn0jLGBY96ffQTXs1X9xjRbbCICSCKOymP7NFY30faVzUviXTapN44NsNCeVYOl0ypu45WCT4lfwZlr+33Mg34dsjokM5X+6 aU8gz+nh QmijIPIXs/VxJJr7pVLfXp2jLeQRaBRrXmVcQz+Q9FpxxxjM+XpXkNQhVj9aEFQzrgL74UwIP236JvBAc6mDskO071fEGph/PyusC2CfUGfd28UhgLS5vGnooiraKRfAP8DEbsgxs8epIG20etIeiY6gvOxoQncvXLwc/YKyviDWIQPrn/Eqm/4KnsFKxKuXNynVc38/zstBPFXE7XRDGFVXGbBaFSggTMNkvLbSn0s4GNyUxNl8sM/8xX/OXtuuxNq4WJcT39Oj2usDYeAla7WozZqgWi49TD5MCmgQIhOIsnLxoRk5mbNcYs3OJvUctRCXPJWIDX4NcFox6Usl6y3VSgHG6ox9k6bUd5IAvJFJ9jy2Q7hwjf2PKWA== 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 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 b5793142904d..90493123bdf1 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -37,4 +37,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 91a367a58f36..53a93617a9f6 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 Aug 16 00:10:51 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765290 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 A9CD1C531DE for ; Fri, 16 Aug 2024 00:13:16 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 399728D0019; Thu, 15 Aug 2024 20:13:16 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 349A58D0002; Thu, 15 Aug 2024 20:13:16 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1C2BC8D0019; Thu, 15 Aug 2024 20:13:16 -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 E86578D0002 for ; Thu, 15 Aug 2024 20:13:15 -0400 (EDT) Received: from smtpin09.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id A537C1218C3 for ; Fri, 16 Aug 2024 00:13:15 +0000 (UTC) X-FDA: 82456183950.09.ED21618 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id EF51340009 for ; Fri, 16 Aug 2024 00:13:13 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=JHtxN0Tu; 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=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767120; 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=RD1/rgjENUpZei3F577kC7cWIX1mC0k7UxN4ESXCQPA=; b=sv0mE9rqD+BQ3Y2ZRcP9takF+f4z0yIypwoBHtikfKWI/uHIMYJm8aikuT2Pm6Ya525y9z PXUFdQrmYeR+z41CTS7DUm6c5vYVIJ/6i90QKN7SM457SIeoRYn6ZBJuF/PiKLL2+YMQXS PmKK8SalC0EK1jDox2RXsqcOpy/NPNg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767120; a=rsa-sha256; cv=none; b=VYAJvgT9XynfJ0+j9KD9mFn/MC44syvqOxFho136UZegLQIxy5DcbC+Eu+dHYk/m7wniQo oj/WaOwNlY8HkQvGSiJxrDXOix28vyQjygJCgmMhz0WmqypzYX+b5cHXHnybF1K9C/fv0G gU3i0Gq8EC9X26A9WTeuN0+An+tGdGE= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=JHtxN0Tu; 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=none) 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 1817562061; Fri, 16 Aug 2024 00:13:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E309FC4AF09; Fri, 16 Aug 2024 00:13:07 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767192; bh=dRpIGeDmmzp1Vjiraq+rUyhEk2AEGmqWjpSaCAS4sJs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=JHtxN0TuBS7ngvGJFlXXIkdsl3sg4yvFdcUyLRg54m+hpn35hw/f5IzFengL0TwD3 TWDOdkgl+zV62FM5U+TRQh7kvdJ/U1iT5m6D8Gn5zMOV+N5x29fcTMyOjyFwEz4XQN 9btrSR3ouZqG4iFH7j4bFZXYoLIoTDu2xLtbRmJky0suLxVJyH7DqgpcNUwtwuyaYA LOnxNIQ8j105+GdhGDSvrjv0VjReIUUS31PeleeXfn1rzPddXO2SMqrykq6SG5WczG 5pZobcfpc6rtLSBeXOvZbQFdYAtjbzRYpXRJ3xSJUHFWN8J1ZI/9Sj9OoHH8KUdbBc FVbqfD4Z/txAQ== 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 v6 09/26] rust: alloc: implement kernel `Box` Date: Fri, 16 Aug 2024 02:10:51 +0200 Message-ID: <20240816001216.26575-10-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: EF51340009 X-Stat-Signature: 4z8iiuxgkfwe57m8n61bxp7ctt4byhrd X-HE-Tag: 1723767193-57791 X-HE-Meta: U2FsdGVkX1+2/ofPvFofjCrb7f62VBvt2hdLVWVOdSdWZkPRY+3o+BG0ePjOS9W1dmh+7BEFyBXCKWeSEpHFc8hiC/umB5Qg13eAeJJ6+5RFE1exsAHly38nF5cMWupGOTy318dud35np9Fc9pVT+pQhxCQkMJt8ZBonv6kTYZ4/sGOVFikbuI2cl6H2UtBXuUMKsk8AroiAHt5llAYXC5kwnfcpBHbdYIBCYMcQ2P0BZnLDr6BV9c4/AKP2UtiVg/ujtEkEKThZdgFXuLOo7ONPlFmu4J30Fzmaa6yplQlgpuGKxd5kuAG+tPG6wv80B2/qO09cD4B2+XM790VuuGHnXIvw3trmH7HBqspTpDpaFnLTPReR7wkidOhOVJVggpQISLCd85ZxAOUdgKGQOcQqV3GuXY8vBEa9LloRLlOhhVDBiSZFuYAmDiKiOUgK5yQCp8ylIyGXaLLosQg/clHcRctK9HOYpVnoeRMTearAfVGgU31M6etH9aNquwCnATivy1LmnY2I8IJ92RsODRhfdNo7PEKCFGFWxFg6k1PtcQQOc/OYjVKUq1nNEjokSJ20tgMoF/RGx1mvVPomeTB4e3/snt86TsVq8BTPjFauOzAKtvqP4SKPOVtBu3I50Y7z/r663bnX658l6zKYciw3+g45bT9jC5IbjX6gQ/zWQ/htmYaLk2XwgnOe6VCtuzRmu78/F34vysWWNI7CEEbvP+ovmCu+Ss3QF8qQg+cR1sBvE9cxNnJtILoAtPGZP/Ed6e23Pq0PfyNKprvinMdG1m4wO99mDPf1ElJ7COcR2aXCOk2qbXSiYcbBNI6QxzklKhBzNoJuP8sCUU1qsdVh57A5WkFAppqWqhqxHSCedfEB9yQ8DMCU9B6LiTy6zlWSVHGJbtP00cbsvcCJGf5Pg61CV7uHBcjDVp/j2gGlq1QRwxUmDygWpCZlfEtAabDjsm2EBuJ/1oQAnk0 dkuL6RRe O5zqu0fZ17Lom02qTL2NNLUp8CPNFaF+E7tg4FBzedOYqBWUI82QElZQGvWwKbuAtE3wFU2yKPBBuu/PGi50U3tH5oy85pDj9h59d9MvFd6Btw6Bt0PXevEHXGV6YE40ChD0nnI/X8G0QoAUvM4z4taODvmHHFcd270aRxZ2y0dhbfGWe//Y4yQJxETrINutXGKlCaXp9WCskCL90Au2f4/jDEOZUy3H99O8mEVGxBL9Now+pG8ZhB2C2sUqIvB69poSekcK3AT3xY9p5XkLxjgc3kb5H8ny+Wmw/i2RrwO6gVsY7aR6GaX06Vw== 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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 480 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 487 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 53a93617a9f6..0c9bb60250af 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..93b1ab9de6e8 --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,480 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +#[allow(unused_imports)] // Used in doc comments. +use super::allocator::{KVmalloc, Kmalloc, Vmalloc}; +use super::{AllocError, Allocator, Flags}; +use core::fmt; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::pin::Pin; +use core::ptr::NonNull; +use core::result::Result; + +use crate::init::{InPlaceInit, InPlaceWrite, Init, PinInit}; +use crate::types::ForeignOwnable; + +/// The kernel's [`Box`] type - a heap allocation for a single value of 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 failable. +/// +/// `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 +/// +/// The [`Box`]' pointer is always properly aligned and either points to memory allocated with `A` +/// or, for zero-sized types, is a dangling 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`. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function. + // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer. + Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData::) + } + + /// Consumes the `Box` and returns a raw pointer. + /// + /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive + /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the + /// allocation, if any. + /// + /// # Examples + /// + /// ``` + /// let x = KBox::new(24, GFP_KERNEL)?; + /// let ptr = KBox::into_raw(x); + /// let x = unsafe { KBox::from_raw(ptr) }; + /// + /// assert_eq!(*x, 24); + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + pub fn into_raw(b: Self) -> *mut T { + let b = ManuallyDrop::new(b); + + b.0.as_ptr() + } + + /// Consumes and leaks the `Box` and returns a mutable reference. + /// + /// See [Box::into_raw] for more details. + #[inline] + pub fn leak<'a>(b: Self) -> &'a mut T { + // SAFETY: `Box::into_raw` always returns a properly aligned and 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(b: Self) -> Box { + let raw = Self::into_raw(b); + + // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements + // of this function, the value inside the `Box` is in an initialized state. Hence, it is + // safe to reconstruct the `Box` as `Box`. + unsafe { Box::from_raw(raw as *mut T) } + } + + /// Writes the value and converts to `Box`. + pub fn write(mut b: Self, value: T) -> Box { + (*b).write(value); + // SAFETY: We've just initialized `boxed`'s value. + unsafe { Self::assume_init(b) } + } +} + +impl Box +where + A: Allocator, +{ + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// 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 ptr = if Self::is_zst() { + NonNull::dangling() + } else { + let layout = core::alloc::Layout::new::>(); + let ptr = A::alloc(layout, flags)?; + + ptr.cast() + }; + + // 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, 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, +{ + #[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; + type BorrowedMut<'a> = &'a mut 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() } + } + + unsafe fn borrow_mut<'a>(ptr: *const core::ffi::c_void) -> &'a mut T { + // SAFETY: The safety requirements of this method ensure that the pointer is valid and that + // nothing else will access the value for the duration of 'a. + unsafe { &mut *ptr.cast_mut().cast() } + } +} + +impl ForeignOwnable for Pin> +where + A: Allocator, +{ + type Borrowed<'a> = Pin<&'a T>; + type BorrowedMut<'a> = Pin<&'a mut 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) } + } + + unsafe fn borrow_mut<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a mut 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 { &mut *ptr.cast_mut().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 size = core::mem::size_of_val::(self); + + // SAFETY: We need to drop `self.0` in place, before we free the backing memory. + unsafe { core::ptr::drop_in_place(self.0.as_ptr()) }; + + if size != 0 { + // SAFETY: `ptr` was previously allocated with `A`. + unsafe { A::free(self.0.cast()) }; + } + } +} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 4571daec0961..a9210634a8c3 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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 Aug 16 00:10:52 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765291 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 715C4C52D7F for ; Fri, 16 Aug 2024 00:13:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 03E3E8D001A; Thu, 15 Aug 2024 20:13:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id F08BA8D0002; Thu, 15 Aug 2024 20:13:24 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D82AB8D001A; Thu, 15 Aug 2024 20:13:24 -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 B0EE48D0002 for ; Thu, 15 Aug 2024 20:13:24 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 7759D40EC6 for ; Fri, 16 Aug 2024 00:13:24 +0000 (UTC) X-FDA: 82456184328.10.FDE6A2C Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf30.hostedemail.com (Postfix) with ESMTP id 3B26680019 for ; Fri, 16 Aug 2024 00:13:21 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=s3kR45uW; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767129; 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=/WQF1QdUnCK76wT9Su5owSTYLPtHY4RkU8IikDNcUJo=; b=pbueFPpYvd+WTTV2XsUcml0p37miFjzZ94W+1uGcF6f2fOgvUweEP46ZjENQphWymsX94c KLLO4WVuLh8KyRz7vztAWV3zgybyrsdq8fdGN5BzsSnnQ/DlDAPvAuxyi4D/jeIxZBRBVa 71i7/Xl6eD5kn7HtaXwPd+e7a6ojngg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767129; a=rsa-sha256; cv=none; b=3YLmA8LY7Zl6p3bdRR+MNU69Ca8FMyPXlJpmKw+kD2hyAnzjM4S0ks5mS+vd/aOXZQ8yeK 0Nn+S3t6BqcURP+eiyCrr4+6kEo/GpxT5igtDf2XNPnLejQg+VEtFz22WXfNeRJsgbtbjz zzwXTJKhGO7tWKjNG8wsEt8aSozyYlA= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=s3kR45uW; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 1B5B3CE1E8F; Fri, 16 Aug 2024 00:13:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3AB3DC4AF10; Fri, 16 Aug 2024 00:13:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767198; bh=oZxYtJNSnwmqvfbp4grzLa0k5OvYlHwr8TWXfPLoijE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=s3kR45uW+1D//uBAq0AMPJBdl5+ezg1TsPgzxDMobbae68vsa+9KqCb6+X9VkiUeL W5ql9jNxJhrUwPJpBDqW+BFhD+F2Yjn0eCGc0/IlTGPE8lHrzW2VgHVWMRk8qF5Tto EHK0CzJQb7ou23+1+jggAiHAd+k1LEksPbSNZh1CCmoNSDY2GUSyYGzHmEtDEN1ek6 cGbQ9tYI9C5NRCifPBAeZ/f+qdbAJTgcHD46Ptnk/MqbAO1NMSAQRmHpVW+ATXJoiQ VsuhllTUgco+HoZy7Jg5SD9nPP4gCu508+KtwRphGTW8CIusfJsAxe6oD+sTGPd6L3 09fBPSHRREpEg== 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 v6 10/26] rust: treewide: switch to our kernel `Box` type Date: Fri, 16 Aug 2024 02:10:52 +0200 Message-ID: <20240816001216.26575-11-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 3B26680019 X-Stat-Signature: zp9mrxi1ir5tacx1tkgwcm83eeshqdgo X-HE-Tag: 1723767201-689586 X-HE-Meta: U2FsdGVkX1/S+CD3viVBoT4UbVXXIIflRP75jgxu2kR6kImiofKvMKr1BAGLNVA7gXSklwM+wsxUaCccoSdbf6Hdn+XdSHJgsBZKto9+7QsEnbe7TMnCKnUzzYWOCPS6mn5BaaYdToKl7C7zV6wY+H/sNJEyhDWVrwtSLcMYEegeRTZM/EdFOSo0CqCk7k1DvtoGugdFcSaV1dzKybrtYEC64eVRSdN+SfMCgbn8zKk2RFMF0A0JgAB/aYMtkA/P9C7yyi9DnlOJvlNY+ywRHeVLuH1bzYPvJFAEAhtPDtJZQ/Zza+duLIFpuf+ZkwpYgppQYjd8g2O5FkcK9duSvkqCzDPDGbCaYl5f1ws/VVa+SHgk/O2oclzcpdJwEHlFlBk+Yf+EH3YOlO2EOAasTf/1jJXpfBA32RDuePRytFh+wZF8unEq5gmYP2uD/hwaWfLC2RtIeXeOBM6h/6fbvJafC2qPHlt+QCzVO5dR7H9q06Sw1F7v93yYJAxlrbXQT4Kzhn9r+yDMZMNP9WZXkKX4dC67BvTqT1mebNB88kCTegTbIGOXd93/2L62qZDPpdchu8LkbRgrcOcDN9BIZpiSzg8gJcZ6te/ov8qPWCSj99Zav97VfL2LEwjSgyqUABSSOPLdeSvyOyE4dmGIvPpvHHd7u7CZanVRZwgsmlfsVgudMD4/j1+kcT+eZJn2jSiBcKCPjK45wfvSxjBTROpVG2HWLjGkh8EX2pgExjM/pxF/GsNZOxjAVpTtEwc2dpEdmygvndp2p5Fw1rQjii67niDufVH+vMmrjVwg9+gRaPYxEu0T7ocZl9wOSW6CZ4HbnJUJdkEkiob++tKMkS61A2w9NgUqGm/BW/F1iYb7L+/iPGlKpUGi6h3WwXAzi2HzSCm9957MuhwmKV96jz+fXgu9PI/mNYFgYLjwj7k8dXi8trcY3IQJSARGjnhllSg374OwepUBoI8OToN TtXbIKwp 3ZijqO5Tolj/p49bARKl8RTL4wH+F7Gx72LUrG5MzpDp1roFrugF6smwbJPTxkAYgqHrPVwJ7eZAupaHOEdegBhJnxx6f45QUHIQveAJ6sLNrxsLIvazRRbZOxEE3k4CILTaanUzqcNBhb2fDry5d3XiechudrCge8BGvpJSwt5rJQBSDoALXGeSJtxzFEtfjss1cZN7xunT+bY7JjJf0UadPD0axNLg/TJ6xxdGu26mjSMXna6N6iuOXd3jmiJhs59Y+ICzCReF8pBULBvDHDPwobQnxghWBed5rUzJ9PRf+FHh5mVa6PNvfUP7mDX/wegMuIO6viFB2bWi8+HEX+JBs5brh3QwZEBRJziUOPEJXI+EbpIUIbqi8GngZjuxiXe0xa3MuNV1OcLCaSHS4DBqP5hlUpD7q1Bl+wZtvxuCb+mxYUDyG9rOvAbBUVc1W9Oukh/IwHQNIaPf4H84ISm9Lgg== 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- drivers/block/rnull.rs | 4 +-- rust/kernel/init.rs | 51 ++++++++++++++++--------------- rust/kernel/init/__internal.rs | 2 +- rust/kernel/rbtree.rs | 34 ++++++++++++--------- 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, 73 insertions(+), 69 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 1c3cfad89165..0646546d9356 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -13,7 +13,7 @@ //! To initialize a `struct` with an in-place constructor you will need two things: //! - an in-place constructor, //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc`], -//! [`UniqueArc`], [`Box`] or any other smart pointer that implements [`InPlaceInit`]). +//! [`UniqueArc`], [`KBox`] or any other smart pointer that implements [`InPlaceInit`]). //! //! To get an in-place constructor there are generally three options: //! - directly creating an in-place constructor using the [`pin_init!`] macro, @@ -68,7 +68,7 @@ //! # a <- new_mutex!(42, "Foo::a"), //! # b: 24, //! # }); -//! let foo: Result>> = Box::pin_init(foo, GFP_KERNEL); +//! let foo: Result>> = KBox::pin_init(foo, GFP_KERNEL); //! ``` //! //! For more information see the [`pin_init!`] macro. @@ -93,14 +93,14 @@ //! struct DriverData { //! #[pin] //! status: Mutex, -//! buffer: Box<[u8; 1_000_000]>, +//! buffer: KBox<[u8; 1_000_000]>, //! } //! //! impl DriverData { //! fn new() -> impl PinInit { //! try_pin_init!(Self { //! status <- new_mutex!(0, "DriverData::status"), -//! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?, +//! buffer: KBox::init(kernel::init::zeroed(), GFP_KERNEL)?, //! }) //! } //! } @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -297,7 +297,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -306,7 +306,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Result, AllocError> = pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -323,7 +323,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -332,7 +332,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -391,7 +391,7 @@ macro_rules! stack_try_pin_init { /// }, /// }); /// # initializer } -/// # Box::pin_init(demo(), GFP_KERNEL).unwrap(); +/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap(); /// ``` /// /// Arbitrary Rust expressions can be used to set the value of a variable. @@ -461,7 +461,7 @@ macro_rules! stack_try_pin_init { /// # }) /// # } /// # } -/// let foo = 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: @@ -593,7 +593,7 @@ macro_rules! pin_init { /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// ptr: *mut u8, /// } @@ -601,7 +601,7 @@ macro_rules! pin_init { /// impl BigBuf { /// fn new() -> impl PinInit { /// try_pin_init!(Self { -/// big: Box::init(init::zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init::zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) @@ -693,16 +693,16 @@ macro_rules! init { /// # Examples /// /// ```rust -/// use kernel::{init::{PinInit, zeroed}, error::Error}; +/// use kernel::{alloc::KBox, init::{PinInit, zeroed}, error::Error}; /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// } /// /// impl BigBuf { /// fn new() -> impl Init { /// try_init!(Self { -/// big: Box::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// }? Error) /// } @@ -745,8 +745,8 @@ macro_rules! try_init { /// 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). /// @@ -825,7 +825,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, @@ -851,8 +851,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). @@ -924,7 +924,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, @@ -1008,8 +1008,9 @@ pub fn uninit() -> impl Init, E> { /// # Examples /// /// ```rust -/// use kernel::{error::Error, init::init_array_from_fn}; -/// let array: Box<[usize; 1_000]> = 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( @@ -1352,7 +1353,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 db3372619ecd..dfb2204918c7 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -102,7 +102,7 @@ fn make_closure(self, f: F) -> F } } -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 428f8be8f3a2..e42fe222826c 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, @@ -507,7 +506,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())) }; } } } @@ -771,7 +770,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. @@ -819,7 +818,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 @@ -1047,7 +1046,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 { @@ -1055,7 +1054,7 @@ impl RBTreeNodeReservation { /// call to [`RBTree::insert`]. pub fn new(flags: Flags) -> Result> { Ok(RBTreeNodeReservation { - node: Box::new_uninit(flags)?, + node: KBox::new_uninit(flags)?, }) } } @@ -1072,7 +1071,7 @@ impl RBTreeNodeReservation { /// /// It then becomes an [`RBTreeNode`] that can be inserted into a tree. pub fn into_node(self, key: K, value: V) -> RBTreeNode { - let node = Box::write( + let node = KBox::write( self.node, Node { key, @@ -1089,7 +1088,7 @@ pub fn into_node(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 { @@ -1101,7 +1100,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) } } @@ -1123,7 +1124,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), } } } @@ -1174,7 +1175,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. @@ -1247,20 +1248,23 @@ pub fn remove_node(self) -> RBTreeNode { 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(self.node_ptr()) }, + node: unsafe { KBox::from_raw(self.node_ptr()) }, } } /// 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. @@ -1275,7 +1279,7 @@ fn replace(self, node: RBTreeNode) -> RBTreeNode { // SAFETY: // - `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(self.node_ptr()) }; + let old_node = unsafe { KBox::from_raw(self.node_ptr()) }; RBTreeNode { node: old_node } } diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 9023479281f0..5a868ce013f7 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -16,13 +16,12 @@ //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{AllocError, Flags, KBox}, error::{self, Error}, init::{self, InPlaceInit, Init, PinInit}, try_init, types::{ForeignOwnable, Opaque}, }; -use alloc::boxed::Box; use core::{ alloc::Layout, fmt, @@ -203,11 +202,11 @@ pub fn new(contents: T, flags: Flags) -> Result { data: contents, }; - 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()) }) } /// Use the given initializer to in-place initialize a `T`. @@ -431,8 +430,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())) }; } } } @@ -677,7 +676,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) }), @@ -687,8 +686,8 @@ pub fn new_uninit(flags: Flags) -> Result>, AllocError> )?; Ok(UniqueArc { // INVARIANT: The newly-created object has a refcount of 1. - // SAFETY: The pointer from the `Box` is valid. - inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, + // SAFETY: The pointer from the `KBox` is valid. + inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) }, }) } } diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs index 2b306afbe56d..2081932bb4b9 100644 --- a/rust/kernel/sync/condvar.rs +++ b/rust/kernel/sync/condvar.rs @@ -70,8 +70,8 @@ macro_rules! new_condvar { /// } /// /// /// Allocates a new boxed `Example`. -/// fn new_example() -> Result>> { -/// Box::pin_init(pin_init!(Example { +/// fn new_example() -> Result>> { +/// KBox::pin_init(pin_init!(Example { /// value <- new_mutex!(0), /// value_changed <- new_condvar!(), /// }), GFP_KERNEL) diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index 30632070ee67..f8f6d530db7d 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -58,7 +58,7 @@ macro_rules! new_mutex { /// } /// /// // Allocate a boxed `Example`. -/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spinlock.rs index ea5c5bc1ce12..a9096a4dc42a 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -56,7 +56,7 @@ macro_rules! new_spinlock { /// } /// /// // Allocate a boxed `Example`. -/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 553a5cba2adc..94318472507f 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -216,7 +216,7 @@ pub fn try_spawn( func: Some(func), }); - self.enqueue(Box::pin_init(init, flags).map_err(|_| AllocError)?); + self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?); Ok(()) } } @@ -239,9 +239,9 @@ fn project(self: Pin<&mut Self>) -> &mut Option { } impl WorkItem for ClosureWork { - type Pointer = Pin>; + type Pointer = Pin>; - fn run(mut this: Pin>) { + fn run(mut this: Pin>) { if let Some(func) = this.as_mut().project().take() { (func)() } @@ -297,7 +297,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput /// Defines the method that should be called directly when a work item is executed. /// -/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be +/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`] /// instead. The [`run`] method on this trait will usually just perform the appropriate /// `container_of` translation and then call into the [`run`][WorkItem::run] method from the @@ -329,7 +329,7 @@ pub unsafe trait WorkItemPointer: RawWorkItem { /// This trait is used when the `work_struct` field is defined using the [`Work`] helper. pub trait WorkItem { /// The pointer type that this struct is wrapped in. This will typically be `Arc` or - /// `Pin>`. + /// `Pin>`. type Pointer: WorkItemPointer; /// The method that should be called when this work item is executed. @@ -565,7 +565,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput } } -unsafe impl WorkItemPointer for Pin> +unsafe impl WorkItemPointer for Pin> where T: WorkItem, T: HasWork, @@ -576,7 +576,7 @@ unsafe impl WorkItemPointer for Pin> // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. let ptr = unsafe { T::work_container_of(ptr) }; // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. - let boxed = unsafe { Box::from_raw(ptr) }; + let boxed = unsafe { KBox::from_raw(ptr) }; // SAFETY: The box was already pinned when it was enqueued. let pinned = unsafe { Pin::new_unchecked(boxed) }; @@ -584,7 +584,7 @@ unsafe impl WorkItemPointer for Pin> } } -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -598,9 +598,9 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily // remove the `Pin` wrapper. let boxed = unsafe { Pin::into_inner_unchecked(self) }; - let ptr = Box::into_raw(boxed); + let ptr = KBox::into_raw(boxed); - // SAFETY: Pointers into a `Box` point at a valid value. + // SAFETY: Pointers into a `KBox` point at a valid value. let work_ptr = unsafe { T::raw_get_work(ptr) }; // SAFETY: `raw_get_work` returns a pointer to a valid value. let work_ptr = unsafe { Work::raw_get(work_ptr) }; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 159e75292970..c327fe0617c8 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -239,7 +239,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` /// @@ -248,7 +248,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, /// } /// @@ -278,7 +278,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 Aug 16 00:10:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765292 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 552ADC52D7D for ; Fri, 16 Aug 2024 00:13:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D0F608D001B; Thu, 15 Aug 2024 20:13:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id CBF528D0002; Thu, 15 Aug 2024 20:13:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B39498D001C; Thu, 15 Aug 2024 20:13:26 -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 9429C8D0002 for ; Thu, 15 Aug 2024 20:13:26 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 4D7AB1A18AB for ; Fri, 16 Aug 2024 00:13:26 +0000 (UTC) X-FDA: 82456184412.20.47349EB Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf10.hostedemail.com (Postfix) with ESMTP id 9EADAC001A for ; Fri, 16 Aug 2024 00:13:24 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=rhlUIPdk; spf=pass (imf10.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767191; 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=TYQj474qWlRs+jy9rHpymoF4rz5fwCoEuII5EGAYQZs=; b=aItwOlpf8NdVck01NoZ7NwmLvxs1vZRPLy6KBnXfdXaE2NQvivIOVXkyoDRP8snM0Waa+7 ry0JesCsDUCkeaspjnK/N2BwaGd5cYRyi4nbfUV9U0i9HYuJ9xFyNiY++ofIMOxZfqDglZ qEr8st9ztL+bUZsEPjKa4koM49vXq6w= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=rhlUIPdk; spf=pass (imf10.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767191; a=rsa-sha256; cv=none; b=whrK0i1O+qc/2ozFujSPsY9FTqS/O/yCg9meJ6lYc3r7uPeIOV4cHmZC7DFxg3ObvPh9RY Idqppt/Aj179gSsujsSwUc5lVGb21QIwOuZdwVZjCLpTd1vs2YwVPBW8fcM4C/z55uw6nD zuEnqW6zrz6ymOGTlS+HAyFTnv91qW0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id D59E960A0A; Fri, 16 Aug 2024 00:13:23 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B45A4C4AF0E; Fri, 16 Aug 2024 00:13:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767203; bh=EKHoRrO2afF0ja3HqngySZJfEnuoc4Tdmd6bnOLMLk0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=rhlUIPdki/y+FLsCOYUXL8a4BzQBi2WxrR9g+9MsSvBTQnN1ZJTb5+I6vUtrN/25w 9lubvdcadqX+Z/buY+UkOxFFHhRWNWM9xmH65ck3yBy4zAwN4QyVOTT09Bs8Ejovu3 PszJkLbcLa0ffMnAaUnZfVgn4voFx+ZQIMDQsdx271GVxKnOGxY2RRdcEYGPH7DhQ+ kv6Ho79VxIbtZujLT42a4GKjxNxyQwyOl/f6JCBBg/Az+SCfbaSTN71N1oVOmL/Zpd eQWJqY2sXH9lT1chjsbD9ONpdBXSx8y6EbRfPx+iHkeNaFSFhKOUEza2ACAgoa0iNd 8gNx0f0CLeeyg== 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 v6 11/26] rust: alloc: remove `BoxExt` extension Date: Fri, 16 Aug 2024 02:10:53 +0200 Message-ID: <20240816001216.26575-12-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: ife143d1ittbuzss6coyei5nddzqu8dt X-Rspamd-Queue-Id: 9EADAC001A X-Rspamd-Server: rspam11 X-HE-Tag: 1723767204-940200 X-HE-Meta: U2FsdGVkX1+WFj1Q/+DlV8UPzSDu4TJcRWp9p37kGgNcAZRM6yVXOIZH31Qf/G1IQ417g9O28BF/7ij+BScAcjvqMoYeWGah1S71UdDGGBwLWP3Ise3bAMjej4CeBpmiKtignh9LQHQLHEO06S/Ws8caZ0Bthz40KbOvqkTNgsbhFQ/2XS4k6uoy0OnUmKLeJ14ODK4uhe5dYDd1YGXq6Y08dLcSREeVitsHXwtvzXH9uYGu+fbIp488/UFpcO/OEZ+kzIr+io1YT9lK64rroWQj8vVmjFfxteZLK+kdnlquhWovo04pM5D/XA9DZf6pjXAhTYI5UpinO0mAb6lZyaF2Vzp1W+GVJm2PvfhoCw9leW5YZKweMIM1qSdSW6nClfYsk7p3Gx7OPU5bkvIr9HH5Dd/bm5KqzwHpHLpJnVr9LO8Oj5Zv7JSWQqoRhCkjf2MuWA2mCA9O5X7DgMpazfhXhZTmt50cKF+3vq4PCPI4z8q2gt9AfRueY8gU9zxA/FkWpcimhc+thIqcl4muJelI/fnK1HgL6nNf6Izf47b+77r/Wi5Ko5F324YR90rlQlWtXtK8tDUdXaUMXdXa8d6PgtqMu9EaBuE43Pv7he+5NUDydLfEqfjnqlt5J4vPif3864985pe2NeAovP4kiBIDi3qzsmd+TAffSPja/N+wkreQVDKs2/gtDC8RbMgQ5EcvEJ7Z39btWUC/8OKlnaOY2+5uTDb2KZ9TH7NrOztRs2yICbIqinfsvia/IWCttlWEcGbnp88nLIP4eKS9I2UlZDMxFBJI3l7vW4xlud4kWwt0x0Tz/IITeKJr8eWqIpfsurGFI050k/cF3FDWWoaS4Z4RPWUbNfwwPz3GHP3eCPll+jwAPJ5BEEJuGElwSnezJd2NOw3upYeu4P+psyO0bcHnRiUe5KOLk4urvX+wLaqwWK18gbHUYl5Zf99achaCnqNVYl6br8UhNyB FFd/XUzg bSwBBRL0nZtXkplqJwhFIXqE1IMc7Xf2+FgSAIAQg7BFuuYKoY61BLaae6WpY1JxlOl2Hg7D1bHnK91E7kPL/KqJAaUipwqzb8srMAXTwrhZi+QzbXyUaUKQOgfMhNfWqMQYQlfVXqqqKB97T0w1e2eXMNlM9XKBD7xPCe2FlQBosZ4OUu1GzmK7juXhBah7b7HJqHDFtYMFwe0URtJtXLRh2HyHs6D/XN3cicPfA4GhWnudb3RSRe9A9fwj30thx8GuwyJAUlgQlHRARQrQ2vkLcfmm4g2bFrf4iJmdRumRrYYarXQbyNTO7aCI6cy7+njchZS10r+fWdgI= 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 80 ------------------------------------ rust/kernel/init.rs | 44 +------------------- rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +- rust/kernel/types.rs | 28 ------------- 6 files changed, 3 insertions(+), 155 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 0c9bb60250af..d248390345ec 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 076d5de5f47d..000000000000 --- a/rust/kernel/alloc/box_ext.rs +++ /dev/null @@ -1,80 +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 value = Box::drop_contents(value); - /// // Now we can re-use `value`: - /// let value = Box::write(value, [1; 32]); - /// assert_eq!(*value, [1; 32]); - /// # Ok::<(), Error>(()) - /// ``` - fn drop_contents(this: Self) -> Box>; -} - -impl BoxExt for Box { - fn new(x: T, flags: Flags) -> Result { - let b = >::new_uninit(flags)?; - Ok(Box::write(b, x)) - } - - #[cfg(any(test, testlib))] - fn new_uninit(_flags: Flags) -> Result>, AllocError> { - Ok(Box::new_uninit()) - } - - #[cfg(not(any(test, testlib)))] - fn new_uninit(flags: Flags) -> Result>, AllocError> { - let ptr = 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) }; - // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. - unsafe { Box::from_raw(ptr.cast()) } - } -} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 0646546d9356..72452ddc0606 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,12 +211,11 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, + alloc::{AllocError, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, }; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, convert::Infallible, @@ -589,7 +588,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1149,24 +1147,6 @@ fn init(init: impl Init, flags: Flags) -> error::Result } } -impl InPlaceInit for Box { - #[inline] - fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> - 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 { #[inline] fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> @@ -1201,28 +1181,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 a10d0e140ab1..4599bd06b1e6 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -14,7 +14,6 @@ #![no_std] #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] -#![feature(new_uninit)] #![feature(receiver_trait)] #![feature(unsize)] diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index a9210634a8c3..c1f8e5c832e2 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,10 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; #[doc(no_inline)] -pub use alloc::{boxed::Box, vec::Vec}; +pub use alloc::vec::Vec; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 9b9e9b913d1c..234b615662a2 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -3,7 +3,6 @@ //! Kernel types. use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, @@ -105,33 +104,6 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option { unsafe fn borrow_mut<'a>(ptr: *const core::ffi::c_void) -> Self::BorrowedMut<'a>; } -impl ForeignOwnable for Box { - type Borrowed<'a> = &'a T; - type BorrowedMut<'a> = &'a mut 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() } - } - - unsafe fn borrow_mut<'a>(ptr: *const core::ffi::c_void) -> &'a mut T { - // SAFETY: The safety requirements of this method ensure that the pointer is valid and that - // nothing else will access the value for the duration of 'a. - unsafe { &mut *ptr.cast_mut().cast() } - } -} - impl ForeignOwnable for () { type Borrowed<'a> = (); type BorrowedMut<'a> = (); From patchwork Fri Aug 16 00:10:54 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765293 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 6E73AC52D7D for ; Fri, 16 Aug 2024 00:13:35 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 08C6E8D001C; Thu, 15 Aug 2024 20:13:35 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 013C98D0002; Thu, 15 Aug 2024 20:13:34 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id DF7A28D001C; Thu, 15 Aug 2024 20:13:34 -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 C168B8D0002 for ; Thu, 15 Aug 2024 20:13:34 -0400 (EDT) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 8113FC1869 for ; Fri, 16 Aug 2024 00:13:34 +0000 (UTC) X-FDA: 82456184748.07.5E56CE6 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf26.hostedemail.com (Postfix) with ESMTP id 82F41140003 for ; Fri, 16 Aug 2024 00:13:32 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=OJiLt7dE; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767139; 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=GAN7ymDWp8Lz5o35DG2vhzVY2kNsSLZxuib0MTJ4byY=; b=FeQmz2LWXLr0s2UxbK4w7MhImLrJMO6PMcZWvqb1+iLII7LOO6z/JWH7QBxdpEn4Xinksk Cf7KmJKy/DYWsYdQY9s6CiA01dTTeP5G58+qvd2BCDoJam3x9kNDbyqgxGcbgrKH5XcnKT 6QfTnuthiv48AfkMa7Oy8iSEGeJaOmQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767139; a=rsa-sha256; cv=none; b=mZiaU7dzzNdnCsIKy8Vli7QguJvW/ye40YFzUf+R/gsKzPe4ngQ57qtfY8S1+s1oHY4zsL I8C1bbhvbPDs7Lafwaa49vlpJBAB0vgCzhEhOmvcwTpccMLgyxwgxrLm7prfmQOChgfoC1 30pxD0lWzSxzq142bLE1GsWfHgfxczw= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=OJiLt7dE; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id A849ECE1E92; Fri, 16 Aug 2024 00:13:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0601CC4AF09; Fri, 16 Aug 2024 00:13:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767208; bh=cG7LgUDIz4/c/n6Pe+TTApJnhkzb0osvgtaCA8JUOxc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=OJiLt7dERCz22f4JtlRQcB/H9J5mN0JO85RbA3rhZIza2Lmp8w4El9tLHSQB0NMP6 Ly9+X1x5lh3SlkBGvlcMnOxFEdMqua/rSiMyPMp/Nx4/VI0UqX0I8AsvKVK4FLeXth MBIMk5wiOcdgMw3vm2G4MH6XIiqIibuT/D4FznJEbCaUlHYlaXLE1mwpuQ/hay7t1H AAYgykhh7yB8bHpgIGh83Ei0YvFdnKwzPk9yJeXl/g1xDanIWoHSIfT1ZWVizaTUDg l4TiH4tbN6oXq016jkOQh59xBl5p67lhsu8rNfN9uh8Om59rI8XZFUVnPi9Dlfm+bz oUpRZSLXp7L4g== 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 v6 12/26] rust: alloc: add `Box` to prelude Date: Fri, 16 Aug 2024 02:10:54 +0200 Message-ID: <20240816001216.26575-13-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: ca4nao1b3ytnce9zdwo6yxu8woqidb3m X-Rspamd-Queue-Id: 82F41140003 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1723767212-4666 X-HE-Meta: U2FsdGVkX1+f4llK+yEWuyJ+UWTg4uD1Ev72V5SVaKB80Lq3lcvEGy2O63mAhWEeGmkus5xFjEvkmTVdj+eYRydESgXXbb08MaCmiBF4TZVDUR8fHpkZY1afD+JCQ+s3wl+m1ZaKtiuQjTUIWXPvtX8+kMC4VWY6ceWcqRaLWh2HyJpW7Row8Db+IBOcepAVmmSgO7mG5UzkgrGT4g+qfQa9rCdVqzjoVLPRd285LdMqX8fgQGe4b/dmGtDJS5qDr5wEL5gIZBtcxbKxTkO3Q0JqAEMCBaAPeqRmu0KmfxM0PvcoxHN2jnfCrGLvRxSHvkcy3TlhZE1Qy3Gp2lIhrNaePP4rXAvzOL9TVbO7m2iof7DFVm1r8yL82O8BQlVx7d/O8AoAJmIJrD67Zixg/SZv9Ne5zG0r9eDkYClPKAQrxKVnwhS1oW+2W3C34p5Goamo/ONPBMoAXYiiODn7PUUCDHoOZ4iQI+jeWPhnx2lFJfmUBDgVDvhj2cRfysTmP2PcPWcFVYeNCQxtbvmxx2dnSqOYm+shMWc11bSPS/fdz15NM3Y+isCj3/dL/TdqKHJTHwJiK//MIKjcc6pTlGULxvN+qIeELBGhOresrXIYLWUadYthIfVujzC8QF+hBtIjIzIOcQx+MmkD/SE6QH4x/v2R6ev62463MtE412kn49lHFEh+H77u+CUxLeOkUXCoKcmOSV/ydv0mHcrKM6nKYRBle3+jH8/RhkHUug2g/KKElL1bUGIIyLFoiWnV637HmLTLWe0WW6SHTZrwVwMafETluDdgol02IumwTFqEbzfnR/uC3AB/6dGgzvJyDTbm9AC9YU6+8BrOEHJrCXe5YZL1nPsEgBVGF0FMQWBBvXFr9xqSTJyLu9kCi8WtWLL1/VN8A2ba3KMBHKWHJyURWzP1+XfZsitKiL3TCvZYL95lQiGmQuvoeJdHkhZJy4zA7xnyn6rjWwGWV/w Tjto/xNF rjUdvThnbGkgpXacLrLQ8LYVCxO07Mrlah4pJc1/Zg8jeWT6tasKIFPhNa3TKc0KHtoO64mRFOEZO+9etrAdVwvomFrJJDEjO9oCLDD76Lxq7poienwxiNGsLOU+YXheYqmEK6wPVcINVphdSI+WL159gBhltHTdvfAWgaxzHop8SjL/vkRjgQ2OdjFHH4Szc1gAslJ/wu8U3DZou5cKaXmFhy0WkXmVOcCrC/kOIzN7F5rTRdMlycpju+iyl78e1s3tKo00lIUM7XQOhCfgdgZNhL1gO6MUoT4t6Ohrw8V61JDeo3/wX0tGE24A/00oOh9j+HoRVVbb7SR0= 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 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 Aug 16 00:10:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765294 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 9077EC52D7D for ; Fri, 16 Aug 2024 00:13:41 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 03EC38D001D; Thu, 15 Aug 2024 20:13:41 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id F30DC8D0002; Thu, 15 Aug 2024 20:13:40 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id DD0648D001D; Thu, 15 Aug 2024 20:13:40 -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 B87928D0002 for ; Thu, 15 Aug 2024 20:13:40 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 6B7431A18A6 for ; Fri, 16 Aug 2024 00:13:40 +0000 (UTC) X-FDA: 82456185000.23.34C2FEF Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf29.hostedemail.com (Postfix) with ESMTP id 1275E120009 for ; Fri, 16 Aug 2024 00:13:37 +0000 (UTC) Authentication-Results: imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=tzXXO1iQ; spf=pass (imf29.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767145; 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=LUDs8npc4NTV93i2rPA8V+XcqUTjl0+lFGDBnPFQFo8=; b=thW/Iuzj40xrc4S42Gypyyrv84tCIotJmddQ/fQ//Eu+RuApBCzPAJK9OtcDjIn8x7oqE1 PAqxXQrsy8C/OeREEZFsHCYeeVRMXz9+piQtazerz7cH/41rcukBg7L1knbiHBYPRjKCGF 6/f7vtFcSL6wRHQa5aq5PfFspp6aPVg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767145; a=rsa-sha256; cv=none; b=2uFSosDNyK+98hRPZtESwboMOCnEvf7PGF0QF8L13h4yP/9Ev9OLNeafd293hgVga2XlGg H2l8jNG16mntEMWGusOGqMNYljL37RdgqMBwDulHQsznooAaN8zW36BhZjvXSfmAVpGtVp k/kCNGmqgJD+CHg88T1Vb649VyNwZpg= ARC-Authentication-Results: i=1; imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=tzXXO1iQ; spf=pass (imf29.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id F140BCE1DAC; Fri, 16 Aug 2024 00:13:34 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 57829C4AF12; Fri, 16 Aug 2024 00:13:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767214; bh=J0k0A1d0DfZcl7vq8Plu0pAdB0VKQLkiHCwAo9u7XJk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=tzXXO1iQyjRZm+jA/2haO1aUE5kI3F856bfUQDO+kkgkAqlZgKaug06bOd+2cpF13 VsBntvFUJBOVSCEYX7P5Bj3qvUFKy/H2eGU2cYvLOgrxQ4AO4jFCCfNXzlg5FhGlju G9j2TYOtIWjYeKxLNiDBrt3mIFC2LLxb4YkREQTDvQG2p7r7jkhQRjrOniB7i5VWd+ /PgK2q9P2TRN+PLBKl4MujhloLpz4QSPxX5g+8qCkqLLFBNojchojHNflWQ+tHQfaC yu3jMHscpHzzamF+CAtPhHJ3G/WFDQco6MfvXT/dJ5LKyIpFORFNxsGdh8qATdQgVY 2qlT7lwH6lcWQ== 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 v6 13/26] rust: alloc: implement kernel `Vec` type Date: Fri, 16 Aug 2024 02:10:55 +0200 Message-ID: <20240816001216.26575-14-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 8mu5q89jcj4mmpojs3u57pj8b44yfa8h X-Rspamd-Queue-Id: 1275E120009 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1723767217-392715 X-HE-Meta: U2FsdGVkX19inkpbLaAurlvueFX33S9SalI3PD2iBV7NQtzgG+jvBp3VICqKr3+mRntOZmICblS+F2jncSTr5e6dGmewYVQCksmR0040aKz5qQZ++UMqzSEozvobeAAPL7WLQF6EAEVn9Qwuvw1SMurRX5axTa7YE4FhZHRSEXku9UeESyJETZS9K/PFPdss32YNTXKYgdjc1YIForhWd//Kc3xrKK+yKTffwm04cOmV/iWjPgeYv3MmYHO0Ct0dkHlBGag5erX8tH72rSAAFBes8t1waInCINl/gFmYwIavK2suZtX9t6AR5Oi3eD5GrDZ6nwbBVuh7hGIFGni8whm7onDjf8Oot/DlMecUD9sSq89Sb9eE8pMHnBeBimB/eBwD3XMetqAgDHKPPR0q0qvqpJGWk7cmX2ZB6I0KMWGzi6S5uU7b6xkMugLv6Mb4EiO721ssIhOP8aHysWegRaWxY+MaOyr6YWetYnGziGaKvZL6TgBSBeYWfPa1aXcSpCSRZqzanaA3knm7p/wz3dS+49v7IYdP8W2owlkQHzpAV9wyO6isLENGV1MKxSkoO0xxd8O5mfq89K0KgsBGZEKeNJJypmCU/JaoJZ5eBwOhtU7YY3kwUqShzI+ne+lk34huzTXIpyIx26x6F4D7nyebGwJgu8ql/H3hgTALGlxaRQhyAHdTy+1Tz7Kz82bXW9UnW6FvKFAYCJtHtJcSJmxl7Vkw/ThndV06TJKckjFLcYSzSOP2mYljJXTnshkIrshCqpktTpWGC6Yz6Ro6tVo+Etnz2Yy0xLFoQzr1d0Da4Wv3wRkaOKHN/R15A5hPKWPz79RmgO0ZtrjxEZcvYgg6bCTnR3+10E8FS1G7giEyf+3MTRe+/lUrbMTx858zim4mOXngY8Qmoht6OFC5+zcXb6FzOPk340dt8NUUtjf8BH1Dnx7L8WD5A9vK+I2hEcI9qXXiAzMxKbU4UxB ah6SQizr Qec909Ze7qI3dXMkb8klAtQ5Ocmna/vdML6YJRKFl/WY0qamuYWiqU+kHjURPSsUwfYJM9igThHtfQHfAZ+NADc++zzTUWPnzK63cvQ9oZLDlZ2RVeVgBPo9/+/GbQNA7zDwnd2qzyvnDwop2Nlviu9Bbd2VDMg76AjDPmBzrP3IhGV4eKGWH01T8EPU6ABFggGNIw4qTbjE4yRfAvwfZG0J7Srs7E8ka3sO8TCLHXdIv3Cl8yA6rmGC1CCdmJ7Nvg49hjgIjshXyf04VsU4zc4qukuCS7JUO5ufRUO36Zp6y8SGbHPcj7c7PCQ== 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 (such as `Vec`) with contents allocated with the kernel's allocators (e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`). In contrast to Rust's `Vec` type, the kernel `Vec` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kvec.rs | 629 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 636 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index d248390345ec..e88c7e10ee9b 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -5,6 +5,7 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; pub mod kbox; +pub mod kvec; pub mod vec_ext; #[cfg(any(test, testlib))] @@ -18,6 +19,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..89afc0f25bd4 --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,629 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{AllocError, Allocator, Box, Flags}; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + ptr::NonNull, + slice, + slice::SliceIndex, +}; + +/// Create a [`Vec`] containing the arguments. +/// +/// # Examples +/// +/// ``` +/// let mut v = 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 +/// +/// The [`Vec`] backing buffer's pointer is always properly aligned and either points to memory +/// allocated with `A` or, for zero-sized types, is a dangling pointer. +/// +/// The length of the vector always represents the exact number of elements stored in the vector. +/// +/// The capacity of the vector always represents the absolute number of elements that can be stored +/// within the vector without re-allocation. However, it is legal for the backing buffer to be +/// larger than `size_of` times the capacity. +/// +/// The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer was +/// allocated with (and must be freed with). +pub struct Vec { + ptr: NonNull, + /// Represents the actual buffer size as `cap` times `size_of::` 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. + /// + /// # Invariants + /// + /// `cap` must be in the `0..=isize::MAX` range. + cap: usize, + 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] + 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 Self::is_zst() { + usize::MAX + } else { + self.cap + } + } + + /// Returns the number of elements stored within the vector. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forcefully sets `self.len` to `new_len`. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity`]. + /// - If `new_len` is greater than `self.len`, all elements within the interval + /// [`self.len`,`new_len`] must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + self.len = new_len; + } + + /// Returns a slice of the entire vector. + /// + /// Equivalent to `&s[..]`. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Returns a mutable slice of the entire vector. + /// + /// Equivalent to `&mut s[..]`. + #[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(&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.as_mut_ptr() + } + + /// Returns `true` if the vector contains no elements, `false` otherwise. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// assert!(v.is_empty()); + /// + /// v.push(1, GFP_KERNEL); + /// assert!(!v.is_empty()); + /// ``` + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Creates a new, empty Vec. + /// + /// This method does not allocate by itself. + #[inline] + pub const fn new() -> Self { + Self { + ptr: NonNull::dangling(), + cap: 0, + 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: The memory between `self.len` and `self.capacity` is guaranteed to be allocated + // and valid, but uninitialized. + unsafe { + slice::from_raw_parts_mut( + self.as_mut_ptr().add(self.len) as *mut MaybeUninit, + self.capacity() - self.len, + ) + } + } + + /// Appends an element to the back of the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// assert_eq!(&v, &[1]); + /// + /// v.push(2, GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 2]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { + Vec::reserve(self, 1, flags)?; + let s = 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(()) + } + + /// 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(); + + Self::reserve(&mut v, capacity, flags)?; + + Ok(v) + } + + /// 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> + where + T: Clone, + { + self.reserve(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(()) + } + + /// Creates a Vec from a pointer, a length and a capacity using the allocator `A`. + /// + /// # Safety + /// + /// If `T` is a ZST: + /// + /// - `ptr` must be a dangling pointer. + /// - `capacity` must be zero. + /// - `length` must be smaller than or equal to `usize::MAX`. + /// + /// 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::` times the `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`. + /// + /// # 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>(()) + /// ``` + pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { + let cap = if Self::is_zst() { 0 } else { capacity }; + + Self { + // SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid + // memory allocation, allocated with `A`. + ptr: unsafe { NonNull::new_unchecked(ptr) }, + cap, + len: length, + _p: PhantomData::, + } + } + + /// Consumes the `Vec` and returns its raw components `pointer`, `length` and `capacity`. + /// + /// This will not run the destructor of the contained elements and for non-ZSTs the allocation + /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the + /// elements and free the allocation, if any. + pub fn into_raw_parts(self) -> (*mut T, usize, usize) { + let 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 SZTs, we can't go higher. + return Err(AllocError); + } + + // We know `cap` is <= `isize::MAX` because of it's type invariant. 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)?; + + // We need to make sure that `ptr` is either NULL or comes from a previous call to + // `realloc_flags`. A `Vec`'s `ptr` value is not guaranteed to be NULL and might be + // dangling after being created with `Vec::new`. Instead, we can rely on `Vec`'s + // capacity to be zero if no memory has been allocated yet. + let ptr = if cap == 0 { + None + } else { + Some(self.ptr.cast()) + }; + + // SAFETY: `ptr` is valid because it's either `None` or comes from a previous call to + // `A::realloc`. We also verified that the type is not a ZST. + let ptr = unsafe { A::realloc(ptr, layout, flags)? }; + + self.ptr = ptr.cast(); + + // INVARIANT: `Layout::array` fails if the resulting byte size is greater than `isize::MAX`. + self.cap = new_cap; + + Ok(()) + } +} + +impl Vec { + /// Extend the vector by `n` clones of value. + pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> 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.reserve` not bailing out with an error guarantees that we're not + // exceeding the capacity of this `Vec`. + unsafe { self.set_len(self.len() + n) }; + + Ok(()) + } + + /// Create a new `Vec and extend it by `n` clones of `value`. + pub fn from_elem(value: T, n: usize, flags: Flags) -> Result { + let mut v = Self::with_capacity(n, flags)?; + + v.extend_with(n, value, flags)?; + + Ok(v) + } +} + +impl Drop for Vec +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: We need to drop the vector's elements in place, before we free the backing + // memory. + unsafe { + core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( + self.as_mut_ptr(), + self.len, + )) + }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.ptr` was previously allocated with `A`. + unsafe { A::free(self.ptr.cast()) }; + } + } +} + +impl From> for Vec +where + A: Allocator, +{ + fn from(b: Box<[T; N], A>) -> Vec { + let len = b.len(); + let ptr = Box::into_raw(b); + + 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 $(where $ty:ty: $bound:ident)?) => { + impl PartialEq<$rhs> for $lhs + where + T: PartialEq, + $($ty: $bound)? + { + #[inline] + fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } + } + } +} + +__impl_slice_eq! { [A1: Allocator, A2: Allocator] Vec, Vec } +__impl_slice_eq! { [A: Allocator] Vec, &[U] } +__impl_slice_eq! { [A: Allocator] Vec, &mut [U] } +__impl_slice_eq! { [A: Allocator] &[T], Vec } +__impl_slice_eq! { [A: Allocator] &mut [T], Vec } +__impl_slice_eq! { [A: Allocator] Vec, [U] } +__impl_slice_eq! { [A: Allocator] [T], Vec } +__impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } +__impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index d5f2fe42d093..80223cdaa485 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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 Aug 16 00:10:56 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765295 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 64448C52D7F for ; Fri, 16 Aug 2024 00:13:43 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D5EF38D001E; Thu, 15 Aug 2024 20:13:42 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D104D8D0002; Thu, 15 Aug 2024 20:13:42 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BAEEA8D001E; Thu, 15 Aug 2024 20:13:42 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id 9CBE78D0002 for ; Thu, 15 Aug 2024 20:13:42 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 3EDB68188E for ; Fri, 16 Aug 2024 00:13:42 +0000 (UTC) X-FDA: 82456185084.08.66B774A Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id 8D16440009 for ; Fri, 16 Aug 2024 00:13:40 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=L4WdWJAO; 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=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767148; 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=ifI1R8kHB8XReRuYU85B9zwZeylS0SKtlnh07Y3i92Q=; b=nfEUCR0yahFA8aiStKzuOa6bfOMD4qeWyd1Aj0I9CuVLJYB0eTEAUcjEgXQoakpzj+6u8l rjMia53ntp0ny77dF06VNjR9jjZC9vCZI4EzDTU2fhF2C7wCkpj7euCQrtUmS+BbSjDNy1 Qtbdrv8aoNdfVklZwJhsnVcLrxmICCg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767148; a=rsa-sha256; cv=none; b=oJxWWNuxb8va/htKEFB77u6DLeUdYE1sajxlHmwJNZWpMhyPP1eW+MgjeQokZ7ob/jT/kT 4Roy96HtBQtlbpfe6rTH67NMHV7ziDxDglzlMiIC+OLCuuJD282EV1PlSIVCuV5gEqagmK 7aKpbm3ud5pBnci6MK3W/D5KrlIHzvQ= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=L4WdWJAO; 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=none) 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 C3FA662061; Fri, 16 Aug 2024 00:13:39 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9FFA3C4AF0C; Fri, 16 Aug 2024 00:13:34 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767219; bh=ZRtvys+hWiPU9zH5CUlK8W5COnhh7tIaK0hqtMfStIA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=L4WdWJAOlQqM9I/rWRCl3rYcHiX5vhZnPH9tq5y/k63xcNbqTko4RR82QR9IAvvFq 03ROA7Q3h3LxdWAStZixhF/X2X7uVd2/maZft0FfLTjSqGXqhINTm0cuR8MzIhkvgq FgAOlTDMJB0Hu9euNMLfkdj1mJy7xQiTSO0BpdwxPEMIFypYbdR+QjjipaI4ipKqNP blt03fj/BMIkOJsDr/1k8gBeTWnTf6sjn9uNyUMQanzugpaIogVqNZhnyBI1Afca7h mWGRonHKScQ/b5Cj6ZEgPsTsU1J9IdcJSy1V/vcaZEFVlX7W0Vvy4jwAYISRTq8MsK is1zPHicng5NQ== 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 v6 14/26] rust: alloc: implement `IntoIterator` for `Vec` Date: Fri, 16 Aug 2024 02:10:56 +0200 Message-ID: <20240816001216.26575-15-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 8D16440009 X-Stat-Signature: mu4r165ietpjwczhbukankopg1wtiibj X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1723767220-811183 X-HE-Meta: U2FsdGVkX18mp/zb6C/DvDmk7jCJxV0VL4iLT5vp13dfLlhAPxUadIQY0cwooBUKYTYwGJXQRusN4v8zJbC2KOQr3A3yvHr75VKW5zE7dJsDq6NBDF9AKHYHZNBYrQ0iwAJPA7hVzp+wyzdLFa9Ad6LPR5Jgh0Xx62wpPZ3xVLUdIoZqzegzqB/mIHT5/Rbqp5UZ2pj1/H52ucwbOFE09THxGmlTYyZ0hWcNEhGrCWUMDbRbVUJsx6B4OQtgT3SbhWmmy9OQr0KviHvqIwjLxR6iAJ3TyxhuXsPtysFC4kCcy4lr9yEoPwhgCXLX+a6564laGdOcIwKK0dkfE4uZ2tyLTtiQw4IKUQRrqUwnVlWaSR4xqmxrTBfSMaN5rwaEf5erkSqBfocVH/NtP18BGjK8Er+9fy+63leLZVNc0qavIFdFlffoRMG4psWy+46VBQSpuE7pBHJf6YtoKKzwGN1DCJzrg8y5SH4QayI5arAvd0F4WNvVqr7axEn69Sy0HVQty9m4EAwguZPo/YqSnNZVHm+KA+8lIeaMuqPToKo4onCt65JYvo4bcbJfNL6U1twVIXOArIqDt7WNmHW3SOn+TcIScxy4UBlJSkEQQ9/KdJzn1oMTLVCobaUPqsGg8dcaeCjVGfwsrU4KB5jCmk9gYIdjFUccB4BGt8fOW9Mtb7XIekb1Oj3Sb1c/uZB9DWxOHsZEMBlMwym/cb76qt3NpMvxFeR0ugZjapkN1my9dElI+kfvEOiK6JxLJfq3R1ir8/xaNITZLSkAEztA1b6J7JwI+BSk3kV0lwRSdCSJhZUauVJxoX0cR//7Rq4FZ92bmas5n6lxb5Wtctdae5USCdkVC5xdAZXRvS9HTZ6HEEaAReh0SEmc3m8wJ2CdIJPdD9S/dua736OJI+MtaZ3UYKdUSAYqUf01Oe10usYfOX19uGEYq0o39ai0O89k+Arcm1CAaNSBJkj55mg I9md4kbV M0aer0Yv2DyxPBeO7Td7mAef3FZqoxx7FVESipXsiQNOAx3HS9D+OX044mju3a9URkAArk6dpLhDX+nsVxcSrgns4BD35Ve6NP2ShsfnmRjrdJ88Xgted9DNvf9GZXV765imA0hkzwgybkE2UZz2YY75J+TQpd3teA+OYHl6NatKGQNbtrclcdkFkL/MjhrvhUUeHpF0n5RNO3boiE7SefxKN3A+iPP+TN3J/D/tOcybzBwJ0o8QouYv7D9B4wp3L2VcciEFfKNwgwJmXwUeodycfj6jP7x6CdkGxGzrbZkl8Gvy8Q5Rn8I0jxQanAKYlOusJLPY7IY370IeGkQiY30+qXg== 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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 184 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 185 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index e88c7e10ee9b..4ff4df4597a3 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -19,6 +19,7 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; +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 89afc0f25bd4..3b79f977b65e 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -11,6 +11,7 @@ ops::DerefMut, ops::Index, ops::IndexMut, + ptr, ptr::NonNull, slice, slice::SliceIndex, @@ -627,3 +628,186 @@ fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } __impl_slice_eq! { [A: Allocator] [T], Vec } __impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } __impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } + +impl<'a, T, A> IntoIterator for &'a Vec +where + A: Allocator, +{ + type Item = &'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, + cap: usize, + _p: PhantomData, +} + +impl IntoIter +where + A: Allocator, +{ + fn as_raw_mut_slice(&mut self) -> *mut [T] { + ptr::slice_from_raw_parts_mut(self.ptr, self.len) + } +} + +impl Iterator for IntoIter +where + A: Allocator, +{ + type Item = 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 ptr = self.ptr; + if !Vec::::is_zst() { + // SAFETY: We can't overflow; `end` is guaranteed to mark the end of the buffer. + unsafe { self.ptr = self.ptr.add(1) }; + } else { + // For ZST `ptr` has to stay where it is to remain aligned, so we just reduce `self.len` + // by 1. + } + self.len -= 1; + + // SAFETY: `ptr` is guaranteed to point at a valid element within the buffer. + Some(unsafe { ptr.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: Drop the remaining vector's elements in place, before we free the backing + // memory. + unsafe { ptr::drop_in_place(self.as_raw_mut_slice()) }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.buf` was previously allocated with `A`. + unsafe { A::free(self.buf.cast()) }; + } + } +} + +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 (ptr, len, cap) = self.into_raw_parts(); + + IntoIter { + ptr, + // SAFETY: `ptr` is either a dangling pointer or a pointer to a valid memory + // allocation, allocated with `A`. + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +} From patchwork Fri Aug 16 00:10:57 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765296 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 98B7BC52D7D for ; Fri, 16 Aug 2024 00:13:51 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 287498D001F; Thu, 15 Aug 2024 20:13:51 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 2375D8D0002; Thu, 15 Aug 2024 20:13:51 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0FFC78D001F; Thu, 15 Aug 2024 20:13:51 -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 E3FC08D0002 for ; Thu, 15 Aug 2024 20:13:50 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 934084192B for ; Fri, 16 Aug 2024 00:13:50 +0000 (UTC) X-FDA: 82456185420.01.8CACF2A Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf02.hostedemail.com (Postfix) with ESMTP id 5C88180024 for ; Fri, 16 Aug 2024 00:13:48 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=YN169jcj; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf02.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1723767147; 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=1VC2CVQJSqrMoMHasis1jC/Ivf36FyK9ueVk50Zc+7o=; b=tUPRdvR5FntstCCIL1gRv4xWSgivS10Li7yWOgW+VRvCDjdbApuL/piq+GMxRhJwv+JAti hrHQPTCVizEgAppOg+6fhpmat1/NFvgMn1Qqwj+2hD0ieJI1jw7rJC/nPgwrWcTv7xZstR ShjlTfNJyMHquvASg8jNwvry5S5g0rw= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767147; a=rsa-sha256; cv=none; b=LkXtzLcuiR/0fSeP++clv8x+C7M1cNuWWspr4CukKjFbAQkwyKUDAsg0FbQ+5rmv0uFroH umV91QPXCuXYIbRbNTzkhPH6+p4zbGg5vrG0Lyg2hWqIe8eRpTjWWYgSA0nXyxxgTv61tt bSw69SiTu3wVh1qAmge5NQ/CVGBmfDw= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=YN169jcj; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf02.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 93CD2CE1E8F; Fri, 16 Aug 2024 00:13:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E8C35C4AF09; Fri, 16 Aug 2024 00:13:39 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767224; bh=I6cUolcDKGiOxN2jlE3/L4Zfc5m68bEHs0e/qmkx1fA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=YN169jcjN81Cmi6OKpdlT7HPyJDRt6/wiY2aKNkcvQL4eo/KLCVl8/ZBlAuASgG7W 5igkBN3w9Dr1JcrgOrglgcb7FhUOPrn6KPAkgLoMT8Mf+m6qWrvzEkdxOfRrsg5x6D HlpqJH2geyzU4Rb7k4tkg8op+ExRtO4eqi8Yh9DXUs+RGy9kVnGHqUq5N0m8t67CkK YAPnH/iKSYdpk59cNGm5lAZR2tSRqRL7PEaReigmEtyCOuvmiwHE30XEgEebteZkII 1GZXiOyJNWR0VwcgYig+oFSYY6nYQjsRvnXw7d4Kn4Bwv11UFuTLqooJbqLsK61760 3ymAtnrv26/0g== 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 v6 15/26] rust: alloc: implement `collect` for `IntoIter` Date: Fri, 16 Aug 2024 02:10:57 +0200 Message-ID: <20240816001216.26575-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 5C88180024 X-Stat-Signature: xi3iecmhhrge7kk394ekijeyc49yo39h X-Rspam-User: X-HE-Tag: 1723767228-836344 X-HE-Meta: U2FsdGVkX1/729nHXlAVF/pbHQp8gGssLt86XBv0ljS701+zDPWfz9syTLbjta/t3r/R3er2tgIaFQmjxSHjwpY7mIPu5y/OpUjBvABbE/4CV9KUL4ZSUxR9hFV+tEFzyNhu7ibxsS8YY704tafr+9tR/9Bn5viprat+SrADnZ5m5hXIq+Grh5U1Xg4ogA7pDv/0m7q9XLrzpiCW5m+SmbX0gvM07hsqMX4MkhbumgGviyFCNwHOgFQ+m2kqP1+5+PxypystT66PAEw7+TfL7QcW0WOHW+bhL+lAJmsiYKJZT23DDR6DyFynwWl3u/HMkgUyhdiNb4x7Ra54Lm2RjQDcm0aT1epocwlk6U2x6xOSm7YPdEJrNsHYedleckRE4EhxM6osOJIymh2DZv24W3FDWdl2JJijH9HTP6DsNwgG38RUliUWGuUpBMjtbm566703LhaYtUg60zmXdUxBPPYvoGfdVfjsUa27CjVitaCaQE/W5RhEOoUoBVe06z9kfC82khgFPBEuvBXVzf0eZaqhBuu30VvgmxaPu/xMeqEwC7gAzf19nXTDaj9KDn/Kyd8N5n5/x75GqxHv7NW2QgA1TXseacEOxrsCEz1xxuO8pBFMJR+P7XTxKtxttLpVeEPNS7aW8vQ/QCPTyzDkVVgc7fL3VMR8EHrO9EM/x+JcbaMZEGpDmlptIhIeg5/4ogMHCqczN4GHrQeFFNsuGs9B9rXooHE4t7kYHv5DJWQGgzxKCKVY5/j/2i9CAhPHIc7W3kkwx3KFLDqYKso4zWIpczU+05PN98MhXlDAU/xVluam7hdMO0l4s+z30i3v+P1Z40BV4eMp+Jzufog0siw3NlF1tC/wbKzt8YSiHA4a2gYBFnx42YPuyaUXrd7pGoYj/UYHe1brWLIAZaZEiXBFydFSQr7oWMlYltLbFxOQOKlSr114+bRqDsZqv+PZna1NNfYy55BKPRCv0zw BUJMfnrk PDVKDQgWaWftLHvq6jp8/rE3eriJrwpdZwMMP9zRW4IZlbh3VF2i81z5b23LgY5FeZppUwFMAinsMbtvKyP2Td01Ty4Q8ThZ9gGtKGdjSZfN3pfdr4qRklHKgjkE1Q+2A1+N0rX2XU9/1hj0bL81HyZ6PUp0hl6UBaqv218GM7Vy1xVPvc+VCtG3iO97efJLFC5kEsFhWc3KxAqlQrL0rN1/NeSNnkzvJy+9nGfsK8aWnEP9l0cTImVaimYlJCc4ZeSrOl2x/0yQlRNmvPCHPRHg4cW9RGZbBfA0d+ZuLkBzBaXIInq9+aXv9U58k3aUmhCtzl6cUBGDEHCk= 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 Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 78 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 3b79f977b65e..ad96f4c3af9e 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -681,6 +681,84 @@ impl IntoIter fn as_raw_mut_slice(&mut self) -> *mut [T] { ptr::slice_from_raw_parts_mut(self.ptr, self.len) } + + fn into_raw_parts(self) -> (*mut T, NonNull, usize, usize) { + let me = ManuallyDrop::new(self); + let ptr = me.ptr; + let buf = me.buf; + let len = me.len; + let cap = me.cap; + (ptr, buf, len, cap) + } + + /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`. + /// + /// Currently, we can't implement `FromIterator`. There are a couple 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. + /// + /// # 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>(()) + /// ``` + pub fn collect(self, flags: Flags) -> Vec { + let (mut ptr, buf, len, mut cap) = self.into_raw_parts(); + let has_advanced = ptr != buf.as_ptr(); + + if has_advanced { + // SAFETY: Copy the contents we have advanced to at the beginning of the buffer. + // `ptr` is guaranteed to be between `buf` and `buf.add(cap)` and `ptr.add(len)` is + // guaranteed to be smaller than `buf.add(cap)`. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr = buf.as_ptr(); + } + + // This can never fail, `len` is guaranteed to be smaller than `cap`. + let layout = core::alloc::Layout::array::(len).unwrap(); + + // 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, 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 From patchwork Fri Aug 16 00:10:58 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765297 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 B8924C52D7F for ; Fri, 16 Aug 2024 00:13:57 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 436568D0020; Thu, 15 Aug 2024 20:13:57 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 3E5FB8D0002; Thu, 15 Aug 2024 20:13:57 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 25FE88D0020; Thu, 15 Aug 2024 20:13:57 -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 10B878D0002 for ; Thu, 15 Aug 2024 20:13:56 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id BE779C18BE for ; Fri, 16 Aug 2024 00:13:55 +0000 (UTC) X-FDA: 82456185630.26.1458DF7 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf26.hostedemail.com (Postfix) with ESMTP id 7E98B140012 for ; Fri, 16 Aug 2024 00:13:53 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=kwNSKklA; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767161; 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=YVlRIGjKrky83SwlEBkRFk0JAB1C1NkcTw6dERrOi7A=; b=e22skFtldKs36RAjHrL/7H6uMHuxHG/3lCAbF2kLUh4fZZemihFdwhnCyl7tU3M5c9ARgA sA8YCswrqXKa4XOU7QXCLOhWzAby1oPwslAGAQ244KWOKrZ+4TtuVnVXIzNchkwudKkjW/ gfU5QEtt9+8u7P/zMM6ML5q29WqfQvQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767161; a=rsa-sha256; cv=none; b=xeiCD06YGwqcHfcKPpV1Z2xmSnUTt8KojfXyWFF8vIRbzCedTNyEgn69VIkHAG+jqEru4E tecpvIL94lk5haCz4+BmcDtpIp1C3QdEaFIQFhXwuyr6NYSdoZO8cRiKtPkXX4INS0mjjM 6GvRpCvG76fjX2o3nZadSq1SxOslKWw= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=kwNSKklA; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id DCCB6CE1DAC; Fri, 16 Aug 2024 00:13:50 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 40A05C4AF0E; Fri, 16 Aug 2024 00:13:45 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767230; bh=/IVTEZ8IJyX2uH5PONM0GW+O0B5cMSclqREBcc8U/Lc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=kwNSKklAX7D46eaXLcc20Q1yBOkHDDqt3V5M3ch90Tz8OQZM1PzhcDvZmPwQ8MEXV g2XUaQDGQbyr1dWqY/v4a3ykaDIIDMVnwmecpt3MvhknLI+lu/1Jd3OLL8oM2lVg/D GPFg0MSjL6JCzLe8jEYXEk7HEb0VY7rwM3wkGQ2CzWf4lO/CW5z931rbdtbMmt1m7n Cx9LNPlC5/IdYS2R6ssl7EGS5/Q1ChM2XPXc042ac7xRwJGxAUwTDbAuKpv5tzbBTt WBYWDgbVOd8Y9qqqCpUQiMXlPnSu3I6HBkkDqhgr9XZoTM7hAz6mfwZsFrjPL9mj9Z P1cYZD7OfjjWw== 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 v6 16/26] rust: treewide: switch to the kernel `Vec` type Date: Fri, 16 Aug 2024 02:10:58 +0200 Message-ID: <20240816001216.26575-17-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 7E98B140012 X-Stat-Signature: 4yjqf9ndx9yiuc1mmqcr15n8wa5rxqmr X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1723767233-210316 X-HE-Meta: U2FsdGVkX1+UtAOTPcSoxRm3MVAzb4llv+df8AhB03P83PiUtRWZJwxwqfiJobHQGFAnqPgqUAcYA7X1v70DexgLQ7rY94s1Q0qd2bPNhrOKO6E+WEbKn72CCD5JwTvslTIl7To6+lat+AlngQusLtmgVi94Mk4RSmh3YuvIcGF38IL8Ab4+cWrt6FfaGTZS9iI9GFyIe6Bd+00UwSil65Sz25wOoGD+zq3I64w+yleMIJM1s0VKi0vjInuPo2JGiHeXqENhhVEWiODolgQhgXocQPLVereJpm8xdwUETC2AH17YLFAvpK1LlDmS1aPok2ISdhfHYuJZlGU97u8u+lEgHPgyqJLR2fzOY/P7RLSUnbsb7CWDxAjbCrLoODTMw5+KTGmc2O4wpIHl6R6Htpuymc6n+/YS9rvvf1EnBCD6Qe2/TxSH5DOxPaX0/yyFYalH5KGmglr/4uq2I0LACMTKvGShpQFxvaw6cjU235mVhyU/BHAytK0QTyCJ5kB64O38znlqw65jZlWAEvHmpXgciEoPP/uwAvSr/qC7HVEdv5VAmIr4EWr/7tU/NrfHyINgv28n+zSh5f2MtjTtsur+sFBMN3s0LswAv80vNuGKQnD89qpTDLbjiNma7K368PDYPa+Jh1fcXEyaR5m8KuIIIiDremEPcOhrYqqYA/UWHY1K/5QILbFji88Dr+61lvV0daQ0gLEj+QbQ0PrU0oUPE7xeYb8Y7UvnJlAT/Ye/dRTJF9QjAXrjagaijcEf02mx4O/0UZyhG/bZI6y1smZRyGa5aD/aAL6rrqABlcyccDof/OhD6K/ze+HiquMxfLupwGaAqLv/xi2BqS5DInqe2ehns5QIyTBbPoTzkkb4/H5KPT8VOKwcQZTCyMMs2oCWjbHUH7ObesIg7IEHHT4ytFO7R4UUeTEPkmGHOLohjaGsJPHgHTQPqfzfIb/HLOL1FwvUpvrqK4FXC5c T9nzUe59 hltmLYBpcb00CKcK4yEgEffVGNOyVeI/bwt5zrlA/yGGQdUPYWAtGekjzPAV/oUgsLc23Xx3IfytXHdo00aTQHauM7CeAXxE5cMkWWdYRFpOko5hd/iiwgAM74PkgDObUzRh863dox56SjrRGZyU+2Ly9Tewru1Q/gcG5be9D6FgD3QPDV+rmMYNtZOS6PiK+5XtBlh8yv9i4zF6l30xCuMxS0EfVetpIKEbQUPm+1sMnayJigCuOyAeo3c3fyMUE/PM2fibQhzkxEtLfgt6YFgqPyQznv/JejmudIZ2bXCRmNS717vSudyiaBvI9c3R/HgFC49k02eVD9ys= 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- rust/kernel/uaccess.rs | 17 +++++++---------- rust/macros/lib.rs | 6 +++--- samples/rust/rust_minimal.rs | 4 ++-- 6 files changed, 19 insertions(+), 24 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..209ad1bb1a49 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,8 +2,7 @@ //! String representations. -use crate::alloc::{flags::*, vec_ext::VecExt, AllocError}; -use alloc::vec::Vec; +use crate::alloc::{flags::*, AllocError, KVec}; use core::fmt::{self, Write}; use core::ops::{self, Deref, DerefMut, Index}; @@ -790,7 +789,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result { /// assert_eq!(s.is_ok(), false); /// ``` pub struct CString { - buf: Vec, + buf: KVec, } impl CString { @@ -803,7 +802,7 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result { let size = f.bytes_written(); // Allocate a vector with the required number of bytes, and write to it. - let mut buf = as VecExt<_>>::with_capacity(size, GFP_KERNEL)?; + let mut buf = KVec::with_capacity(size, GFP_KERNEL)?; // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes. let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; f.write_fmt(args)?; @@ -850,10 +849,9 @@ impl<'a> TryFrom<&'a CStr> for CString { type Error = AllocError; fn try_from(cstr: &'a CStr) -> Result { - let mut buf = Vec::new(); + let mut buf = KVec::new(); - as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KERNEL) - .map_err(|_| AllocError)?; + buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?; // INVARIANT: The `CStr` and `CString` types have the same invariants for // the string data, and we copied it over without changes. diff --git a/rust/kernel/sync/locked_by.rs b/rust/kernel/sync/locked_by.rs index babc731bd5f6..b94517231fcc 100644 --- a/rust/kernel/sync/locked_by.rs +++ b/rust/kernel/sync/locked_by.rs @@ -43,7 +43,7 @@ /// struct InnerDirectory { /// /// The sum of the bytes used by all files. /// bytes_used: u64, -/// _files: Vec, +/// _files: KVec, /// } /// /// struct Directory { diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 234b615662a2..43f6efbe31c6 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -172,7 +172,7 @@ unsafe fn borrow_mut<'a>(_: *const core::ffi::c_void) -> Self::BorrowedMut<'a> { /// # 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 c327fe0617c8..a733168d40f9 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -238,7 +238,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` @@ -247,7 +247,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, /// } @@ -277,7 +277,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 Aug 16 00:10:59 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765298 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 307A3C52D7D for ; Fri, 16 Aug 2024 00:13:59 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A9FC18D0021; Thu, 15 Aug 2024 20:13:58 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id A4ECA8D0002; Thu, 15 Aug 2024 20:13:58 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8C81E8D0021; Thu, 15 Aug 2024 20:13:58 -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 614998D0002 for ; Thu, 15 Aug 2024 20:13:58 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 1D2944192A for ; Fri, 16 Aug 2024 00:13:58 +0000 (UTC) X-FDA: 82456185756.16.46796DD Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf14.hostedemail.com (Postfix) with ESMTP id 77E6A10001C for ; Fri, 16 Aug 2024 00:13:56 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hrHvv9G5; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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=1723767154; 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=Akj4VIwMWsLBcM1TY5VHKWHBd/uqoBzyNXIY/cXgOJ8=; b=s39XnwPvR6xyZ536u8WG6M+zXzZayTLNh0C+JwCgWvn0TcHLZPmcqEC5J9gG2t7mhUXYc8 RQGP0AIc6rMGDOTECADoK31GMovHFjCd1BvmXz9pPDZrY2ZMLEPt1s5vO2GIaos7xh51MW +Ey80pnlKlrMtT68BRc0F3OtCOEyM8k= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767154; a=rsa-sha256; cv=none; b=NLGKVxpkWLAWt9mdUBRHwEh3vUSdQN/78GFmervMCyWKfS9/rxS1tGUc4qBcHLh1ie7AAA atV19374SQMieZ9hm11BNBwowiocKResVTByMgJHugea6I/HNN95PMsMcrzKsf4oc3eVHh 37V/AsGT1MMOVD9+WN6VjYyJ8C33864= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hrHvv9G5; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id B0CB762042; Fri, 16 Aug 2024 00:13:55 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8AFBAC32786; Fri, 16 Aug 2024 00:13:50 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767235; bh=MgY1WTjE/5WIIbHlHLrQ2ICcRm1pEmv2eN1ezkFWg7E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hrHvv9G5MrqdTvqOxOeOstTj0Kt0TStNOiJo20mdZC3q2MRUMoNIjifLlJ+02gtws HcldMv0505Y2VZ5Ix4ChGPTVlTfZgGelIxkdcLcgKLnKHz/QlJW2KCpzQ9lHNYWvs8 XDl8pqFJ/UcL0XW+kIZN46n3pbcbgV53PLK2WEkiQ9Mal8R4jktuWtrdxBljJ9yr8b v0O5JqQ4nQaW3klQKXUP4ig7t5frcHilGalSg2N7R+DyF6rAey9A1wMm1yRTT6cYrr OW/MBSW9wahi3ZjPW1vHRhivEsUTJ97bb7zGdgb7A4q3Dr9lfm+c84EKar39FlipmO 4uubw6ppJrlJg== 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 v6 17/26] rust: alloc: remove `VecExt` extension Date: Fri, 16 Aug 2024 02:10:59 +0200 Message-ID: <20240816001216.26575-18-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 77E6A10001C X-Stat-Signature: qpbquqrieuz5bej54bwufjdsq1xeww8q X-Rspam-User: X-HE-Tag: 1723767236-554244 X-HE-Meta: U2FsdGVkX18Gx6LqJxHR4+z1xZt7CrqVKio/4riop6L1iY7Mn9OiYPNvDdBXPnrsLR4LYpVD25tm79UeImb8VeM4sgCLg8rs5n/vlHDKLU686k6HSj7ZFKRXdMCxbY4O7MR+ngHzd1sQjEq+F8GKN9pXbaGXmyl/SV025uy1lGAcxxQyObagevH7F+UBThNJox/JaQvSMO7F+apCvNraQgzRQXmgSW/1ZpiKjGnwbviRgUKgXE5RLMyG3w00GqA+EQJXfa54byJmX96X77D4BVlk1QFWiwWqj4b5WvpbZZEiglnhU9fQsLGqLY+7HWdqkP17OlC74sPTBJvQxl/VGrxuJSyHFK0eH8ERagJv+CKjN4RpMXhorpQ+LNQ3F4fRpc3wxBich9RjP5dHfwwpevnozVVxfvAIz/c6MaMT+8yMUXQL52w6R/wW3YXnrg10Lf2xQAuo6Nnimr3IET36um5OdgsMRoLxU9BtWkgncKFuIcsJqjIhGpRiu2nYzRexYYkLdiUQYAnURA0szSAd4WtbrEa5NYO1ixDN9MDc00X+e+lGUDld+C/1p6zr2posbTjfRlzwScijKTs79UymH3+x5T1S27T3oHWFwKNQz1FPUZq8sW8qc9h4bNbUdgBj6fUdgmCy4jclvkRfF8l67djveHM/7bdHdUWth6o2PbqHl9Ap9KX5SLSrJdxd5fqzdqLJ5OeV0PTONAMgMmiyD0qGR55YqLO+VBxZsOqxaHqeENpTEK0AhFexVUqwCKl3BM5DkFKowkLwTqz1C2HGu1GK75PZlUAFLCzRGzHnL2Bv3Mp0Ie0vlqOENA67sdo4fWoCYBZ+iSXAkQs5xeQyBB6Da3dGT37Fz59eWnmb1+rDz1CzMG+Z0g4TNatfHfAgnUTJc1aHvsk2FajKsf2OJqGs016MuyCGKk5TO2GMyJjt1qonW1PyzsesvEt8d5HV4eIuNHY9MPiAzVGbzy8 Zgzhg+Mx otfixhyRglb6+xKneHgWSfxBLvCLZ45A2kpNH/CS5awuQcxYB651uLkAU9ENsZAguPaEgwySbbCRQtMnc8QWAsvWV38yijj3ZIwNEhqkf7hBcH/sYHHgE1taABizLjzYajJob2usnR3hEJFIWrIdzQ2RI5BB6U23JPnrnmX4S6YN1+ixUMNfEZtKwYEGirCPQbG8H9CD7PZx3QHC7IgSjGV3bTqbGju2hZzv7P46DDH/MCfWkVwm68DzMfS/2NHisSdyruj0Ark73mXrrlKljygFW8nZJr6O1Z9vRO86eKHnVnOGPODgU5B/UF3q0BXNW5Rhti3xnmAZCZHo= 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 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 4ff4df4597a3..1feabc817d00 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -6,7 +6,6 @@ pub mod allocator; pub mod kbox; pub mod kvec; -pub mod vec_ext; #[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 Aug 16 00:11:00 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765299 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 740B1C52D7F for ; Fri, 16 Aug 2024 00:14:07 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id DABC58D0022; Thu, 15 Aug 2024 20:14:06 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D5B438D0002; Thu, 15 Aug 2024 20:14:06 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BADDD8D0022; Thu, 15 Aug 2024 20:14:06 -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 9AD5C8D0002 for ; Thu, 15 Aug 2024 20:14:06 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 50DE21C429D for ; Fri, 16 Aug 2024 00:14:06 +0000 (UTC) X-FDA: 82456186092.28.F596EED Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf24.hostedemail.com (Postfix) with ESMTP id 3C05A180011 for ; Fri, 16 Aug 2024 00:14:03 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GBDdyls+; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767231; a=rsa-sha256; cv=none; b=nTEYvwkuj4jRuAN3OFxceusLmApxBz6o97oZ2lTH+oIyxpjGbuCujuPkwC1IyByWfFVU/7 fkLTU2glAPNTJuwL9IKkI31IQCErU6reOFQZ0axsMpVk9zkOmDoGv2NYQixodbK20vIKaO 5uOCN1RywYDgPv8UjO4AaB9ixx3pcjs= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GBDdyls+; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1723767231; 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=u+VoiLFAetgzpXhJGAFpXoxUqUSb5c896RWORtIY3q4=; b=rQbpP3T9l2AmuHHzT1G+XTYyAlzNujzwVdyR42C9VrtGSI4uSKsGM6Q6ccYmxR5iATNpOk KtsjiG9Y7d9Hk9Sk3+EAMxl7Mv9nM3I1RPO79MP5agV3FEUPASVU1n1zBwH/r1n25jzbYF jrjT2Q+vAez2AQsFLVCW4rf7ZIljLRI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 7CF1ACE1DAC; Fri, 16 Aug 2024 00:14:01 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D66C5C4AF09; Fri, 16 Aug 2024 00:13:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767240; bh=LpXBgctNj+tjXHis1qyn9ZWQx0pllgQA+Wvf8FmkV/A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GBDdyls+Jd6wNrwqtFAQcJe7OWuWdRUR96D1OaBuBLszf+b8nx5uFxqZCC7OHJ6S0 K5OF5QRMmIHCzD5MO3IZWfIfCnuBkCn/kvF3Xgwb5pPC33irhCPNQsYMZdfYvR7j5q CdiQTBsJyfR3D20Ck/lN7opv7mZ3Y6xlcAR6izoua4HN6xkQMdpDoFFNARJ2iy1UdY pLSOJM1qqSk52E/4NJ4+9xTEafjOidA3suCELiyV2uX7INt8MueM6Xgqx2QcYIEGH6 icUps7nSIKG/MiYfHKGFCwZsbHxjmFkSQbBaRctQzxgUTKCvV/Lt21vXa1JdD/hpHd DtEcWeKOOACjQ== 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 v6 18/26] rust: alloc: add `Vec` to prelude Date: Fri, 16 Aug 2024 02:11:00 +0200 Message-ID: <20240816001216.26575-19-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 3C05A180011 X-Rspamd-Server: rspam01 X-Stat-Signature: xryfa73yadp6fap4o1xm8jtpourhxjrp X-HE-Tag: 1723767243-937775 X-HE-Meta: U2FsdGVkX19zypHLeVtYzrHgrufWi4WdpusnOaCiYlJxxz3s/o+3FztNsutszcxCt+ZMDGa29PblaUaaRXoDiHZdtECVhgdgC3Q31k0ruGRwzMM3mUWXcNm5Zht/2ODT+OUSmQUImV0usLv0q0wKsxmXdiz+nxDnNQuGG7jnxGVKxv9oZqCUJG5EEV++NkfyiT8SJblOFP2To7mez2kPGHW7jTOJ5jAJripsrZKIVSTP5N6XF8OTf2GZr1kn93EbB8iEABsUhMAMAxYhVoKuvKxRB+8Seb8RcZeAkqJG7F+IC63VBNZy/0WG0qh0+WYVaNKjX5ns4FcOa/ux4vtyuaG3ZRFl8H3KN4x2LFd3WMLxH2+FYVDDFV5c1AHpxGAn6ufPRxSjgmtJN/vXYLmg0ARftJg255qBuGXY28m+u+XxPJKegMf3SfJuJ8n6VtcnC9fgIepLUi9BAWY2TC7Se7y1vz5nCgoPA85S5OH7QawsQSunueI+8by1FuFC93ijU689634wB3VHOxSGW5QoUDKpB55jHF3sz8vSAHUYJTj5/4vDvL6BB83LMNL+bEoBu3jiYldWXnxMKg9utlNd9RMUMe9Xby2gRBaVi/VbL79ED0Qk1vl5EcRRrpFx0f0G8JCKKFX38pvu8KSZfu98KtBtHCdrabKF8MWeMY6vKcFROhNvODIDhX/eucAiPe+OE49sh8vOOUKOaa6tknefsEizppTHLsDYWjnhWXxPi2AMtngdNYakWgaRs8lu0Ra5e782gxrPbUQHGcJxvveeUAZQcmfX6y+44bsyev16+QCC0wIHkpSYn+fDNP+AZwmAutjcJBJgrL388wxLQa6ds6ubXuUDo6a8mDS5A5PurZUZhA9/Zd1C2wMKjdclu6BJ6J0ZKOp+XhTUmFydo6VzKwYRBbf/095Idh6w0vDf2TTMhvZZCqicnNY8g+koeMdP1ePBw9gCrAxuimqCqzE SiObuR/j 6CG6dnPcUbbDp/QTeER2e+5GsVgsVdo3WzpxEKXFZqvIeMn5JNGCDq1Yio5ndCkXbWk4Hcy4DXhD0Ct1jox5KwYYOOlZDEnLReP9GPHOWPzdJ4lsTmRJ5pl55pX8iHmeuda4x5J6YwylgiO82WYjwvBWMXG771has/DVVbCiEb5w/q3tX2fmMzvtaWNkGLtmHEU1TJ9mJXEPp/v1fJHSQ3PvM32r43PwHz36RIr2Zwk2tGthSPsPsyOo7PXkQbRD260b4f2NVT1ZHlo9hn9aBFZPlzM3Zu1E4kSJOi7t1uJQv7B0YlmeRJFA6XyyIRMeaFsqlqE29WQosyp4= 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 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 Aug 16 00:11:01 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765300 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 BFC95C52D7D for ; Fri, 16 Aug 2024 00:14:09 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4AC028D0023; Thu, 15 Aug 2024 20:14:09 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 45AD08D0002; Thu, 15 Aug 2024 20:14:09 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 2FB198D0023; Thu, 15 Aug 2024 20:14:09 -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 11E3C8D0002 for ; Thu, 15 Aug 2024 20:14:09 -0400 (EDT) Received: from smtpin24.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id C1352818D7 for ; Fri, 16 Aug 2024 00:14:08 +0000 (UTC) X-FDA: 82456186176.24.30F5F61 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf07.hostedemail.com (Postfix) with ESMTP id 2EF4440002 for ; Fri, 16 Aug 2024 00:14:06 +0000 (UTC) Authentication-Results: imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fKJgKObJ; 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=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767210; a=rsa-sha256; cv=none; b=jrlmR7virMdKhAQTRMKAfzGUmmINGZK0RbAYCy1GeC5PKK4/IdgfkemmPjUwbDID9MPJus jERR2T0r6IeW7PV55JL1VdQgysfKnrV+ZLm/WvVYHahqrCW//KdNFr+rIuoiYrYu9Hj29H KcrE6srS15T5uRBKpd+D8seSEP7rRnY= ARC-Authentication-Results: i=1; imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fKJgKObJ; 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=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767210; 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=TFK4eSeH81s3JqHhGp3C8G6y1LxBws64zTolZRv58oM=; b=6TkshBuhtgHbqJ+9YTT9+4w9BbkWZAPunAHh4GEiJqhbBtRKwAVcsY5wS3JUrZKCz59G39 WcGB/X5xvozA828xAdQqtDa/hylwCiSPjMDC8FdkOnT6vlEgw3W0A8Lfw2GOp6QKlzEh/M efwCQmp6dXwplX3EyBY8aoS8zI8y5xk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 54D2060A0A; Fri, 16 Aug 2024 00:14:06 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 274AFC4AF0C; Fri, 16 Aug 2024 00:14:00 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767246; bh=unZr/wctKeO2llH/7rXaGgjBoxn3EEVi4EeNhTJ2sVM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fKJgKObJI+X2UmQVowJ7q51gwpaf2MwFkO5t4y1aBGn0icOlMhlqwKReb6RPYh4Qk j7MMCR3KgSXIZ5dKB/BlbC4UkjsWvD+GY4qr9tp0cBdcMouT8+MFpoBSwFXDQLYQcW xkb3Jp5QOnRpnKNoYBiz2kLl3LfwyoIxd4bkP18/3wBgSOoxFXKkxdV9rD6yGlxtYi 0NO17v5AJDvxUBL8EzYxA1wkP//qS8XDAcFundYdEW2S+VWF7N3yLhKwld88YtjRdc LTn2ggh8HgiHkQdYneYku/q+d3FequHq2IikvRSis2NcmFhMVmr7j7HYwrcs8i9jxa YNou96ZIY75Mw== 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 v6 19/26] rust: error: use `core::alloc::LayoutError` Date: Fri, 16 Aug 2024 02:11:01 +0200 Message-ID: <20240816001216.26575-20-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: jnuresqr97gwaiz59s9ici5hzrbj4g3n X-Rspamd-Queue-Id: 2EF4440002 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723767246-668011 X-HE-Meta: U2FsdGVkX19Xf34rnnJCJpW98oqX89M/sxb1Yn/iWd4+QjeMdXQnU/2IvxTRjWSJrMtFXL/LuIc5xgTsa/G2FrT/3lHcWFLzrkI+zT5X0PzQi2ti4rMYzqB76JHbsPNaVq2a4mTrnLRtaHZfMgnAfmGbjhGNnIkcuvKwPRsevHr+smcIJ30wakOP5Rmxo8UORlLxwutkndxRyFWEAPxsdhGDLjLMvSCDR4EmU4p+kFX6MtSZehPj/Qu0k0Wc0DtPXuTpCmHzp7YqoLq0m9734oXXNS87dSFlcqL+Nvy6MBCxw3g5YdXN4wx+bcSlDPWqe29HOSBzsS7Nz5sXDmOW6g1sKWhc0KJme2Mh4EBMt0yB/lzmaSFb1LHXjzcdoR7pjTpytiP8nGDIUlXoag2aPDe5GphbyiknYCsNrGnllDvmt7PrEUnKHZqsuvGBuIdmP0RCvJeoCqQ+oxpU1tRDWQP2LpdkFJ5/fPk0Z2gCsK0ctdDs44e5HJ/fQGtkxU0xudkK4628ufE5RS9Koz5aIXSaZ82HeXS/2TwUY1k0bxSjYXw5R2ldfmnYEkgHQ57Ymc9I6KeeZpd6PkWCmEjHIBL374275WaZvPxcR/qRXIMLL5Gx/YqjiZBgyPJbUL47pJuVtzfTEJ63lND0H/NqDXEVHoBSoDESazjwx0urE0l6wJGl9dS5bB0oVfoRLAG5Wt9DACW2qTu2pvdymtT/r4mKPjnUhtGx/TxScjV9WRm2ENxPB4SdXmVmiIkiTVoYvVHTyVWmAKLMrEIvT3Zqr+S842wc7tfLCbs2zj2fLpIEh9CW/hYMkCjjnWnsvxl6wYw+T+NlffYgh85v0tUgq0y7RYUQYgrbsquegVZ1b9lNU0DNprQimZxQvXUKnTBXXamkVqtC4uPS2g3jiDB8VDLTx4Pclq/a0BKP4x9P/NSu7Pn6WGnn6xbxLmSUbBiqYaeFsPEHwBj2mmLl5qw 2wV7r+1o pyxWkWK0kaafuk83efpFcOiofX8sdjJRnsNYLekNikyP5Vc3bgOxEvCZPb1UU7FnafkBifwvRltYV8lI5G0RuAGjfRm0lOqU4Fju1KCBNy7lN+EoBxc5d8unKdBHbB88C3bjJFjs9bQmew4mjdV1bhLGfsIGv0CuxIFbX2a3WESF96XHvG8mFVZSbVW5a/LfCLjwyfyQehRsFy0oAt2zF9ZRCMwFytmaDM3g2d91cTKflyeLFvjoxsgMMgoAUJ6yfIU55l8NZmXKcvnXFHMmvOTy65orKimhxJ1yeSpcHKfFlz9L0Aj/1gbRfem487Cti9i8CZpoRFEYdjQQ= 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 Signed-off-by: Danilo Krummrich --- rust/kernel/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 145f5c397009..2d012cc3881a 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -6,7 +6,7 @@ use crate::{alloc::AllocError, str::CStr}; -use alloc::alloc::LayoutError; +use core::alloc::LayoutError; use core::fmt; use core::num::TryFromIntError; From patchwork Fri Aug 16 00:11:02 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765301 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 F03DCC52D7D for ; Fri, 16 Aug 2024 00:14:17 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 807988D0024; Thu, 15 Aug 2024 20:14:17 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 7B7008D0002; Thu, 15 Aug 2024 20:14:17 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 657AB8D0024; Thu, 15 Aug 2024 20:14:17 -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 446948D0002 for ; Thu, 15 Aug 2024 20:14:17 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id ECF6D1418BE for ; Fri, 16 Aug 2024 00:14:16 +0000 (UTC) X-FDA: 82456186512.03.CDFA261 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf14.hostedemail.com (Postfix) with ESMTP id EC333100007 for ; Fri, 16 Aug 2024 00:14:14 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KDFzCKig; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767218; a=rsa-sha256; cv=none; b=Xu5kx6Z+ARpNS/qAU4JYFwDz4WMJNcnAbWboyKVLbGzmldw9jeZeqvUsHJl7kw8oIdsCXt cdiz7B7tEVwyKe+88rV+T5KcDt+l++qdILiOnMGznal1gGfrZTeg2woZvqagcmbGXKZjzn Eph7EoolaxgU6bzhTUwrNh0/IJyHWAU= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KDFzCKig; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767218; 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=IUALEMDAXrq9HmZIMcM12fe7YQSg0JgIp1W9zkDVVhQ=; b=mZbuNqE/irxqxiehlem+QZ7kYYUERZXvr2IMILr6Nu3BiARwERy5MHYVOPtdfHqLeATCRt GszSpVZHUqKEbUudwEoPCm6kEwqxel92jxU2iDvS1SzDyx2s41G6H6ZfHFZgjUys/joVS0 N7TjvZJQ7wGxeGVK6XxpioGsl3CgxWk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 2453BCE1DAC; Fri, 16 Aug 2024 00:14:12 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7733DC4AF0F; Fri, 16 Aug 2024 00:14:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767251; bh=2JZ/HPYqMBMv9V3VcU7sSwUGHcVU2KFw93XwDqoGeDQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KDFzCKigmPq8S5g5JjHxUVJaiXQcpcx6LPz0k+Mik2iTPq7nOt3vh/1QYBTXXd3Xn TFg6vqur3nJzb+OvP8mOVgmWqylFXdn9K/0kEiyGSLFfkMq1AsBcYjhXtpYY9cz0cJ 5s4xn9tMnpGQinwPfZKPb3Sru19j59yWh2dUn31cNU9NU2xUQYRZZMhsYjEPtVBIJq J2l3066gtvSBLWXDcMx8w2WRtnRHqDEGXfU+xS1462CaNEfWeH6XmBN6O5BslF6Dfh bR8G2mU7+WRzSYLV3JjCX6qIG1aJ87CMXghyr/+ahsBm10J0y67ifwe4LB2sgcr1eb fDA8jt6ZJSr/g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v6 20/26] rust: error: check for config `test` in `Error::name` Date: Fri, 16 Aug 2024 02:11:02 +0200 Message-ID: <20240816001216.26575-21-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: grzz5mrr67xctu8ssuh9e13ddmo6585x X-Rspamd-Queue-Id: EC333100007 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723767254-167663 X-HE-Meta: U2FsdGVkX18A4ZqJ/qupPeEuw09KOBcivZ7ezGDVJ0As8tg6hgJ2S2oF3liHx6uJxPrFzGBbMDBH9tfQW7rsPPjPg1r/B+fNvSzT/3PQg7h+dQ/QFJxiNHD8Du0nYeRLcFX4vfBVRBcaA0Lz4+OuWC5mu9jATNDBVc1zKjciA7mcNFjuLh+to7V/ltfXYrflgJggYgLSGAgWuYVVysZChkrUw8XHNeKP02HIwIqEBaj1Y8N7S9ImG1+gJ0n9mmFnmDaDTj2lScqMgBXaw7Hu+JY92oM8gvEOOgUrH/HoERT28EYyhNV0MX9Q08VI22EmKLGWEuJGp1cwjM55ESgE1Prgdb+bw14ep97f0IINbHvyMULMsGiurJj6eNHM0MU9//DKwR0Bp/Zvh/XHUPceMJuofmAZPTxgJuXLnSYxDAu1yOXTjt5TG4SO5BF2DEpGipthdNmPpQwXrgna68WZ7iPRmlXY29QxQDRfNdCkcjWxacfL/0Z+AszEOrLVB7GVBcInCrA88aj/rbHlfNrRl1w27p88akY86v6LwGbGXNE+zn5hUCJ60Xwmobny/c5knOtqc74V3Y9KH8/qTDBtiBDp8I5DU4CXIOE3C2GW/nzZCFVKqiF6QbWUzEXqvHD+/EP5uEh6L0doXLiH8+6nXfbywidZvtSL2FGg4uCCLe4sr1Mkm+ASINw6U/erLo9qOzihdCZlN2ib1DoBPuGOjsrXV0SGxMfklRGO6oTVnFTsVHhxg63J+ShSBLrrvLbOHp4FFNvrBDlM6wX05TAr2ORAkcKZfbPrOspi2ta/AAT0b0HBzvCq6xJ2aBJelqhL7HEWF06XoA/WeN7Us370sQN5u4Q0rjv+PYyImSDZ4PXEyBT3AUp6CdBI7VW4ynVAlLq+py7tBwF5fuYpdY4tp61CLdEBZLUyAO5LVuyfkRdrIx0mHf7Wdgd8J4YfOESiML53QHJ7Eot51F21kMz ODqgmFG/ fTCZu6HTgoCW3cuqvZ2A/4YTX0u+D7wpBxiSBS88aBZyh4JO/1R+2baH1NuEUEjr68UYHYyESTtSJJmI8iFiE0WU03SmSZOdLLM16F9vknKNRXrbFMgRtCgKD5mC1sgaaBvSDK5XtReRlERZY3oSfQ2BfubDVzjh281g6Ir7cY+PZauO0V9moFMRLWe8zV886zk3UshJ4lzREDvFeIdlQcPBoLlTlLUwTUFdHOZoALzpw6npo0d4SgRhkxvzWeizc5cTh2HCsUM4x7Gr0QYAMe5jqa98aR3RL2BC4zZRxZE8WBMng1QBID6GPAoYAgKoRJygB+iABv2lYDBA= 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/error.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 2d012cc3881a..7adf889b9526 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -140,7 +140,7 @@ pub(crate) fn to_ptr(self) -> *mut T { } /// 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) }; @@ -157,7 +157,7 @@ pub fn name(&self) -> Option<&'static CStr> { /// When `testlib` is configured, this always returns `None` to avoid the dependency on a /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still /// run in userspace. - #[cfg(testlib)] + #[cfg(any(test, testlib))] pub fn name(&self) -> Option<&'static CStr> { None } From patchwork Fri Aug 16 00:11:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765302 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 64C49C52D7F for ; Fri, 16 Aug 2024 00:14:20 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E6FD08D0025; Thu, 15 Aug 2024 20:14:19 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E1F518D0002; Thu, 15 Aug 2024 20:14:19 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CA3608D0025; Thu, 15 Aug 2024 20:14:19 -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 A94FF8D0002 for ; Thu, 15 Aug 2024 20:14:19 -0400 (EDT) Received: from smtpin22.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 6804FC1879 for ; Fri, 16 Aug 2024 00:14:19 +0000 (UTC) X-FDA: 82456186638.22.2DACD10 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf23.hostedemail.com (Postfix) with ESMTP id B5B9F14000B for ; Fri, 16 Aug 2024 00:14:17 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="WqXor/E+"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.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=1723767244; a=rsa-sha256; cv=none; b=ZLQ1GcrCeXDWiwLhIqMVzPL6yqZdGMpLRZ24zoNRCEK0qA+LObHF0Dts0KVcSfllvwJk7I ZtWb8nNDA4FeJ82Bfdf3x+3yeb2PiK9uwPZfSNS4XDESUlv0HEIEBgHPDbsbtBJ3BoTaF+ PiY1nxddArpeZ+O6xx/Eu8Km1emgGGI= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="WqXor/E+"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.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=1723767244; 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=kChiuJdmdjKhXxG6h+3P8k4QDHFFSxRJ7dbGjLlKHP0=; b=FfdGQSy8pX2NUYopLoARZ6wskCywrHn5C5KyNeN+WgxZQErWMbmxmrmkCfOYs2LbzHwdcW wKqdDnWM1Ot8ukf3rmUJe1RazQrBpjKj+gkEOfE771bMXF0HbwE/0Ae/jfPg2UP7zFso2B pbuzdkie7Zmihl2dUsDYoiASj5dMj9o= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id E7E236204E; Fri, 16 Aug 2024 00:14:16 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C4286C4AF11; Fri, 16 Aug 2024 00:14:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767256; bh=rW6cn/nXJ3kgyxI1gVJEu/DxMLK8/5Ne1MREjzDSSjs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=WqXor/E+3OtKDVZYS3a96f+AYYecETGqzOUglOaueHa5Vlw+FyhTOgesTNX8DXyYQ feTxEQGGOMjBQtufSDQVIyINAeEt1RX7pEbrHHnkiO8RiwEe8dbS6mnGdfNWQ7XN2G IUb7quUg4sTLPb4vtiLBghpLWRzbWoQhcmHtNF4CoCn8R9OYFU6PyF7Ik1E2/QCVWF nql9dgriy61q8p4Xf3HT6uLmU+s5Xb+pXLQvqrUnRdrVqOBfcp43OqlXmD78rN08JS Svgry7HwrJQxFFW/sX1tgfhx42X71TYl2tFL5OQE67jkSJdsODEa5ddF8COQrbcfg6 4xK7yVyVUgmsQ== 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 v6 21/26] rust: alloc: implement `contains` for `Flags` Date: Fri, 16 Aug 2024 02:11:03 +0200 Message-ID: <20240816001216.26575-22-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: B5B9F14000B X-Rspamd-Server: rspam01 X-Stat-Signature: pxkrwp83xidbb6cxbysnys1jroi4ywjx X-HE-Tag: 1723767257-55415 X-HE-Meta: U2FsdGVkX1+zLoE4s5ceYJtwRES5tjiBPboGDoWaKYKmVxaGlXNx1vjRVtuLcA7oKlYsXPp6xrnyyQXXr+3aZCZY3qGnXMQ8hjGUYUt/GAUHEKNqPhG5h5IInt8YLDXGfU9KIBIb82aILoC5YDmEkIVI4DOdWjyaKVgRVHEyuLOK0SyZfxb6sqVk4FtKOTf+1EXMgg2+e4EJVJgjbAUKYTQP9C0q1SPqqud5HIssNUN4cefGynueEPvspXlnBS2KsiwEPg9sXVKZmK+kjAjVW6ht4TB+SMrz5Z4TD37ibWl3eLiAWSVU0DOiccbJc7MWBt9RdqhIuNwKajZP06Juzpx/jk/ef7P63KC277fmS3bSJ36K5AjjiuosT3X9s1U16Cw8g8GTHi0dqIe5qK4eT1PZyaSQL+WcR8tdePzOswM1b9jqzMCQ70JPGB76LDepVb6QXf5v175ikaZLWxAT7h46PhV3nveItjYWfOXSFNzqIEWiGBRLqNiGPEd0CbVO69VKEIzRqAR4IumK8RJMo1FpWTfo1A8cSLwEOiwdvkOLAdVkD4Mddo9CHSy7Xy3u105sjNyjiffYCiDyybTmTDcWsUp40OxVWGI4b7WhrLUu7TkV2ZO7xrU6bE2o885viKp17j013bFo3U5art7lUl+0Xg0D9tliAN9w2UVEr4bC6seimrYKZOZ4JrdcUBiUFPvlYY06SrCgvtZPlB5tw55FlMUSkqrTNaX5cuvzynxODZQoMnEH8sajOaQ9Uv3AQ2FoDvj4w8aR1N6BsggzOus2uypdYUe4fTeJ4KL6m+3JO1Af7fSpa8gIpBS9nEYYus2plzIrZCDZFt9Vp3Kx1X5Kjcenl3Xl78aH2eacJ5dy0WikehEVqvLC2XhQ5a3svdywK+KZyEjBW/kd3XqjYhdeH8pXaAAseVHz0672mr+ptOGJ/+urHbiUW9pJA0wOwf1izgjaWh+am70rE5b rcbuLGTf 4ZGd4Nu5FdtA6KjXCGg+E9vxsMj95+PPoIoYRdY5GQumUrTK6e6iB2wHOSr5NnuTrqEdCValAxtJZN8hXekZa9yVAkJA0TG7j6MeSojJywCqLnjtIL532ruFnfnUSWu7GkE+29nKtWshzQDLLjF4M5mzMAG9DRumwcvjK30fvBVs+Qf7Vq5NeaaRffdMSvgKY4NxDe+RiqiPXuUII6M3KX+luxTDQgPuSt/7Dtes5ith+DDDCqVEJ01+6nfYylddnadqwLFndSGZv6E/VxmehHf8CqlWgCjhe7JMU7qc8lpniRHllIZ+7Fnr0ezIVXgK2ZNkvngS9C7pbkOg= 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- 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 1feabc817d00..5c66229a7542 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -34,7 +34,7 @@ /// They can be combined with the operators `|`, `&`, and `!`. /// /// Values can be used from the [`flags`] module. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq)] pub struct Flags(u32); impl Flags { @@ -42,6 +42,11 @@ impl Flags { pub(crate) fn as_raw(self) -> u32 { self.0 } + + /// Check whether `flags` is contained in `self`. + pub fn contains(self, flags: Flags) -> bool { + (self & flags) == flags + } } impl core::ops::BitOr for Flags { From patchwork Fri Aug 16 00:11:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765303 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 A1CA9C52D7D for ; Fri, 16 Aug 2024 00:14:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 2FEB18D0026; Thu, 15 Aug 2024 20:14:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 286738D0002; Thu, 15 Aug 2024 20:14:25 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 128298D0026; Thu, 15 Aug 2024 20:14:25 -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 E1C818D0002 for ; Thu, 15 Aug 2024 20:14:24 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 9BDAB41565 for ; Fri, 16 Aug 2024 00:14:24 +0000 (UTC) X-FDA: 82456186848.28.DCF9386 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf09.hostedemail.com (Postfix) with ESMTP id F1CF4140022 for ; Fri, 16 Aug 2024 00:14:22 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="co2Cxo/8"; spf=pass (imf09.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767189; 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=0tTlidtmmOQAWjyw9vqvZw2qilcOf97wHHt0+kf6b1c=; b=PmZCMJTV11KKhJhtzhG/owe6N7JtAoKy3vUm43j9Ri9V13xUMBV9zIhnJcoex8d2bccleQ WwOHDS+ov7k8LJk5N8zAI3HRuMMtufwwbwzEXTU8T4M1tmMFmkIQzYQ/siw0zArRbS/lje bUpOlcSDPnUVYaCNhq9f2pg857IYAmM= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767189; a=rsa-sha256; cv=none; b=zp1q1OVfLHddF6WkM4Ahq6fiCIR7Yf4KYs/7sAgdNtGsYZ602iW1/ONow1b67ys3DR7joW EKyQSL0/ObmkyqvaQExGBQyH1POqRzrKD1xMz/2YHYXKj9EKddb+4Cz2J+wfxO4kBRUp9U IgbPHyF/W/D9q+9C/FUp6tSYWhVFuNQ= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="co2Cxo/8"; spf=pass (imf09.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) 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 3ECCD62040; Fri, 16 Aug 2024 00:14:22 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 181A4C4AF09; Fri, 16 Aug 2024 00:14:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767261; bh=bQS+R7rUpUCrHg7w7Wbs4uih1faovavqPA1dZK4lOE8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=co2Cxo/87VbXdBwuqojeKmzm23LO/RIK14f+FTu+LF+rprPRCXT1tDINHnYhyjnCt SMao0AWgVzzXC3OLvkzmIycax/C7a0Me8IzH4XSHoSVYrGzD+0Ly/fgqfy1UB/L4XP yDLZfq7gI55st1vASvGOaQqaHp2mfSwwB2KQU7C4Qu2+qz5DYsQA0054VeSdBfRSdF tOwcSDxZ1RJ9zwxXORqx3C/RBxVpHy9cObcopIwOK4aRSTV13Ggief/V6FpgiMOiFK w1JrC6/279Gd+5vkJED2Rq33iguFOL3+0v7aWmKz0376Sxz9W8WoE7eWYmB2KOY+TK 0Ieyst9xxUVeA== 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 v6 22/26] rust: alloc: implement `Cmalloc` in module allocator_test Date: Fri, 16 Aug 2024 02:11:04 +0200 Message-ID: <20240816001216.26575-23-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: F1CF4140022 X-Stat-Signature: mace3giks8isi7rb1upn4uwbr1ex4c91 X-HE-Tag: 1723767262-528652 X-HE-Meta: U2FsdGVkX18/estnXA9O/V4qGzejed5GhaGg3FaHjAieGLIiMsodsLVuPD0Z+VVDFsZD2k4fhRyb1ZmolqTrKHQMqVWoDHDSrvmjVCQxuEMFe9EbbY0G132uac8FnlgavWXb9jt+eZ+sBhgeFn5zlvR+33SG2iWCcHLtK3WxS8cM6YFxH41Y1bIFl3tSzD17HUye11qFWzoxYVERmS+ULxo2mhqOPsA+6w6O8eDKLZGv1LYD1UJswrGfWMLsNeWpWU45o8qvKdttFGSyUPMeQLJw41bVWZ9A1EeHBQYaSzjxmsJe2MVwv0a/ojpi1Xjcc549xVGUNTzUVnU2DXkyq6xl4nuBBhxAen+hBh54Bzpo01HyMz6phjmcWwi39kgqI+VU7pWNtXkfiPiP8WAAjBhJi1E//ozt2PoEdVvwk6hMjqrZKFen+aAD7w7WEVISQoQPLPNDmbwoVbSkLlRVr0gytvP4ZMf/6Vry3qkByh/AIEyn58Qc819zDJQtBpJX7ALodzADvL4X2am1qffJweNzeAtPyTVrgkIT7zKFJix4TNupUbUqr70YUVJ62i++phXTi9A09SzzzD0j+MmatI3Tk7RLLRwnKn31j/+rlzPHADhUUR/GFl2BZHQW+IeNm4AafzvFbKivDxKskfOTzuWxDRWLluUvnUOxt6mtGlDR96NgXsiepzmmDPMLX/MJrX4bsVfxd6LMbbqnuGQ8IyRePf2bhTPTvywYh/8kvb4JhZohblRcEOoB1E1WOrQ0J4qstmGhTndS4+sac3Y6AJA6ajcFGrf641fxzRn6Hw+XAHOWufnRB+iJ0dla0vMPVgGsE3jv48cQ+Dp07b8cn8/rE2MsoMpMb1H3X95qGXQRPcpxAc+SSuPbBqzGorrycvzgtuLMWAJKU9bHygS0IdpZiQ0QxbxZzdcuLezixgfuykEG5AX3PRtnBqnUNR3G0F+9l1hKh/ueKwdgGY2 YWpq20E0 Tm45SsR/pMLdcv48So38DFSyyDBN+2BpO/v4M8qKu7x8NQ7SGVzYLPphAknC/psX4oltCKEISNlZSBM9mEehN7SK/e+UyXyNMODmxFZn5Weg1JPoUPT9+xe1JqWVTij2zkoac6ITydCRWmEiqxWiPVHQ/FpYCP/5hBMILjN/M3PDFVxeDs8KuCTBKt2EF+FmtzqyO5prSw+c3bp90rdtMZbaUgeIJLRgecbsKkF7mMXIhSI1iexAFc4r6KRgiS3mwxorBRsD/JP4+NMw4jFC8/kNj+ICLMKQG5sGOOTZmNtC8r+78lRRKEa8XmUXc1uC5ULqBHPDQpve2FjaGfKX3cueNru9ZTBmfw9F2ZQgz3rVKSTs= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users of those types (e.g. `CString`) use kernel allocators for instantiation. In order to allow userspace test cases to make use of such types as well, implement the `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as allocator backend. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator_test.rs | 178 ++++++++++++++++++++++++++-- 1 file changed, 171 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 1b2642c547ec..7fff308d02dc 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -2,20 +2,184 @@ #![allow(missing_docs)] -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use core::alloc::Layout; +use core::cmp; +use core::mem; +use core::ptr; use core::ptr::NonNull; -pub struct Kmalloc; +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); +} + +struct CmallocData { + // The actual size as requested through `Cmalloc::alloc` or `Cmalloc::realloc`. + size: usize, + // The offset from the pointer returned to the caller of `Cmalloc::alloc` or `Cmalloc::realloc` + // to the actual base address of the allocation. + offset: usize, +} + +impl Cmalloc { + /// Adjust the size and alignment such that we can additionally store `CmallocData` right + /// before the actual data described by `layout`. + /// + /// Example: + /// + /// For `CmallocData` assume an alignment of 8 and a size of 16. + /// For `layout` assume and alignment of 16 and a size of 64. + /// + /// 0 16 32 96 + /// |----------------|----------------|------------------------------------------------| + /// empty CmallocData data + /// + /// For this example the returned `Layout` has an alignment of 32 and a size of 96. + fn layout_adjust(layout: Layout) -> Result { + let layout = layout.pad_to_align(); + + // Ensure that `CmallocData` fits into half the alignment. Additionally, this guarantees + // that advancing a pointer aligned to `align` by `align / 2` we still satisfy or exceed + // the alignment requested through `layout`. + let align = cmp::max( + layout.align(), + mem::size_of::().next_power_of_two(), + ) * 2; + + // Add the additional space required for `CmallocData`. + let size = layout.size() + mem::size_of::(); + + Ok(Layout::from_size_align(size, align) + .map_err(|_| AllocError)? + .pad_to_align()) + } + + fn alloc_store_data(layout: Layout) -> Result, AllocError> { + let requested_size = layout.size(); + + let layout = Self::layout_adjust(layout)?; + let min_align = layout.align() / 2; + + // SAFETY: Returns either NULL or a pointer to a memory allocation that satisfies or + // exceeds the given size and alignment requirements. + let raw_ptr = unsafe { libc_aligned_alloc(layout.align(), layout.size()) } as *mut u8; + + let priv_ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; + + // SAFETY: Advance the pointer by `min_align`. The adjustments from `Self::layout_adjust` + // ensure that after this operation the original size and alignment requirements are still + // satisfied or exceeded. + let ptr = unsafe { priv_ptr.as_ptr().add(min_align) }; + + // SAFETY: `min_align` is greater than or equal to the size of `CmallocData`, hence we + // don't exceed the allocation boundaries. + let data_ptr: *mut CmallocData = unsafe { ptr.sub(mem::size_of::()) }.cast(); + + let data = CmallocData { + size: requested_size, + offset: min_align, + }; + + // SAFETY: `data_ptr` is properly aligned and within the allocation boundaries reserved for + // `CmallocData`. + unsafe { data_ptr.write(data) }; + + NonNull::new(ptr).ok_or(AllocError) + } + + /// # Safety + /// + /// `ptr` must have been previously allocated with `Self::alloc_store_data`. + unsafe fn data<'a>(ptr: NonNull) -> &'a CmallocData { + // SAFETY: `Self::alloc_store_data` stores the `CmallocData` right before the address + // returned to callers of `Self::alloc_store_data`. + let data_ptr: *mut CmallocData = + unsafe { ptr.as_ptr().sub(mem::size_of::()) }.cast(); + + // SAFETY: The `CmallocData` has been previously stored at this offset with + // `Self::alloc_store_data`. + unsafe { &*data_ptr } + } + + /// # Safety + /// + /// This function must not be called more than once for the same allocation. + /// + /// `ptr` must have been previously allocated with `Self::alloc_store_data`. + unsafe fn free_read_data(ptr: NonNull) { + // SAFETY: `ptr` has been created by `Self::alloc_store_data`. + let data = unsafe { Self::data(ptr) }; + + // SAFETY: `ptr` has been created by `Self::alloc_store_data`. + let priv_ptr = unsafe { ptr.as_ptr().sub(data.offset) }; + + // SAFETY: `priv_ptr` has previously been allocatored with this `Allocator`. + unsafe { libc_free(priv_ptr.cast()) }; + } +} + +unsafe impl Allocator for Cmalloc { + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + if layout.size() == 0 { + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)); + } + + let ptr = Self::alloc_store_data(layout)?; + + if flags.contains(__GFP_ZERO) { + // SAFETY: `Self::alloc_store_data` guarantees that `ptr` points to memory of at least + // `layout.size()` bytes. + unsafe { ptr.as_ptr().write_bytes(0, layout.size()) }; + } + + Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) + } + unsafe fn realloc( - _ptr: Option>, - _layout: Layout, - _flags: Flags, + ptr: Option>, + layout: Layout, + flags: Flags, ) -> Result, AllocError> { - panic!(); + let src: NonNull = if let Some(src) = ptr { + src.cast() + } else { + return Self::alloc(layout, flags); + }; + + if layout.size() == 0 { + // SAFETY: `src` has been created by `Self::alloc_store_data`. + unsafe { Self::free_read_data(src) }; + + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)); + } + + let dst = Self::alloc(layout, flags)?; + + // SAFETY: `src` has been created by `Self::alloc_store_data`. + let data = unsafe { Self::data(src) }; + + // SAFETY: `src` has previously been allocated with this `Allocator`; `dst` has just been + // newly allocated. Copy up to the smaller of both sizes. + unsafe { + ptr::copy_nonoverlapping( + src.as_ptr(), + dst.as_ptr().cast(), + cmp::min(layout.size(), data.size), + ) + }; + + // SAFETY: `src` has been created by `Self::alloc_store_data`. + unsafe { Self::free_read_data(src) }; + + Ok(dst) } } From patchwork Fri Aug 16 00:11: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: 13765304 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 DC497C52D7D for ; Fri, 16 Aug 2024 00:14:33 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6A9FE8D0027; Thu, 15 Aug 2024 20:14:33 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 656698D0002; Thu, 15 Aug 2024 20:14:33 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 4F8BE8D0027; Thu, 15 Aug 2024 20:14:33 -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 2D25C8D0002 for ; Thu, 15 Aug 2024 20:14:33 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id DA391818EE for ; Fri, 16 Aug 2024 00:14:32 +0000 (UTC) X-FDA: 82456187184.25.19D59E9 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf27.hostedemail.com (Postfix) with ESMTP id DA8934000A for ; Fri, 16 Aug 2024 00:14:30 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ExCVsShO; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767234; a=rsa-sha256; cv=none; b=sALcTHygaacdbM1S0Zs5UoouYHZewpXqXGQEo/vmGsOH2N8PgMc9w3FlhpRpS2rzBpaWtU 8NCIT1bKpUb7WIa46Etv8UBFpwISETQEN4A68hUZiF1Lj+WRh+Sl0MrkrDmUhxYjqGe954 Vw68iiDDC3IibUs9H85C8W10kxmUo9A= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ExCVsShO; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767234; 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=0D7FqZUWgIaqAHnwMJev1VjFQsifHHTjQfERRAF0RCs=; b=h2sCiuPsDeKuQ3C6mO58TQQQ9xO5UlggJzsrYowP6weKTWvmUDapYoYIFzKlurPkuxtaYX A22r/9/UqpjpuweNgHWe+l5vllyieXkb7LoL21FYsJt9Cf0XkQ6hArW58NgRbx2xUA/mMP Mo/kMshglCm2s0xJ5vHl5K4DEnBPI+0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 0A938CE1DAC; Fri, 16 Aug 2024 00:14:28 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 631C6C32786; Fri, 16 Aug 2024 00:14:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767267; bh=byWvg3/QTModmmEnrau3RUl54V9uowntF04isjcbzmY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ExCVsShOu+MJYyYdh3Bouvz6RbIOq9x/nfwsjA+xfaTBafsQ/7F1iqdP1l+TX/Yjg 65XXWKpcYDzhdg1TpyB2x8z+mDg9uGx0raYVemR9FrzpnNnUYDQx23BL9hGzvaUkTA xfdhGCS//QauVuv56XjPoHXcjgfzT6pkP2WvovLYzPo8yr1x0Xx+E9LcXJa8edt91d UtWk4DypRH1l6gRpe22mvohkuJ6xdwEEsCVLsTGE04coDgZgWtyHHLzAIZFxu60pGL EA7QkBvas09Pq57lxKs53sOQYzML5eG0QRVC2pE5u6wuRvw4Iknw3DUEvAtsfHcERA 7mqZ2lz96lK9g== 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 v6 23/26] rust: str: test: replace `alloc::format` Date: Fri, 16 Aug 2024 02:11:05 +0200 Message-ID: <20240816001216.26575-24-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: w5ua6qwkiaswgigwiijyze6pfg9unt3u X-Rspamd-Queue-Id: DA8934000A X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723767270-461377 X-HE-Meta: U2FsdGVkX19HHBLjdofOm9Hdqqs4YnMb2/+0EfJzLOcZ0qE1j3DXN7Us+kXA8nZCgglQr9OcsrrnhLOuzMoIjSdbPvscatUIT4dXTTNnijO3k2cq3B8mNaz9OCO1uLQTOspw2HTAhCjeIRgODSzU1erL6YvGhjomjnJgsadDs/IiuZqjKX0wNCaXv4QCULabvYCTgTXsv3nSNTdfbwqxRkzPSpHaiNxT+Nntm6wDliqQ8gYvWjpa3gP2poqZDcGcj5JV1Is6w0QgkBrkmytmdh+ZMOI4Qh1xzX9BaAT/1bromDC5IiLTFHtaLBhFqCpbcVOZhNe341eBME/SmB1rHOfMx/IhtH+FOq1t2TcviDlpKj3/5eb2OiVxoO8CbuCSQGKThJpsrt6ObJFZE/B7CmEqxkDu10u/zqPSyiiaqli/H9lnNHOojS82NYwqNK8QyIpynHOUK9lDVVMhz8X06WFjjiwSzlqAnkPnPQa3A69/wNxl7BzbEQUkkpI3yQeymO/MetQDtmGf+X2zCDsoigGHJGbE6hTsAWgtTk88xeSoL/B0O2WnuU6sxDBeYoQL0lBAeZLAHfkOBVj1bTLWmakXIrI6EWpHP0nAINUbZ/tt0kQSSnl3Ja8Ml2QANU69jJOgfaBzK462EHob+fXUrd/34BmLnzYyQTCm6UK2Ln0hmaXefHbZR0gz4EH5tDmrQQpO7pwn7EXmFLy5/PvbTTuzDe+Q8uyRgsrYIRTieZv9cjLp8VKaniTf8ULdIP1bJnouQkZs27s5I/saTdWQvEM5PFgOC6GuyBOvNjLwaErDm/d4lzcBu5rctVnqbOD2sM+yzZJ1h+qD50ZFdlyb99sN102TFzHfSj6cd4ZYFTjlLpG2m/0yDw2eAYarSCjwSoV+CJRAxZ2GnXHXnVaZKQMDyfxSRyYoqa5sVhC/eaFSXi4EhFK/VxByAHK+46BoYeFagKUZ3PnCwH7iLuy e+Z6Xv5N Z09/bA/7M1PJxjPtorayG4tGIsM41/S0h/VBm6OGJ0g2vO+lNZ4s3JfcFGp4xC6Pb8X2274JmubfEyLDAGO8dQIzZlDGbRdraW+YyplkwuVLGD/44GiusnNhNiMMwK9BC7n++yzRTm5BR22Bwbnz7HMImNcxgXcxQpfUnIuWn+oLC/YxG5gz4xz5SlfnB673N084RFgX8gID2uLym7j2NxuomjUrqnPbmf/XmrIydwxBHdmhs/Mhd5pOIpEH0OfLXyeiu1GsfoovTcXPq+fTyVrdE424hNaJ8Af7Bk4iU4dXy3uzo+R6pM2SefIcWMYdvVYDappycv9dg4xA= 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 Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/str.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 209ad1bb1a49..726329530338 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,28 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; + + struct String(CString); + + impl String { + fn from_fmt(args: fmt::Arguments<'_>) -> Self { + String(CString::try_from_fmt(args).unwrap()) + } + } + + impl Deref for String { + type Target = str; + + fn deref(&self) -> &str { + self.0.to_str().unwrap() + } + } + + macro_rules! format { + ($($f:tt)*) => ({ + &*String::from_fmt(kernel::fmt!($($f)*)) + }) + } const ALL_ASCII_CHARS: &'static str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ From patchwork Fri Aug 16 00:11: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: 13765305 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 0012FC52D7F for ; Fri, 16 Aug 2024 00:14:38 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7E0C98D0028; Thu, 15 Aug 2024 20:14:38 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 790D08D0002; Thu, 15 Aug 2024 20:14:38 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 630008D0028; Thu, 15 Aug 2024 20:14:38 -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 400968D0002 for ; Thu, 15 Aug 2024 20:14:38 -0400 (EDT) Received: from smtpin24.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 003731A18BC for ; Fri, 16 Aug 2024 00:14:38 +0000 (UTC) X-FDA: 82456187394.24.7405506 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf09.hostedemail.com (Postfix) with ESMTP id 11EC9140009 for ; Fri, 16 Aug 2024 00:14:35 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=TKVfWubt; spf=pass (imf09.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767240; 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=Bdvv7NK/3TQAckImkDKVU81q+Ibuu3mhAdo2vVO8+TQ=; b=nQX+tQ3DlAmdHOEDyE9tOhAJ9tKWy5ziJ3mbuDMdiXZDmteRm4xr1t8qeu5DRofmPQcEKl KJ2Gre3g2sqnDA5GS5N1mG51hWnshsA9OhEowMGvm9arVNLSJ3oaf1sff72FM/k6ncJbLB 2RLt8LFh8sNeDjtVbt4Pl0/Dq3dNw+c= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=TKVfWubt; spf=pass (imf09.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767240; a=rsa-sha256; cv=none; b=3cZrE5hwggmg8QhaRGIzTNy94GVtMmfyKtQhHtFRnNVzICrMTNwgYPNTw4hpDY2dK79euX jQyC3Iky5sWVx7Q2znypGQp/a/jDd+0aKKk4DYP5yOd0dIRityrVGFQb/y9IrjQlay79sI s8zkYqhmqX/RUOswvXvqVTtTg0tUvNI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 54FFACE1E7E; Fri, 16 Aug 2024 00:14:33 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id ACCC3C4AF0C; Fri, 16 Aug 2024 00:14:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767272; bh=hE66PL1XT1fcRs3UTiebGaIqq2XjEPx5BcyZuKDcUQA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=TKVfWubth0bLERTXQ8mlKzdE11QkH/+igswwE1Rpmi8GRKX1TG1+vjUOjQ+yV00zc 9EqLsYhd+/0sTraI8cf+E8BM4We282bsHHxDL67KvIaM/fMJQV8mU0Q5ztlTYgE3tq ip8Vj5g1BYRtCuK3uMaEHSrr4nEJh4Vaf6/MuZndaGMApNxf0EqYZIPM5R8mQtwoC+ 8AOxynaWFSbl+JHXs6nNBQZDLvnipOgZ1Uvk6V3OdjjnDBy72Uve1NtL7xTP2P/5tv Tzsd8Z8+LbdPZo2ni4bBcfdw7RAU2GTi8Z0QyMpcbEPbTy7Nocq/htxnntM6ti3Z6r 4stIQT6g9FnZw== 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 v6 24/26] rust: alloc: update module comment of alloc.rs Date: Fri, 16 Aug 2024 02:11:06 +0200 Message-ID: <20240816001216.26575-25-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 11EC9140009 X-Stat-Signature: on6bixfmc8jmkasy5iomh3eqqg766c8i X-HE-Tag: 1723767275-376753 X-HE-Meta: U2FsdGVkX1/EOyDk1Exi8lmUbgEAteFllm6Bl7xLiujy1LOSWc6IQyxkUQ4COJAHjKtc6keZunZV0AEQfYo1WoEqCdxnvF/SnCkoGWo0CqrnCl8cvjL6ROsXHT5fV5zkq62K+Za3iIFr6WaYajydTHN3R//vHyxnUQoSv7vwJL/OQ3ENIXZ2HUrHDas3Koo6u7u0nhHud/xq4grzoLu/tAgSe7nfaC+QIoMsHoMUhXMXaN8Ni8zA4ed65DuGlaNlWCm1UFlgGHQFoQQdr6TzdNL8axhWJB9Yai8acJVOxv8TNNzzSriJuci7dvuDmP4oPVCPAJcle0Xh9y5bEEFFTB8Fnllkjjl0hQlUshuCdUxdSNJSAvgKZcLJPlF7A/Wy7p2zQNeXk23siAdS/duJ7Eu3raUThtEnb89zAqd0koiTHGHndpIx1E5Kvn86LGQ3xp+7fermY5aiPsVM3HA1Q6zJMliUeWxfu7Buh4yCv93sqZUhzFyHrBXXQ87YZCWY+KgXs+fM8GrCjAepp1I0ecwQDnwksODoG77OBl6dY4Ox75Owjqpfd+EW7z9MMQk4zvBbdFZrm34lRBf7K3R5lnlf4xvoBsuLWAv2K5Fc3EPEkr5atLX4inGf7Imxh7WJ4p+WMCbCNG+Qlvrubb+hQqiZUFiJZqxHQPajCOynySRFiy0gYxGSleMVlTztOzVQsobvSFwS5lcMBcUCP8Qac7/eHa0AZhdruq9tjGT6FTaWhsLr5UXblS1ou/hO5l00KKHlUn0ZXi1yZxb18Fvf1QEyDSKkaCpBhuB7TtpVJmQIMr6Xf95Telxn+oG1wHZlKttNSxzumIp5jIH4K8PxRqttnTz04YpywXCW3F0me624+H2P9snVxwwvQe44W9WRCE4/3CbxA1ETDPgQ3dLU5WD/jeU2btHfr+kNQNK9fqrYv9KhDFxSUMHf/tX71tzQq7xxwo+oNtZVqM/Ofvi 9VhOgBtS sWearuUgFmiKZ3kh9WohB2DqXUzTdClHH5skJVAG78kfYMtT7OWFbfvrwH97LHeoOp2fQcgDblsH6libiGIZxiv8+qvMu3tRDWy/hNJ7ZDbqD1P+IhGwvKG9fyo2CT3CKC5li/ZEm/tjBbg8sWPmUPZFjP7ETkgiCPa2Z57nH7ckFRu0urmLUn+czHeRM8/kG9KzLed+MdMZR66dTNa8HX/786+jDQDKpx7SVgcLHqJ6e5BMKXS7tXzX3VlLiQP0JlcklZauk0LFC9BDfB/eAb6lmZiZ47sjitkPKnzWQm8KDBHB8ygKp078pxiYAsndL9KDT94nkhztn3UtUL7LZ0ks0abdu4Fx0dQkn 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 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 5c66229a7542..282afd184957 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 Aug 16 00:11: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: 13765306 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 AFA7EC52D7D for ; Fri, 16 Aug 2024 00:14:41 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3C18A8D0029; Thu, 15 Aug 2024 20:14:41 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 370AE8D0002; Thu, 15 Aug 2024 20:14:41 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1EB1C8D0029; Thu, 15 Aug 2024 20:14:41 -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 F397C8D0002 for ; Thu, 15 Aug 2024 20:14:40 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id B956EA18A2 for ; Fri, 16 Aug 2024 00:14:40 +0000 (UTC) X-FDA: 82456187520.17.A80DC6F Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf30.hostedemail.com (Postfix) with ESMTP id E5FB18001B for ; Fri, 16 Aug 2024 00:14:38 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=A7FE89vP; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767205; 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=bxnaFsT7gSP/n7kWrOuBITkpZyezhUjOq6t+CpTy7D8=; b=PKdVOmktGW9GQ5oBpVHHsI3arB3X6X31/bgKCvpNswdpQJrQrn4aSHyD+LnUcBU8rXD7hM XVXD8bVXPgOOuKzOM42NUw2Hapx5XJjXv1f/bLhPRujbX567TIGbKWP7XY3DVd2sqhL/ay OmIrhH+Xk1cp9SJp+JaqeW2obkcDnVc= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767205; a=rsa-sha256; cv=none; b=hpWWR/zOWCKHuhv+TY1qCSO2+VQ6QPjeZPN8lSUEnLN0ySxhd1zcN0g4IddV/fzd3GviBe 9NKFhj6U2JOu7NVgCIr7EoHJIx9TIoatib/UEnd4vUCwzLTh8szn9UWGWf1L7rBUthQ541 ZEKRQ4QwIBnAQwAWVk4XIWD/b8H2Nrg= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=A7FE89vP; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) 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 29C7862042; Fri, 16 Aug 2024 00:14:38 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 024C9C4AF09; Fri, 16 Aug 2024 00:14:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767277; bh=Mc4vA4TFAlIDCefeDqCZYTXD4Svo9NHa4xZnxysVLd0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=A7FE89vPFY+MwRFEwIlTOO6aIUZsAxv0cMMS3KWmeF7LkM+aNmR9O9iUJTZrUGRBu 5kl5iyQl4RrqQO6e59xDGorQt2AtO8FYDNHhFy8lxa50QOCYnrJ9FVpovHkb99LNQY ZPsYTuHi7I55t9MsmoJ+fD6p46KQhon8qbeHIYSbHftiNt+DFkakIkVlgDsyYw7FvM J1i8blwM5z5APU8N5xPIZgjtt2dDyq6zflW3+bsWV02soxdr1JZMThQ5XtQD+IlbSk rxmYTM12yqLDBXNei875y5bogt6KYxDzT7ZLHykpsxUdZBYaQOOuYxtIsVbkqIqSO3 gdb5PPSf2dXxQ== 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 v6 25/26] kbuild: rust: remove the `alloc` crate and `GlobalAlloc` Date: Fri, 16 Aug 2024 02:11:07 +0200 Message-ID: <20240816001216.26575-26-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: pyd8c1za4cb97jmzw8s6yg7qu4bi4oag X-Rspamd-Queue-Id: E5FB18001B X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1723767278-276935 X-HE-Meta: U2FsdGVkX1+xH44SJKfdSHMJfV7h1c3hEU+1OS9jMzm5cauH3SQi5GOEeHQ6jGkAMmQp4+GJlgt+PdIa1is5tBjt94HhPrYL9ql7Or6iEwv1X+u3uV4pnwICMETG404QXSKbATCr9RK8yJmsqLph96rutKCr9RcaY6auUKHInyqE/JERuofxs7vHrbxkrffcfpm2rmpll4ZQQFlnhgNbt7V518rjY3xvnH0WOuv5dqT3NbD/LgpBZwAx/UdqU09vNlwQJFF8o5vep7l71qrKVi4AlDPYTjajPFOw10p7KAD9dCLzcWC2t81rq9QnDtpdp/U7MUuThHj6yDLKyoMaRYINff8a6HACKAvSYPSwhLbNOSlkhhcp4yCCCq34UnAixibKYARN0opklQgRi0dPIefhhONHmVOrLQHcTivkbXIkkjgkICDgBKyoI2zxCmHvFGF/HihmNPT63+hpNgkUV52eHJRo8MF+C1mESTvFQSy5X7+P1veZ96hD6ZG7OuY1IvPeNGXrMHqhoqPwCkDi/wX5dlDbAYeLy5JdzQwAlW7brjRh4iYhqS1K+rgXDoeFcDHDnaINbifUpTtCxIw61IKIWJsC6X0clCWECUHScytV8sfzQEz3CTfeTTcno1NqCwZkzQ8vyDKy7F4caCZu4ibI2mAywWZYPVY1MTYJ2PmgoRu/oAi37JXpukqVtTn9dvpjUQMzEO5QYLdOxjjVq44G3iCvreL9gvzrb/Xf9bMa1SCFjtqVMitxrF51VSQ9Qi/RElmdtiFQ5beAwmB24Asb9gfUpnrbuEvdbYsPIQHmAyASN9hRDNPmigTaQnBw9VjRWdHfeCbmM4AFnpUWiyC952vtStDev1RLvMaFBOZz+Wz4nB9UPt1yNjXlCU8KclJXmmB8b4rEJGyaZHB7I1rS6gKbsP4D1hlfElKE2+xulWgkAQj/rnoTSk6F4Ro0GQE4CmZ7R6cHpfl/waZ sBOkNjuO 8wPgCxfOtRRJC6uPAmL5dYKSbQCPy+zX219ceIOqueVGQmPRQJ08sujsfwoEVRZ1RKYH/+5McozvfO/sY4r/hgdf4u3h1N37JANEzVTctupcjJC9u26Dm9ZCiBKKaJM79eulqaiXXes6iaYQi7DX+2wpFsoY1wqa8IDVovr1do5tOFcoyfhirSazw3FL/bgP8NDIjzXmbauk3Yoh3m4KefCIDZPSQbtlcZhxJTlxVseKmGREj0c1IVsN5TkFcTjrjZeoC4cGTXcWk1qBP4Q+ljpY4EwsI5khpzatklXAdnV8iPPiNhI7ogHVZ/aA7Etrdn41IBPd4K99d+U725iJZ2PQ2HrzAYNvYFanRubTy2TY/90A= 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 | 44 ++++++----------------- rust/exports.c | 1 - rust/kernel/alloc/allocator.rs | 59 ++----------------------------- scripts/Makefile.build | 7 +--- scripts/generate_rust_analyzer.py | 11 ++---- 5 files changed, 15 insertions(+), 107 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 77836388377d..8963f53c5d6c 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -15,9 +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_bindings_generated.h \ - exports_kernel_generated.h +obj-$(CONFIG_RUST) += bindings.o kernel.o +always-$(CONFIG_RUST) += exports_bindings_generated.h exports_kernel_generated.h always-$(CONFIG_RUST) += uapi/uapi_generated.rs obj-$(CONFIG_RUST) += uapi.o @@ -53,11 +52,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)) \ @@ -80,7 +74,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 \ @@ -104,20 +98,11 @@ rustdoc-core: $(RUST_LIB_SRC)/core/src/lib.rs FORCE rustdoc-compiler_builtins: $(src)/compiler_builtins.rs rustdoc-core FORCE +$(call if_changed,rustdoc) -# 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) @@ -161,7 +146,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 \ @@ -197,7 +182,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 \ @@ -310,9 +295,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) - $(obj)/exports_bindings_generated.h: $(obj)/bindings.o FORCE $(call if_changed,exports) @@ -348,7 +330,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)) \ $(RUST_LIB_SRC) $(KBUILD_EXTMOD) > \ $(if $(KBUILD_EXTMOD),$(extmod_prefix),$(objtree))/rust-project.json @@ -380,12 +362,6 @@ $(obj)/compiler_builtins.o: private rustc_objcopy = -w -W '__*' $(obj)/compiler_builtins.o: $(src)/compiler_builtins.rs $(obj)/core.o FORCE +$(call if_changed_dep,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_dep,rustc_library) - $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE +$(call if_changed_dep,rustc_library) @@ -400,9 +376,9 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_dep,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_dep,rustc_library) diff --git a/rust/exports.c b/rust/exports.c index 3803c21d1403..1b870e8e83ea 100644 --- a/rust/exports.c +++ b/rust/exports.c @@ -16,7 +16,6 @@ #define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym) #include "exports_core_generated.h" -#include "exports_alloc_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 0183fbac1ada..44eccc2b1819 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`. @@ -131,41 +114,6 @@ unsafe fn realloc( } } -unsafe impl GlobalAlloc for Kmalloc { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL) } - } - - unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { - unsafe { - bindings::kfree(ptr as *const core::ffi::c_void); - } - } - - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - // SAFETY: - // - `new_size`, when rounded up to the nearest multiple of `layout.align()`, will not - // overflow `isize` by the function safety requirement. - // - `layout.align()` is a proper alignment (i.e. not zero and must be a power of two). - let layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; - - // SAFETY: - // - `ptr` is either null or a pointer allocated by this allocator by the function safety - // requirement. - // - the size of `layout` is not zero because `new_size` is not zero by the function safety - // requirement. - unsafe { krealloc_aligned(ptr, layout, GFP_KERNEL) } - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL | __GFP_ZERO) } - } -} - unsafe impl Allocator for Vmalloc { #[inline] unsafe fn realloc( @@ -204,9 +152,6 @@ unsafe fn realloc( } } -#[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 efacca63c897..7e7b6b3d5bb9 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -262,18 +262,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- - -rust_allowed_features := new_uninit - # `--out-dir` is required to avoid temporaries being created by `rustc` in the # current working directory, which may be not accessible in the out-of-tree # modules case. rust_common_cmd = \ RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \ - -Zallow-features=$(rust_allowed_features) \ -Zcrate-attr=no_std \ - -Zcrate-attr='feature($(rust_allowed_features))' \ - -Zunstable-options --extern force:alloc --extern kernel \ + -Zunstable-options --extern kernel \ --crate-type rlib -L $(objtree)/rust/ \ --crate-name $(basename $(notdir $@)) \ --sysroot=/dev/null \ diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py index f270c7b0cf34..3421a9ea3604 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 Aug 16 00:11: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: 13765307 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 BD9B6C52D7F for ; Fri, 16 Aug 2024 00:14:46 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5BEDE8D002A; Thu, 15 Aug 2024 20:14:46 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 51E2C8D0002; Thu, 15 Aug 2024 20:14:46 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3E6AC8D002A; Thu, 15 Aug 2024 20:14:46 -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 1EE708D0002 for ; Thu, 15 Aug 2024 20:14:46 -0400 (EDT) Received: from smtpin27.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id D92601218FA for ; Fri, 16 Aug 2024 00:14:45 +0000 (UTC) X-FDA: 82456187730.27.5FF53CF Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf28.hostedemail.com (Postfix) with ESMTP id 4AFD3C0014 for ; Fri, 16 Aug 2024 00:14:44 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Fpi8d3xS; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767212; 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=SR93HB5lBGHs2eHQLlala0EbgZGrF5y9dUKH0i9Jt8w=; b=UZw6Ym4kTr2WKHbbq0iJ2G8tfFRpcYG8bGs+IDVOK+h5yy8au5fnl8NvI6kvz2q9LJAH7X zhYF+bWurt37VLq36Aa36ByiPZ1oVtWFWwT7TtTI/TJtFi9agU1TRpTBJlX2/aK0GufQ0V piZDlgtxhgUgCzX/TxZ/1uGiurpYL9A= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767212; a=rsa-sha256; cv=none; b=Fww83Yg8l7UD6mFK14J1YRkkFnOh5vTo/uIF2T3pnuSSKVyxzsFm6yWP0o94w33KVFaZIK BHhxn6XTmhnFAkasiR+PY4zgZimHVlBfXC0X2fJrssO63qQVYAhIKG5hrSqswZKgmIE4lU 3F5PpCE63JVM0x/63TxZrTnAqXzvlaw= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Fpi8d3xS; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) 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 7684460A0A; Fri, 16 Aug 2024 00:14:43 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4E006C4AF0F; Fri, 16 Aug 2024 00:14:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767283; bh=0vRT7A88Z+C0vOfDex96MupvcF/nPHLRzZQHI1NMWu0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Fpi8d3xSzM8wjRKtjJNsznVuhGC72mP4ZaQ0gtuCnnzxdVK+yORnEznzd1krP2U3k xM8uNfnqulxOgvRW6s/PZaGN5GuJMt3yyJGmcDHdq1S5PuJCnF5P3jjxiLlTs0pVhE 55B8GnhvR06FNNErgi3d/UmizyH4qltjrkiri6WRPoTnJi0F37/OLZmuAuqPmg8zmm 9IWkiFiAuCK7XBxGQOIhKIpmFCWNKfpU6oFBWFCDVB7zhKb6EV/YTTFNPFa2qyIXzf UlGYTCOqOtcbcYddp+vz+HV7fZKaaNeia27DBJtPaXhI/xxZM3uFnMEMA3aDNAMbwn rhwy7Q5KJQyeA== 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 v6 26/26] MAINTAINERS: add entry for the Rust `alloc` module Date: Fri, 16 Aug 2024 02:11:08 +0200 Message-ID: <20240816001216.26575-27-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 4AFD3C0014 X-Stat-Signature: g81cua8odf16cf5gyayf4mnrnb51ioyw X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1723767284-336039 X-HE-Meta: U2FsdGVkX1/tvetjvTkI0sTO2gV8lwSD313NiHfdl0Tx8QjURc2j72anPl4WdBjM6SuDLSbJZ8/8UUf7eWdfqVAlzmaTcf3AfGc5zckju+23LJUFPDQo6GKNVVhQpM5xKbQZ/+Q3lu9bsyXgMOvk58lh6YeV2MwZKliII/BMMoYrjwo3/QBk4DkVofIGlgA9xAY5XuErFwpaiSkKr2QWM5T8ToOSqxlqo9+HFA5sr3TTKRZwUqV0bLGDtIoEY7i3QeLWx8DjemdXY9TWS8rV90bVlAGi0am+iAiJuyne8o3e0249fHqY9A2CLgikeRoYUb+hRKxAFiU9/5xisXNRx0gHyzdd0cuj/WCbGLaDaPgPxzf+Vug6eNFa36aIo58OVbX2BC2GkE4lfeomDsheW2de2y3+Q/07l1Vl8YZJHeU/f5vd8qnx6f+9vlq5c71GKjrli0QD6txiuKsafKH5nO6RNl7ysIPvsxNB9MsW5zSX09UF4rbzAocHNFKzdTC0/3MZFhiZkGym0pLPcgt+KVYfkJObHmpjC2OGsJcR5Oyi4QsaPDN8wjHS66cMSG1AliFwNULuLwMrJi9TpK9Gp6uJAK2hLZa4xLIaLhaBTFYBG+GqB+eytvdHzP/OmgGFU8Ff/td588b0cTO1tY/FdEmYk8P5PJy7d/9cYPpvog/MnjLbVXOQk2ZQjRpRUNE4Bsur+Ps49Uh2j86GrJsBSbnGS329NaU9xNH6MR+NXB4CyEgYY1FBZXpgqoGAZBaYfkWU1GwKWaRaF63hugxlNE8kOEA0oUjhF/68qrx9mMRpasEDn+aTG8O1FVZoFifjmoXXueWbPZtRXiB5qwTZrqprHtR31wb7lwfkr6n3hgElWQmZ6acUllB4WxJlJTQ7ddDjQXbnfRqYSFki5vb1p+hQF671+Tym3gA5ITTExbYb0DikNLS9muk6hr/Cw421BiYP+NyyRjS+JbRxowM JLCfQyY8 jGMHZOcIoQvlBRShbDLH4J4/AouamsJb2w7dWyMdx78goe+zt7NHL4h80siZZwfY+Dw4YB9CcLiC4f6rJg+Kmk/yx8Mql8J3fjyQ00+WdRI4lGPvtu82SISwfkZ6kK9j50lxGqW6Ho/aMCN+AqhrPo9n5aCjWHPm1N12BdEhWxRy8NOQoEW1oI+xWQE2vDSE5op3duLdTMT89OrclMCz3T9n8vzHt7Yn25YMaNquNuROsTunXzAQa7EZYry29mkcrKmC7/vPLowqjwCTcJij2nrxTLbmzNAfHtpQy40Tj8g7o3R/UbNoYwht0hZ61qqYcNzqHwyuVbXcF7Z+9u+GzrgHon/NfzPd+Ak55/Lub+t8s6NLu8F8CyUwI8FXPLJo4s52YPEIO8j7giAg= 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 42decde38320..560516b3aaf4 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -19925,6 +19925,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