From patchwork Thu Aug 1 00:02: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: 13749340 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 D07E0C3DA64 for ; Thu, 1 Aug 2024 00:07:06 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6AF556B0083; Wed, 31 Jul 2024 20:07:06 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 638E36B0088; Wed, 31 Jul 2024 20:07:06 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 500596B0089; Wed, 31 Jul 2024 20:07:06 -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 30B736B0083 for ; Wed, 31 Jul 2024 20:07:06 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id AB2E11C2C8E for ; Thu, 1 Aug 2024 00:07:05 +0000 (UTC) X-FDA: 82401736410.28.5759C09 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf01.hostedemail.com (Postfix) with ESMTP id 690FC4001A for ; Thu, 1 Aug 2024 00:07:03 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=EZyPia1n; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.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=1722470761; 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=BAEAXc4XtzeJtIivSCOhHPkcB/x9zV7EStIejOmGIM0=; b=vZk6G4O6tYiqtyhTKUb9weOPul23bFTSaejD0cNStEeCGWKJPzVYLiKF3+BBpdvvvBPrx5 wmyWQS5Rm81acNd/4rY/Oq9GlwhrRjsev3SKAM4f5zClwWBCariYhJ2q1MX0FZLzrms8AX oBhk2Ve1KPM26oK8BpF5vKiY36nnjk8= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470761; a=rsa-sha256; cv=none; b=qKkr/JZBk+Hdy95w0abbVI0F7x/Lup9hJ6F8x3vxeUZxAyk2avFWGAm3oZ8mXyZdjP/Bqs KkCcy0SIaawg7uS9LPi+6B1g3hGy/ueNXeMd6MwwtUM5nTA8uJB0x+agiiAkEKT83tnU9H XacMSP7GWvBKPblH3WcehUXuCIpuB6g= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=EZyPia1n; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.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 810FCCE1811; Thu, 1 Aug 2024 00:06:58 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C6C43C4AF0E; Thu, 1 Aug 2024 00:06:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470817; bh=kRuEhdnhz6Oh4MuGdrkk5vMdvHwyKzjCm+Q5vf6XVyw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=EZyPia1n+C0W5qz4kOxNx9KtE86e+aYpLFiHeEsfmLE8REX244dH5Fld8vnG8OWiZ I94s406MrWq+XMAJ5CvqLyEZ6/oG7aG3/Yn5PO0+VRj+dr1OS12yfrs/2t+4d7ZLss z3HvFFA1Luj4pnTMr/Zt3ZNMxItVXCH0i8tO24PlKAabfOrX3RqrGhxClSvFmhr6bI W7i63bjwg+UbUJyliCuE1n6qme78rFHJCXcUdP/nQTwb90pZc307evxXka/xaZAL2S sHNQvp2tGtawND8QO0AXNQvYv7RzXPrtlQLkRF0+ESzwD0h3Saa+NkJnaazUfsg2My gjjaI1s6MpLuw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 01/25] rust: alloc: add `Allocator` trait Date: Thu, 1 Aug 2024 02:02:00 +0200 Message-ID: <20240801000641.1882-2-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 690FC4001A X-Stat-Signature: qj4dwb7nz7qgku7nfaz1pfdwomkrzeug X-Rspam-User: X-HE-Tag: 1722470823-49291 X-HE-Meta: U2FsdGVkX1/Ztt0eFYhZCsYFyl+SpmR1QNIolum5NwLFMmBEoi+9viylVvCNHMXkJScCANzuLNf9uhg7owkOXntoKO6wFrhdVzBIqa+HA9sijX807ZuD9HXpK67cyDqj6jMGybog0prGvK6/yFXfqpJ2mFujOO2sGUeVXfyuPqtjz2Q71pqaSrhtJC/O+RajoJPOQ48CuqSG7RrSXMF+R8Az4diiM7kaeZ0Bg9/7B2Nb6/m2eZ6bCIqV57Bh/jUfu+KJK4wS9aR/K037tkQ58ShLIWIbcb7Smi8R7v1OOYwdv1Mvga6RBK7Je0Qhpg6Nh9VzI3r8JhM7OMOZLXsVAg0fqLUveR4Cc4aYkaNwrIcQGgTG5h3gNH6XojMdfqf17oPI38l5ofg5rRHeYsVKjwqJd1ua5Bi+IZXZ4NR09My0si9X2lc9GazXZYhy5e1KaHhE+24Pg9IqsMhCi91BFoDV71Pdyr4IdJHuwxNttZqxUvfOsjSxAdYvenwfoQPiO/lTIK7pMi/MuDh9ue1aNkrqahTZBtwX8imA2kbgvxOwmG6Li0aXmMwBAhIZPJTJe0+yV0MSENZYeLUMoFiSCIygoMv/CeqY+ujZ7Y8ly1gOJ0/+V/vYGebi/3+d89OCUTX18DDISZUFSFc/E3KZctGK+0y4+NXds1sNgFUGjk07u6myY+1q9c9UARyFB+Pxq4iA46ZECiOM3Ul2Sevm5Y/OwhVECzZo9uCbJ86mUDtd495Okzm53HtKSqRNRTiyXr2VFvag3nqtBr9q9LAz0VcN+/M0P7fI+gQ0pnTgD+w//qop3KK0od1xa+9ZwZyM7XSRDBN5f3KSEQhyN6RL83ED5j7bFbfyVFJ2q06Yr+Lqt11Zuxk2g+K14oYJFeCowXUqWbINTwP5li+D36XewK+enLHacRr/nTMCA2jQH/4QiYonXwRnN5i0tX5hrTGUq99lgYuZhxzo2Xa4Oi8 ZyMhicFG CFrxsoLgVBsoSbRIutq/+UyUjCy3kClEt261d+76STeXrZILsiqAOyFsKYAvWltZSR6Lo2Pd1E3ssM3UYr52n4XS/uy9ozYaVJx0sQl4554FJkRN09MfG9UDJAcYxfjKUogdzmLU9Yqy1livLm4Klix5idwxFiBOj3UgqGy0Hc3GcHNNHCZoJewE5yC2d+XJifohtysgQxf15w1XyQFyl26fFyVGV7HOUwveEJ8RXYbTXI/uOJ21mKEVKKiBYLLn2kNOgUGa9RkrT/jV7X3G2HqcQ2vijQ9hCWEQdCEHYR12p9pmpC/1yeaHUKQ== 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`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 73 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..b79dd2c49277 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,75 @@ 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. +/// +/// # Safety +/// +/// Memory returned from an allocator must point to a valid memory buffer and remain valid until +/// it is explicitly freed. +/// +/// Any pointer to a memory buffer which is currently allocated must be valid to be passed to any +/// other [`Allocator`] function. The same applies for a NULL pointer. +/// +/// If `realloc` is called with: +/// - a size of zero, the given memory allocation, if any, must be freed +/// - a NULL pointer, a new memory allocation must be created +pub unsafe trait Allocator { + /// Allocate memory based on `layout` and `flags`. + /// + /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout + /// constraints (i.e. minimum size and alignment as specified by `layout`). + /// + /// This function is equivalent to `realloc` when called with a NULL pointer. + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + // SAFETY: Passing a NULL pointer 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 + /// + /// `ptr` must point to an existing and valid memory allocation created by this allocator + /// instance. + /// + /// Additionally, `ptr` is allowed to be a NULL pointer; in this case a new memory allocation is + /// created. + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError>; + + /// Free an existing memory allocation. + /// + /// # Safety + /// + /// `ptr` must point to an existing and valid memory allocation created by this `Allocator` + /// instance. + unsafe fn free(ptr: NonNull) { + // SAFETY: `ptr` is guaranteed to be previously allocated with this `Allocator` or NULL. + // Calling `realloc` with a buffer size of zero, frees the buffer `ptr` points to. + let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), Flags(0)) }; + } +} From patchwork Thu Aug 1 00:02: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: 13749341 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 488BDC3DA64 for ; Thu, 1 Aug 2024 00:07:11 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 023266B008A; Wed, 31 Jul 2024 20:07:10 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id EEDF76B008C; Wed, 31 Jul 2024 20:07:09 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CF20F6B0092; Wed, 31 Jul 2024 20:07:09 -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 A980F6B008A for ; Wed, 31 Jul 2024 20:07:09 -0400 (EDT) Received: from smtpin29.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 67DE31C2DC8 for ; Thu, 1 Aug 2024 00:07:09 +0000 (UTC) X-FDA: 82401736578.29.799A78B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf06.hostedemail.com (Postfix) with ESMTP id 373B9180011 for ; Thu, 1 Aug 2024 00:07:06 +0000 (UTC) Authentication-Results: imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=caZue2SC; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf06.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=1722470765; 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=Q+939kC/O+kSEIr8mFyDMfc8xtGxKWUWzEi/7lcM42c=; b=W7NcAbH2OFwoxMDP3x/331iWDxxa6zTJ2gctOpJu3yiZ2xfM7NPTN6PqjbgrP9iOWUpiPz oLVEhuFBZNgRYQLxNxyVxQMyuxA5q7HfKk9qLnb8webHq4euhwd+/XpTdkwrV7aRDHG5VS VeD5jFcxALa3Y5+TAWaMCu4eEyG5njQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470765; a=rsa-sha256; cv=none; b=hYc5golflIsyeAxEKaCET62Q9Xk8M33rskZe+OelswH4JY4WnwuAADSKMj53FG5FuAGf/L EDD8UiVTmKBPiGCyw8K01NNhyYyp7gnayp6Wn6RwxthyX1KXpdrW55sYuQXQm5fgkWwMEG 4o9hGkNo7xeQdi11YNRWyYkGVk9a8oY= ARC-Authentication-Results: i=1; imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=caZue2SC; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf06.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 02871CE182B; Thu, 1 Aug 2024 00:07:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 492AAC32786; Thu, 1 Aug 2024 00:06:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470823; bh=EF5TVGHtjh4ZWyprrgf/Kmvg5Hex1RNnX1bjJzrWn+g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=caZue2SCBQ/qK9rQ+EruSBuRQ8G1EK1zbXMqxoKz6hYHoeDLfVV3Gxkt91OXG61Jc jboqn22gfBqYo8AszpXaPezc0qwmvpK59IAAnLbnK6j7bfBlMWU3ZESLJvEMvHoSsV 90go6u9n/yUL1GwZdoiiSaeWK1rQer+UGHh0Jpy7eHRVTcLnOFrVgHogxeDuZ4WL/c 61FPwrDO2wlP4l87Exc3c4iwlqLRe37EFWUI8qmB+poi8TY0THXzlmbvDQ4hliWjjX HtyGuALr4g8rvlLIDZ4FPHixvzc8lLtbwt9NMN7Sel4SVPjU4LDA5ljn57FjrJnAoW KEZMZ4RqRCpBA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 02/25] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Thu, 1 Aug 2024 02:02:01 +0200 Message-ID: <20240801000641.1882-3-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 373B9180011 X-Stat-Signature: 7tg14su67r31wp316jghcr634ybgn7aq X-Rspam-User: X-HE-Tag: 1722470826-749614 X-HE-Meta: U2FsdGVkX19gHV+U/3o04QNh1n3jYRoW1PMKWRyynihayckVTA8GtHL44RK0dIZHHpQympgqYAEfvcdc/cI3yQlbgb/ZZ5TpmfObt5+plwUphzSQqwzIrXTQCNPXebbZtl07sGM8oTxgzSa0spWAze/bhPRHZ+lxGTOi1sYrtaDVES5Vy6p6HMsbJBLw5ddNx1X51TlahwPCwfcu18c9bNhIRPE8trYuVpDWWuknvedn2PBwiuMaaolpWTySGLr+duDnJHDaZWh8O1GH2phM9LJ5+aaLlE5AqU1pBh3f+ES779NtdJ5X9RSVmaIlwzKUOk4GGyHvfJibwDdPbrYz9SM/zz4BzjoHHhlROo+DuG1ZogX1uyuLQ6BYbhAIIJFUWrpvEN9oNzWK6FkZSlJsEE+K49oGG7bKp4PIvXjA6TG0J3dJ5JMda1olvnFi2v/W2+xbY5bMoV1PzQGJIsnjzwqhp5O335VZESOyINI4t6WQ8iDMpRa8oIUApzSTQYth+Maie/mxsSJ8OVND1wyIMrvfXmIeF2KKt4s35YzYhEfnBnsx5wHNJYDmm141mREIzQTZ68fl5dEIV26h4rT20HJc/sb0D11/DjKKhr2WKfMq+eK0UG9jaGjoqZE1Ykuv6fpGkGaquo+/hOPw5BBz3C7a9EczOjLNXi5jOQSR4Bt+OA43wZEc4WTqmnfKN9yW3VKsfVJMNjptnFwFzwRYTDUdmeeyZqYx3oRULHStNXBHWRMoZlXE9Ct9LwtNaOvfUOmmSgl4qeS/hp74zc9HQAYSMYikw/oT3saC4tQ1+Vd153j4jc9mwu/mxHC1R7TvwpuMQv4keAPgA/ktB/vetAASXjHifmgoNBhizSaFIUYsgjBOOKJGMCcC/wbxvHfX4+k0/V0LpJobvw5ZKWxffVDvpZuJy8cczhCcufqzl79jh/msjdq41bsSH/54TbH4X2SiOKjtvbZton3oVUd 0hxVk9HT IuvQ8GOvkRIb0ZWCUxsN7jAKUL8nk+m59nzvsZCHilfhnkZGBGpuZjMUAwnaygF4pIAbDdrj/xNrmTzFyhc95y0AADCDBWXBp5+t4TFr7RatWOKEc2usQO4yB/7qJq0nIZ+GZdq1wIecp0Ob/TWtHvLh9KvY0/RnJI/NfzH3jCt/0BWFhUqVFeuzxAxO+uLS/8mPe4P3PdxN4DEYOctn5uyanz7SzrOqcR3lYgggzhCer7ZupWBxvgqxh9iei5SzNQgn1+7Bpvna15H2kOSkvaDxN6PjL7lt+nSjLIulLPFZbLLGeZVXOofhMqp5ujROL+jxwNd8+E/MF0+ijppC+eKSfF8Tq0UuyTDjXH1GAs1wrTwU= 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`. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/alloc/allocator.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..6e133780a4a1 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,27 +8,35 @@ struct KernelAllocator; -/// 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 { +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). - let size = layout.size(); + 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 { // 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 } + unsafe { + bindings::krealloc( + ptr as *const core::ffi::c_void, + aligned_size(new_layout), + flags.0, + ) as *mut u8 + } } unsafe impl GlobalAlloc for KernelAllocator { From patchwork Thu Aug 1 00:02: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: 13749342 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 AECACC3DA7F for ; Thu, 1 Aug 2024 00:07:13 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4B7676B0092; Wed, 31 Jul 2024 20:07:12 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 440F36B0095; Wed, 31 Jul 2024 20:07:12 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 290706B0093; Wed, 31 Jul 2024 20:07:12 -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 EE3106B008C for ; Wed, 31 Jul 2024 20:07:11 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 78E5DA080F for ; Thu, 1 Aug 2024 00:07:11 +0000 (UTC) X-FDA: 82401736662.20.7BB1F60 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf27.hostedemail.com (Postfix) with ESMTP id E8E4D4001F for ; Thu, 1 Aug 2024 00:07:09 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=jBYmOPoB; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722470802; 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=sb+sRk/KhpG1et85JfZ2RFT8A4dLjjRlp8oY/wKYqa0=; b=wrIZwBGAg3oLbwi4qs8ZUgUpXnc+ikYWiD5CV6PCPtxIEPOKwhoPE93hAqLJZOgxV2y/vE Lrf2x24S8llSEKcKEXjce/O1op+BrBJfhuWx4FKwHOMNA+jaKOHlgU4Ekzemij1vvtl7fJ sYtxjPOvx/k8kmcZpopiGu+S6cUkiFI= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=jBYmOPoB; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470802; a=rsa-sha256; cv=none; b=LQDRRW9URR8ALZsxqprYAYBJUNqWqFTIV5WJSeX4ScLDmqNNcAJj60gvhYxcl+40dLGtlQ IG+Zi4EiC/4ZEfq07gnQeZGUVWSE4bDG9zlNMT9XaauzeiZm4Kvsoe7R87S5xINZHMT59S UtgBwDLzhQwhg/uj0q23cZ4mSWfpjWc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 1CF966246A; Thu, 1 Aug 2024 00:07:09 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BF2ABC4AF0C; Thu, 1 Aug 2024 00:07:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470828; bh=aW/HcnaSGCL2MNKjQfZpCrQAc7Fxs7Kovj68XjWpzPo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=jBYmOPoByXs5xNTmUlHB+YhPa15GwpymwwL3KlcJuVBlUgTtc2hF2vc3WDtmW/n4s AtGeSVMmAW6XLXAA4x9LOYxMQcMf4rX3jwCcLcnPffYQKthc1Ui8NedRYGZvLXuGf8 tPEnDcanlJB1nFStDAxtV+TwXU5Avnikrs9qSnrxRYD2nMbwPzs7d2sQ5CnhDvQZm1 r4m4DohrnpYXvGpWZDX/P+SFcDLTPVmdDBM/Ufv01jPXdUX/Kj0pDvT693dRN31G+L KoLAFANNovd+tWyzyHNoyUH7yWgCbFaSpcBitHT3xZmwW+Dcc99tLsI3aB5jt8aZeX tixOGPlXJavbg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 03/25] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Thu, 1 Aug 2024 02:02:02 +0200 Message-ID: <20240801000641.1882-4-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: E8E4D4001F X-Stat-Signature: zc4fyc9pstuyu7wnfjpwygo8cuwgrhq5 X-HE-Tag: 1722470829-519734 X-HE-Meta: U2FsdGVkX19dSXBmnxEwD3wW24J9Qxmkwgpqs+EvSNecO1AdH31A+Mx/ZtbuD7N/AXoOFGOLeSIt8h45GGBlMGT3pxc+/mK3G21lzmCBK2ut0Xbp/p8cZ6T46OSwpvdPx2tx8nS4lK9x2NmSRBclXnrjAw+bJeYXDEdaNUmkLtV6AAcgfeyh4IzaQ2QEZYTCf1pDzL+Sl/1jbp6S23oyIZQky3ktdeaLVF+Z8P/Vonkt+celLkW8I3H2ygHnC3mOhrts7FcCOdZUgFeV/ozH/gw1+N23UVbe3BXzDFpdDXJVsN7DeR7E5oDRkahTsWehtuOJzq2rSe2hYVb0CZUjIGOxyncoxayUWZSZfsGWlaOws+7VBGlWmAspps182gVuoQxFliG4IaigqgAPL+Xae4gcT21nG5o7iebs5ROkjfGdzJ6ZvzyMUVLjPZGDsy3dyifJ5pjKNi6n18tNJSKK/iMMOvt5hQreDC4lJUGWqZf16dBAOQcDUMbuKzVnIrXaiynG3plP80jB/V9Xxww60+h9HKD0/QgL5xFESWGlxWC5XluiHranB+q4RYlrpuuN5++u9E4g83CV+ctHbldNX2nIUffA5YIQMqsyTehRmhXa/RckJHY8RGSNjyxOq3ACRKirSteKjzqZS08PMrUpi/xHDFwEtyKpb4O1SoVz4DLLl1x6NQVkKy5ASm8oG6Kp1d6H5H56n3iteyrn0Q1KKHHQ30juuwLtTEezw1uVH+mMywRxEvOIxscC2f5pnmCXIwgRg4OQKtLat7c8GHILe28j3QbuKbhChA8FAImAIe5G5OMdn2xaWZY30+gsILaIOt9j3h3K8Gf2Qo+j0Dsiku65zkTJPMvEfWB4GstArjVpyMt180DW+ZKAJCfyRIx/sG0IcFmLOo4le50KkHSn335Pm4sabNtzq1SjlNXBPuf1TVXMI9c6h+4y1dk8mmora3fAMTmsB8vezaSn1FA JV0X561P iBYekvUrGbLYj6B9K6YhswLvH9yxOUHd+ICkNAGtRTNURe0sW3yXbOei/mzmqW/D/qauPwRjwtok3BfdRX5G3HUI5oWa568NccUhUi7NA1Mg9o0QuIruB5VIx8fGxZxYphDVO0k72DUeyUz//2UYN6o9IVrbj6hA6XcxbTUxZvtwlN+kYSj1z2GT7G+en9fMc9H9I9LuowRLa3EnJSlNUb/+L2IZ3bITwNcqevQ7RFpaqsy85I3j4AUF3+p82/G8l4Femy5tKYksUeiSnbbhTOPziIC6UVDF30zbI81AlPRvPVY0KLeoTxjCJbv8+rXbQAO5SeGBQRPr99rA= 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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/alloc/allocator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 6e133780a4a1..10774c51ae26 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -6,7 +6,7 @@ use core::alloc::{GlobalAlloc, Layout}; use core::ptr; -struct KernelAllocator; +struct Kmalloc; fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. @@ -39,7 +39,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F } } -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. @@ -75,7 +75,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 Thu Aug 1 00:02: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: 13749343 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 D875DC3DA64 for ; Thu, 1 Aug 2024 00:07:20 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 63AD86B0096; Wed, 31 Jul 2024 20:07:20 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5C3956B0098; Wed, 31 Jul 2024 20:07:20 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 43E256B0099; Wed, 31 Jul 2024 20:07:20 -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 23EB26B0096 for ; Wed, 31 Jul 2024 20:07:20 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id E0946A07E7 for ; Thu, 1 Aug 2024 00:07:19 +0000 (UTC) X-FDA: 82401736998.16.DD45FFA Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf21.hostedemail.com (Postfix) with ESMTP id A529E1C000D for ; Thu, 1 Aug 2024 00:07:17 +0000 (UTC) Authentication-Results: imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="DG/yCAlC"; spf=pass (imf21.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=1722470810; 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=mJELk9aAnwioKgHChjfu0TpdI3TImwGpczRJrfMaEfs=; b=cWq3z3iY2IMwOz1OKlhuey/3dRDyCTPuk6I4vPqdtVabMA4wpRDpR9d05/FtMQ1fJrlgjw FM0okH+YDtsm6d4YWEMW4T/DzHTEzV3qBfCDGUF/y7lw+RcDoni6j7N/hFUQxuzvH/DG03 /i8ljT9et54Oi8/ZLKhmZZpg3PuO2PY= ARC-Authentication-Results: i=1; imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="DG/yCAlC"; spf=pass (imf21.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=1722470810; a=rsa-sha256; cv=none; b=kC+L4v/7rUqtrkMP5l64gPWnUEKnQIwTJLPbpI6uZtIWzs/859odfwo0/dcLgM89cGsvc0 Ht6FPg5jHJHHdQFcPwP9QDExGNQ1w9rHQ+5yJRp2rd84rgKv5m4CvsnosbHmvi9Tx5Le+9 WrrZHeXlDihtnvz3KCITra3mDmmOvww= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 08213CE186A; Thu, 1 Aug 2024 00:07:15 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 40F03C32786; Thu, 1 Aug 2024 00:07:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470834; bh=0w3mioTnyHncnDbTDnqArHEDkcmV3wgJvYOvZszLfu0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DG/yCAlC0W0UoH0gBjbQKLyIz1lq+qfvgUQGa2czCTNVyuX9Ygbi1vodeHPhP5gNg 9ZlEHV/epF+rc/4PywoBB2iRQGZLsxY8brfKti3MtPxy6lBjTvGFKzJFMRcb/FDnK+ 6/VrTFUCm3NXzq45y3+ZVPMsuZN5w0Mlm+M2b8qVQuX7YZkLZOpl7b2AZ/zWD4tMjK FkgYCouDy/ahsejtOmAsvtkZDdrRc9HJxplYYvC1+3Kh2TT/SQr+S1nq0YClOI3cy0 kAIw02uw43vQHyLdqkbE6LPFC8HAfxcPZx1XCgioanIkZUzAIMeZDpsINPR/tJR591 Q3MsKF+c8hGfg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 04/25] rust: alloc: implement `Allocator` for `Kmalloc` Date: Thu, 1 Aug 2024 02:02:03 +0200 Message-ID: <20240801000641.1882-5-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: A529E1C000D X-Stat-Signature: qfxq5jr6cubkgj43m3pmg473okc66qwu X-HE-Tag: 1722470837-315727 X-HE-Meta: U2FsdGVkX18JZ0ZTWcNCsXGxjl7o6pkXfX3h6jTTioOo/rqCwM2zNHnCHlqwSghQgaJatOdwthtyxv0CVnuumiGtNJQO45DUqUXcejE8gpDub3x2tjkSFa/qHVLgpryDBQztfmtWXYAJhsiltmIJBTYcz6eXouqpCuFgnmBi5DnyWE+YWpM0yCkTraImQ5eJPs0IMHdM/k4jihNJyTLbyN8i3xB2KJ4lAeEcbYb7QSuq2NNbTTqcXn+wMtEgHb1ynDsA3XACixxOxOljhR0c6kOCxybo+Fh/TiMAnO9LQ4wpI/zugGabsnKveb2RjHDA5/juEn0qUE3UVgvDkxirzwsW8UaoBD3j8/5orEktZeiJRjKHG9E0k6fCeGUk+skOHZ7xW1HmeKt1T32MqjvzWRN/UETvylVL+QBQl74wPMLc/NKm0qHS8eNolX4v8PyDGE42H4/KsBi1TeoaBbOip0cqBh82aC5BxcKQE4YziX2NnLLTKz+mIDTDKC3pYp9Fwhoi8KbSh/I1Xon4PcFYSQLFJU1wdtOZL/vKZ7l0MkJL/Z05t6g697UwCrLGVxCTU7XUUW1r7EfkCTUDRzjmJNTZ8CT24loOnscYEBIc9ikkoiDOT29fKzqCtLDyfJB5fnZArFbFajglNtGo9L3/BvjDDZBxX48dpPxtR2U5zEvpcxJNxJT2fSiVpowcA3p9WgC0WbTX0SNrwH49mEWF6TxLx/y/K7+6sFVng0AqGizLco8HRV2Q+5TSKCqWa6ivjmduDwMdNLP5BopVtQmonZLSL9NiuHyaaansL3ZO2jrUfoHt2U3D28VCfO6pECCpYtmRE4HcqFlO3jKMqIhB9xa9P388OUhrp4eiEWjdDVCzzMDo9691kptKGZBL8Y209Tm513iXlQraYUJKtHBvyP/gSy78vgnuRGZ8t0L47KEyMN0cRmH4lcS2g8yeaepgggZ4ytYp6qXPYaXbyZs 8lA8GBqq xkVrwbNPPlnrOk9zjBbR9nEE4MhHkh5YUdQh/LrYkvNAD0IrXL6LovnE6GFAVtScY0pxWTTHYzpsgynffatqKnwzQN6uGrqKwV/LvT7XqtdMHMVHDGTRYJqwTZbMV7i27SckqMLyzpbnO2XCwC0cciEiWOUackVw4QUDHDGNLBPERcZH/W9uC2sT58XOcN3agMFdHrDcsXVJ7q1r2NCASNGjZLl2n2EuC2v8S2f+HWtN8TTEorUbrHuyO06EoPvxE0U57yFLvCi9KrVwn8WxbK8yN09n2hW5qnJBhWwaOD+Scn1/m1UNPbdsM0A== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `Allocator` for `Kmalloc`, the kernel's default allocator, typically used for objects smaller than page size. All memory allocations made with `Kmalloc` end up in `krealloc()`. It serves as allocator for the subsequently introduced types `KBox` and `KVec`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 66 ++++++++++++++++++++++++++++++++-- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index b79dd2c49277..8cabc888393b 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 10774c51ae26..397ae5bcc043 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -5,9 +5,18 @@ use super::{flags::*, Flags}; use core::alloc::{GlobalAlloc, Layout}; use core::ptr; +use core::ptr::NonNull; -struct Kmalloc; +use crate::alloc::{AllocError, Allocator}; +use crate::bindings; +/// The contiguous kernel allocator. +/// +/// The contiguous kernel allocator only ever allocates physically contiguous memory through +/// `bindings::krealloc`. +pub struct Kmalloc; + +/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. let layout = new_layout.pad_to_align(); @@ -18,7 +27,7 @@ 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. +/// Calls `krealloc` with a proper size to alloc a new object. /// /// # Safety /// @@ -39,6 +48,59 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F } } +struct ReallocFunc( + // INVARIANT: One of the following `krealloc`, `vrealloc`, `kvrealloc`. + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, +); + +impl ReallocFunc { + fn krealloc() -> Self { + Self(bindings::krealloc) + } + + // SAFETY: `call` has the exact same safety requirements as `Allocator::realloc`. + unsafe fn call( + &self, + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let size = aligned_size(layout); + let ptr = match ptr { + Some(ptr) => ptr.as_ptr(), + None => ptr::null(), + }; + + // SAFETY: `ptr` is 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 { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc = ReallocFunc::krealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.call(ptr, layout, flags) } + } +} + unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety From patchwork Thu Aug 1 00:02: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: 13749344 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 A78C1C3DA7F for ; Thu, 1 Aug 2024 00:07:23 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 37BA76B0099; Wed, 31 Jul 2024 20:07:23 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 2DFF86B009A; Wed, 31 Jul 2024 20:07:23 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 159606B009B; Wed, 31 Jul 2024 20:07:23 -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 EBBE06B0099 for ; Wed, 31 Jul 2024 20:07:22 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id A63038082A for ; Thu, 1 Aug 2024 00:07:22 +0000 (UTC) X-FDA: 82401737124.14.8E5F7B3 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf19.hostedemail.com (Postfix) with ESMTP id 0939F1A000F for ; Thu, 1 Aug 2024 00:07:20 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="Qnbk/8bq"; spf=pass (imf19.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=1722470813; 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=Ktja1Qz4V2ENHBxtk5PtFAadBKLEPzG193jzgSKbVBA=; b=YPnQSekQKNsAt8LbJWcbAV+OcUqZf/nCrxyMDTyfUoZqmjzcwAvuIEbtkLFo/vFa9xQCCh VgYrTXsQsx2c4rNXl0R7bx535bBzGtZCVjx6RQunJ3h1MNGWy4KnDzbjNq0A7twsXENUa/ bmeP/CL6/RoywS0XVmMdrrgAG87on34= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="Qnbk/8bq"; spf=pass (imf19.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=1722470813; a=rsa-sha256; cv=none; b=2uLm1qe/Luxf+coHiKYi6LHaIP7I+UM2LtIO0kbXSkw3drdDnD51XcetO/1NJroDEjolk4 0Os50+iMOa8bFSVWa9tEPE4+6LlPcGBfYIRpvlzsEQjp7KEwlrWwjTZuR58DzNQ4meAiyE A06TVlw0fByaGeYvr0wpsUQMOAH5r1M= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 1E2F56265B; Thu, 1 Aug 2024 00:07:20 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B8539C4AF0F; Thu, 1 Aug 2024 00:07:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470839; bh=NhoXQc/3NsMmnAPcZ6sxE5qBH2rG1UwJKGQPjBzD4UQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Qnbk/8bqEz+f7vIQkgZF3ii1t/44Pt0IyVAeduPEsyw15aUBIunIRCTOcLkj/4tFg UioDGgVy1iZi90grH4zYgsok1EQjaBYAXqmCCK9fo83geupijgvjO384a+8MtpK4B0 gWUo5nulw0azUB6RH4NohTHVjRW+jR/6peGuZQUJM2+JCvHGfY8MR481XpDvXig6IZ Bm1J547kzWyUWiGfNhfol3gYMjEEcEdIe1qajTqXxvZcKwigeC3EDtuuawQYo1g29M E1p6il6mkzvIMyqZ9qRtLlAhB8SkvbsxdpfK1nUo8WEtoY8NkbXIEM9y8C8guyxzhY rPB3gdike6Apw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 05/25] rust: alloc: add module `allocator_test` Date: Thu, 1 Aug 2024 02:02:04 +0200 Message-ID: <20240801000641.1882-6-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 0939F1A000F X-Stat-Signature: mrnqpu3gswq5tby5ciebejtb3zfrpow6 X-HE-Tag: 1722470840-490207 X-HE-Meta: U2FsdGVkX1/aWZTP0TRGVa4ojYhpO/JD6lJMlk3Fh7vNqajY+mI9ztOB+SaBtZifN7NU6QWAqcnHrZRkltw+vWadjz8WkVPobuJBlMjn84h+1sDR1+M5TdQaAMUj9xbl0R47Xjzd0Iv7iQarD6mNuwjl9OhUBy70x9qdziApKa+DQnCR/EWo+p3NgGLUgcc12+pAj+cxqCjz3G31CXHPByxpr/4j6gyuNbpczqODkfIpoqQJfWODnEGX9mo/XE7Qa2qGhukJjYFw0dCHZhMRZ3f9npfdGaFAUX4030qwuA81tBTefGO37B1Jzx1znt8/D2CrDM9juciSBlrPaRMOgRj5itpYqYbe+8x5pVPkYi+Hq1sZwbVp0b6K6IeBsgWIRHA/gH9NnxPAIVf6gFR40mdj/USOPQY6NwwtRD8xJAeswH1Ff9dWD3A0rQLnAuu9ZYP9cOecRcWSOlx7w8mkWSfnnYebHaUuGFIL/cd6+vCZGMNl6va+JsucpgM4HgqmfSqLss4W+5s1KviO9BNQ5sLtySxpbvgRPSFN9QAjO7XRRrkij1sYiJket7lx33qjZzk8WPSSH5xIZ9YykUb22BAvnbvQvP3g8cvydjdkaPqKyvmj/WiENN7UNqPd6o/KMz6fibsfGSFiQO7/G4zG0Hk/IE/P7tIejGiz1aAK2ROGCszwDRKGZraAfmGYMamHFxm/SV7aQ7dO+KSr6kBt7H82kYVCzmZuK4fwywoXuh4dWlvXlRV4gJq4naKSY3mJGQkgctKwE+EmT6qiHjx7F+vH19bKHe7AjNYb7BinLUAEcI2bnPUkqd89XPS+6BE05tPEL9hgbU7uLBwSomgKCFoL3Wpl68R+eAzq8Xd2EmPLolPAAMU6iT9Nwo7Qa2CjiIkibtrVByCpGlJVZ7klE6L0xDYUJ0HvBA6zNotO0UmwyB1v6GUrjotOeKm9YFsEjsEo9zUZCHaymok8YFn 4n+mrNiQ VPT5J0B8v9zasE++sp873dsgoChfnzkbpMU1K2XAnyA2lthYG9Wp8OaabDH99PNQ2+JlGvYCzu9NIvkzkeCHcaQfa4ReMPy8vXB+Ijxqc/Bv/pD4YdJh0GRg7Q5jXy4EChgB8srtEI64mNx7dxCbrGMktY7WEz5ZZaoH7UHXiighr9Muvcsxg3YbFyhUrTjX+enAmU7dSP7q66QumtzsiwYep4CxTJSnXTeMgYvvj2Ti+GzDa9e1wOjh6W1Kz0EzHkGy5DkieRvR759cXaRk1HWGnDaZk2LiuL3m6O0IrqLocCG0WZlnM7gKIlNqSwwDcbgw8WJTBuRcDjWI2UElW090hz2Cg2TeDMRPJVD02cfotOQ4= 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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- 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 8cabc888393b..90f4452b146a 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 Thu Aug 1 00:02: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: 13749345 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 251FEC3DA7F for ; Thu, 1 Aug 2024 00:07:29 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id AA90B6B009B; Wed, 31 Jul 2024 20:07:28 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id A58526B009C; Wed, 31 Jul 2024 20:07:28 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8D2D76B009D; Wed, 31 Jul 2024 20:07:28 -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 6DF8C6B009B for ; Wed, 31 Jul 2024 20:07:28 -0400 (EDT) Received: from smtpin04.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 2A9F81606F3 for ; Thu, 1 Aug 2024 00:07:28 +0000 (UTC) X-FDA: 82401737376.04.C5FC6D0 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf13.hostedemail.com (Postfix) with ESMTP id 68A6E20005 for ; Thu, 1 Aug 2024 00:07:26 +0000 (UTC) Authentication-Results: imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f4TjSZqx; spf=pass (imf13.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722470791; 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=y9voaciKr1Vp1HVw452qlJs0DayVYIJbO2RFcmKzf0o=; b=8JcjVTv6izSCaDdq6PNd+hQ+/Udq7TsrS3VdY6PGDETdiX3uhjU877YdF+DTq4HkimS9Rh sXBCCTdR0Dv37GgkkH/eH40GyM8XFNDbKsddywaPt2vc48gXNQQxBWuIgUS+0HKon3E+GT 6IKI+JDVlx6jyX/Zc/vFVtmGwBCYWlA= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470791; a=rsa-sha256; cv=none; b=ebmhjaHIjuQBgLNuk0WG1PVRRTvPzEobZKc+DHsKTB6buzY/AJFUR41z0AOs8qzVz8dgFe pc4DI6zOSBxr1z5KKKIu+8dlbMalhuq2LZWqMcaHos/BCZa77qlAsYyc4XClsQ7rVxUPuN q1vW+I66b9pzShW1FSw2/6hlNLDEuw4= ARC-Authentication-Results: i=1; imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f4TjSZqx; spf=pass (imf13.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=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 954136246A; Thu, 1 Aug 2024 00:07:25 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 45EF5C116B1; Thu, 1 Aug 2024 00:07:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470845; bh=GDa7Qic2Pqt1tK9CmgQPCpMbrxajNVkM/PqJ2bN2JNk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=f4TjSZqxqVmzLQvxNTJHLNg7/RlW2OXK4+0dwEJakt3RGW5505QubVI6Z6tVK46Uz IdScThKwTlfahGAF8bxd2o8GA+NrGumvAObrRPSmouCsa+n3vJ87K0RceE6zbnWf1Y jBHcbMPp906rAIQo4+rx0ETiriTvp3abqAFUTqoHz6W9yfIDSiB8wZ2Bcw9jrADOso efQKlU64f3dnheWV1I4rIAf2eKyf/lJxXHMm+g+P2ojV8VqXKx9fB45uTohEkzHerF WDfyIy7gid4U22Aif7zDvnDgluYy+G336U18jsq99ynxVJzxh4tt6QD82N/TQg0yJt acLK8EXntm38w== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 06/25] rust: alloc: implement `Vmalloc` allocator Date: Thu, 1 Aug 2024 02:02:05 +0200 Message-ID: <20240801000641.1882-7-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 68A6E20005 X-Stat-Signature: dcg5g8t1tbq7zg1so79wfazazoyufjm6 X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470846-315501 X-HE-Meta: U2FsdGVkX1932VNP20YADnb+Qr5yOj+5RuyEQueegjxICM86Ufz9WlN4pzmp136odi1esTNgMIHq1wzasnJXUHdOmyOwGIFtMwkdfhcMT+yzof/TnPGPMhfWLYBSHMz+xESMXYs5fsz63UiYg0SHSDjEgP4P7m3LFbUtf5bqMXLp1UQIEeUcrvWG1+54w+5TD58YxGEjZdR9tJzCl1zv6e3rnHpDKBd9ThuhUBcJi9WEjT+R2FwouD1JMFq8zNUOYt//UjFOctWk4cNb6ze1CY1k+Voh1Eoq0eBI/8jOIrpRPiLqGIGxFLTdt7ujKvg3gVFv408IitcZKsobpyPI1co8dwiJuddrygE7fSF5ByOs8tSDr5OWhccPwzR9FPzhOAcu5YEAEHX86kOH+NdK5cVCEjQmxWaX4HluGXmX4o3VngaIjHYAgHjpj9E0C8tv6UptvqOrFh9qu3I8K0pgZd0GBA1J69GuyLO6mzNCYe+nA7aTHaOdgiw5qsxmIa3wG2VPC5eM0oAEyyMyN/qTTth9+2Hbuu8Z0blMozOq3rVFwdyFzKIH0vFKVBfqHg0QTr0t7zheTD/GvfDi+wHZcZ9mdjT92UnYVuKaiB19Ib8+tXua53r7ESPSUkRbmiFfKq/8a76FGGmqI7Ua27GgcWybH4aJJgoLkp5qdW8hPuYq3dMxPR/8JDbyGKT+48aHRqI5kIny/eo32Tm2s5TDaq0zxmcYilVaAvwKBavTPxJPg/qsp7ZURjXzrB2A34CqNW9BPCBjYfuX8kURWMwD5zOQnhT+uMz42I1lYA10fc9QrjIY0KYphyxS56WQw/yIrmE5pxMB+me6Z/Df8Ev0/3qDpUTNBaR1HggpbP6dEw4+sjuM3MAmW1HtRYhDRq7vqYFurIdG3/3n+dEhfBS+kXNejFwgCOX1UyAFmC0Hc8dSjnHyjWx+T5F0WyQ6onHDBSe8FkMJXuAzacWspMQ mRTGumVB uIirwwBaRGySc5zt1S3m8Zn6gx4SabQV//2J9aDjno3mWSC0NYzQrOYzta40+U9fxKxrACYUELJs/TO508PlUwZMwY8peSKp578cEiB4WvDwbISaVl7mmtqX3W2y6DURDrDMhTMYTQ47BewXDDrgPvfmWEVSBmNTXVuCTJET57aT4c0TP4n5qfCVBHJDCIsAPFXjfpMFpskQhMO7+goj/LsvK00yocth4PvgckGZK7+cI7xNBeCoYHYEiw3Qr1TI6XpmoZ4yV5MymNZlT9f2cY+DfG2hTpdWRzdVUBjCutYuuXLHerwGdutrokw== 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()`. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/helpers.c | 8 ++++++++ rust/kernel/alloc/allocator.rs | 24 ++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 33 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 92d3c03ae1bd..4c628986f0c9 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -200,6 +201,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); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 397ae5bcc043..e9a3d0694f41 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -16,6 +16,12 @@ /// `bindings::krealloc`. pub struct Kmalloc; +/// The virtually contiguous kernel allocator. +/// +/// The vmalloc allocator allocates pages from the page level allocator and maps them into the +/// contiguous kernel virtual space. +pub struct Vmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. @@ -58,6 +64,10 @@ fn krealloc() -> Self { Self(bindings::krealloc) } + fn vrealloc() -> Self { + Self(bindings::vrealloc) + } + // SAFETY: `call` has the exact same safety requirements as `Allocator::realloc`. unsafe fn call( &self, @@ -136,6 +146,20 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } } +unsafe impl Allocator for Vmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc = ReallocFunc::vrealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.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 Thu Aug 1 00:02: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: 13749346 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 AC15EC3DA7F for ; Thu, 1 Aug 2024 00:07:37 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3AEC36B009F; Wed, 31 Jul 2024 20:07:37 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 353026B009E; Wed, 31 Jul 2024 20:07:37 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1F3E96B009F; Wed, 31 Jul 2024 20:07:37 -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 0122E6B009D for ; Wed, 31 Jul 2024 20:07:36 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id B0DB5160816 for ; Thu, 1 Aug 2024 00:07:36 +0000 (UTC) X-FDA: 82401737712.14.1685D2D Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf20.hostedemail.com (Postfix) with ESMTP id 4672E1C002B for ; Thu, 1 Aug 2024 00:07:33 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=o21YFXJi; spf=pass (imf20.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=1722470798; 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=MGpbhRuzRd/0lKmk2mt7wYVrOta4jOEI7JFbV9c47Eo=; b=K+IvtlPrKjQ1Aq6YERxp4k/DrAcixGFSjmMsyzwbd3QDrZNYnfFF6P2cvlBIn0dqjHLLxv DGv5BDoqRWPFtrwgTAnEN/T3pVMNNmrI/jYaUOIrosoLdSmTabLE6scwiFRV1gyOi2wGbU qst8XQnujgUNVSfr1yF9P+2x9n3J0TQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470798; a=rsa-sha256; cv=none; b=zr11vRWajiGTtePFUgmSKzDr+fStwjtnd2uFXGdVYqb8kOHG5j5L02F7Cv/BO7D6RwnO/c ZVjCfayYpggwxawMl3Eoir3osC1LO3TWce9yXn7Y2N7Rd4spJo+WXwMA9DjUYa+zZa4hLO dqEpX0102nOLLyU/VJCruPP3Rlye/FM= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=o21YFXJi; spf=pass (imf20.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 9B4ABCE186A; Thu, 1 Aug 2024 00:07:31 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BA3D3C4AF0C; Thu, 1 Aug 2024 00:07:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470850; bh=vpuQqVGdruui4OBsLFoLlveSHdy3R+nqUtK2TdTuy/s=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=o21YFXJiH68ZpPo4iNUPdphpPPYfsKEMZCBCPzYfh/vAR0GDVtj+LZXIeMANyxArZ DYmzdHQYBRD/8fWd0BDotHVm7vBfvinT+cAleKi4RuY1WeTjiypprJp8xXL3X7hvC1 wYKQbfVhD0UBCMKzN63FlFziuaYEFp0jtmFStkbopTbpLaMJ5wym9m8dp2rErXd9B8 RWelDLz8llXjECN6gmrbJyaIlQYkO7UPZt4XOMvFuzbu6IZsoyuzfq2yBO7rcbQ7US m2Nd22NIm9TLiDaj+/MGiESojJ1k2/+xGn77288VwrVUKIYRdcS9Yqo1070D8C5Ymt 5RgT0hTUW7mDA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 07/25] rust: alloc: implement `KVmalloc` allocator Date: Thu, 1 Aug 2024 02:02:06 +0200 Message-ID: <20240801000641.1882-8-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 4672E1C002B X-Stat-Signature: r88cpr38r1cbczubr9k5sgs135xzrokc X-HE-Tag: 1722470853-804076 X-HE-Meta: U2FsdGVkX1+c/i7mRMLJ9aZ3fSlRqFsMzpewfPFvKeKC0iVAW9ems7fC8u9Xtly71xwQZMBopouZ4FdDslAjKrN5UvIRzy5otx8R0sX2T8hLCB2NMwB8bT2olMGtuAdq9kfm/qXHIjncO9b9TPasypyJUdUWNS2/l4Bs4k3/CUXjRInMlolhK+poEDWBB5hfopFQgOXA70vn0vfchTI3qP4/WWe1yzsuDHczNxFTvuJkODznkAcpplNC+DEpOTovjfShm5Boklo3BGu5VXixjMDMevurabivSCZGb55c0DyRKcxRssgO7BaZeVTiMnq4bWqn5DFuBQiuxUnvbCUCJvqkeZQYLB/MvXfaJycuyOpzRKYgt4ePuBp10IU/zZ6w108zsL/SXClq5pMFb5k1naPha5e5ETK9sMnepG0fpLfs4bFqNObC301alvG+V1W4FdI/V0+najPqYmqzh3mR5QY81sE2Ah49zLtAI7VZle9GkLUBdpIzFqCfrCT/7zkHAdsGRJj14zmrhrrrh1EnnRuIunix5MlWWMSOE6rSc5z1iYwn9TTEfG2PcvxtUyVEsJu3zc6Mq11v9bFbDauoF0LRxttFGqc5hWB76zF56UTEsvJxuBbmP8Fm/WQ+iRAj8y4dDQodEqT57mwHNiZwzkm8j51dtrZjY93xDW1JkVQJMqYgecNA9NIX/DDdn0qEylekpxyxZDhgD64JkgezinW7tOYhPk1lbW/qYZb8HXF+KpKXZZ06oqLso/IWK01EthVRUtAlP9QcK0rzxmScB6DwsAFeXbtvwQuDKglV3FopSXZDuTOXZA6LmfoUKOY8AQ/uthHx8TUXXV0cJOeX4tigBwN1+VknY2jzviAig4FGSesnn1E4fAAFziUZaZXVQHKBkQfXH6y9kVh3OAyUu47xtBQhmFJuT40dR5/9aEXjPWeecgpR59guCDLVWSTDAlVTIDKhzJPnwLJFA6/ oXEv0R26 +VFbHLSjcnn0bab07puah+2T3EZypg2rchVYE/q/71MR5TekmhXRPdX8oo1jas8xVbd9KIgm8pe2NgJzF4vupb/eaox0Vj60b6PwptbUoZWqiyWLLzprneBedrGUHvIZIJz2hCRYgXjptrzdHaNTkXN0ORCF6U7+HLtm0dTdT/pNDunl4hGUz8Tmwiph1Iybh5sj7n3O+SuNf+pkYZlrWDAkA7VogzyAEVo4Hkaxer6sYuWcHsGzM+S+wDOWL/+NCDEZMxIp2VPVq43xRWrR6KI+bNwygC7yP5bsNLKNTUQgUzly1nab+JqnTNA== 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()`. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/helpers.c | 7 +++++++ rust/kernel/alloc/allocator.rs | 24 ++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 32 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 4c628986f0c9..4ad7dc347523 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -208,6 +208,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); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e9a3d0694f41..1e53f149db96 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -22,6 +22,12 @@ /// contiguous kernel virtual space. pub struct Vmalloc; +/// The kvmalloc kernel allocator. +/// +/// Attempt to allocate physically contiguous memory, but upon failure, fall back to non-contiguous +/// (vmalloc) allocation. +pub struct KVmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. @@ -68,6 +74,10 @@ fn vrealloc() -> Self { Self(bindings::vrealloc) } + fn kvrealloc() -> Self { + Self(bindings::kvrealloc) + } + // SAFETY: `call` has the exact same safety requirements as `Allocator::realloc`. unsafe fn call( &self, @@ -160,6 +170,20 @@ unsafe fn realloc( } } +unsafe impl Allocator for KVmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc = ReallocFunc::kvrealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.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 Thu Aug 1 00:02: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: 13749347 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 C41BFC3DA7F for ; Thu, 1 Aug 2024 00:07:42 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 577826B009E; Wed, 31 Jul 2024 20:07:42 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 528206B00A0; Wed, 31 Jul 2024 20:07:42 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3C7BC6B00A1; Wed, 31 Jul 2024 20:07:42 -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 1738B6B009E for ; Wed, 31 Jul 2024 20:07:42 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id C45CAC07B7 for ; Thu, 1 Aug 2024 00:07:41 +0000 (UTC) X-FDA: 82401737922.03.781AD1E Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf19.hostedemail.com (Postfix) with ESMTP id 84EDE1A002A for ; Thu, 1 Aug 2024 00:07:39 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qnKAY9mZ; spf=pass (imf19.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=1722470785; 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=aGeqMyC7GCy/MfpZbpdsFcxVZpw4WIh6a2U4e8v46BY=; b=1ury2kFnuyqnIbRIMrfn3pKChCOhaa+v8V5oXJpr4KAf4TZSaGn6QurEXxbcqwnRcBY/8f jh8swQ0UjevYlJMT+AWgu3s6glxw4iiu4g+VlMZ7mRTtQvyVj8sl5g4spxExwNSbshoTKd X6pbB2wtXkCPd067LoQm8b3ElsXhUbE= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qnKAY9mZ; spf=pass (imf19.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=1722470785; a=rsa-sha256; cv=none; b=TQGBjrIKYzkBozbDBZn3ASt3DITEXbNtEEahMpARhjgTDOqnzMfH/IBQlx/OAjBdqnUFqM PP5+D0Le9GEpyWMbyTwfSGPn6ix50cGYkX/gRcea3a+VqQlC7ZD7LXMW3Csx5/YfAGOvZu 1MbBIYJrH+uWfNTyUvOSCXlBjzPnY9Y= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id E36BDCE182B; Thu, 1 Aug 2024 00:07:36 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 36BCCC32786; Thu, 1 Aug 2024 00:07:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470856; bh=5FSlmk8uiC802CZQ4+q6oRgODjrvttEYMjmd4A1Q0DE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qnKAY9mZbcsCbF9DQaUa7rRNVkMDSwbsrxRFtaDrjtQt3Z/cIgbs1zut+BbliJAdK 02zGAuUF/fWyyxTRKQsHtznT6ozKJVeCvoW6+EVV5DfMN/BsmrXoW8MDT4rnA6yBHa /xgrWKbCzvTKFyWD5m8918wkQETNmEB/b782b6+QRu1BaCATYSzYyk6WxBBcOYirm6 Nh09pNPRyA8MaYDBRunWAOM1xS0zxtrXTYOQ8xxgNDWI3Nii4kDZsDh38BsVlJmtMW wMRyTscpofeJMM43u+vrlx/0ibjWjkfqt0hOGPoqEyR1vFiX/wae3AYVEDy9JjsDw+ S2pfumYJIRWCA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 08/25] rust: types: implement `Unique` Date: Thu, 1 Aug 2024 02:02:07 +0200 Message-ID: <20240801000641.1882-9-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 84EDE1A002A X-Stat-Signature: 3idsub64yewpwkd7pqxqemnja9izpbty X-Rspam-User: X-HE-Tag: 1722470859-36515 X-HE-Meta: U2FsdGVkX18UDdA+S3x1BF6jstfxgudQM2AdWxEIENTLuiQyrBHjTZ3XhEOToOfve8ZgC0FWKsuPN3mqbHXGuokQsAEQp4H+0ce3uCGg0I4y1C2EJo8iWCSNAVF5q4xyKc91XZ5kv24oDgmn+/Yy5DnuyLrmj28BdYlU11GHYijohJN4bPBb/9gUs/82iB8k2MZdVu7xJef3Hizcc+2RSlHmmrd044vE/Ea1lQ7gPEFMtnTY8NXtxtOzydSs1DAQ4q7p1olNsu2uUPDby1YG18kAPT8wG08Zur2r4DrloJRQFn94LBWCUtHd7QEFVDw06KWD77XY8J50+zk67GIVZHDSaDPbPGgilYzWJcEvx/m4iy3NCn/KHhpRI2A9498vFX/Q/0UbsOGGlXQpsiZ8LLUMt/UbRcC41eksp+pQBx+2r2RJNsVz8EI5g8+gO8tfRpkbbdH0x7wubASosaoPxcSR2QH5Mfb+5B51rQgbk0ar2dlRRkKtNYkw6yy/3ng22cUJiyvmZ9vEtOwpuXNYjjFEDmPd3J9ktpi0XUGWw1XX98rAGJZSq/xeOlAuCRRxXVv8fcDQuSWfPuAv6AbBP2jde+KIcBSN3ZK+DQZ4mAlOBLGntw+kTilYKDTjP2VuUCvkUaIcXDknJhHiEyVBtYvJSapb9iOpSNV+FqJsFjy7o/ZRhRsyFC4qF9OeXu9ls3QqNT1xXhvWSkXTOb2y7oKdAd42QNqVzZhjwcxsf5XiL/Rpvi81VyCpf7MoX4p4WEr72qs4sRNtLjtnuTTJYfSMFjCares6aaQFZRe+l/8izv1+e9W9PCN8RoJwmdW+EOuyuX4eMULvGgf5i/2ds0h0DhYtuEPS5xW2rClIv1nwvBLRsbWBfSdQQcbptitiM3YIRSFeiyy7OkCMwFeOH6Hrb51OtyDCBTYZQ8wG867pVlG1M43QateiNwzkBFoyeSZ1o/OxQtJp/JOoGAN uP83kqGA 9xdoUFpBgDhpJ/ZAzEdIcwntHRYzt6jzZHltiuif8sFeBdtaFGgJUwlsH3s/KvqxTc/xaZrh659jbKiD3cnycgIGDb/xvCtaHS6cgvV8lw1tNf73JykougK/R66JUIWpVE5kFpaqljHNIZemqCusrvLiM+F0Cp0VjXXDfPklsU78tLEeionVuBqEskFQklP8G6EL5f35BQqFM1LILKEpYqtNMaI6yCt2TYSO6CogP7GsIWSMLue6SZKw8GhekP+YdrRA19PHw/O+mtkMbZO2HpahwkQ2q/vf90q2YmJF4d6rmWCW8JDz+W9/eo6yqQ/bvh1fmxCY52tY2OME= X-Bogosity: Ham, tests=bogofilter, spamicity=0.012997, 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 the `Unique` type as a prerequisite for `Box` and `Vec` introduced in subsequent patches. `Unique` serves as wrapper around a `NonNull`, but indicates that the possessor of this wrapper owns the referent. This type already exists in Rust's core library, but, unfortunately, is exposed as unstable API and hence shouldn't be used in the kernel. This implementation of `Unique` is almost identical, but mostly stripped down to the functionality we need for `Box` and `Vec`. Additionally, all unstable features are removed and / or replaced by stable ones. Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 183 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index bd189d646adb..7cf89067b5fc 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -473,3 +473,186 @@ unsafe impl AsBytes for str {} // does not have any uninitialized portions either. unsafe impl AsBytes for [T] {} unsafe impl AsBytes for [T; N] {} + +/// A wrapper around a raw non-null `*mut T` that indicates that the possessor +/// of this wrapper owns the referent. Useful for building abstractions like +/// `Box`, `Vec`, `String`, and `HashMap`. +/// +/// Unlike `*mut T`, `Unique` behaves "as if" it were an instance of `T`. +/// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies +/// the kind of strong aliasing guarantees an instance of `T` can expect: +/// the referent of the pointer should not be modified without a unique path to +/// its owning Unique. +/// +/// If you're uncertain of whether it's correct to use `Unique` for your purposes, +/// consider using `NonNull`, which has weaker semantics. +/// +/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer +/// is never dereferenced. This is so that enums may use this forbidden value +/// as a discriminant -- `Option>` has the same size as `Unique`. +/// However the pointer may still dangle if it isn't dereferenced. +/// +/// Unlike `*mut T`, `Unique` is covariant over `T`. This should always be correct +/// for any type which upholds Unique's aliasing requirements. +#[repr(transparent)] +pub struct Unique { + pointer: NonNull, + // NOTE: this marker has no consequences for variance, but is necessary + // for dropck to understand that we logically own a `T`. + // + // For details, see: + // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data + _marker: PhantomData, +} + +/// `Unique` pointers are `Send` if `T` is `Send` because the data they +/// reference is unaliased. Note that this aliasing invariant is +/// unenforced by the type system; the abstraction using the +/// `Unique` must enforce it. +unsafe impl Send for Unique {} + +/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they +/// reference is unaliased. Note that this aliasing invariant is +/// unenforced by the type system; the abstraction using the +/// `Unique` must enforce it. +unsafe impl Sync for Unique {} + +impl Unique { + /// Creates a new `Unique` that is dangling, but well-aligned. + /// + /// This is useful for initializing types which lazily allocate, like + /// `Vec::new` does. + /// + /// Note that the pointer value may potentially represent a valid pointer to + /// a `T`, which means this must not be used as a "not yet initialized" + /// sentinel value. Types that lazily allocate must track initialization by + /// some other means. + #[must_use] + #[inline] + pub const fn dangling() -> Self { + Unique { + pointer: NonNull::dangling(), + _marker: PhantomData, + } + } +} + +impl Unique { + /// Creates a new `Unique`. + /// + /// # Safety + /// + /// `ptr` must be non-null. + #[inline] + pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { + // SAFETY: the caller must guarantee that `ptr` is non-null. + unsafe { + Unique { + pointer: NonNull::new_unchecked(ptr), + _marker: PhantomData, + } + } + } + + /// Creates a new `Unique` if `ptr` is non-null. + #[allow(clippy::manual_map)] + #[inline] + pub fn new(ptr: *mut T) -> Option { + if let Some(pointer) = NonNull::new(ptr) { + Some(Unique { + pointer, + _marker: PhantomData, + }) + } else { + None + } + } + + /// Acquires the underlying `*mut` pointer. + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub const fn as_ptr(self) -> *mut T { + self.pointer.as_ptr() + } + + /// Dereferences the content. + /// + /// The resulting lifetime is bound to self so this behaves "as if" + /// it were actually an instance of T that is getting borrowed. If a longer + /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`. + /// + /// # Safety + /// + /// Safety requirements for this function are inherited from [NonNull::as_ref]. + /// + #[must_use] + #[inline] + pub const unsafe fn as_ref(&self) -> &T { + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a reference. + unsafe { self.pointer.as_ref() } + } + + /// Mutably dereferences the content. + /// + /// The resulting lifetime is bound to self so this behaves "as if" + /// it were actually an instance of T that is getting borrowed. If a longer + /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`. + /// + /// # Safety + /// + /// Safety requirements for this function are inherited from [NonNull::as_mut]. + #[must_use] + #[inline] + pub unsafe fn as_mut(&mut self) -> &mut T { + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a mutable reference. + unsafe { self.pointer.as_mut() } + } + + /// Casts to a pointer of another type. + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub fn cast(self) -> Unique { + Unique::from(self.pointer.cast()) + } + + /// Acquires the underlying `*mut` pointer. + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub const fn as_non_null(self) -> NonNull { + self.pointer + } +} + +impl Clone for Unique { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Unique {} + +impl From<&mut T> for Unique { + /// Converts a `&mut T` to a `Unique`. + /// + /// This conversion is infallible since references cannot be null. + #[inline] + fn from(reference: &mut T) -> Self { + Self::from(NonNull::from(reference)) + } +} + +impl From> for Unique { + /// Converts a `NonNull` to a `Unique`. + /// + /// This conversion is infallible since `NonNull` cannot be null. + #[inline] + fn from(pointer: NonNull) -> Self { + Unique { + pointer, + _marker: PhantomData, + } + } +} From patchwork Thu Aug 1 00:02:08 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749348 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 0CFA0C3DA64 for ; Thu, 1 Aug 2024 00:07:46 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 8FE496B00A1; Wed, 31 Jul 2024 20:07:45 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 883E56B00A2; Wed, 31 Jul 2024 20:07:45 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6FD236B00A3; Wed, 31 Jul 2024 20:07:45 -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 45DBB6B00A1 for ; Wed, 31 Jul 2024 20:07:45 -0400 (EDT) Received: from smtpin24.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id C055DA067A for ; Thu, 1 Aug 2024 00:07:44 +0000 (UTC) X-FDA: 82401738048.24.3EE0690 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf02.hostedemail.com (Postfix) with ESMTP id 0808880016 for ; Thu, 1 Aug 2024 00:07:42 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=CXC8lS8m; spf=pass (imf02.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722470807; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=gTyaW5RtWhb/ak2GgBN+C69GnpqWispyGfZ/q0Ekzfc=; b=pUh9sfHbv1MdO96xtEzM87N95bwnlNlV5pug3e4GBmXwNjmQ7br7v50gWxCgNW09cmxwnx OpoDZjnwQdrhn7DKVkb0szymejUKcXoMqYBeMmD94j6jVexA2CX0fTktiv0A/w8ecLYN// ++gH1Nn0259blgJcXyOGwbROAH54z9M= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470807; a=rsa-sha256; cv=none; b=p7Gv6IooQseNbLzezX4TJRzNz6NV1Bs4U9J0YCXrx20Brh9RRjepFhXXIrbaUWfeItPkLI HBF6ZFZmNEhVbxksVtzWSraDqZE+vTTH79h3gT5d2u/VGv0fGMrwjOZwxhGFdkWC/fOPJ3 8hNEuTaBQheLFUzig2h6QTPwWpIl73M= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=CXC8lS8m; spf=pass (imf02.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=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 3783C62569; Thu, 1 Aug 2024 00:07:42 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id AB206C4AF0C; Thu, 1 Aug 2024 00:07:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470861; bh=GIIQr/i+64amdQyS9IJMs4Zt0ZKp+i5PZEcmsYshO/c=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=CXC8lS8m+OXWVbWSKRT4xVYth1dDC1STwiLCcJLEX4dPGeKqgNmNsjizWhEWzIhve sPkyA6Mr2FwIr4ez6EEdhCyDxTtaksk/L6OfaSxKpuJRYQN0HJHLQN001B46CKQ1KE rP2ybpsDx8YQCK/lXGMD05kBgAO6t2Um3NLl3z47FfglTBJt83CwRturPdOJv7LjTW 7D0abFzNaF9X7ly3xPG+C0tuW4OcLVmLWLuX/5XX83I8sBhmfu10eLnkcWevXbVjen QMxLERC3pORA5abJ0hcHTCuV4A2X1OSyq2E4GDSQc7AGTW3/k0qAB2pJ7IVmJbVKyX xcGroPahMGwog== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 09/25] rust: alloc: implement kernel `Box` Date: Thu, 1 Aug 2024 02:02:08 +0200 Message-ID: <20240801000641.1882-10-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 0808880016 X-Stat-Signature: enuf4zhkwteu1g6bdb6x9rrhezai4kqh X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470862-37370 X-HE-Meta: U2FsdGVkX1/pPTxfsDqJSbHddt81TOF/edgZcVULkFyYBu9p4MVfMWYdV7i2Ey6Qn95khmpYP9ny/D7yBtXd7cro0c/H07cm0PEjz6pPspuwplxQai6M/20KhAybqUZazhC8D1bnx2fQuu1J/g1lqIKq/A493jsjWqAKQnSlYwRPbBk84P6EPLsoEuUxVsZHF01yWf3yFiPRVTkmmGZwsiZyWMKf88nyhdAlDwBibizjrt/uieBrN/T0DSQUf6i1JfFejHu/tV9SIzo8sBH8BVNbKmN3sCuo/Jg+oERfOX2r/4bU4uHNYrEcRuyiS+MClW7fLb+dXXq481tDBGq3eWOeC5J/yoxFgyLMD4BuQ9njiZq+0QILr9/fO1BtR1QxH8poNPMY5GT/7o0xwmuR1quIEDgMzo9eh7e89lC7nN/Unb3rXIPEhKflOJQfMIXW9f9nGrSOZ97A+j7uWWSXZR0cmYkHJfv71oQGFppq61g8P0y9r+tQztDGSdw6oISacIReUAIR9YQlh02cDjMRWAujWJRs8wpRfBgEQ1xvE1q/zkmbWCjx7n4d6gDoYEXn+Yp2zhBSS9rijstxnP758AJoAuXXkMqG8PbmWZ5j6B6fnNEuy42+qjZg7nTLcjz8vaf0hqRPmdLu/8eg7syYcWD8s2GhNzjD7+BIw0XpZHgZQoP3jIAWND0e2ESRScZ+bB515edOQscf+rZwCIznm+k2Vinx9v6KxV5LPt7YP31zSX+9v4F8lUPx7YBCZ88rYffyY5uzHqmc3Dyli9yd5GpWeuPm1ir2W9UuaFDOsTHAU2eEoC1MZwJ+gAzp2ZWOKOj6X+S4vaQe8LJVGoqSX6wK3x11g3tZ00oOKC+7EOmr/nxBsfy0k/lzObK3NAYW16NMGi7DKF5sk98Vk34BaRk8iFgMO3Yfh87vMkk1iakTIp+pEWEHpr4JDFEBWo+4YdQzpZsI34PO5iQB2xQ ogsnnljI o7jCWwx7FuZo/c1jzDVOFh0s9yzmHkEyZMSwoaukqK/zLEmeCJRHT89qx7V8ngmf2TLycQkd7dKqIAaiIpOD0Nw9HJpganUZGG4Mpqrwa8Ndj40KYc9Ugoe3xQGw3hquirMKzOFBB62Qaqzc8t2++XZTkuZFdbBUD5pp6Ow49vxVZCWWf1qGnZWfGZdmzD1Al1IK8INKhzwFp3xhbPfaRopT0fjWW8o6KHOvVCKhICMQTbfkMJI26ZlTnO1EZdpjEbdcMwiUSxK/uwzresD19P6N9Jv6+BEjN+o0sBEt3b/wgDIIQN42RL9mZRFw6QXOW+dDUDhgr5nQ2pgdyevPEdjtyQXmoO1B8E0XI 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 | 326 ++++++++++++++++++++++++++++++++++++++ rust/kernel/init.rs | 35 +++- rust/kernel/prelude.rs | 2 +- rust/kernel/types.rs | 26 +++ 5 files changed, 393 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 90f4452b146a..4e99eef26156 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..7074f00e07bc --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +use super::{AllocError, Allocator, Flags}; +use core::fmt; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::pin::Pin; +use core::ptr; +use core::result::Result; + +use crate::types::Unique; + +/// The kernel's [`Box`] type. +/// +/// `Box` provides the simplest way to allocate memory for a generic type with one of the kernel's +/// allocators, e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`. +/// +/// For non-zero-sized values, a [`Box`] will use the given allocator `A` for its allocation. For +/// the most common allocators the type aliases `KBox`, `VBox` and `KVBox` exist. +/// +/// It is valid to convert both ways between a [`Box`] and a raw pointer allocated with any +/// `Allocator`, given that the `Layout` used with the allocator is correct for the type. +/// +/// For zero-sized values the [`Box`]' pointer must be `dangling_mut::`; no memory is allocated. +/// +/// So long as `T: Sized`, a `Box` is guaranteed to be represented as a single pointer and is +/// also ABI-compatible with C pointers (i.e. the C type `T*`). +/// +/// # Invariants +/// +/// The [`Box`]' pointer always properly aligned and either points to memory allocated with `A` or, +/// for zero-sized types, is a dangling pointer. +/// +/// # Examples +/// +/// ``` +/// let b = KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// struct Huge([u8; 1 << 24]); +/// +/// assert!(KVBox::::new_uninit(GFP_KERNEL).is_ok()); +/// ``` +pub struct Box(Unique, PhantomData); + +/// Type alias for `Box` with a `Kmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let b = 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; + +impl Box +where + T: ?Sized, + A: Allocator, +{ + /// Constructs a `Box` from a raw pointer. + /// + /// # Safety + /// + /// `raw` must point to valid memory, previously allocated with `A`, and at least the size of + /// type `T`. + #[inline] + pub const unsafe fn from_raw_alloc(raw: *mut T, alloc: PhantomData) -> Self { + // SAFETY: Safe by the requirements of this function. + Box(unsafe { Unique::new_unchecked(raw) }, alloc) + } + + /// Consumes the `Box`, returning a wrapped raw pointer and `PhantomData` of the allocator + /// it was allocated with. + pub fn into_raw_alloc(b: Self) -> (*mut T, PhantomData) { + let b = ManuallyDrop::new(b); + let alloc = unsafe { ptr::read(&b.1) }; + (b.0.as_ptr(), alloc) + } + + /// Constructs a `Box` from a raw pointer. + /// + /// # Safety + /// + /// `raw` must point to valid memory, previously allocated with `A`, and at least the size of + /// type `T`. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // SAFETY: Validity of `raw` is guaranteed by the safety preconditions of this function. + unsafe { Box::from_raw_alloc(raw, PhantomData::) } + } + + /// Consumes the `Box`, returning a wrapped raw pointer. + /// + /// # 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 { + Self::into_raw_alloc(b).0 + } + + /// Consumes and leaks the `Box`, returning a mutable reference, &'a mut T. + #[inline] + pub fn leak<'a>(b: Self) -> &'a mut T + where + T: 'a, + { + // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer + // which points to an initialized instance of `T`. + unsafe { &mut *Box::into_raw(b) } + } + + /// Converts a `Box` into a `Pin>`. + #[inline] + pub fn into_pin(b: Self) -> Pin + where + A: 'static, + { + // SAFETY: It's not possible to move or replace the insides of a `Pin>` when + // `T: !Unpin`, so it's safe to pin it directly without any additional requirements. + unsafe { Pin::new_unchecked(b) } + } +} + +impl Box, A> +where + A: Allocator, +{ + /// Converts to `Box`. + /// + /// # Safety + /// + /// As with MaybeUninit::assume_init, it is up to the caller to guarantee that the value really + /// is in an initialized state. Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + pub unsafe fn assume_init(b: Self) -> Box { + let raw = Self::into_raw(b); + // SAFETY: Reconstruct the `Box, A>` as Box now that has been + // initialized. `raw` and `alloc` are safe by the invariants of `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 + } + + /// Allocates memory with the allocator `A` and then places `x` into it. + /// + /// This doesn’t actually allocate if T is zero-sized. + pub fn new(x: T, flags: Flags) -> Result { + let b = Self::new_uninit(flags)?; + Ok(Box::write(b, x)) + } + + /// Constructs a new `Box` with uninitialized contents. + /// + /// # 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() { + Unique::dangling() + } else { + let layout = core::alloc::Layout::new::>(); + let ptr = A::alloc(layout, flags)?; + + ptr.cast().into() + }; + + Ok(Box(ptr, PhantomData::)) + } + + /// Constructs a new `Pin>`. If `T` does not implement [`Unpin`], then `x` will be + /// pinned in memory and unable to be moved. + #[inline] + pub fn pin(x: T, flags: Flags) -> Result>, AllocError> + where + A: 'static, + { + Ok(Self::new(x, flags)?.into()) + } +} + +impl From> for Pin> +where + T: ?Sized, + A: Allocator, + A: 'static, +{ + /// Converts a `Box` into a `Pin>`. If `T` does not implement [`Unpin`], then + /// `*boxed` will be pinned in memory and unable to be moved. + /// + /// This conversion does not allocate on the heap and happens in place. + /// + /// This is also available via [`Box::into_pin`]. + /// + /// Constructing and pinning a `Box` with >>::from([Box::new]\(x)) + /// can also be written more concisely using [Box::pin]\(x). + /// This `From` implementation is useful if you already have a `Box`, or you are + /// constructing a (pinned) `Box` in a different way than with [`Box::new`]. + fn from(b: Box) -> Self { + Box::into_pin(b) + } +} + +impl Deref for Box +where + T: ?Sized, + A: Allocator, +{ + type Target = 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 ptr = self.0.as_ptr(); + + // SAFETY: We need to drop `self.0` in place, before we free the backing memory. + unsafe { core::ptr::drop_in_place(ptr) }; + + // SAFETY: `ptr` is always properly aligned, dereferenceable and points to an initialized + // instance of `T`. + if unsafe { core::mem::size_of_val(&*ptr) } != 0 { + // SAFETY: `ptr` was previously allocated with `A`. + unsafe { A::free(self.0.as_non_null().cast()) }; + } + } +} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 495c09ebe3a3..5fd7a0ffabd2 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{box_ext::BoxExt, AllocError, Allocator, Flags}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -1178,6 +1178,39 @@ fn try_init(init: impl Init, flags: Flags) -> Result } } +impl InPlaceInit for crate::alloc::Box +where + A: Allocator + 'static, +{ + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + let mut this = crate::alloc::Box::<_, A>::new_uninit(flags)?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid and will not be moved, because we pin it later. + unsafe { init.__pinned_init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { crate::alloc::Box::assume_init(this) }.into()) + } + + #[inline] + fn try_init(init: impl Init, flags: Flags) -> Result + where + E: From, + { + let mut this = crate::alloc::Box::<_, A>::new_uninit(flags)?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid. + unsafe { init.__init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { crate::alloc::Box::assume_init(this) }) + } +} + impl InPlaceInit for UniqueArc { #[inline] fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index b37a0b3180fb..39f9331a48e2 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 7cf89067b5fc..a60d59c377bd 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,6 +2,7 @@ //! Kernel types. +use crate::alloc::Allocator; use crate::init::{self, PinInit}; use alloc::boxed::Box; use core::{ @@ -89,6 +90,31 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { } } +impl ForeignOwnable for crate::alloc::Box +where + A: Allocator, +{ + type Borrowed<'a> = &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + crate::alloc::Box::into_raw(self) as _ + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + unsafe { &*ptr.cast() } + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { crate::alloc::Box::from_raw(ptr as _) } + } +} + impl ForeignOwnable for () { type Borrowed<'a> = (); From patchwork Thu Aug 1 00:02:09 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749349 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 8FE65C3DA7F for ; Thu, 1 Aug 2024 00:07:54 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 243916B00A4; Wed, 31 Jul 2024 20:07:54 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 1CD456B00A6; Wed, 31 Jul 2024 20:07:54 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 01EF16B00A7; Wed, 31 Jul 2024 20:07:53 -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 D1AFB6B00A4 for ; Wed, 31 Jul 2024 20:07:53 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 87397A06E1 for ; Thu, 1 Aug 2024 00:07:53 +0000 (UTC) X-FDA: 82401738426.02.B8104D4 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf10.hostedemail.com (Postfix) with ESMTP id 4DA7EC0006 for ; Thu, 1 Aug 2024 00:07:50 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=e0jQY6jn; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf10.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=1722470867; a=rsa-sha256; cv=none; b=Xen1pzQLspksN1Luk8X8pgUHxp68xb3a/i4aLKu9PDPMYyzLt6SdynFzg//nMT3R22eMV/ EtA8p9N867l3s9/ieCNQoEISg7uECkoF0sUJwe0a4NQpZwcspLKZ635UvwH9Ee57myPc2Q Fq1qmyKzp0yN0sDf8CNNsy5Z0UZbbLA= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=e0jQY6jn; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf10.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=1722470867; 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=m0pPGT4L80353PVcW7e1iOzNGA3rltWkxHhd/ZN4/co=; b=zCuBhHnGg/fGpQL97cZVFueuCyYNT9KvDfhEx4hOrTm7U1vH3QDvNHolR8l8YT9qz6kIPm 9zn76ZIs6a1yP9m+J5Ja+YiNh0dqMughclzg4gH6t8OyrAvMKYQkaqPgQ4w+XroYTJJNlZ bRtrQgadS9zR6Tr5eOaMjtfA7fQAwqo= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 165D6CE182B; Thu, 1 Aug 2024 00:07:48 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5C059C32786; Thu, 1 Aug 2024 00:07:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470867; bh=udM8gowoRtDWYZ1bTx/TqIq3PTvtL9tWCZwGcw+omGE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=e0jQY6jn6wlz6vPDBIoskcwPnAWFDG2c6l64xgJldldQbeUQfy9HK3JaTcAj6BG0g CCiaLEAHaplAd50mrSji1yL5aDMyfmRG1c2bOmVyCJtX+4PcYqpJ5NZzoTiFHvZrs9 pQYrBHVxNGuSqcUYkE0g10v3KCE+SI7ZSRe8YelO5jeQhG/u6QZsX84vMQsXfxDRuj bhlkfsl1taKxiFyKX5bYxt/N6c0y19J+Bg8Tx7PMu7VSioU9q0EliZVUlCzzbblS/P rg0KEfxR2HeJ/NShYYwwJ1FHi2i5OayzHU77rPnm3clZYpYnoz7CZczXYtK/vB7XpF KxjXSi4O9C6DQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 10/25] rust: treewide: switch to our kernel `Box` type Date: Thu, 1 Aug 2024 02:02:09 +0200 Message-ID: <20240801000641.1882-11-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 4DA7EC0006 X-Rspamd-Server: rspam01 X-Stat-Signature: cf6u9oe88t4wfwu9e9rresp47sepkokx X-HE-Tag: 1722470870-555132 X-HE-Meta: U2FsdGVkX1+Q0DyANByLwdOi9WSCPAjdbHDX+mk4e3Bi746Yf+3PuQmQUUmXP1Sfe+pzW2LmWi09uIaRPbBo4/jJ6LTd8bPbyflq4p/5vGGsDqroLhXgaqObpsEwJ9LqBx/wjESCxtXMg1Hd/b3H7ARvNwHCzpDwdM2yhhFXEUnQNz5rv2+f5sg9BhZjAW2Cb4DG41bKaX58+U4QJbWCmzduy+Yi2M8wPIZz2P91YPR+cwys3S/O6JnIQZ/RTUoLEIigG7pkRmo7odi0xnuPcTOStOqHMKfxvanSDthKz6rb6ICbNurhZqP+YVRSBXGbxVG/86QaF1ovorq7P2Si1n4XGLsmqjKw+LpM7gr8a2JHIELy6wcljGfzeFWbnVL0S5LaYBywzjMRDRyMUXxwjovgVG/GvNEl5dM1TFxCu6wfppIwaZJnZyg3x/VSTuh/9vz7hyVj18LMrxedIojyhQ0k5VmwPLN9E6TiIC+NOXzPXnNtcVLMGHealUTDqqXlwLVJZzu9KQ/+DFsXAbUc0ybEMXZCY+DR1bQKEsqFKB7Gy/q8efmYmm05lV3kkyaUXE1KwvAvftKZyUJycZ7BB7UQfq02OSeBpFHNH7VjxvQiXwsTCQOnQDXnOkuuW5KTZy8pV5oESYNOfY7HMMPYYBi5699nMDYNaZ4r7gRBKNmyErKed7DRN5Jq//AGtcVkMaXcWgQcVBjckdYMUid4IgFsaH6JohqUZYpO8ItFzMrBAkHl7JY76gQ9nnUEUiGewygQSUV1PtS0M1L7rfjZgo/IANdi+gqsqetPGVwAi/svx+xFRxYR+mYaDxR1j5mhYH8e0Pfdi16aOT3xrUa0Ys7cRo0n7rrJRXuqXwy8KFoMprwQVJ6lD4e6rv4CjkD/paxvwbPHzXMTHHPXOv6sCKreErXNYEe+gbelfmSYRnU4fUWBpg77DGNVijbDBhIk+kv7nxesKnHWu7Jl/mN NfUyeNXL SVMvAs8mo3fDs2qhLJqBidZjoWYUAiNZuvIx5tp7IjYCvf4loo+sM2TotioUmNc9eXIDfKH89Co/U+k80MEO3OOdEdK7tzqJWdmD0+0YJgPYlNzxXIOYXpc7tnmvHkELgu+oN1VHaeIcr+s29SSqyo+F/vU96Nfb7i/juYjINMhRyI8YngfBe/2dVZ9DBMnHQfv4ECGah3nJStPPDk3j0Jza1bLxiIC8qFVsQxwc0hSAOxvrT3Im6GTvxyqxyeURnXxpr/3yP9cqgs50zR6KbgyXwL6dS/krovS/VAMIQSNkoQY5234TQ19RryoA+pjhCkN5rjHCeDTOasXH4TfgskkmK1NsZ7r2m1jHToF5Dth4Qfq6WuiAdUj6Fnt23ae3jWtVU+zD9ntXNXWo= 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. Signed-off-by: Danilo Krummrich --- rust/kernel/init.rs | 41 ++++++++++++++++--------------- rust/kernel/init/__internal.rs | 2 +- rust/kernel/sync/arc.rs | 17 ++++++------- rust/kernel/sync/condvar.rs | 4 +-- rust/kernel/sync/lock/mutex.rs | 2 +- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/workqueue.rs | 20 +++++++-------- 7 files changed, 44 insertions(+), 44 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 5fd7a0ffabd2..b3159eb1eb02 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -68,7 +68,7 @@ //! # a <- new_mutex!(42, "Foo::a"), //! # b: 24, //! # }); -//! let foo: Result>> = 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, Allocator, Flags}, + alloc::{box_ext::BoxExt, AllocError, Allocator, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -297,7 +297,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -306,7 +306,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Result, AllocError> = 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) /// } @@ -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, @@ -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( @@ -1349,7 +1350,7 @@ macro_rules! impl_zeroable { // // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant. {} Option>, - {} Option>, + {} Option>, // 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/sync/arc.rs b/rust/kernel/sync/arc.rs index 3673496c2363..b5c84995d7d2 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -16,13 +16,12 @@ //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html 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`. @@ -422,8 +421,8 @@ fn drop(&mut self) { if is_zero { // The count reached zero, we must free the memory. // - // SAFETY: The pointer was initialised from the result of `Box::leak`. - unsafe { drop(Box::from_raw(self.ptr.as_ptr())) }; + // SAFETY: The pointer was initialised from the result of `KBox::leak`. + unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) }; } } } @@ -668,7 +667,7 @@ pub fn new(value: T, flags: Flags) -> Result { /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. pub fn new_uninit(flags: Flags) -> Result>, 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) }), @@ -678,8 +677,8 @@ pub fn new_uninit(flags: Flags) -> Result>, AllocError> )?; Ok(UniqueArc { // INVARIANT: The newly-created object has a refcount of 1. - // SAFETY: The pointer from the `Box` is valid. - inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, + // SAFETY: The pointer from the `KBox` is valid. + inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) }, }) } } diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs index 2b306afbe56d..2081932bb4b9 100644 --- a/rust/kernel/sync/condvar.rs +++ b/rust/kernel/sync/condvar.rs @@ -70,8 +70,8 @@ macro_rules! new_condvar { /// } /// /// /// Allocates a new boxed `Example`. -/// fn new_example() -> Result>> { -/// Box::pin_init(pin_init!(Example { +/// fn new_example() -> Result>> { +/// KBox::pin_init(pin_init!(Example { /// value <- new_mutex!(0), /// value_changed <- new_condvar!(), /// }), GFP_KERNEL) diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index 30632070ee67..f8f6d530db7d 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -58,7 +58,7 @@ macro_rules! new_mutex { /// } /// /// // Allocate a boxed `Example`. -/// let e = 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) }; From patchwork Thu Aug 1 00:02:10 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749350 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 AC609C3DA64 for ; Thu, 1 Aug 2024 00:07:56 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 41BA06B00A6; Wed, 31 Jul 2024 20:07:56 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 3A1486B00A8; Wed, 31 Jul 2024 20:07:56 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1B3D86B00A9; Wed, 31 Jul 2024 20:07:56 -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 EABEB6B00A6 for ; Wed, 31 Jul 2024 20:07:55 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id A8E14A58BF for ; Thu, 1 Aug 2024 00:07:55 +0000 (UTC) X-FDA: 82401738510.06.0DD6EBF Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf08.hostedemail.com (Postfix) with ESMTP id F0CD4160015 for ; Thu, 1 Aug 2024 00:07:53 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=SXBkz8M1; spf=pass (imf08.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=1722470830; 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=hfC7oNmGYb6kTSuXmE2fOfeov2fsQv0ZvXfaQPMDkro=; b=dxMlvOSpX0D40eR4vC2d3A2BDOlceVisBmzkQmUFrKQiCmlruWMXry7tuvZaRb8m9zzKmA LteT7ZLz+xXloDRp2BDuAezgot7ngCBGJ+rNFLnHpQU3bj96JHoW2wMKvBnO2hoWO/zDIN S+0VRrKquu92DnpGGWWhRUvmGyzEW+c= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=SXBkz8M1; spf=pass (imf08.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=1722470830; a=rsa-sha256; cv=none; b=ypWV+7HUgO4qBaQ4mRB4RhJc8tOabGyAwAxynZXkhCXp909uqdWD4L2rTqfJ6wikdxRtnU geTQQxiBJlntRhT/wI+kLhqYBMXpwIyjxqzM2G6QxwKswfhD+5ynA1rkFr42xTEO1jUNrJ LZtQElQxIl/JZJmdyiwbtBP5Es6kbEI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 2FF846246A; Thu, 1 Aug 2024 00:07:53 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D347EC4AF0F; Thu, 1 Aug 2024 00:07:47 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470872; bh=Jlj3EU8/IO7GF4pIr0Q+B8zRDyXQHEaY+HcLK8PqT2g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=SXBkz8M1f7KMCgcd//CRSFmUpv0FZUQV0ZsDA+gVfY+z/YTRS+gKknmn12qkrZfv4 qKt+IbHK6FReHEBUFjntle8RyBwvBBkkIgmPEsKOpV+MKG4murae1icVEF/DziIVTw 8rKsO0cts/6nEGXrmGpUxyOGLcq6rzCfJq4kEL6zNGxVRk9cLKJR/5UKODDzlTO74V O4xNPWTF/0j9kQ0Oopig31giEtZuANBEGpTQHxn6Ip1Q401iS2iD86w9MAb9TCMxLu 6aiejfJsMmNlr01xxRALdMtujomM76ABtM5yfGcVw2sUc11jPhJoZOHIbuiiwtLh0w qrkojia7KxNVQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 11/25] rust: alloc: remove `BoxExt` extension Date: Thu, 1 Aug 2024 02:02:10 +0200 Message-ID: <20240801000641.1882-12-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 6hf468xyez14bq5d8siaqynf5mty5mia X-Rspam-User: X-Rspamd-Queue-Id: F0CD4160015 X-Rspamd-Server: rspam02 X-HE-Tag: 1722470873-126725 X-HE-Meta: U2FsdGVkX1/4iu3Z3Eenpad/wHiUZEbREmw0mNMgQHXmqdZEi1Vnvh0d5+Kxky5IlP6RMjCCYE0bJiAIFjyvNbxhPW3xEJs1/Hu4oiRFbuoM065EOMhAMQp8+/nL4EtGdVtvLgoZQNv6kKKWxltooJ0pnL3NDxFlEwEDeXapkG8uQoQWvqzBSYA7YHjmqh1IM590LWQWDoCAGXIj8Rotktt9zbQH3tUnu8eFRd3HUFpH4pYCmQY/pZbtsCRWUzSZV3JfO0LeYGH06xaP1bWCEmiy1EzSKWi9Vj6tEQGmnQdafVI3RPag/KNqhJnirC7Q5fWiurtMO8SgaUoWTt4gx1ORFnWVtWOUP4Mit9dGdtKEYpFUI+9lHxJqB1a38PL9+D4OCHV/QkhbmT98fKC5eN1QZe5aTiUSblZmx0r4xPBMrKrByVyohKb4hIjval3OnEQ2caalrBO2TpEQNvWsxA640Gt1eBKEgqsvQgH14ZaEysKkXbCC69Pa23v9v7NUrJ9zfsQqkBMz524RWHNLY5KEZ61Q1dNJ5GjaFsqzT/gnL65XqSAnFtMygqkFeYbeex8EF4TVgX3TEFgtZ9Ej3j2d25cL333e4/m/Q4xwiPvI01ydmdMPrM2JJ/1xwChIiMWFnlKbasRea5pvlRF3mOgUeWlWa3t516HE2mcIC6BHxgCSx17PAv5H3MVfpG0padBHTfpRzk6L0xaHHsVXlfjj2Y4GWwF9jpvoq1p+I2uQZ0vgNPILlIHx4QX7ZTk9g+sS+JOAmieQR1pWYxRgJU0Y2EKb+0hKCWiCYfBC24nazPkYRsgvi2HS4jboJon+e8PGP+PwrmRpP/PlOnXniYoiMoewwH3jLxHAVVv/+vihyE6qTSMEK095Td53YBdeN/YEOGJpqQdTWM54v1RC7mKmp9G+4kfRxn6rFfbst94BbbzQo30UjQe0wrEGO+/gsY7BAVelNByeTp6YeWO dIxLU3Fj 9fF/KnghIg1FGDUSWygW9tK4HJsILBA5jhfEHT1b/ZSoEvdrv2iJbQn+SpZgYu4ez0qBNCfZEwt/rVxH7nLI9YAvubWhvEsqwDrLsWBW64rUrqXbmmv2yUVkbvO5UI9QCYr6RBEsSwpygxWTlAMIAP7a/Sx4pUzLHDPFeUJqwHAHppYaA3ivzlQgJrk+4FTPHB7Y5kKgb3K59aq7z6emX0oVpWwaJ9rsw1cYk/Xkq/vb5hkAMrLWpX2lWPmyZ5k2xD64nw19pqO/OybcqbTBylPBlTYhYtlHOE2JXj5YB0/p/rbIC4a4qfXgAMA== 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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 56 ------------------------------------ rust/kernel/init.rs | 34 +--------------------- rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +-- rust/kernel/types.rs | 23 --------------- 6 files changed, 3 insertions(+), 116 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 4e99eef26156..4bddd023aa7f 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 829cb1c1cf9e..000000000000 --- a/rust/kernel/alloc/box_ext.rs +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Box`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::boxed::Box; -use core::mem::MaybeUninit; - -/// Extensions to [`Box`]. -pub trait BoxExt: Sized { - /// Allocates a new box. - /// - /// The allocation may fail, in which case an error is returned. - fn new(x: T, flags: Flags) -> Result; - - /// Allocates a new uninitialised box. - /// - /// The allocation may fail, in which case an error is returned. - fn new_uninit(flags: Flags) -> Result>, AllocError>; -} - -impl BoxExt for Box { - fn new(x: T, flags: Flags) -> Result { - let b = >::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) }) - } -} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index b3159eb1eb02..ae533305d40e 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,12 +211,11 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Allocator, Flags, KBox}, + alloc::{AllocError, Allocator, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, }; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, convert::Infallible, @@ -589,7 +588,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1149,36 +1147,6 @@ fn init(init: impl Init, flags: Flags) -> error::Result } } -impl InPlaceInit for Box { - #[inline] - fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> - where - E: From, - { - let mut this = as BoxExt<_>>::new_uninit(flags)?; - let slot = this.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid and will not be moved, because we pin it later. - unsafe { init.__pinned_init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { this.assume_init() }.into()) - } - - #[inline] - fn try_init(init: impl Init, flags: Flags) -> Result - where - E: From, - { - let mut this = as BoxExt<_>>::new_uninit(flags)?; - let slot = this.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid. - unsafe { init.__init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { this.assume_init() }) - } -} - impl InPlaceInit for crate::alloc::Box where A: Allocator + 'static, diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 274bdc1b0a82..042f05c45214 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -14,7 +14,6 @@ #![no_std] #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] -#![feature(new_uninit)] #![feature(receiver_trait)] #![feature(unsize)] diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 39f9331a48e2..a8018ef2e691 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,10 @@ #[doc(no_inline)] pub use core::pin::Pin; -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 a60d59c377bd..2aadf715b336 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -4,7 +4,6 @@ use crate::alloc::Allocator; use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, @@ -68,28 +67,6 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option { } } -impl ForeignOwnable for Box { - type Borrowed<'a> = &'a T; - - fn into_foreign(self) -> *const core::ffi::c_void { - Box::into_raw(self) as _ - } - - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { - // SAFETY: The safety requirements for this function ensure that the object is still alive, - // so it is safe to dereference the raw pointer. - // The safety requirements of `from_foreign` also ensure that the object remains alive for - // the lifetime of the returned value. - unsafe { &*ptr.cast() } - } - - unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { - // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr as _) } - } -} - impl ForeignOwnable for crate::alloc::Box where A: Allocator, From patchwork Thu Aug 1 00:02:11 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749351 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 27BA2C3DA64 for ; Thu, 1 Aug 2024 00:08:05 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A825E6B00A9; Wed, 31 Jul 2024 20:08:04 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 91F496B00AA; Wed, 31 Jul 2024 20:08:04 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7A57D6B00AB; Wed, 31 Jul 2024 20:08:04 -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 5B5016B00A9 for ; Wed, 31 Jul 2024 20:08:04 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id D6EE51C2DED for ; Thu, 1 Aug 2024 00:08:03 +0000 (UTC) X-FDA: 82401738846.14.9DF794B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf14.hostedemail.com (Postfix) with ESMTP id D4BED100026 for ; Thu, 1 Aug 2024 00:08:01 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=IRYFZy1h; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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=1722470819; 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=Ti17svBMYAUfR9ZfxGdgNbIAVGHYFHfIl4BDg2Ry8vs=; b=NGrqwQFvCTKlW9NnBbYaErDKbqmQyWsLqsmOc41gYi03+pgoX6MyTwJYJtiq+aqE646dA5 2sBFkbZfab2SlSq5OVe+7tm4b3NesKVU55olPwzv8k5m5b/uWb/TD9dszob1nGpT6b/JzL MTSfLK0bPSnJpRlWxJDPDGyk5aH6+9A= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470819; a=rsa-sha256; cv=none; b=haLbmvEsgvPOZ/BwG+rNYNEJanElfo1jOZk5G3KGwn17xLV8N3lHsa5hG7MCjkqCu3Ytqf RYJHUaPO3H5I4nidt0T42iN1ks3LhTQRkH4ve+r7//DTc+aPWYHHaegQ+v9nCdzkmWHzOO o20RcZVvLWZN9re1TNCodRa2ahWgyM0= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=IRYFZy1h; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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 177FDCE1846; Thu, 1 Aug 2024 00:07:59 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 54438C116B1; Thu, 1 Aug 2024 00:07:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470878; bh=IsegupDL6dNouhj9LI4K0JPI4QQWWwWlwU04wMc/SwI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=IRYFZy1hq3Z3+PX8qgT+MsS8OA/+Rxv4P/v6eqnDklPF9QlxvTVw0QxCzrF60YK+t ySR1ELEfYvaH39ogVK5IQdBjcFG+z9sefH6R5KwlG1JH4XYUXn67HpuYSN+vxGVn8W uAX/A0jAJkhjzp8cC/km6NDyVe3iG3db4GQt6IOEUH4ZyNXS/bqFJh0hSCOwYWZh0M l6KlEaCB3/4qJnnD6h7cRsQ48FvJcxnODhWrnwxpJWj6fgo5Br7lDc9KlElgVC4oGv zFLiG84rkDETV9+CFCjwCLxY7isa79gI/y9Nf+hADVfGhRT5TJWblFWc67BVMx+7gv eE4FT6aWXJmHQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 12/25] rust: alloc: add `Box` to prelude Date: Thu, 1 Aug 2024 02:02:11 +0200 Message-ID: <20240801000641.1882-13-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: D4BED100026 X-Stat-Signature: dxdxp6t5e5ee5qfabmoaxga6eo4esn8c X-Rspam-User: X-HE-Tag: 1722470881-483794 X-HE-Meta: U2FsdGVkX1+4XgLhi3mMS9T8sEMB9SAHz9QZXQlDBuYt/257fjJhjtFcdafGKY5vTCDMEEaLHj2Oo/K6srpa2S5EMJdA7ub2pjmD2jdnUogEcGgzO/m9FENx2Jni1E7Zkq/HzmtbJJiRu+E6QjtllFyyXSlKOQfNeoNvg5OK6PUgdu9QeymwH1YVHnYvI78OmScS7LsmtrA6mhNgzfqbFAWRXUlQo3ez54CZfSxMJYKN9zLMpP/s3/5obpr0oF8iemReOV/5h0qb3++7Qs/6lLH3Hj9SCjSqfMOngx0u4A7ffwFRtqlmopYxuZJzr3JnDGDXsBtE8ji8EoKlEFGBR7Cw+Wh1lhv7fuV3F03qUslurtZcztU3I7GIbu7sOT8cA4rIN8EGeiqx6R/XPkKnOWx+TBG8P+x4Zpb21mFyoNVCiF/M5sGsNTSWelvaLTelgfjB7D05ivulqnJaWDr/6i57ggG+LF5SfBiF35jCktAhDWIL+4q8tKaLYxfyNYPIUgJjDs1U3kBdylQFyqBhIFLUiOOE34PWxvcEQJhatVkD5jR+dU3VdH93i+x6Dgnq0FXQ54OxO0mbjtDzBhd8cbZlAJSANTHWmhxsrfpIhA8kC8qWBaL51NL93GrYZsGSTjUeOWM4dPGTuabgeJZ9R6gQrFK1w6hRAMWVRP/qZdjG6e6zGQBlLaGDeq4k2UZ8/rSIsbsdrwKX7Xo4lSjQXOnnUHnsoocxVeNhCfaHFKi7ZVFdm1v9jSfrAwQMTZZ/uxS2q40y1VZkfJvKHznsjQ/xjSqaBiDnhlSXg7oGSvKHt91iSR0CIhnZUq9VWsfhCJHGEs6Ue0LPCOEx+3PYgCrD3S3I1DpR4NQcZegOLh4Lcejj8oo4ejqR4d+00eiBXclBDWTe4mGQyxWF0lIHpJy3c4gZ8lnsP7hSUuluXuufuWUBWV+M+rOLGBzF2tLDMxHSP+BYRzN29N+RaxO 0w01v6sF +Pr+zEBJsQW+sUYBF66n4FOB79WB5m5/wJErETV9E7W0umxn7y9JUNY/i9lRtwXgNIgcmTGUHqacYuaF2CuiV4QOyxnfVLQjTdPST61effqTUzVceTrt2sRjBvMEz0/5TspHdJQ1nQFdjhH3/6/WuUtbiwKTx5QfFT59BMGIpjXaGsfNcnm29/nj69AgKZ0YzEHOO379VmYYHR+goKTYfSB+r/Ju1t85E7PLqW7thiVIt0r7xlNjQBlDMAEFidFsFBnDRHvfpHtyf2xfDC4k6kHTseS5c+nsV+/At+5Wxdr4MXDmN0qyZIWObZg== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000001, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `BoxExt` and the corresponding includes in prelude.rs, add the new kernel `Box` type instead. Signed-off-by: Danilo Krummrich --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index a8018ef2e691..6bf77577eae7 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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 Thu Aug 1 00:02:12 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749352 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 90126C52D1D for ; Thu, 1 Aug 2024 00:08:07 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 133156B00AA; Wed, 31 Jul 2024 20:08:07 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0BCC56B00AC; Wed, 31 Jul 2024 20:08:07 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E78016B00AD; Wed, 31 Jul 2024 20:08:06 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id C70886B00AA for ; Wed, 31 Jul 2024 20:08:06 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 82BC61C2DCB for ; Thu, 1 Aug 2024 00:08:06 +0000 (UTC) X-FDA: 82401738972.26.FEFF790 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf27.hostedemail.com (Postfix) with ESMTP id EC70F40002 for ; Thu, 1 Aug 2024 00:08:04 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=AYxUKb4V; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722470857; 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=ZE8k/WzEZ0nopWdJ6aywIWGXK0SDU6fjQFJzYLuntVY=; b=I3HgQxNqP26+ijwhkMYoNHLYi7aPyV/EIkWhhKfsLCvefbabP6w5H+w0btp3yMp10D5eOO 0YdRYWZVqiB8EwaLmB9/BDdT9Gr9rj5NmNRv+pWbN9sCR1lnehRSdrTDOYmkrqqU7Wl0Ox xDQ8+7g4ppz0B/Ii/JOcFuoL4hZY/Jw= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=AYxUKb4V; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470857; a=rsa-sha256; cv=none; b=xQqeerh9cyOrTTJeKjTtPeaHvjZMNgPdHMeHKExmAlQK39kZQE2CGBj4Gz+VtN8iBajHqu uw7A5aVy7NM22gC9s3r5W/SXRdU4rTWNTrECvx940/NrPoWtdNFRYKRTTjBCH2z0dnbt0H dcf4kRJ9Yo7OwCYqpLyYJvYv9p0gXWQ= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 34C7962610; Thu, 1 Aug 2024 00:08:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D4A4EC4AF0E; Thu, 1 Aug 2024 00:07:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470883; bh=w6PgALWiEZslFA5r/x2p08ONTo0/JO09gDNDQem/zbs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=AYxUKb4V1+mWLyMLbmg/lrmQ/MpwgoFzMkBm5upnFiq0uNUepCersNXThbHOs+Ej4 vlt/uoEQ7BsgNjHg2m7bp+LWIoqeYyHeSFLzgioWidQeDHftOPwdv7rilxyAOS+WoO BGLdSDI7hLHpTiUtKzhWc+LxhbdrB1WEze5I2Vx7e0u518+fkzkgUwvnIa9MiTORkq o4iTRGGS69IqkRbQf+f7qsmMiSu3EDq3jLAcbTodaoS1v/AH00kGKq0CCJxtwr6+8X hJJXfsPN9BEBUDkmHG7lLcfbpSCl30d5gtzLttCAw1a8OZMyIXgUJEYM78Hcuy3oI1 2xs7GpyVzkJqw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 13/25] rust: alloc: import kernel `Box` type in types.rs Date: Thu, 1 Aug 2024 02:02:12 +0200 Message-ID: <20240801000641.1882-14-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: EC70F40002 X-Stat-Signature: 5oner5cn5fdhnnmkhwjt5e5ihsrgy6z1 X-HE-Tag: 1722470884-869411 X-HE-Meta: U2FsdGVkX1+eYDUhA0qWPVhDwsVfeP02UxUKCDZThFpvIZabMwgP7RY2lHFkdQ+GgY9DqGtXhK5CPPCsOk8USocwZjXtqHPbLkNTuFfcznBM3PilI/lgPA8Zm9LHKIMhDhw5eMk5SHiBT+NwHro/gxHpXtjQzHu2duk0WKKZGjyMoeEZXKCWVE+4cxn5zgDjak+VIsmIoUe5dgK2ZOyIVYbGfUU4papQb8igyShcnCgATw+S8fCnaJ0Rs3t7RQNIeEycG0quBWu8QYtkVWE5+uyEVVTXfTs716abKsei44dtiG11eI6HwCYbE8JbsuzU/Os+Rb5O1U02JR06PBePx/JdHu22e1MvH2jYFYNv69xjMKtnIJ2bnDwHH3rvaYLVcca442hmD0a2XnYDsr2XUOgiuZQh2OIP9VIe9mEcgSbN0m+WJOmVp0KRi/1ZahCBIkdngn3WmXtBL/fwZLO9xbz3Hdce/a+nskyHmIC92fR9j4y3pO05j9+EIPoymRsIR3W7Db70eyrSKILA+KL7sRKhCwM7ZImvB6uUXRDwRyEF7FoFNKV+Xn9DJAqQ/M9l4PtaQ4rPakQqZvLzAMuDg9O+AKF9Lut4peKOAdvX7G1VmtDSJgpMdcMvfT3SPv8/lQElG57rYc49rvR5Wxn1X18emnddP62uy9nguzez7442k9t5p/xsqBogcxH4Rq20t08Vyg/VHt+6/Tza0HkPwq1v77JKgTiJ3HNHMIxjXq/Nsqx6n08YNq7Cm5JF2G5O4ryzc3eRQ+xTAx1LGr+R1wB6ffw1DuxRybBsjQT1QUuHzJx9me1e67tIs0bbP0+2btbxbIMSbfzFKdS/TL/zB/gM6O3loN06t3H5AKJBLuQU3q5YhabG4nCFTD3EXcyQ51hsLuOJ95W2rGMJxtmlZiPFbsmQhLz9tLEgx1YawJNricde6Ki8F1ueneveIrXZaKEXk/55k8vIxRlL6zB 08f57/2K Ra2VBrelJY+0lEy3PBzoo/pL+YWbC6vs1tnYlJqKtHeuPYDvQR6vXPki+dO1z8WTzW3ZHY5t1/NjkhfsLdWjiv6FxItLHkvLlYBHR1D5EQ+ms9otYQN/iPptnN1RygOnls3zVTySt+ZusqZLowjM9XnAoQfFQ/NgROXLU2NFrxhh3jQ8i9PtyELJF133nztukznTbHauTZ/h6qRQIEyqC47s7hXKz8+khQTG4CCDw/9Oqkfrnn+VoZ0zb1tskVxbwiSIIczxfHRExVwksf5SXJKUL2tpISfrfVfrSaZr3qDVwVHn9p3n3Y0eAow== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000001, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `BoxExt` and the corresponding includes in types.rs, add the new kernel `Box` type instead. Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 2aadf715b336..809653b9d945 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,7 +2,7 @@ //! Kernel types. -use crate::alloc::Allocator; +use crate::alloc::{Allocator, Box}; use crate::init::{self, PinInit}; use core::{ cell::UnsafeCell, @@ -67,14 +67,14 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option { } } -impl ForeignOwnable for crate::alloc::Box +impl ForeignOwnable for Box where A: Allocator, { type Borrowed<'a> = &'a T; fn into_foreign(self) -> *const core::ffi::c_void { - crate::alloc::Box::into_raw(self) as _ + Box::into_raw(self) as _ } unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { @@ -88,7 +88,7 @@ unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - unsafe { crate::alloc::Box::from_raw(ptr as _) } + unsafe { Box::from_raw(ptr as _) } } } From patchwork Thu Aug 1 00:02:13 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749353 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 0CB86C3DA64 for ; Thu, 1 Aug 2024 00:08:16 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 948D96B00AC; Wed, 31 Jul 2024 20:08:15 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8F9A16B00AE; Wed, 31 Jul 2024 20:08:15 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 79A036B00AF; Wed, 31 Jul 2024 20:08:15 -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 5708C6B00AC for ; Wed, 31 Jul 2024 20:08:15 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 189CFC079E for ; Thu, 1 Aug 2024 00:08:15 +0000 (UTC) X-FDA: 82401739350.23.4488671 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf11.hostedemail.com (Postfix) with ESMTP id C89014000E for ; Thu, 1 Aug 2024 00:08:12 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cuq4GKG1; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf11.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=1722470847; a=rsa-sha256; cv=none; b=1WmbVr2OpyqQcAXC/WfxUXlijjd+Ipa47Qdtbfdf2wHXuH4I2YMOPD9FDJUjj2/vzMPBPp T6OVgggdKM7p0zQMYlhY6SodjGI+tZabWj4b0jr0GKngUq15vsRbvOtLQHNt5IBoh0sdFP wbYpnHg/A8QUh5CX1CASVhrBWAZ7YK4= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cuq4GKG1; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf11.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=1722470847; 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=eXot3MZHYnZ3K6+E1NVzV0/frvElP3kiHuHsfR9IzbY=; b=bVFEFAb7LsmLUAVNrGPAjwj5muZ0qKn6CrGAIj8T9Rm9pN93MRdDkm5KwFqYDJdF35NwkR oSvX7sEGZlg4PBkRpWiVl+I5ERCMfboiMCa4dlnO7rye4vCTAXPCYIAZKFOqZh3Fl7Rovl jr8DfsvKH6MdCsxJDCM7sNM5OPgiRMg= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 12F1DCE1836; Thu, 1 Aug 2024 00:08:10 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5A302C116B1; Thu, 1 Aug 2024 00:08:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470889; bh=IVeFanrsSDZ5EV05jvxVmzxFrqOI4KjMh5AykPQhj/Q=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cuq4GKG1noPXG4VromqEQ5zTR/nbJlMJsyPeU7CAhTOpPfxxu0+6HNgp9Z4iJM2no TYLribq5kSOg7QueTYWZ/kivvl8DXQBnDqU1VCfad2nhN6gWLgrhyuIbFU8AkiW0gK UfscVewIgoA7NhLfnntiU21/c+3RrPIk0DTJUk5Q1qEXoOIKFixLbE8P3iCTXBjfOk ZJryrH8v/PpxMJE9BMgPUTA0O/0od0lVUDNowGA0euP+QWNS6fLMJkklMY1DfbUCvS odtDuWRg2OXRcMi+Ox1HrsiRYNn5jVhqQLjG7wpjhDw2oQxunrHiPUkQhZ4d6kTZCt hI8HmjqY65Svg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 14/25] rust: alloc: import kernel `Box` type in init.rs Date: Thu, 1 Aug 2024 02:02:13 +0200 Message-ID: <20240801000641.1882-15-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: C89014000E X-Stat-Signature: zy7mwdj7u59953jbhj7ecmed41ynrb3u X-Rspam-User: X-HE-Tag: 1722470892-569429 X-HE-Meta: U2FsdGVkX1+fFLT9/2EKwmuux8E8A0NEwvFt4hdJiTdkXUKnRy4Xc5XAWXVXMDGTNce8glnP0mPwkpJONFx4Y3BBgdr7Xc5Pkp04EKQsl9XxJ87j6nbejalKSwCOL8Dq9mN/h+xUjrUic8YaPIxBqLo5NQQ98wKc5HT20yOrMpES/RJdWb+AfKwfTcsUjgxCait9Y+njVPWfkyYKC8dOvW5dgaisPEXNDeLbAiWbrMU8fBlQKOyV5R0roIrcmitLOSwtMkVSbcWjukZHVfnsjC5QxqFt6FFe0VonujcowzL2ywYgtJtoWzxiwGFaAy/Ly1VmS4TT12jctHnMj2/AcEjq0spTyWjUCjZwUjxBluCLWI0vjDpjPJqAwRmpgNTobEqmdshnQzx+q7QwulkVLNjPWY0VD7B+pEcibeoNg7A5sQEBE9x4rECRzvUckP9/agsmiPxSf1580RQRJ50cy/KsUuCQZ1fnjqblMF/hTxbZLCgZKJtwLCHbx/gHLtq67rtGuMN0yTgGX6k/nUM5KWl8Uw2EAsmI7XxZ029Q3hZq1+EryWbAihI8YduF20k2aruXhjXXBs0dkc474bRVUy4iwoa/HewMXRg99ZP3gIdFo8tkKA3Bb2zllUe9mx38imNvEJPKE5hpOiIWYsbyg+42Y0pmc6bZONkW0q7ydMgoplcXZMac+5ocoyeVvdW8cBEQ8SH9Kz71xgjdLLqQRNKu2Xer3Jn51InaAFkK6svQq0OkpqyWgd29HaSKzNAy1327OfbD5zS/rhEjpKg0PWNAlZyNu0gR0QpnIIVquEZppuvllHIFxsVEZpt+QS2raA8zg2rnVPLkVdUXpdAYhDDyGgS7F/8ItvgVlCXbwuSSTIHXNXUUNHAsl9QZTadI1O27/A9dfboHXU2LRuJ49ziIbZdyzY7jGGyuY8fMZCNLcKAj/8dvbefkMxjSkQpFQuOez5DU6hRHHAYFpSK RWv/brdm Dn4u23Qbgr86CQi1YdH8EBmL4DQUrRpK4YrYSL+p9eCGd58sobs6Nya7tQNmRWPIT0tIy0CPE19JZu2MrIpp7MbKPlV1+b/EZEEGjw2+bVu16dnd+m4MvcCQhSFri/w1l2jXMNuaP0/8dju8vkrdsdW15RM4CyhypXJ58STr1jPSQEAIKCMnxtixrOdcDxeiwW4VLDtEzyMCcvjfHVIF3C7AFy9PMU2Hq9nG2wtLGrwqUjdhFQCX7W1xCNxNK/Xm8dp9UU9yWCYqSjPxME8tMvLMxGNphGwWz87K+AMvVjQxFZJXHs3DSJTewOQ== 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 init.rs, add the new kernel `Box` type instead. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- rust/kernel/init.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index ae533305d40e..350582662964 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{AllocError, Allocator, Flags, KBox}, + alloc::{AllocError, Allocator, Box, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -1147,7 +1147,7 @@ fn init(init: impl Init, flags: Flags) -> error::Result } } -impl InPlaceInit for crate::alloc::Box +impl InPlaceInit for Box where A: Allocator + 'static, { @@ -1156,13 +1156,13 @@ fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, where E: From, { - let mut this = crate::alloc::Box::<_, A>::new_uninit(flags)?; + let mut this = Box::<_, A>::new_uninit(flags)?; let slot = this.as_mut_ptr(); // SAFETY: When init errors/panics, slot will get deallocated but not dropped, // slot is valid and will not be moved, because we pin it later. unsafe { init.__pinned_init(slot)? }; // SAFETY: All fields have been initialized. - Ok(unsafe { crate::alloc::Box::assume_init(this) }.into()) + Ok(unsafe { Box::assume_init(this) }.into()) } #[inline] @@ -1170,13 +1170,13 @@ fn try_init(init: impl Init, flags: Flags) -> Result where E: From, { - let mut this = crate::alloc::Box::<_, A>::new_uninit(flags)?; + let mut this = Box::<_, A>::new_uninit(flags)?; let slot = this.as_mut_ptr(); // SAFETY: When init errors/panics, slot will get deallocated but not dropped, // slot is valid. unsafe { init.__init(slot)? }; // SAFETY: All fields have been initialized. - Ok(unsafe { crate::alloc::Box::assume_init(this) }) + Ok(unsafe { Box::assume_init(this) }) } } From patchwork Thu Aug 1 00:02:14 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749354 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 A3408C3DA7F for ; Thu, 1 Aug 2024 00:08:21 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 307A36B00AE; Wed, 31 Jul 2024 20:08:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 2B7536B00B0; Wed, 31 Jul 2024 20:08:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0E2EB6B00B1; Wed, 31 Jul 2024 20:08:21 -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 DB2246B00AE for ; Wed, 31 Jul 2024 20:08:20 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id A13C814081A for ; Thu, 1 Aug 2024 00:08:20 +0000 (UTC) X-FDA: 82401739560.03.977FAAE Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf29.hostedemail.com (Postfix) with ESMTP id 52E18120025 for ; Thu, 1 Aug 2024 00:08:17 +0000 (UTC) Authentication-Results: imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=UMT+LlkR; 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=1722470842; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=EMIh51YGiTqxs0wjeSGkI2mLiiBxT82IBTGi6t1uFkI=; b=iKJEkgXS49vzJR+hz+Qv4LvzUbXPClv/T3odYnELb6STOzykASXObZXru7Wx8SYHprfVw1 wZBr7Ev/ogzaoPVwuoboyU7TlCPs3fTCzyrs4JUVfUJzMg7l2W6DQDPfU+Qc42Xw4dFauf wnd/VTLRds2Rsolqq0HEhhiOs9MoqPs= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470842; a=rsa-sha256; cv=none; b=uNcxzPLhN9xFXbi6X0mfxoDwQMW0xEolTFNCGvY/H4cYZiDc/3E3i7ThzxlZIzPJXWs1fK jsvwXk6bMKtQHB4BNeQhQJUN0pahs0375JEf7xJ5jTBAh7vQS9bMMEB/2K042p7UPE029/ H9X/hqIcF/QhrFF8jIHemm+t0hxjwqg= ARC-Authentication-Results: i=1; imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=UMT+LlkR; 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 8D4F9CE1846; Thu, 1 Aug 2024 00:08:15 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CEB8BC4AF0F; Thu, 1 Aug 2024 00:08:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470894; bh=qJH0b+zT7Zd9g/zzdC5BDkCk/Fs04Tglg+wahllGbls=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=UMT+LlkRiSD0Es7ekiX8WZrbf5T1T9+elhxsrIKw0Gde7zOp+HWpXyuYLRKzIaEWh SudV2hR/kX64WlvlQ0EG7HlvjI77NayAtDzOryv2DLwVFDMhBt01vvDnUN3ijhrTC0 zgMEUUQnkEIvEZW7iEvNL8+FTpZLTSBtMHrBPWc10Ht8NmjYKQE8CzlrvH4h/f7/+b Ki37Lqc1yp7v1zebkeFdPMjeyjMBiH06o19/gpplvfV8j+7IdexsqmHJjKpR6cO54v e0PtuTE3KoRJS4lC/5IwGiww19Jrtcu51+5L2otyzjfXTKEprkgKgndmAfpBAbq2fy L/WLjffZdjbmQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 15/25] rust: alloc: implement kernel `Vec` type Date: Thu, 1 Aug 2024 02:02:14 +0200 Message-ID: <20240801000641.1882-16-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 52E18120025 X-Stat-Signature: h66gwi57oys5os7i9phh1aowix9fzehr X-HE-Tag: 1722470897-268403 X-HE-Meta: U2FsdGVkX19fzGhgrsz/GJTC0Ttr6Iu26X84r7FvCoYnadFOU1vlZwljay4mVcIR8ZIAbDmW8ULOC8vFfgyaidX3zX/UpDS4KSMG/+lcU8JAp94YRB26JsWkMaWPzqkcckw3pTdlgAg9VEoAgKskc7+bfDaPDteg7yKpdX59rLkBDAY3xy2ph8LYITglzeLNXZM3H063ETnydna5DeQCzjgUJrbY3VvcDdGarmhm575XyxzQqyJiri31MoFsqrR/hegtjlp9wpbJWapqCodqKC9UV0OctHSKYIHvL9HMSjmlPoT4LGgjVq8jkNHT4srAS0apKmWAeII6fPFQWdExfV5G05rMPgzIxvNHngK3E5BdzEtGKUSptOVhhb249X1LHmUhO2LQTKsRFMtNS2P2/kxKermOLm4ApHvgJq193WgWm1+DdUl3zjf5euJbCpiavhiPCeFWgtmSmzeXvo0yE7jfE+YmxdtJ4wQajHBGQaKoZEbkluGS5/wNsiozOAwofmd+nc27NCazYc0We/+w0+X9rrr9Wwq2I+9uh13y4Jxe/uTnOe2Cxi63U1b0wmcze8Rff8wbYt8Wpx7b8o5hl+O+qeHxOv6ndRQskmGGVvgKhQHzjoqsJBJsaVxRnnUUdfaonCW5Gl7cTcU8A6spkvaofiPJVzCgCZJhMzhclbqwWADzX5Adj/yNNv4vAohljqdjjp43DkUj7HUtScwTP87a0JUTuKIJ6e/NpfCaJRl9xZ6guyZSKrkyJnZY2sRkAydw+c/iB5Iks6OXPyfgWe8yspZOG0Lmr9TmBT6w6Ztd1ibSP4rZ1L2XY7QbQUiDwy/LmxQ08uemWacCivOHfVA6M3DIw4xOFKDcon7W0ALB7s5kC6sfYO62Pimu6eBPyyqSnzpx+DymoROCzDtCl3MgHfv6V6JTylLyB6LZfJi77OZyKhRxIEFlrl9xYPG9QQJOc5Pa6bXTsjgGjR3 5cy7YnTM ZlYPyphU9tfKLtKck8fv7SEEvydVYURGap6K4g9aon7xjoPnZgWbVJVDkW3jOpBEjydwvY622uhAmh5UiPTCNNc5rabToUmPcWWFGth1K7Noei4NyjAzI78fhzOYo+WppHNzbkeCOGnR8uCB4SXcNW0b4jJNMYnIEZlihDVRapwrJ+X6WwZOY8avASaloSBl6Bp/gdHXklQpyrx8JQQGA76IwWu+wQMN966WI7+39ijGe0vUPhdVGJ+tuM6wWuxYJWcO7mlFQPgWX4dI3551OI9Zht3hVt4KZ7d6eBwVQObjR+JPuAYI2+HWqr9yywwpTgbuNpIBUa+9USOezM6UrgUtU7Q== 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/kbox.rs | 16 +- rust/kernel/alloc/kvec.rs | 583 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 4 files changed, 605 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 4bddd023aa7f..bd93140f3094 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/kbox.rs b/rust/kernel/alloc/kbox.rs index 7074f00e07bc..39feaed4a8f8 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -2,7 +2,7 @@ //! Implementation of [`Box`]. -use super::{AllocError, Allocator, Flags}; +use super::{AllocError, Allocator, Flags, Vec}; use core::fmt; use core::marker::PhantomData; use core::mem::ManuallyDrop; @@ -169,6 +169,20 @@ pub fn into_pin(b: Self) -> Pin } } +impl Box<[T; N], A> +where + A: Allocator, +{ + /// Convert a `Box<[T], A>` to a `Vec`. + pub fn into_vec(b: Self) -> Vec { + let len = b.len(); + unsafe { + let ptr = Self::into_raw(b); + Vec::from_raw_parts(ptr as _, len, len) + } + } +} + impl Box, A> where A: Allocator, diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs new file mode 100644 index 000000000000..04cc85f7d92c --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,583 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{AllocError, Allocator, Flags}; +use crate::types::Unique; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + slice, + slice::SliceIndex, +}; + +/// Create a [`Vec`] containing the arguments. +/// +/// # Examples +/// +/// ``` +/// let mut v = 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([$($x),+], GFP_KERNEL) { + Ok(b) => Ok($crate::alloc::KBox::into_vec(b)), + 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` 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 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` of the vector is the exact allocator the backing buffer was allocated with (and +/// must be freed with). +pub struct Vec { + ptr: Unique, + /// Never used for ZSTs; it's `capacity()`'s responsibility to return usize::MAX in that case. + /// + /// # Safety + /// + /// `cap` must be in the `0..=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; + +impl Vec +where + A: Allocator, +{ + #[inline] + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Returns the total number of elements the vector can hold without + /// reallocating. + pub fn capacity(&self) -> usize { + if Self::is_zst() { + usize::MAX + } else { + self.cap + } + } + + /// Returns the number of elements in the vector, also referred to + /// as its 'length'. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forces the length of the vector to new_len. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity()`]. + /// - The elements at `old_len..new_len` must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + self.len = new_len; + } + + /// Extracts a slice containing the entire vector. + /// + /// Equivalent to `&s[..]`. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Extracts a mutable slice of the entire vector. + /// + /// Equivalent to `&mut s[..]`. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling + /// raw pointer valid for zero sized reads if the vector didn't allocate. + #[inline] + pub fn as_mut_ptr(&self) -> *mut T { + self.ptr.as_ptr() + } + + /// Returns a raw pointer to the slice's buffer. + #[inline] + pub fn as_ptr(&self) -> *const T { + self.as_mut_ptr() + } + + /// Returns `true` if the vector contains no elements. + /// + /// # Examples + /// + /// ``` + /// let mut v = 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 + } + + /// Constructs a new, empty Vec. + /// + /// This method does not allocate by itself. + #[inline] + pub const fn new() -> Self { + Self { + ptr: Unique::dangling(), + cap: 0, + len: 0, + _p: PhantomData::, + } + } + + /// Returns the remaining spare capacity of the vector as a slice of `MaybeUninit`. + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // SAFETY: The memory between `self.len` and `self.capacity` is 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 directly from a pointer, a length, a capacity, and an allocator. + /// + /// # Safety + /// + /// This is highly unsafe, due to the number of invariants that aren’t checked: + /// + /// - `ptr` must be currently allocated via the given allocator `A`. + /// - `T` needs to have the same alignment as what `ptr` was allocated with. (`T` having a less + /// strict alignment is not sufficient, the alignment really needs to be equal to satisfy the + /// `dealloc` requirement that memory must be allocated and deallocated with the same layout.) + /// - The size of `T` times the `capacity` (i.e. the allocated size in bytes) needs to be + /// smaller or equal the size the pointer was allocated with. + /// - `length` needs to be less than or equal to `capacity`. + /// - The first `length` values must be properly initialized values of type `T`. + /// - The allocated size in bytes must be no larger than `isize::MAX`. See the safety + /// documentation of `pointer::offset`. + /// + /// It is also valid to create an empty `Vec` passing a dangling 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 { Unique::new_unchecked(ptr) }, + cap, + len: length, + _p: PhantomData::, + } + } + + /// Decomposes a `Vec` into its raw components: (`pointer`, `length`, `capacity`). + 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 `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)?; + + // 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.as_non_null().cast()) + }; + + // SAFETY: `ptr` is valid because it's either `None` or comes from a previous call to + // `A::realloc`. We also verified that the type is not a ZST. + let ptr = unsafe { A::realloc(ptr, layout, flags)? }; + + self.ptr = ptr.cast().into(); + 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> { + self.reserve(n, flags)?; + + let spare = self.spare_capacity_mut(); + + for i in 0..spare.len() - 1 { + spare[i].write(value.clone()); + } + + // We can write the last element directly without cloning needlessly + spare[spare.len() - 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.as_non_null().cast()) }; + } + } +} + +impl Default for KVec { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for Vec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Deref for Vec +where + A: Allocator, +{ + type Target = [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 6bf77577eae7..bb80a43d20fb 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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 Thu Aug 1 00:02:15 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749355 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 F1342C3DA64 for ; Thu, 1 Aug 2024 00:08:26 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 860476B00B0; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8115A6B00B2; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6AFB26B00B3; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 4B1A76B00B0 for ; Wed, 31 Jul 2024 20:08:26 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 0E03D1607DB for ; Thu, 1 Aug 2024 00:08:26 +0000 (UTC) X-FDA: 82401739812.12.7666DFC Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf02.hostedemail.com (Postfix) with ESMTP id C91818000D for ; Thu, 1 Aug 2024 00:08:23 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fb5hc0kR; spf=pass (imf02.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=1722470876; 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=FWyc/CXsa+KXeNtwmYJ8C/VRwZSK5FYscCv4PqQAmQ4=; b=pnUQdkrTYUqgIkBJ/Shcv6JlIdt83BhTxnUKBdzTYgZuYh93NmvF50/kLxkrN5KrmJhCHL 1K5DSXczv7szvvtSNa+v6CLjI30Ferai1+MgkwNdjLjayzxVpUJtrH/cQAVxbEJxLxMPVp RGi+VumysCi6yxFQD4mihDjuxhN2AN4= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fb5hc0kR; spf=pass (imf02.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=1722470876; a=rsa-sha256; cv=none; b=YIbL0uM8QnsfRIUPj7CxIWkP3BkqLwY8ydBx9CZLokVyEtdccqzBrdhcVTW2TwW6zBpdIo ZDSay7WTIhuF3p0h9FGHV0Nt/QRitFmf9bakZr8qBqrGXFwxfzNKW1AwPTGF6rtEKpn9jn xnyHzLbr25+HRouX8rwMNj8qnKyRTkw= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 0B210CE186A; Thu, 1 Aug 2024 00:08:21 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 53364C4AF0E; Thu, 1 Aug 2024 00:08:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470900; bh=jAbO/ocd+GDx9TX4LOAzMK63XGdOeFxsvuJ3d1oWSfI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fb5hc0kRBB53GlmIo7ISRm3ZFGGf2BIUq4w2KkggQ93QJruFcu0+zWcZlEknwxFpd 7gU/6/qKYBi/+KJFxQl6YAej/rg52M/yx/fWUky0taAaqdMr34zqTnsvl72EbQWQaJ kg5d4W2Wjmp7ma17noKc0jvUUAcZGMCuKVBJI6vUPkr5Q9Ru26Utz+J8oLPYFeiLEC lVatKFDoPzsDrZmWVb1qHzOwemrWt4xemw9F4jjjrhCx0T2b1t3soGoiJzZi5ICeow hjJEPfZm8AkPv+DJsF/UXNOHw15IrZ9XHdysw8ds+T11sWKcwO9vR8oBJydXpTTi1A d5IxqmDYCrh+w== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 16/25] rust: alloc: implement `IntoIterator` for `Vec` Date: Thu, 1 Aug 2024 02:02:15 +0200 Message-ID: <20240801000641.1882-17-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: C91818000D X-Stat-Signature: iz3cmd5cx31hnzxezxw8ou46pc8a9k9n X-HE-Tag: 1722470903-962502 X-HE-Meta: U2FsdGVkX19BbSgkqjreQDDzj/CkMj326+l+sBvucHqfSn/vkR/GY+MP9/T7Q8G6jBVaemEBWgn7qlPkstaYgCfJPFLOOQi81DWsrV6C+LDl7Ek2cFvOlNmQZjABhLMP4RMM2vKlqeC4T+1idGxfoKj1tcRSq6F2WB0bT+hEC+Aa+TFXVHIr0fCtoMYztuYNZ9D1M+ro1/SMVO2O1y3Cnke/ZfqrUn7IkXBdE36BY9e6ls/LcPM9iN7L/aDRfSx9TTSlcJtgp+5O3UE8oGevRdOqBiiQwDj7siO3qQYoPJD2fkU94E6jGDzVmGHwebfS6pyxMm0eq0jcXfDcm7IES38pDXflV94rQFHYZKAog6lJvCFIRyK2IPi8oV2qI8xPpWZRXGzbb4RXBbNAkfus2Y7LGGDKM2srZ8PiFV3/PfDYDohMh0idq4zqM7MLE9WWWosndXhdks5nrdlFFzqpRquqvmddDE18JOio9DXwFC7Bxz7rQSOtABRBnk1E44rVfQ/o3MiNi8dLLcmHPa6iCXJS6XgMTo7Uv2iKexB0JktEfdrBtmQ07cHinfM4VAxOUDqZZni+BbIi5fQKUpEFPSDMrhNRo99t1ACxRguVbYgQIvviNB3f2k/CJvqi4lwE4zo+/HLOpvnBlu88TgTacmn3LNmHY86dY+W/22KbwpSWXu6dpLgad5NxUDDx0hHsfW5/5GFdvezwowi5nOvoe79oq6aAotKKwokFd7rclEv6hALAyfdRdCMd+7sbLBsvQ8t2zpnvgwaeaOBy8VzT2oLJCaLVrSKY+xppjo38ly6ynsRYGjSlaZVUPbTtt4z0y5Zn9xsxel7HfYWNqkSIt1RPrNuwofjvpgWGUIPoOKn3BeGyseBWkKLOQzOWkJgjsolneQ8AJMHFHN3UNmiWevGG71rWJgeSQoZ0MV/fkO/37aylM9xsXSnwKnRsyQRvw2w9sOFWyzfOxnU4OrF hWX+xhPx 97Rqn5J38GtVboAbdjDY4CSu6xjTmYSEfEFP7dcekq3SVxP9WK4KePrhY9xxV5eWqRyjuxEbWtYxYwczKopGpWyId50JdNh/81esmYsq2KlmN6BSO0xCK9xsGkyOrofZrmkHB8a18GGpweYPE3FL+dWsWak04MHHOHtF0sth7msWt4bBP8SyDSXoasYj/5GONk/yQUV0PMclmE7wwHZpOa1fc5c3Rk6EG9k4rssGZS8K5yTxp+2O0MwojrakSYTKI5IptdZWG7nYFEWvyPz7GD9mVPqkJqkKEvNYHI6EOnc51zJXSp3nwcFaj7BAD30nhVsgrdMc45uOhQQiAYEyAQa8qSw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000001, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as `Iterator` for `IntoIter`. `Vec::into_iter` disassembles the `Vec` into its raw parts; additionally, `IntoIter` keeps track of a separate pointer, which is incremented correspondingsly as the iterator advances, while the length, or the count of elements, is decremented. This also means that `IntoIter` takes the ownership of the backing buffer and is responsible to drop the remaining elements and free the backing buffer, if it's dropped. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 186 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 187 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index bd93140f3094..f2998ad57456 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 04cc85f7d92c..50e7705e5686 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -12,6 +12,8 @@ ops::DerefMut, ops::Index, ops::IndexMut, + ptr, + ptr::NonNull, slice, slice::SliceIndex, }; @@ -581,3 +583,187 @@ 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 that moves out of a vector. +/// +/// This `struct` is created by the `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; + + /// Creates a consuming iterator, that is, one that moves each value out of + /// the vector (from start to end). The vector cannot be used after calling + /// this. + /// + /// # 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 Thu Aug 1 00:02:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749356 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 82DF2C3DA64 for ; Thu, 1 Aug 2024 00:08:32 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 1A9FD6B00B2; Wed, 31 Jul 2024 20:08:32 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 159686B00B4; Wed, 31 Jul 2024 20:08:32 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 020C66B00B5; Wed, 31 Jul 2024 20:08:31 -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 D65276B00B2 for ; Wed, 31 Jul 2024 20:08:31 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 91D4D80827 for ; Thu, 1 Aug 2024 00:08:31 +0000 (UTC) X-FDA: 82401740022.23.5FEF7A1 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf13.hostedemail.com (Postfix) with ESMTP id 4CC6120029 for ; Thu, 1 Aug 2024 00:08:28 +0000 (UTC) Authentication-Results: imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cfkdalvu; spf=pass (imf13.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=1722470854; 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=e2vTv0v1PKHoTtMrANr1QT42n0js2jn0FwIFujzfHWE=; b=7mZSj1pVVSDzvg5QS7cDrZKylRY70sSJ12sxk7VGAOtiCI+BPyH3Zd+xCFiX8dputSVsgO 8jxBquP4MQ484wJQaQvuQaag1UyYarLJocSEDX2NLEh5vZq0A70+07Xf8UD4VGPrnpqMoo STNQBOQPDgSqq+yXaqHCVwDhvNE3bZo= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470854; a=rsa-sha256; cv=none; b=Q3KmGMN9Gh/xKJmedKBv4kGhTIlQUl/3lnTDQ7kfdNTqP89qEIWHj7BGKDnj1ZhP/bUW+4 Xa3j1MhtcSyeWRtqhxcsgUji1QlIpWK8mKmC95/ZMSKp+yGD6KdNpghn8yV1JXYVnxVXQf ltheuXC3AGCcpjvPu5UBJ54ilTKqleg= ARC-Authentication-Results: i=1; imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cfkdalvu; spf=pass (imf13.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 7DF16CE1864; Thu, 1 Aug 2024 00:08:26 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C747CC116B1; Thu, 1 Aug 2024 00:08:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470905; bh=ya7gCjOyLIf+BXMFI3ReM5Yjgni5ExXPOwDEfypgmCM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cfkdalvu2BIweYpQssrcwA5J5s887qnF4a9CDA0S02Ei57c1u5ZpK8mxhrMNdDs1G o528UVlNzMO7n2gZuc4a1wyzHQHbE3h+713SMxMQbVQVQWhTNxhhHLZ/kcfpqoXBJG NBwlhJl1p9Fb+oGTm7O7Zdee/+T0SS/TvMGD1wu5nxUVfsXlAo16vcblidYbM4GAOG Su6itro6vrd84BDLH+pzhbNPdwrk6DFYzWqeA6jAzCqumZtEppqgXhj7o+TffxYBwF sMW4nec2uBGommHu9GQPK1QD5fStrfcnqX7BPj7vIsfp7mSIgAOuv/QFObpmyOjI7X oRvraIYa/r0FA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 17/25] rust: alloc: implement `collect` for `IntoIter` Date: Thu, 1 Aug 2024 02:02:16 +0200 Message-ID: <20240801000641.1882-18-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 4CC6120029 X-Stat-Signature: xfk4k1rsgfonee5f16k7rs5sxisiux5m X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470908-956996 X-HE-Meta: U2FsdGVkX1+FnhFTWjGSmP2BayyBXUXWvRfHLL5HzBZP2GOYDaYZ3/Jf2PrsCJGXVA8A/BxW0Fgya/rDwR7yIfp+RU4S4NxLqPCpj2bfPdp7mktzDLrMMAkW6izvDTIwsjXhDoK3jugMslUTM+/onSzJZfqJKdsXlwCT2cztvxOcKQED3yiR/xbO505GeKYXpy6N4XyPAebnGs7yFaiDOhvAFj0pfxDaKE/7e86l8ipxg8WgEV4fmgzMTnE0GZ2r/bCCPVsY9lxuFy1XMxFgV7ttfc8GfbUQxL9WbcVqOjpSYR5Mi+3PsIeELat+bb+iyo4TA2OJWE/Eh6JkMIfG1z6U7FM+QSRCRiY8ngNaz2W36DXg2Iz7JG46fVL4Nrr55Nffj1uMEPs1tCfOHNn3Y+YQkmiiI/Z++WBLb4Gvl35Nxp/1PI1iF9mqSDpp35Y5+yZ70cnYPL4xLlZ8Pj1aA1/X0oygKdKdtjvR+YeqhsC+k4byWEDv6oRV2nP+w0OXh8VH9uCtQC49d6zx/zkAEmbuPxt3RvvL6PnGESIet3uJ6+ZnjkkzC1l3WktsYFl3YVED8LEzO04P53Dnq6dWR9OVkjqMslnheLzHlS1BWa4LTfIPgREakE1YKaAL+0N8Fwf5twbfcXERrFilHHzIUV8R8uk65l9SfoHFYmYHO19uH/E8JmpY2XTexUStdxUsM3ddKwAU8zZuyTKT814khZ9kEvU/wy22yZzkClxW224URbBCH0CaO8b8fLo09fQU8DNrT6PcHcGjp7Vm+7ToCtkkBeW1VEWEcf6EP5XUJ7yPZqRyk2GN20kAJR9tGP+CpHQmsAF/4MJI4jfRrc3sZfyazBlPLZ1i1VyoKA3HXAE8/PBAN52ZTMtguuHCTybHxrautxjcQfQoVzpB3Qkv3jiwiurzJKBqUj62V4mSvlA+LjNU0qqitjit0DHd95v5HSdweqvpRm1qx0Mj40Z aEnY6VwV G3XrmZl7uPWKuwrZaJ8G1vgaUBj3n5sddA8MM6v1866K7EnhTW8UMX16y2nGcJ3lPFKfpMSbdNMgNTys0jP7dOahBfc6p7FlqbGzBAQnSYf2p88o68q+jv96735WSK9nALI/NIOjgAN7hoqOu+7/oCQnVA1DjnFwHyXMXNwbWkhFpr8pE1s0J/snh/30I/MsDk8qptzH1HJsU36mpTkaWhW6x3YBKDVPyrIYfwmtDhWkKHdglK7EmJzEZMo8M4FIiuQINWVvR5Emj+KVQfvZhV9bL7XvEGLb/y4cyLC+W8mEdtYkVWLp3pMSBYFxFxhZk7nQXGAqd4XUGxNRv82E0pXjgHg== 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. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl --- 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 50e7705e5686..6f151ef5c988 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -636,6 +636,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 Thu Aug 1 00:02:17 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749357 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 005EBC3DA64 for ; Thu, 1 Aug 2024 00:08:37 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7C49E6B0082; Wed, 31 Jul 2024 20:08:37 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 74C5C6B00B4; Wed, 31 Jul 2024 20:08:37 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5C5646B00B6; Wed, 31 Jul 2024 20:08:37 -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 3D3FF6B0082 for ; Wed, 31 Jul 2024 20:08:37 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 04136A5F89 for ; Thu, 1 Aug 2024 00:08:36 +0000 (UTC) X-FDA: 82401740274.20.3CBCDE0 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf23.hostedemail.com (Postfix) with ESMTP id 9FC9714000A for ; Thu, 1 Aug 2024 00:08:34 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Js2NMZY6; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.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=1722470873; a=rsa-sha256; cv=none; b=AUSMQAIZIIG0KWynqmRd0LdRqVO+bReFefsvpH4xoeh0sHOiNazSe2qaiXRafCzSLS5NnB 9x4ww3DKO64f8AkRFiPdbvKuOBUz5BgKjLvS2bds0+UnwpA8EwnoKAv2XO2MDDkryT3hI4 JvRE6fTW+gj3rj5WzsHjbIjKcU/HaWk= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Js2NMZY6; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.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=1722470873; 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=UvOfU0R+hg1oth9/zC3aXsxQxeeSoH7BgqFff9j+An8=; b=RDr86MO7jWbC5DDJxWKfVlUOSKeAIVSYFw+JWpCiNEOE3oH7ByLlshssa65dNQE2oYGHR6 BHwCbEAPnIWRxdp5/atk71PPyydFqS8ORRCo46BxsXfC9T3JZRc3ieapbfxZgnUSK4ZiCf z32DsLffN+ARVXTtKzzyFk6roRLlxOs= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id EF277CE11E4; Thu, 1 Aug 2024 00:08:31 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 463FAC4AF0F; Thu, 1 Aug 2024 00:08:26 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470911; bh=OUyFX4Ajg0yzg7q3aN3a+WdxriUzErZ+JXbxE/+fux8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Js2NMZY6KzQF8+HOV/w9yQBdGTLitDFYjSDJAYJkoz0gvQOXybeowYVyKR1HmX4rC BKfFSWgc0PTmCt/CV4FK3bEntTZ43LLG0ANOF7SchZlYZZKOptkJfSAiDe72B0YXsV 8mMM+N3dPxgTdBtUo/UQjSD2CNgJMzvry0fU5GkfQQMFQxw7dSJiGVSd89Loae0/dP LMhti3ixkeUFln9mVriL9OQCtzb+g/0UtXUrob8xfQnApB7ISDqlh147HA//cYwreG BCirXNxiRHFFRXbIZoehuAKavolfU1YGsdHljBv7yH8PJfdxkjSGXJm7yXaBEAmwtS 1t7Q5rYR2JsCg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 18/25] rust: treewide: switch to the kernel `Vec` type Date: Thu, 1 Aug 2024 02:02:17 +0200 Message-ID: <20240801000641.1882-19-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 9FC9714000A X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: pek1f5zciu3rmbugwte3eq4xfhy9ofrz X-HE-Tag: 1722470914-357637 X-HE-Meta: U2FsdGVkX18nrrebooVwXEckYUdQeliKmLkEnRB0CJYmBylkU8Ym5jcmuMFzU9e33DnRljnGcgDvCXzFdeLyIKQUW4iff6OhxL0GSGwSS1G3MIdmKYqz4n29aq+RW05hYOJszIXftQBPg0manyozoi3fHrC5mrW/LQsOKBvpfsscwEMb9xqvn5Js0oJgN6cn+3GNGQHuS4ZqAXiyv5bUNVCeHIY8DWL49SaYgYZDTgj5Xi4tfgeQ2Ffr0VgoF6Q/1EaVuiXUpSeKyb/4L2FMZXoUsUIV8LbyiMcQI8V0IiaYhFfo44TI1mr0HubLlYvi+g7YjHa8CaWc28VrUBOX9yJvcpmIS489I7NSnjjyn6XjgnS3IdbMDS53h0eqpVKDES7WdLBxNwfqv2uVDz1LoazXrw/bBYEwHRYqGksZZ3VI2OHE3QLxX5lvDuzJtzt2FuTEBWmQ25Jbiziz0ZgjiZq9LSQfjbYfYuumLOjNqnD5M51wHcYhLzeelH3HYX4DTTYKBxCHDtZ1wc5PTZmQqqoCBJWevf3LpzW61qZYlQ3Sw0w/CRzYH+jNZHV5hR3wpWhkBFMHRcfGx3hAYUEnepbque509RsUn+hCHoEHr9LLWlU9h1gXE2mfSvgcHiRRqv1WChvHBVSq4osp86P0yoyfcfnbAjPFQL2E2dGGKtFOeK2WyYaYta5CeJJyAPqA0W+Bzs9StL7dr3AFvFqlIt7IZ1r56cbYG3YPXWn7q3uoEpo4aIGDvdrDr0b46jUd/ZWVFUbqshut0Vh+s2dp7D2RjIERCES5mRVCChwTKBt0s7dB85nlr3DzGEnYd/qpN7tlQ9dyQcfBRUXQ/oXgUP/6qKvM5X4Yxs97RHWEUSwElxQV/w0/y+7tIHEX4tTLET8VkpYyUIcP/K52gp4Bg7etlE1+7HKEjUkhYTm32AKPLwWhIuqR0q9emj7AcyGd7gYgcDtiEVQR1nd/zhz z9EsugIK PFD6mISJ0P2kcr5fMrVDxF/TZ5C/lt97KK85O3sN8pDn8dJjK+TUwjnlyn/JL5scuyAkuiIyy19X9gR7ZdD/uWUuYy6DtskZ+IM49BXp+NR3R2xxLsh/bYiUtqmWEEUXlmYm+HV9AdIIw7ogW7AJXpjMWU/Q5LZRQe4J6C/BijZ5stp/NDzmRnP1Zcb+kQgiaLGT69nkb/nrCvEDeISI8rLDq5V8wvH0zImdtBOAKMvhtD9B36+3osvZlbk/mzNEm1tK65o4Y6QSl2b1098mNZ6jGlUAItk1x9XObhZVH1Oeb8IKFgOiyfT0kfg== 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: Now that we got the kernel `Vec` in place, convert all existing `Vec` users to make use of it. Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- rust/kernel/uaccess.rs | 15 ++++++--------- samples/rust/rust_minimal.rs | 4 ++-- 5 files changed, 15 insertions(+), 20 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..0b6ffbade521 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,8 +2,7 @@ //! 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)?; + KVec::extend_from_slice(&mut buf, 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 809653b9d945..1d90d2c68f74 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -158,7 +158,7 @@ unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {} /// # use kernel::types::ScopeGuard; /// fn example3(arg: bool) -> Result { /// let mut vec = -/// ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len())); +/// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len())); /// /// vec.push(10u8, GFP_KERNEL)?; /// if arg { diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index e9347cff99ab..d19002308636 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -11,7 +11,6 @@ prelude::*, types::{AsBytes, FromBytes}, }; -use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; use core::mem::{size_of, MaybeUninit}; @@ -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,14 +75,14 @@ /// 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); /// } @@ -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)?; + KVec::::reserve(buf, len, flags)?; // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes // long. diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 2a9eaab62d1c..4aaf117bf8e3 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -13,7 +13,7 @@ } 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 Thu Aug 1 00:02:18 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749358 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 3CCBAC52D6D for ; Thu, 1 Aug 2024 00:08:43 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BE14F6B00B7; Wed, 31 Jul 2024 20:08:42 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id B90F26B00B8; Wed, 31 Jul 2024 20:08:42 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id A0A8A6B00B9; Wed, 31 Jul 2024 20:08:42 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 803036B00B7 for ; Wed, 31 Jul 2024 20:08:42 -0400 (EDT) Received: from smtpin29.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 45A14A0524 for ; Thu, 1 Aug 2024 00:08:42 +0000 (UTC) X-FDA: 82401740484.29.9AD9D53 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf11.hostedemail.com (Postfix) with ESMTP id F2B594000A for ; Thu, 1 Aug 2024 00:08:39 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=vFjQK900; spf=pass (imf11.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=1722470865; 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=rtC3voiqc1TATSURcgUfsIku0ZqTvicYRBDy27LIdE0=; b=W5CHp2OIs/NGMWPL/aNarGRAAqkSHkudEj04wnoRJGddcFAx0++9K8PLtBvY7wJpTjP/bP +eN3S+6jmJ+bvPcTxM3aeBhmDmElF2R8ZZ7x/H//ps8yS5TWMQhrhlOYGy+2mO/wwwkAmU FknHdjuqiFHAVJ+3d2jyGyRwJrp6Lzc= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470865; a=rsa-sha256; cv=none; b=cFAsqRX5TC32aK3M/wSGVId6vpyeYE4iIOFAPMi4EeqnMT/m005rlxbxPdBlkdP5VtYJtd 3QMmK1Xv0+fzKtJ54WZWocYyXVytRROlnJqs5QhqKSvmdNjF5vj1xAdNwUaCTnwrQr1OQG tCYhgC+Qhz0wexh8B2tNo5EupKSzL3A= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=vFjQK900; spf=pass (imf11.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 72A51CE1844; Thu, 1 Aug 2024 00:08:37 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B77D9C116B1; Thu, 1 Aug 2024 00:08:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470916; bh=YfFWRXZVAmGw9pBzx/NDL1iukdDa6E0oQN8rrPpR/Kk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=vFjQK900MVem7/NPiWivgBuvWPaRumOWSO0Nnt4mk6RGp65hrCYT4e/GI56/JgV4+ VpDx++hllAfIAmsSgscJlFRDM07hOaDgzvk73dYpC2k1wFrBnX180bdx0XVBiGEgZ1 5xCzcDrW6Dvsf8q2GcEWOm1v4Qe1rYdSVfuM8Dc/OtDSwspVNV3g/dM42ikVScDKp6 rdRTDJ32ETi+01uzgPzMEHI1mL0I+XEtnmkUhah9xe+LmlzXOKPQAV6YgCvxIlgmsE f/0BbEvO/a0QOEjLRHmpRXjr4hJdLQ0RFCTvbJRALPTFFyVh6Ojo1zNViiXHJHDvFo ccCbvEaVfFZjA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 19/25] rust: alloc: remove `VecExt` extension Date: Thu, 1 Aug 2024 02:02:18 +0200 Message-ID: <20240801000641.1882-20-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: F2B594000A X-Stat-Signature: 1h1xuw344pcuw13amxwm1r8xja5nt8ab X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470919-946525 X-HE-Meta: U2FsdGVkX1/qlVCtJ+hEH/dFncKTRtSzcvw5BLHT+qQAqGomSRmqLq1YD318ApcV30zMeiwrsKaRhFZczguOAScVK7Can/mhTazsgGmBsoaTdQ5rYNjolB+4WUCqoiOE2ClgWMhpmEgTtCzLmejrVG0hgTjZ1a4A8HsPCd0Y9T6fQMM0yalY4ma312AP84WqTki74o3AnDHbpWrcEoWLRydVl9+v7q75F0szgezrx6gNFGxThPMpaMVb1WbXZQdtGtls0ey9J6IQddBgvV+DlSPuRbvRqmrgO7rVj4Cutrl3zIZ9s9T+FR7DvhHef6pDKdfTNK9a7+ekyU6xQZZ7oc3pzHa1welXtf8kWtuwGx0uYQt4vNLLojBVIn+0NwpF21YnpInh1pda9Bw/vKryGWsCUkAnWRAqeeBatjXsYpm6JRUfFW984Nz8p2mHNYi5HR93DN7fFbO1pXO4NdYL6eoHqiFfRymaYsjAUnUB00xiuwtdYqAjEDIq0B6hqmJhsmKM+IH4pMMHMM/BQyaNyN+LGc1I8hzZfAEa93UzZHQug6JB0kLUgaRHLSC3k8Bucuc4WAUmUvsMuuVMg6h2y72m7Yw8ZmnJ7SiHD/by3xoUY/Gya1fNL69uY0U/GNzjYQik9Pxm0buV+yAPb1AoH79u7QRt7QAFZF01ysIOTwp48Ty3hwO+k/w+nAllrvg22o7EsZKHWv9rY35RZQKAR+V3cdrWhxsJqg3zPyDWFPoCu0RO2r0ji5fHOQJSU05ImDP07HV9Dryaq2oBcFbXMGac4xPSfPoKdm8LaAgX6B0n8DFgWZRrWipRXSIYUaje3thGm/Vx5qlfI9qusT7AsPbFhUHRW0DkShMiBCjjv7UCYxuhSsO/XUv0yQIILhOFlr4x6S99k8qDG4UaBN5PlgOr8gS/SH+IZrnHzKq2InuHv9GKv0mlNo19kMRs+uJsS5bDKRfZdGqtpVkQnmW UBSLSI27 ef/jTeZ0TNeOzPJWWJFH0YqZgr/cXnaIube2tO02fk9KM3bQceQH6XXitJ7A5H8Yp+Ae/s9zap/eCzl/F9ZjtSMKPtiXfVXSEl8yjPZYS6AaSRZm2GI4G71BdfL/uDxtXk3T9nZSslzifK11e7BPioZApjgI6r3rL1KpJ244SmDqKvvgkkPSeG2T+MeRcV0zPi3FwkL/1zI7dB1h4QAB73SRyvzLDIplERETvDzbq8mIkRdm5eBaDD20mfC6mX1YxZWMm9C8snnG/v8jn9td9TzASeLQQ8Qv8ZLy9tjl+fLdZR7syZ48SzCC6bw== 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. 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 f2998ad57456..fac9d3976657 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 bb80a43d20fb..fcc8656fdb51 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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 Thu Aug 1 00:02:19 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749359 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 01BFCC3DA64 for ; Thu, 1 Aug 2024 00:08:45 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7C4CB6B00B8; Wed, 31 Jul 2024 20:08:45 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 772D66B00BA; Wed, 31 Jul 2024 20:08:45 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5C8CF6B00BB; Wed, 31 Jul 2024 20:08:45 -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 3CA7C6B00B8 for ; Wed, 31 Jul 2024 20:08:45 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id F2FCA120878 for ; Thu, 1 Aug 2024 00:08:44 +0000 (UTC) X-FDA: 82401740568.01.13B42BB Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf06.hostedemail.com (Postfix) with ESMTP id 5D783180015 for ; Thu, 1 Aug 2024 00:08:43 +0000 (UTC) Authentication-Results: imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=dwGLMjQ5; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf06.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470881; a=rsa-sha256; cv=none; b=EAVZMFPzN70z3ZPRr/86aiYYbw4u7BSpyMlxRuw0gX2CYQB0AOvwAsCmjItrTlghV9qpae GDy5RIotm5iC0R5I3Mr5L01ajzUrJ8nKJjWE3xIFJbXZNP/2wAPcagk09o5benHZSYNJfk YraWJTeO59JVGn2OpPI9v9DqzNNkgl8= ARC-Authentication-Results: i=1; imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=dwGLMjQ5; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf06.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722470881; 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=V3RV8SQZBp3cdXNz8SMSCfTp6xtcwDI9ECD1In1etJo=; b=FIIXiivAkGBRGtceCwj7TZFua9LWm2JKDaefVKPpWZGTmOidAdOsz53vhyXU0C1PAC/KIu pUZtu4B6N22B49V7vyiroD8cEmuP45MozhoYz11tAEjpvbqfNdE5tIaKYTFASrfAyo9T3E 7+UE6Vc6jRXO9TfRZRNWO4ZJk+Y5UGs= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 941D36260D; Thu, 1 Aug 2024 00:08:42 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3AE73C4AF0C; Thu, 1 Aug 2024 00:08:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470922; bh=x0JvvRfi87BBCBI94b39MtnQOfc5sS9njBcl08nLwWQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dwGLMjQ5O1RqCMU95r74D1I+1i4C2i/6B4l3UPVvQRz/2DEFPmAhuDzrdF1g4mbXC IX4i4Cz1YT7NLKQ5R8xfrwTssfFtC+w0hi0LhTtf+IrUromujAPVnw1USOJeyPZ9Tg 6RhiksAY77LVOu5xR4LWDNL7eVQxbbbBeyD5vIA6h4xRjKkcIFkIUyOEQJf33PGUvu XZjNCF9isBwE2ZQ9c/bkdKTK0CNCsZUin43wkg7Twglu7+Pt1V2IzrWwJAwSxeRQSk rHAu9H10VJkPqd1VGowv3LuZPHigi9QyXCcMfZA8I3qcLVNHakZEWXiHPWuUnjqVNI mPdaApxLLfZSg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 20/25] rust: alloc: add `Vec` to prelude Date: Thu, 1 Aug 2024 02:02:19 +0200 Message-ID: <20240801000641.1882-21-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 5D783180015 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: u8wjtghsp8kxryfpqs8rdxosemyarw9e X-HE-Tag: 1722470923-605048 X-HE-Meta: U2FsdGVkX19v3pxMhNGZw+QzxQEzlkglg6qSbzkOOVrt2Ccitqi82tTJkZA76kAqw0Q6obtMBbeMqhogB7c82T8GwJmSxaL4N/W7Fif+OGRyv0ar/PtJlgP3q9aASuAWymEPJV6RvQkmIY6macSDHPI1obnjXOiQto2pg4lsWrMY8ohVhwBG6lzgn4Q71KkYOUFVI4BUH1vrkO+TJ9GWbCZr8snETGe8ZY5drE3QwD9l5MwDSozQ+dqQwiWiV1CMg8WlQ6bzuoZeVjjY7qriZSPbBcj3o1FAwNeyxXuJzCeI/LAE7/iOkrloJ8HmRQlNC5JHVSRB8naxstzfX3p5Nu7BRR7ffshl+aNt43gOc/7vtjAwybFMullLzYTihMFlrmhLAbiLMsFdRyY1xXyBRwI+Q24jnomydU1lcxcGxYCBi8sXPfh2kDJGBvxvfxvyTWWlAwwCjUxCYoz2Q0AvJTxkUnqdD67upL7KwsWG+Y5lXLQn+iP7s3znk1KTaRxghIYEwMCqGz5OKacnP13nAlOAF/GBaDA+ZZPQI9MjZyyy5+sTYMN3iLa5Z9WUUyziBMJ+/hwE7k0dZTvkolMJ4eXjfx7prEHTmmr8IpnOJo9tGp0rS0V++2kWuqJnt5At/f0a/qtxYxkUPf5ffbm6ehx1JfpWBBsnEkgMICRNx8YRGx6GmZaJkNJ08hpBpFsQKAE3rv81B6JYnloEoflL6BGDGcq3jFW64jQRKCcKGjvq1lBT6jsTnJq424deE/syMombpVa97EDonNPm5w2LyuhaJWqc9Ruyk1jwmQaMl3wZak5zpSElpCIGck31s+Zro/3Aj1GLRZpE0LwbMhcb/TxY2Wpot68cwxkI/0NQa4N1HrTiWsWsLwdqrmXLlVFnf2POMArXFxD51WGFX28+OqOejEvXBoLD2EljPV6JzoEBDMX8U27hB6jOYlugbaaXh8wK87cmxOK5SBCZTAs iUeznPFu 9C+FcfKKRkgJsEqixzzr5V0bDD31qbtmcLlabbI8IPEjRmiZMpa0klyDSDkj94t9Nz3uepOwzPTnH3oIJUjUKTpWoIJ0VVgDyGRbG7vIz+4mKk1gpU09CJXevobjAG49QB3eCiGPIMlCmT++BgHyjiChLLk0AdOxkTlT4KQcMaGedjdV9cOn5GwxXFWN7GtNbMFQvR5qk1Zez34o5PJzDyQii+EkHmpgxZY447krmyCMAI4hN/qsbhhdyQ82HQHfKR+NMLn/D4rXaHJTIv+TsrZGiFO88CulZNRRORH33JEXPGvgcLXpSGs2Txw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000005, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `VecExt` and the corresponding includes in prelude.rs, add the new kernel `Vec` type instead. Signed-off-by: Danilo Krummrich --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index fcc8656fdb51..b049ab96202e 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -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 Thu Aug 1 00:02:20 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749360 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 78E7DC3DA7F for ; Thu, 1 Aug 2024 00:08:51 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id EC9866B00BA; Wed, 31 Jul 2024 20:08:50 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E79706B00BC; Wed, 31 Jul 2024 20:08:50 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D1B446B00BD; Wed, 31 Jul 2024 20:08:50 -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 B1A5F6B00BA for ; Wed, 31 Jul 2024 20:08:50 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 7A3911A083A for ; Thu, 1 Aug 2024 00:08:50 +0000 (UTC) X-FDA: 82401740820.03.48014E3 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf20.hostedemail.com (Postfix) with ESMTP id CC4F71C0003 for ; Thu, 1 Aug 2024 00:08:48 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Qi8MBrs4; spf=pass (imf20.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=1722470901; 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=yLl6nSqaJL4J1JLoizhVMMWA8rjQy+MNayRc9dzj7U0=; b=Gd5IJURZaLgBkOZJat0Tv/8+LR1FE6Q2CRxBn9uvwiT0nuTViOjLfezSp9ZDxAzN1jmi7v Q/pRGOJwgNxk2ihmX66FGtIJP2IxuhYUImZX4+/vAehJnBrZrqXeegBU6On7Jbz9ebw0Jv 0zcRSbn8PItYTUm1ZaSXBS3ReH3L1IU= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Qi8MBrs4; spf=pass (imf20.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=1722470901; a=rsa-sha256; cv=none; b=5OvLvWcyYWz2yoOt13rz0QnLbCIK0NeZ8XbZ0DfX7KdQFAXrMgaI6gGhqJvCjLnXrPWU06 5gH/83A+ZepxxoQz3TVeWlOJpARzbnPp9ITADJkfo8fc4SmRHgwnlvvTcWHUWtKbcMN9Ed HPzJ1+Bgrr+VOPA6vHYKqr31ONj8xjE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 0CD3162646; Thu, 1 Aug 2024 00:08:48 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BA256C4AF0E; Thu, 1 Aug 2024 00:08:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470927; bh=hs6yx2vsssnsC1cMGPjQ8GCbMEe+TcUfgVzllRdmHcQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Qi8MBrs4TK3ypoC035nwRtxZmqKOxMEzojXeMd25cO+4CUFXRmQO7ThgKpbjtikcV YGbp9dUOlqTlw1s76GzTmW34h/Im39OUf2w1FE4ltRWUIOGUYvB7P4R/4x9PUoQslE ochEnnxMM+QLZxg/fs7fe48NtEc92gXHDwB+F2ldYLXrYcZSOq06Xw6SsZObmLCgFU iMF0TK0sR9f32LnvsBN9G3DRj12GKGm/l2ai6sXvki9jInqTIJV8U1l8y6irmWXtWC FyJLf78lg1CsOrLnljsDyuxz8y3D8xXhrlCWMdKqT3Lyms/9Emh0ruTfxXHrFofzsg lVWbm0OqlK10w== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 21/25] rust: alloc: remove `GlobalAlloc` and `krealloc_aligned` Date: Thu, 1 Aug 2024 02:02:20 +0200 Message-ID: <20240801000641.1882-22-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: CC4F71C0003 X-Stat-Signature: 1fkjn7z4johct3ibgx3ac4yf15uitgk9 X-HE-Tag: 1722470928-503055 X-HE-Meta: U2FsdGVkX19JeRtWnwh+HrelpxzF2Fl3sgWle/VF7+alvGhR9GnU5gPbPLCc2qst9BCAg4shxFmGgrlVMmt3SGiQjoFvoEnaJaD6KOLQCyOSIR1r/uBE2LYo/e/qbjwEpfQtLTTH97Qj30umNtVabneY1qbcB+cdO1aaUqoZ4Q1kaB9SRYno+TdPUhw8CrA+lc8s8uhUbqBglv8vRcd8SB50aaKmTw+/h2A9cM1s2gYGzM2pwfgXAm1FwWFCAAvpeugvo/c4ikuXR8F7160zqnA3U+Rf8tCX9fvr913LA77VrTII8FgbjhI/UrTe2oeABVr9nIpxSYcg8fOuV58ZHhl7709BOlaovjgQeu3Rmgms1r+5Fg8iDPToeKnNJhbwZnFRNrFJ1j+x1AdqkSEfayEg+emvlZIEy+r30jSYADhytmUue8jh+k44f6IJkm8Xlw4Vbw1Z6Jh64EZvGS2rWIl13TFF2W3gOqrAM9ppKu92+jG+kI56nobjJHCQ5kAr7AYdC/lbji2Lh2Kkomw3B2SY2cA44FGddFL0zycVcmiOtN/8Y2xtBThUOC7VukPgSGg92yeKCs8HcCqzoC1HEUTEGmFrJWj5QD3OrvvCA8G4cKEk/9kJdildMGvrI0NP1zTS1lHMwEpcZUokqQzjDSQle5YPiJr/sFYCtZCRMsxRRAikMp8XQGD8uPP5MeBfgaMhB2np93Q/bP9NqRP+UIRxA9mHgtwD1AsroCOvY5E6WvEtT0OoEY7U3LKR03im2o7PtP9yZMUx456UnMipXVQ8heKbsCWfjXcbBGmZayFSr84VQ9pvQ2IbGpogFqk1YuuiWziuWXOuWaeOYctRxzqJuf/FizPL2h/G16Nihm9qYyKE+RxBYM3+XxGZKk03nkt+zvtogELbZNimmkLgdTwVGnjnCUR0WrYo71jnPv+5YpEBnyNDh8qFgReELll2US/2HGk+uWXQGs6LZRS 1ltntT8O 5UNO4suk2Pgio3WZjIWlA9LnB8IWS1bKKS4T3So+VKxMRJfwS3xObkO4W71PasvXrrevyx2djqdYw0qkHq8iLpOYxJTJ1lpdTNECWumIaAuKMbP3GrMMX/PkSLjK/d3UzwZJiGnE5BTpWsxF2A5WVQFsIqhYb1rsn2uci1oBz7qF8K3ddNVVfdRPZuYsCjwRS/lDyw0NbKgGfL3shVmA2S32JbZIDhcwJKYyj3HXaqirSkvPITWMct7EHnsara91KcgyaLjCUFY5oB1gvkFG6MaLp1HQSCPs+TVEeZytWx5WdmJpbeQsj/SMAVHzut8H38rhIHN0HcjYTYjQ1xslxrhS3O0W8mxwtz1vxcmUuF5h0msEMti6bR2eg/if0QILz8A1V 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 all the `Allocator`s and the kernel `Box` and `Vec` implementations in place, remove `GlobalAlloc` and `krealloc_aligned`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 63 ++-------------------------------- 1 file changed, 2 insertions(+), 61 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 1e53f149db96..fbee89ac3be4 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -2,8 +2,8 @@ //! Allocator support. -use super::{flags::*, Flags}; -use core::alloc::{GlobalAlloc, Layout}; +use super::Flags; +use core::alloc::Layout; use core::ptr; use core::ptr::NonNull; @@ -39,27 +39,6 @@ fn aligned_size(new_layout: Layout) -> usize { layout.size() } -/// Calls `krealloc` with a proper size to alloc a new object. -/// -/// # Safety -/// -/// - `ptr` can be either null or a pointer which has been allocated by 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 { - // 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, - aligned_size(new_layout), - flags.0, - ) as *mut u8 - } -} - struct ReallocFunc( // INVARIANT: One of the following `krealloc`, `vrealloc`, `kvrealloc`. unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, @@ -121,41 +100,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 { unsafe fn realloc( ptr: Option>, @@ -184,9 +128,6 @@ unsafe fn realloc( } } -#[global_allocator] -static ALLOCATOR: Kmalloc = Kmalloc; - // See . #[no_mangle] static __rust_no_alloc_shim_is_unstable: u8 = 0; From patchwork Thu Aug 1 00:02:21 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749361 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 DB60DC3DA64 for ; Thu, 1 Aug 2024 00:08:56 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 63FC56B00BC; Wed, 31 Jul 2024 20:08:56 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5ECF86B00BE; Wed, 31 Jul 2024 20:08:56 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 468776B00BF; Wed, 31 Jul 2024 20:08:56 -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 245226B00BC for ; Wed, 31 Jul 2024 20:08:56 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id E03C81605F1 for ; Thu, 1 Aug 2024 00:08:55 +0000 (UTC) X-FDA: 82401741030.03.38796AE Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf03.hostedemail.com (Postfix) with ESMTP id 4E3E42000D for ; Thu, 1 Aug 2024 00:08:54 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=kUivBdiq; 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=1722470879; 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=JiNiq3w86fsb6pYyZWDbsYIgV8yRol5xnlA84a758XE=; b=GWc3I5Kqs5qk7mUeMYX+NsQP6pudiWCnjMNun9Cv1mqSPkufa2l61q+5okl7ngAHCnPrce /OwBsCHoD2rGxvnF5mzHK29x86BejkxShbUKN8Y4Wk9EmfFB8jBGS3iim0WF9tM8MU4WiH p31+A1dmpeHGNtKxLN6T3Wa4Ke68AlE= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470879; a=rsa-sha256; cv=none; b=OEYgcpiabV9rG1fTMUwTaexVUb6DU0a5IyWvqcHbusJkx+q/YP1l4N9dNeB3f/WfMdBtg5 gxSTdc0KFY+uufaJ+JbYuwgXe0txam0ZJJrmbiWrTGaYS9k3Vv8JRDWgmcu92trlk+FIon VESUi3tNIHLR9EGWnCbIQbtvG/iFfVM= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=kUivBdiq; 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 Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 8486862665; Thu, 1 Aug 2024 00:08:53 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3C057C116B1; Thu, 1 Aug 2024 00:08:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470933; bh=ifLa6ui520OxD4tx6GpOL1mZtUOCjuqJJxFCxi3qo5o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=kUivBdiq+ljrI8Gj0tdo4pLab5vvfpKTImgKvmcvTlTlbF5y7wRSOxm4qYZPTwRrY 9St9UbAqB/1kv8ZPBXZIS8y3eRCZKDQ57QumGUiQIsO00sUO9UfMQOijL9qMuudvnz aKOC5wQz2A54+FBlR9nidtxr4w67RBmayYNlzhNolOJwOFsIjD0Ym1brzxi1h7QCf3 qiHZur/RDhDo9nOBevWr39KwXMfkYs3kTPoVkSR2/Y3qC6Xog5zZp9GYEV0X4aWYz/ DDXt3B7GcuuZE7t1VZNtZkX60Rjn3wfax61v1tlZhI3RDyOotEPkpxGFK1zrpAPllz X9DqJJD90FF7A== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 22/25] rust: error: use `core::alloc::LayoutError` Date: Thu, 1 Aug 2024 02:02:21 +0200 Message-ID: <20240801000641.1882-23-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 4E3E42000D X-Stat-Signature: 8aet1yek99y47uag3tcebx31yqmm3okt X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470934-652886 X-HE-Meta: U2FsdGVkX1/l8TaLMc74NOBxv+SCzpjzWhxCf4tRivKq5EOWbNMwjGxLJ/4+KJQHMj2mLyF7ata/TWRQ+6OwHuT25YRoFtt2Ft7JwwNoZNgVFbwbCe+mB1xBQAEh2awkxOHMMafgkZvnCTs3Bhwxm4ml8XpjRqvn10fCfTDwU68heBQMHQ4YRN4MQtDLnFPvV4oC4Wo2jcRE9BZ+TBmHUWZtYl2b97OIQOlFBbXGOC4mzldan+kL5EZ2EigjhM9JjKzUnLd3hKvVlpm5WcqL/cts9bcXbCdmOOjVKICl5oLLIG2CrUMka7y9+ZyZOm1CQyLX1IO8Ga3FsaSJkKgCj/rQ3HrryVwiL27AuYl2FqTB6zDs3JsZucJ+lZgpOtXftRgoObQFz64fX1ud6Re6LTnivmUAlSb5IHv97LaKIk4mhr7FUJcMMVK47nLkmtSwY7vDJr1TBIy+15pWnlfUz6LkcXPLQkNRsLp++n+/iJCghBSYNRKC4M9S5sM7NWnAHZCcd73ZJvp2WAsG0UPC3eN3pDqBO+hfQiMCrC8+LDuir4EU/EFpjA1FW0l+ycfbOpEGXUa2r2bhoNmLRtRmXNCA8SiZ0szu62eaI9be3nKlaBOpuckbrgFO5kkH3zbGs5OCuiCK5qEnWKeQygH2pz9DMNYS41eDIOjSfBHRjLjFgjDmI7jnWEfe9IfC/v+wtWnG/C80TCKpqR/yyGYN+oatJDCBSa8A4UhwKdVnLEwAo15wLsivZUPXvo6yb6iSOTMM9/09PNl8+Uy6KSeoJNbSgdO3tGYDV/2DpVryluuUX8GzDxoy5BbSwfB8/d5sxnzLg5zELeCa5OoLC0dZM7xicpUFBuNLIfmpHfrgXZB69ehZFMyh6habf/n6+Ja5/8sHmvKxHC9iOdB3WgO2Mw7SkCXF4rJKq4sNiIvTlLyeFqV9AUoJz9/ab5CPp0zdZMnToHOnZ8XuhgryZYb rJqbcaXr CYWXIHZ/UjPwEtN/HFBpLkuugqqWuoMt/4JJdfrILlGpvOx+v/0GhqMm5P6kxhWSASJIdsrYayt67esIj2LrHX6/LyvQABxPrSZ0vEBetgId9oXsHYKj+2KUiP4BVFBmzcIuqKRU6YsX1g5vZurz95Qhl5fTkoOm3EgAX/hm6xDPjvmHWuHWPeXUPdp4jXctpYvD3c7wx0c1poTTeqQEDgKGwBxxB8Sw66UGKVVmajW5Z/FN/2ydWfJfGeaELW40sbPuUJAdcfeZwjYCs6y7XdIxh3xrtQspEk2SsxQTcRLj6VIQW1XGJBg9dWw== 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. 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 Thu Aug 1 00:02:22 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749362 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 85ED4C3DA64 for ; Thu, 1 Aug 2024 00:09:05 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 112FF6B0093; Wed, 31 Jul 2024 20:09:05 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 096106B00C0; Wed, 31 Jul 2024 20:09:05 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E79CB6B00C1; Wed, 31 Jul 2024 20:09:04 -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 C8B7E6B00BE for ; Wed, 31 Jul 2024 20:09:04 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 8B9B5120873 for ; Thu, 1 Aug 2024 00:09:04 +0000 (UTC) X-FDA: 82401741408.03.3E02796 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf12.hostedemail.com (Postfix) with ESMTP id 50C3D40021 for ; Thu, 1 Aug 2024 00:09:01 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=XLI33TE1; spf=pass (imf12.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=1722470887; 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=kcX4qbBcCzJj1u3+EdQ+OskijfGpr/4rSqwVh4l9oXk=; b=PoZ2PDSN9XeB7cax8EmZU9AQ0Qnb+wkqI01aVwWMnirFY8tqbmyKrCB3K6b8JlWMYmWbqm uYM2WEOZT8e1i1xGLH56/83Z1rLDRgIXwGrLeme1zSPberrpYrSOXxJXDYePojLulXqXg2 ml+ZUNvnVacjku06EEzjyKlOl9t7NdQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470887; a=rsa-sha256; cv=none; b=7XkEE3cOS183yYouRDJ7h2HJhBp6iENzZMAYLte16L9dXweOhkFTbLY0gljPv/4jl7K5J/ gqj8DNiDg5XiHk/qPHs4XDbQ1fUmRq7rk9JSoud4eeu/JxbPa75quoaJOk6O1NcksEpvn2 2orNUb8qTbgk4sNCgqT5KiLTdzwWimk= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=XLI33TE1; spf=pass (imf12.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 831AFCE1864; Thu, 1 Aug 2024 00:08:59 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C75BEC4AF0C; Thu, 1 Aug 2024 00:08:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470938; bh=T1EttxerGLScRoG6GW0jYhIkm3ad2nbCx6FWpPy4fh4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=XLI33TE11rEBeKAF9x4e/go5ry1nbCbZLeZptgDKd7shye+j1XGZVFWvN8OBlbRcU IZf+fS4ws62sbARE8MZ6EWcmcipdJK54pawAUOjAq2R4mIf1sVEWjK1AZgfQ4VQP0C DtBxVkjCeMhxBet8JfoaEGe6Dg+VO+8ZhqBcTetlWPyBiRKVYGdW/w2KTMUaMvV3Aj QJfuN65H7dfLO4n6fLba59oM/I2rLChWHmee2J1TMmLv4Gn4EJQbfJwfAOcfxavrxO ohhm0Rup6IIUC8X1jSz1lAO0ibZLDPIQCMvhtkhKrsSFVLkdAdkXCBTsfbatXvbTBi vEh4/uwRp5Fjw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 23/25] rust: str: test: replace `alloc::format` Date: Thu, 1 Aug 2024 02:02:22 +0200 Message-ID: <20240801000641.1882-24-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 50C3D40021 X-Stat-Signature: i6g1i9y9i41ri844bn8gtwk4r78ck3gy X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470941-913701 X-HE-Meta: U2FsdGVkX1/xJfmNk65Ip2yLwlXIoWcelZiqlZitNbzsqt9zQwEotTU4+z9qCUxtiZKKp77eC8LCcozkv9LBu7zL/s1F166kMHJtJbU8NKIj9R+j76DyeWmdhH2No4UpHoyZ3vpj/KPuAyNgstbEWmj3w5x6O7vL4JjqdGJFY+1R6t78VYlBw0kNHtCQYIqrTO0OfAruVSSicfMm0yGlM5O9qyq2UwHJMLoWNM3XKN3j38q2pn9qeaBCN9k+7SDoYN4SHJv601kzxfqbRVW+8AwhfWb+xSBouUDWXZv8ERm//SMSD8VhxzSPFFcHaOyFo6wXSpxE2xJEXOGkFpQRhl9CNJSHFvF5EgiJmRDxnkuaxQcEb6JWcDgcjjufz32P+ieJ+DcNGLZhjFgnBeztTFVIsrpeErNCcqotSVezo1aavKosb4Jha/g5WLmmJwRIDgNhIKFhFb9Yp5e8caLS/kRA4MuKKuSRvUUDa9/WM1j3O5L8p+QYZu4lw8avsJR6i44Q0a2bFM+9Cvip6dXOuhhmLJbq5/2tlVmSIM8IXio9H/xrE5TPfcPHXynifWspJNAb7kfxh5L+t8+p8jK3PlCKQCYTuuXpsUugyR+mmLXVxC0L4uAsVRZJKCFQLg859DNAAkznheHgxKekMV8B4XjhJYwtX48jH9HllPrabbamLLyNvMfM+mTStGk2jiYZwxU5Y30CzN64KvAlRz4iwcwAol8A0f0hSDDjv1jHcTGLNgJ8rlXz9gZ8qyDZGMTWbZIf4Q6dRrInAnZpYJ2vOFh7xk+srEKHL+MvDY0rmRgrqTLXjiQGLc49eFb97scRuMpe3V3KqkbdMx06YGsHbQzMjohZ9dGuzcnKRGWKnf9M1Qh730wKJUHJ6gDxweEZiT437OwRjGlynLh9ASXsOQZH2+3asuJyuiJgpJnj80RDaE7iF/4tqf1mbodp1lmRkDwAccUTGd4p72gCVUj fBf7HPT7 6CYFpdqJMYEX3e3rGutTDUJgcv6gGRmW2f7mTea1hkKF143C4QNJXOaHGisDladuK82WYhbbdvQyW1TAk1h+lBd5PQvL/oNVBGmXzGQylwCzOecjcrkr482verCHErXO/V1IVDIsOPPrJH1KxxcSMbXMOkeL7UG8lm/Pw8HexSFIxrXNRt2vOAPyj5iBGBCgmRjVrkPt5AYscVQRKahGYlBB3dOYSWnwuyLAoKQnxnSgeUHJI46AoV3ECpGsHp6GSkC6t7Xc5lWamhEU1njJdPLPDo9kEVl4+MlcXzizrl9Et8Q1r3LIole1wng== 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, we could implement `format!` for `CString`, however `CString` uses the kernel `Vec` type and hence the kernel allocators, which can't be used for tests run in userspace. Instead, implement `fmt_assert_eq`, which formats strings into a stack allocated buffer for comparison with a `&str`. Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 66 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 0b6ffbade521..539be40754f4 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,6 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; const ALL_ASCII_CHARS: &'static str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ @@ -539,6 +538,33 @@ mod tests { \\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\ \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"; + fn format_into_buf<'a>(args: fmt::Arguments<'_>, buf: &'a mut [u8]) -> Result<&'a str, Error> { + let mut f = RawFormatter::new(); + f.write_fmt(args)?; + let size = f.bytes_written(); + + assert!(buf.len() >= size); + + // SAFETY: `buf` has at least a size of `size` bytes and is valid for writes. + let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; + f.write_fmt(args)?; + + Ok(core::str::from_utf8(&buf[0..size])?) + } + + macro_rules! fmt_assert_eq { + ($str:expr, $($f:tt)*) => ({ + let mut buf = [0_u8; ALL_ASCII_CHARS.len()]; + + let s = match format_into_buf(kernel::fmt!($($f)*), &mut buf) { + Ok(s) => s, + Err(_) => panic!("Could not format into buffer."), + }; + + assert_eq!($str, s); + }) + } + #[test] fn test_cstr_to_str() { let good_bytes = b"\xf0\x9f\xa6\x80\0"; @@ -566,13 +592,13 @@ fn test_cstr_as_str_unchecked() { #[test] fn test_cstr_display() { let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); - assert_eq!(format!("{}", hello_world), "hello, world!"); + fmt_assert_eq!("hello, world!", "{}", hello_world); let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); - assert_eq!(format!("{}", non_printables), "\\x01\\x09\\x0a"); + fmt_assert_eq!("\\x01\\x09\\x0a", "{}", non_printables); let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); - assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); + fmt_assert_eq!("d\\xe9j\\xe0 vu", "{}", non_ascii); let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); - assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + fmt_assert_eq!("\\xf0\\x9f\\xa6\\x80", "{}", good_bytes); } #[test] @@ -583,47 +609,47 @@ fn test_cstr_display_all_bytes() { bytes[i as usize] = i.wrapping_add(1); } let cstr = CStr::from_bytes_with_nul(&bytes).unwrap(); - assert_eq!(format!("{}", cstr), ALL_ASCII_CHARS); + fmt_assert_eq!(ALL_ASCII_CHARS, "{}", cstr); } #[test] fn test_cstr_debug() { let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); - assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); + fmt_assert_eq!("\"hello, world!\"", "{:?}", hello_world); let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); - assert_eq!(format!("{:?}", non_printables), "\"\\x01\\x09\\x0a\""); + fmt_assert_eq!("\"\\x01\\x09\\x0a\"", "{:?}", non_printables); let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); - assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); + fmt_assert_eq!("\"d\\xe9j\\xe0 vu\"", "{:?}", non_ascii); let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); - assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); + fmt_assert_eq!("\"\\xf0\\x9f\\xa6\\x80\"", "{:?}", good_bytes); } #[test] fn test_bstr_display() { let hello_world = BStr::from_bytes(b"hello, world!"); - assert_eq!(format!("{}", hello_world), "hello, world!"); + fmt_assert_eq!("hello, world!", "{}", hello_world); let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); - assert_eq!(format!("{}", escapes), "_\\t_\\n_\\r_\\_'_\"_"); + fmt_assert_eq!("_\\t_\\n_\\r_\\_'_\"_", "{}", escapes); let others = BStr::from_bytes(b"\x01"); - assert_eq!(format!("{}", others), "\\x01"); + fmt_assert_eq!("\\x01", "{}", others); let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu"); - assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); + fmt_assert_eq!("d\\xe9j\\xe0 vu", "{}", non_ascii); let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); - assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + fmt_assert_eq!("\\xf0\\x9f\\xa6\\x80", "{}", good_bytes); } #[test] fn test_bstr_debug() { let hello_world = BStr::from_bytes(b"hello, world!"); - assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); + fmt_assert_eq!("\"hello, world!\"", "{:?}", hello_world); let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); - assert_eq!(format!("{:?}", escapes), "\"_\\t_\\n_\\r_\\\\_'_\\\"_\""); + fmt_assert_eq!("\"_\\t_\\n_\\r_\\\\_'_\\\"_\"", "{:?}", escapes); let others = BStr::from_bytes(b"\x01"); - assert_eq!(format!("{:?}", others), "\"\\x01\""); + fmt_assert_eq!("\"\\x01\"", "{:?}", others); let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu"); - assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); + fmt_assert_eq!("\"d\\xe9j\\xe0 vu\"", "{:?}", non_ascii); let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); - assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); + fmt_assert_eq!("\"\\xf0\\x9f\\xa6\\x80\"", "{:?}", good_bytes); } } From patchwork Thu Aug 1 00:02:23 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749363 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 10FB1C3DA7F for ; Thu, 1 Aug 2024 00:09:08 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 8FBF86B00C1; Wed, 31 Jul 2024 20:09:07 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 885B36B00C2; Wed, 31 Jul 2024 20:09:07 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 688F06B00C3; Wed, 31 Jul 2024 20:09:07 -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 496926B00C1 for ; Wed, 31 Jul 2024 20:09:07 -0400 (EDT) Received: from smtpin27.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 0C650407CA for ; Thu, 1 Aug 2024 00:09:07 +0000 (UTC) X-FDA: 82401741534.27.EB2D336 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf10.hostedemail.com (Postfix) with ESMTP id 66E1DC0006 for ; Thu, 1 Aug 2024 00:09:05 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="bc/eNROH"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf10.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=1722470882; 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=DDZUmJBGkDeLbeHTa4ItJaU+bWp3UTXEPx9OC2yXvsk=; b=p/399oU/9qhVc/60harmaXoxhOYKc7BSA8iu1LXqV3G2EWwZf8kigmxp9rhA/VoB9EXzVJ rjQmriC5ZwTUOFk1jWorLQVWjaLSwFdsS91L6MotS1NUDMTv/5j20CEpvENL9TMhm7TIJc gBBsgh0SVGYAoR+QGi62HkOYDFq/qyU= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470882; a=rsa-sha256; cv=none; b=lIvUgQp+2tdKdMmhM+v2l8+QudTzH/3Gd1AISg858e8BxgzssXm9FSEBwen+mnAjoletgL zw1pKMlrNUYVZQEj5YFtbxfrqZOP8jGuADMp8jcny7zbBRV/Ljl5904WnkKsL4N9mo4Qcp ofvviAP8g0HXiwqCr8uL9uYp7o2GAQI= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="bc/eNROH"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf10.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 B43D96246A; Thu, 1 Aug 2024 00:09:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4B979C4AF10; Thu, 1 Aug 2024 00:08:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470944; bh=ObSjAHQUm342t0TjAyXk2qDLNAOI/PmmwgaYCp3gBdE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bc/eNROHFgcs4k7xegrUX2OWcpX/2DX3vk7FyysAzBfTl9dfX8ivWOFAve1/cjUra oRImN5g1Yomayw/YQa+oYym8NBsywCwCNYuVIbpDLNrYrWbnHPLR7yBLYJP/g77vRH E6fzi9GyzScU6dukXdLhtwwmLkmUbfQM062rfD0eDW8fMcVt2b/Sy5bX7q0YzBak79 Qm3xza4QFHUrUVxe28y87Th9cPmumEGN3fX+a8Fq2yLST/M5oJQP2CodML8uPSRHUY HwNJ4AjfIVHyV0YI07wta8qyCJK9oHqeeXgCNYujyMGxwq1mhQ+dskrR8rNYuQqMU6 PazWlmANGc+OA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 24/25] rust: alloc: update module comment of alloc.rs Date: Thu, 1 Aug 2024 02:02:23 +0200 Message-ID: <20240801000641.1882-25-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 66E1DC0006 X-Stat-Signature: sfeb8zkj1bqqundp49pigwuednd34eif X-Rspam-User: X-HE-Tag: 1722470945-187675 X-HE-Meta: U2FsdGVkX19IJkDjyMA0gRYRcpMZ8MpkBJH1QkWv80tGDXr+HIumq+7it5FSTqHru1PYOT8PA/otl8FaAyAorsGI7yomAupF6Q60JS8GA0zK3XJ5wsY9HM83GBsqJVGku3S3ZAaR44cU+HlQx2iMweuOOSWFX1JU/IWmOyTdzfbHA/xdAu10NHMdyh/K77k+H5wX8ec6Owa4UJolwTOchqqSvcqhQ51+h+H7OEf1HGKGQlko13fee/1MnjKQudrEqkfLrA1obkjSe95bG1csZRKMVNdD0vpxOQZWftRkO582lPVjr6tO9OC8qyCFVa1BD4VnBRXymOrX5Wwv64upSQMbLTOIeQ7usS4fgdstwU0g5aPgiWSleAmmzL+Ta7n0qAAmgaobua2ML6Yp9Zumk5sacOvKA+LjzoSnFaXlgIngj1QPV3gV8q+cQ2FmrFuVdFtUpevJQUrUBJFc00zk9f4BfSVOXcPI4nTdjwlABQij0pb2kYtjl837YG8Er5AI/l6g4AwfKCMMqt/GFJN1NrPezKrCBQROlbVe9L1CMH7bqIDsTL9agPhvKzvF/jr6pooKk1GsoJJ6PkgUOm6nsLmHLoXwdUjsjI8oYdcjy0wVtAbFeyyX+jiOXN7qmcNqek87lClcAevria20c/5qTxPxhg/o4PUIxIFz0HFHXG7mqKiEi4y4QNr4VKiUoeUn1SeLhDSBmAot48I8fxPsSlDBK0Or+4wqHbrVzSkBu7gFL3S3fEuIsJF20RLiqGQ1TH1st1IHEuidIldqXw1pZ3XcS1zymYMX/UonfGuUEigW0J7jgCKraL8lBfeM+uzbRS/qST6fW4Mvi6m/C2eHodKv5dC6xVcumCMk+t8Er8NURuIfomwfdYRChHFDOT+1YP/Xffat4u6AguyR4psueQdVut0s0yf9DXUxG5zh/eNCBHxWlpEV/smLWObHD2mVd6WtTrkxxxgA62cnQY1 cGS9bntN zRT1n1hkS4OndNLoC7gHWzG+jxm62tF6W4Kicwe1bc1rdt5qI/gqGK5AWXfR7vm93tVYjkGNoYd2q8eGLx0aOpPLiAumoCSAqBAemSpNd4Yscg8dZPOaM9y5n6I2NScOz+WSst8SiPZ+5kb8B13XfCZRBwXyfIcMFh8Cy38+Kuu26LdGmBlvTByyCdpBEMm7fhLWYIOH4B9G+QHjW085nelzU/Jy0x8ZtPPusliH77SY9FjhHXBqmtjotEfjqvW9a0NWVCHbFGqzTibRfMNf1o8CysMAmJkCGmxV9Zen4Hbui9FZxsFoc+lI0Y/0ILy26dV7WPT1i1DBzX2uI5wzP++wg+w== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000021, 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. 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 fac9d3976657..903e2ba33491 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 Thu Aug 1 00:02:24 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749364 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 7BE26C52D6D for ; Thu, 1 Aug 2024 00:09:13 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 0E66E6B009A; Wed, 31 Jul 2024 20:09:13 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 06F2A6B009C; Wed, 31 Jul 2024 20:09:13 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E506F6B009D; Wed, 31 Jul 2024 20:09:12 -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 C2E606B009A for ; Wed, 31 Jul 2024 20:09:12 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 7EF80A0597 for ; Thu, 1 Aug 2024 00:09:12 +0000 (UTC) X-FDA: 82401741744.25.2B8DBE9 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf26.hostedemail.com (Postfix) with ESMTP id D5AFF140012 for ; Thu, 1 Aug 2024 00:09:10 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qqXl2YJc; spf=pass (imf26.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=1722470895; 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=XCd6H5wfXRSjlc5Hf1Hr7cVQkBFSeEHTm4qS8K81Z78=; b=TGYAZWrpNlubK0AIUKjEY91/sIqjp/1ztlv1LDSVS2WfNgqM4MFqL6jIDbGQ2dm48IXDUI NMWRwNh5OxI9ESR1OncfxEZC4dNGlcb0ABzNIZFwa71Lqr2wfzNxkB1CzYQp+bFyefIBa7 SoeD/3UUQvHMRXh9IaqJstiVaQa1rZI= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470895; a=rsa-sha256; cv=none; b=QK+NZcFKzwMcGkQ7Ofj97fuo/So9M695UScQiXmpnF72q4jxOw6p4vZxEHB4dt+AWN7Bln vgGFs/IpKDHVAtHhlsXQ7Jox8GbtYtBoIDAgx5HEX53po5iu9/bsxv/k5lbpgNQdo9Efsq E/IOiEa75r+28Wz93qy6wxjtC/xGsRI= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qqXl2YJc; spf=pass (imf26.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 19749626CD; Thu, 1 Aug 2024 00:09:10 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D75ACC4AF0E; Thu, 1 Aug 2024 00:09:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470949; bh=BnmAT9t/c5IIktW7mx1EDTKEy8RKB4RK+wsZKxEJOuw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qqXl2YJctV4+2BxtsudvILdtsnrDRujuYFcK21c61VUzWMO6s8gKoKdd6VeU4Zh2/ NOw7F1yFbCrIMM1ZZUQchqSucqHSSNIeGOB76yTwVyzMzP9fCFHfv5FQdktcziyCGc 7/XrrIn5Wr2cuYEgMu96XF3nvzAJKc0ULuQg9VontBVIBpcSizZfcHUOiK1O4cVeX/ zkpPIsldXC0oz+htxFFvBkvp5f98umynm8rZXHVYtdFTUdlSlMBihqDzA4YtnNTOlr WHJKAPxP9z8+9kdAcXAvGKj9CDYKdTHccKcEmTHd9GQPNs4MWOTLTmwIXH4mC17kUZ N0li3AXJWwPdA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 25/25] kbuild: rust: remove the `alloc` crate Date: Thu, 1 Aug 2024 02:02:24 +0200 Message-ID: <20240801000641.1882-26-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: D5AFF140012 X-Stat-Signature: j39chsnfndx636nxzig8ee13yfq6e7yz X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470950-692253 X-HE-Meta: U2FsdGVkX1820mJAASMhzv5a9YTTpicOEWRTA4soW4fzrV3ugVIf8t0PAf+RdPX7SviZ+rAYr56PFNax6Rhq3fDlhesNAovuII4BebBtZ10zmyCfhqRgKNkFKB2opFpidk0sdZUI11D5YoXwJ/ptGgUlAKirhEfIItRz+iv6sfPLcWmv4itGo5bpKUpLZ/vLrU+RcWgsH1v3pPpFUymrFUStgPq4irHBzCpJDPe3paRJlZwyZda8ln2P5I7A7X5gIOEXlce9n5TFWFY0WUvYJZwCSEkfNWIxteSsJOwFENGKovewGTbR+8PkrY0688BWWheXJET8OfYAHrCEFgCbdHfNJ8HizUdmQJLDSSJE11+5uEylw9XsIbXFe7kkewWw2RvzCPNoNwT0hmSHDYxVcbBeGvVPDpcSGEn4pBGU7r0BuDwonPWoN2Cg18Iq8oJLCVBzSwXooP3vZl0/ujfg3kpbuSjTEfndfNzB0IMmgJ407/9V9eYcaniTef97I3rNPZtetsSh4IbPyrtyNktIiAfcJsosIGFjPdl1w7lmRvsbS91pJVwlUonuO+xg3S3WBhO2szfCSdwu4tKeG1oU/eIaCb7JX5O09Uh6FgSxUaBLrD0eCQqZbdYdbdXOr+IXBxVY50AHf5I2J0Xn4nUgDqlLJcOhlnRnFv+Q7p0PBu0HwURdkKNNNcOb2b1EgvfwO+rEOphpenhcklWE4Ch0MuaeF5OBOU/lQYOSRnteE74kGoYT7HawAT+LRQIWLMmse/x05Jw8nXY2t9qttR468USpOnjweSsMIDqANo1mKyRFrKxF8p4Ces7EI9n9v7x7u5GM8v3Rqt4C4lxdR9NFgpAN6jm1KVrSAvgfikN9pBedfyErzjbcX37Y0EhqLDaCfnL3XdcKuj/IGLb/CnX/q0SJT/wtTBL27ic2IYBIzXvXLnZKXGGidld0gDrbha5ATxxmXKa38Y8R3zkNs5g PAxoHaX+ 79KsahXBah21qjORJOFy1EtDYpeR0cit9SN4h/Ghv+56tq6s6wsD2yonMfVSwplz4Cyn16DfFdtrRjiXdf2zTL41r0RhQ0yCdnArv4oHbMRQYLj28NfT+tNlcyPacjSrJQnNjzLqkc+x6a3VOkLsYfQVUo+QCQACtSbbUI0deXfR3EBskrXdCYJXoCjVsPUmrLmgE2VTNed+kuNsoGMiGYUg9DqVT5TXt30WrmEwJLDUJA8foWWEPQgvuiFC36T4AYq30nVo6+xD8AtnvqE5rEvGCIgLf/qvYRnKZi5Lab8bSYnZnNfXYpu4FGw== 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 corresponding unstable features. Signed-off-by: Danilo Krummrich --- rust/Makefile | 44 ++++++++++-------------------------------- rust/exports.c | 1 - scripts/Makefile.build | 7 +------ 3 files changed, 11 insertions(+), 41 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 1f10f92737f2..8900c3d06573 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -15,9 +15,8 @@ always-$(CONFIG_RUST) += 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/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 \