From patchwork Mon Aug 5 15:19: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: 13753710 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 2FC92C3DA7F for ; Mon, 5 Aug 2024 15:20:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B48F46B0085; Mon, 5 Aug 2024 11:20:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id AF8936B0088; Mon, 5 Aug 2024 11:20:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9994C6B0089; Mon, 5 Aug 2024 11:20:26 -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 792326B0085 for ; Mon, 5 Aug 2024 11:20:26 -0400 (EDT) Received: from smtpin29.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 01AD11A0306 for ; Mon, 5 Aug 2024 15:20:25 +0000 (UTC) X-FDA: 82418553252.29.53BE8A5 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf23.hostedemail.com (Postfix) with ESMTP id AD7E3140010 for ; Mon, 5 Aug 2024 15:20:22 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=VAqcutSL; spf=pass (imf23.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=1722871193; 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=AxYpsWo2EnhIOTGm3LdMoQCGO6y1NpWF1vV9URIPTKk=; b=CHF1QuuipbVDopNnBkD7o9asq/SpPHXsOfctnjHU0AleBiA3sKha3uvYGlgy5mN4ix3JtU RzwrfuyAs9iKtYRYJp5gOGup1dLdMZ8bjJBE1tkHM289EAk7/hTD65/qGKeyt/54gvsi4r wP1zjnjvU3nGji3ampfD+pOXK+oHqG0= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=VAqcutSL; spf=pass (imf23.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=1722871193; a=rsa-sha256; cv=none; b=Y731YKFO/XMfTLgs3uA1OuvbyJ/4cfZTyKx0bA7E/ZUAA6eiSguvwNeG6cwLjJFYCReDPA 2ofFMrfwrGU6RNaVsHEmltQdurllgLtRDLZib8C9LoCbBsVQLZworebswSopm1n4Yxx+l3 5sYezmlRsUdIzd3EW2MpLjgc9JzU19k= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 88875CE0B2C; Mon, 5 Aug 2024 15:20:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C6339C4AF0B; Mon, 5 Aug 2024 15:20:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871218; bh=bj2UZpRhWMoc+XVgxuPd+wiqHp6BzB0ewgAdFDBiTYg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=VAqcutSL+jtXhIoRiTSkMmZPCI/bBw3pmkzBP8y2/RKxoqqrgTmBCuv07L8Iry7FG NT2oRfpAarApvL7iwz1AChRLNislMw1SRumZx0OJN2RUOInTDpwna/9AudOBqeXaas NtiHLp1V7RyLar9j3jOLHHQY1wCFnYmRj7XndwW+QkisRNcEYP2hodWSAE4U4lkJ/k QF/m40DR9nXme8xAsCTSNfMtGHmYASh0XxAyI+bL9DFk9aqL1aVsr7+7xGl/GL/qN/ mTObrcHiOO3uxo9FZ5CEIXnOXpJLv4ANJ4VS8ESiTb/M3LMiILxa7UllD0tlUkS/Pc 577mQVpjXuo9w== 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 v4 01/28] rust: alloc: add `Allocator` trait Date: Mon, 5 Aug 2024 17:19:20 +0200 Message-ID: <20240805152004.5039-2-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: AD7E3140010 X-Stat-Signature: xa5istskqd8htcnyhag81h9dye59sz1o X-HE-Tag: 1722871222-719163 X-HE-Meta: U2FsdGVkX19+4SIJOr+pNTogmEG+sa482QEwkskigHrCaj4q6mlBE524lqdIqYtbFeeTA8moOLhFBvkbtLUqVoTTWSxIJcRqBJV9mii2JK6mJygfDqYRxvh6lCHvVbdb3nH/V+gXL0og0ZgatsmyJ0NJdoYVEkkudIbd+1xsZluG3+42hSk3H5+GUD1E5Y7ZIh8A5q3fxuURRFH/Qk+Ll/O5ptP1Jt/gt2tnIHhQKmy8bSTyLjWAt/+p9Fm1vkmxxaT4VkCX7tIgNeG7cXvtX/kE3rQFk5ahEGelMXeqEH+3ET2HGzLf20jtdDWPzQTJxdnBpTlZIol+tiN17SuyYYbusB5Um45abCfZal6j5mMEn5VEWDfThuwnbiZKfjCKqIEmB9o7FMYx0kaIsKDuCCudhKLQ2+IAvWhR7/M84ia/micihGJKrhDR3Bt/iYEx8fG/Z99upFyL/grezQOvTCgxSrXINxPFn4KFRmeYLJpr7jVoh11y9pZS6aWlmSOzec94E6AUY6YSaYL4qy5PNM2fcbzfYt0+TWhwMYIKYbrwmG6iGnkxPqQKEqhJXNJfL7dlqVFoFeldGBy3tBgnV33UqNXzs6HaOpsTVY83dZF0o+iuvC7ipkYUtLVyZ2Ml5t24TzI4dPOz/UfSOO31/FrnPf8xi4MFWmaCRXr7C6IQDmx9f0dMPP/UdGfl9RaY0J6Q4wW+iR8Wh+jq/oDAf1e1GYWvrqrj2kC+TjyENOlF8iNuV9D1nwAePT2o6oUL1kNyki1IBdhO00CGGfDokDVwRA+OGNxBAJnWT7JhwI5ZmPPXUbd9j3wAL4lirFjaJetIZ6QSEXL37VFW9dM/tPJ4XB2zgTkmXC1rW1Ci1Q/k4Wq3SdJyyg2Ev9WxablgcxNAox+TUa1a5GzA37JmBM+uT+72P9NRhgLYKyYkLPg4DqAus5a811Od6FPIa9n9M7YnLLiJ/obcYFK1W8r 5kQPrYa7 uUcxDdh/bwdba2/lytFPMikqp/LD6d9aQeaXTAWcQFXXolW1ShIPfGUybbp/zHwlOjtVhffnfjG7Bjy2aKnW9hlTZ1Duk9WSIsZDMVA0sT2cPG3NX87AdDr+VolhRwGZuM1+pvgjRf8BtQqQTznfeAnJT/K9+H8F9B+rsIojuKX0Vs3C6JQy9zNJPzdxPU6nBraaCNrvSwxy9VIGPb3sMC1yUp4RzjHx8Z+AjcWX4HlOy+rgVpWOSB52q73oLMk9Gl0ouSt7QHhWENXmSVvtO5EeqfQEazqtoYxJA7kfgNaBZjrCLX7XJRpGmrA== 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 Reviewed-by: Alice Ryhl --- rust/kernel/alloc.rs | 79 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..8a71a589469d 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,81 @@ pub mod flags { /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); } + +/// The kernel's [`Allocator`] trait. +/// +/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffer described +/// via [`Layout`]. +/// +/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on +/// an object instance. +/// +/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design +/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind +/// of `self` parameter. +/// +/// # Safety +/// +/// 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 of the same type. 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 + /// + /// `Some(ptr)` must point to an existing and valid memory allocation created by this allocator + /// instance. The alignment encoded in `layout` must be smaller than or equal to the alignment + /// requested in the previous `alloc` or `realloc` call of the same allocation. + /// + /// Additionally, `ptr` is allowed to be `None`; in this case a new memory allocation is + /// created. + /// + 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 Mon Aug 5 15:19: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: 13753711 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 B8C1EC3DA7F for ; Mon, 5 Aug 2024 15:20:31 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3809A6B0089; Mon, 5 Aug 2024 11:20:31 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 32FE46B008A; Mon, 5 Aug 2024 11:20:31 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1D12F6B008C; Mon, 5 Aug 2024 11:20:31 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id F3A706B0089 for ; Mon, 5 Aug 2024 11:20:30 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id A62BBC03E3 for ; Mon, 5 Aug 2024 15:20:30 +0000 (UTC) X-FDA: 82418553420.28.E303084 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf17.hostedemail.com (Postfix) with ESMTP id 5DE4B40030 for ; Mon, 5 Aug 2024 15:20:27 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=X77UjPV2; spf=pass (imf17.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=1722871167; 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=Q12BLmKhrNaYMBS6KUGNvGkpze+WrX8idHU2MXPizUU=; b=Zil4j5Q3HdM4vDuNzfboKlacrGWYS016dZlbcdkmBLEHGxNTzqI7Aw7tkqzCaRIfzdYgcm +9o3ITUfqHCqTnrj+J6kuNYzsX7LevstCo2gQWnwBzF8Pv1tl2IIGZeKDZl5WsPPHFlkqw vieY0VdfpI2XHK7h8WBMrrNmk9yx6TM= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871167; a=rsa-sha256; cv=none; b=vMQpw1gKUTZLFYnuCxTJLcNpjssGhVOniKAx0ZCx3UKes7CB4xLqjDjojIES1u9lWbtWvg Aq3gZAZsGX/HmHlpD2yVRQZOh+Iql6t7woAotl3iU4Uo3Qky+NqvWNpEJdZQHGv69wTJke FgxyyjnCG8AeJsmhbfvOZnCcu0mLl7w= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=X77UjPV2; spf=pass (imf17.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 2E15ECE0B2D; Mon, 5 Aug 2024 15:20:25 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 53277C32782; Mon, 5 Aug 2024 15:20:19 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871224; bh=PKEwZd3yHqQQqT8mEHKKvphM2Pe67I1NR1OPtC0T0To=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=X77UjPV25pEFDWaPq84AeyqAqV6uAdZksZPYQUqppUCz33XeJi1l7MK10KLbf0tbV 1gzJyR/gqXeboD6/+PfujdxjK/K4YorMQKV2i+6CtJjJTkdm31OPPP4WGDsy4wM/wE iCsc/dfVvk0YM4EQNp02su+KeYPCYvQp/Qz0O3UCPWA81wABOZR3++cXO71S3jytsL 3j2+CK5sJAdYdHLX5ornikWobgm9ufjXlj46zb+RBB1jQm+QeqMSgCABFndl+5xVe8 aMqMS0NjQ8nrvu61TGZ05I78vnCyrNNzHV9terWU4iL/PgCi/NJd09luI4ht5nHBGL uSXgPuiwLcsJA== 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 v4 02/28] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Mon, 5 Aug 2024 17:19:21 +0200 Message-ID: <20240805152004.5039-3-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 5DE4B40030 X-Stat-Signature: s8xs4zr5poeqr1dpmd9hfgprjbi1n3xt X-HE-Tag: 1722871227-248470 X-HE-Meta: U2FsdGVkX1/Pb8u0M+PbAxo2KLWE5nGWMJ2d93A2rpIYa+rXXb2Z3yE9HsIVSESy6soFvw4IjCZi1BFgJdAtL7rHmFBaUPnLQairszRdLPlCGdIPi01XUohGf7ivHylbyJOAIZYZkHxYwYF7JqE/IKl4kvkVbflPXluZ1InW3VQsvRZkXSIGC80KzHrPhGpDgaqZBmZEZNQY2ZPqSIxdXbVrmLbl+bWH0+aZrZWbnqWcGzKwOJrzeONooskEs619e8afX5kCkdfBv2y0jCF0d7eYQ65WXt+niEiid/wZ66WZdwq1zgAnUHj7FI4mCrI5rK4eoElTaRHplP9QjS62vfNGUJdw9lSAT0vZoU0ucUY7HAcIybqgbcl1rgvdUmQFXcjSrpmM680Ke0u9f5J2QOnVHglg/XwTr531EbqlxGV0Cna4Xyuauvd4Nt98cFzMNDqGAs1H9bBWhc8g7cHF/DCHqk4C+4BkfkipnaHDMYO0kmWf6gH+/sll3+NQRH0ywr4SMkv6b/V4cVctMLz76SI9/Ibv2w4jWThvT7uu9XUVFWFeebO7ADGWA0f5Z4jxevkzxlUgMNDIaCHtRmpSJWh3rzz6t1FB+BQ9fnsQSBvHguZr95VF+6nB91H1I13XRfBBfKX/W+/XdOPe6GXfAPqrooh2uGptYLyvour4y0LLBx609wKy8XOslWQMxa6jDihTVN9hnr1X8vTfldAENEdZpT5HqsBggiimxe6NLFjGaqWIQldaD4rrS/2orZi1UfJa+9GkUL8q2LmqG6zGoE8LCjp0IAE557BkTG5C+Ozqt5qjDGBPq3G05ixYKDtIOfbX89LUlDLumLNx7D30yufxgnGYbsm2lOMIHvys8DZ28ZHBTmwHkV2ABE/wmFRXKwACtBiIC0XI8AmI/JMWGhan1lVIuivAaS/gFumh0Y9AnVQKnVHD3OUwh7xaG/81Z/nm0pKVdWySg5uev2d TFDOoAdY Rd7pIWuS81bGtGDMspoNr8MVALdK1BqVXF+2fgjGBG3IXqpTGppVTRZP2tmy1QJBMKu8Zji5kvrPvQQaJu9EdoJJMfvd0dgJpP/Mig52es5/xdjBMo0zNo/EskwHKcYT8Iv9IhMVj1CyuoOEJdMRJuigbKH635PwZ+zy98XqaJafpfO8jpRUmqLGMDAonc96TJfCXagYNBen9e4t8GFERkQdmdbc0kWtoRkcwYEovUV48rUiAaAIxrMB8HJo8Ey1QAlp4Jd9zcyn15pFXJmztTSvMmbsLxDVkSxV6Lbg58F7cD0CucIkigRNR3ORaA4a+dpa36whzS5KZVusQyIGlJZwunXrJKq4H8Mylpy+8hq+V8aBufMiXlC5d35IzvSMDgATp X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Separate `aligned_size` from `krealloc_aligned`. Subsequent patches implement `Allocator` derivates, such as `Kmalloc`, that require `aligned_size` and replace the original `krealloc_aligned`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/alloc/allocator.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..e7b7eba84acb 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,27 +8,36 @@ 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 { +/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. +fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. let layout = new_layout.pad_to_align(); // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` // which together with the slab guarantees means the `krealloc` will return a properly aligned // object (see comments in `kmalloc()` for more information). - 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 Mon Aug 5 15:19: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: 13753712 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 B02C8C3DA4A for ; Mon, 5 Aug 2024 15:20:33 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 273346B008A; Mon, 5 Aug 2024 11:20:33 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 21E526B008C; Mon, 5 Aug 2024 11:20:33 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0E63B6B0092; Mon, 5 Aug 2024 11:20:33 -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 E4F8E6B008A for ; Mon, 5 Aug 2024 11:20:32 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id A371AA6B06 for ; Mon, 5 Aug 2024 15:20:32 +0000 (UTC) X-FDA: 82418553504.10.1C00A22 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf18.hostedemail.com (Postfix) with ESMTP id E619B1C0012 for ; Mon, 5 Aug 2024 15:20:30 +0000 (UTC) Authentication-Results: imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DAEFhR9a; spf=pass (imf18.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=1722871170; 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=7m74TYzpgrLgZZopJEzoEqwhboNjYPP/WAgufgI4d1o=; b=6mnZfiGEyONUXEXH3HZL+508r5wMV9PiNyS1aL6l0nsxU16oJ7QCdKIM9024G0Ykph8IIC FEqosz/TBIHzPdSZsvN23UOPy8Ss1ZE2L90yzji/vS+xYHY3YMi+K3RS2Jw+ir5MqrPyOu 1qmh0iRO+tMRrfFCRCmlbKOXV8SJJdA= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871170; a=rsa-sha256; cv=none; b=OJq8ELsX8U6i8JMWDSOFCFKngSINULfC9iJP13wyc4xr1sRKBzq6DD9c18lRCqBoLV+dCx BqpT6lESNpz1ixtHG7nx9ShRRxpwo+7PhAMukHw/Wp51RT6dKQOs4lDz5n3L1aNmNJzUTs GyH15FOYbkx3ghKiQTXoDMxWX82+RVw= ARC-Authentication-Results: i=1; imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DAEFhR9a; spf=pass (imf18.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 27A5A60CF9; Mon, 5 Aug 2024 15:20:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D8AE8C4AF10; Mon, 5 Aug 2024 15:20:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871229; bh=OtT50VkQ4IhBDfNNG3JPXaxsaB7mAc0R/AyuRkhis70=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DAEFhR9aVevAgqQ6ElgV7Cw56P/HwNiDuiiitRoBj9UULByi45M7SLaTEVX68yLmV cjn4/P0ycimIRj27eLfZXkyB/YZuTg2IiwHFXQYw2pc02ImwN2/hwReybehcWo5NQm Nk1muDVH1Iey7GlX6fYVgMS55urQaTDSBArGzS5Xws58PEdKZFHHS4+7e88i2wfgU5 vCGS0oDPXlR3Bzx/VKH7n16V/KuUiVLF+GS2ldj6mdojwW5fa5Wz/hhvYcyOHnlrw7 q8jpo71RaebkuQPg8UrUT6y6eJEL+jwkelqbO27EsFg5UIXz5QZPEWviuJgkEctN5M RtGhnHltjm3Iw== 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 v4 03/28] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Mon, 5 Aug 2024 17:19:22 +0200 Message-ID: <20240805152004.5039-4-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: E619B1C0012 X-Stat-Signature: r1zjaza73nkc9wb5oif9s635kkrxpk7m X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722871230-443545 X-HE-Meta: U2FsdGVkX1+9pzBU5P1nwYSdNQnMFSSw/4II92eLLIwF0mn3BNz01y3Utk9bCF/nN1kmhUrL+WmYrlohKe5L78oEehWXsiVddopwmaFbghr4wcu5poqiuDMt1SWaUi+8TwumMPFmdYS39EkuaTC8rHS5CQsIzuz6ZZFjN5DVY2hx05KP90A58jbT0RJVk/7boPuylnsZgWi6pOVIygijFFYe0pzEjCOzpm47TKnn6dKpbHrj6DB8yFIgBdHREnjjVgFVcxfbr8v1egXnEc9C6HByqjTtJU8bz8hYB97sec1zOIJcXiuM4e5okiU2dNaXca5d0tW4fQl7HYNXbk7SHT1jmIf4qni4+t2je9vj4FlS1M2dAjrPbJnId1rKZjZxEmStexLjcMacAOqaTe5iuV2D5erufuD3xeFH8fZcCF32q/6Lm91sdtaVcxnvh3rp/i5YkpKcfcrbpspDSHcOj/TWyo6etyQgllSemEJwcJMZVsgX95jpySiBD8Ka010bv8G50nuw6mhGT3hULLI6wgnN93Tmr1qY6M8vzV4ikcRrczh3G6FFPho+8njRviqJaMUiriBYsHoN6zwQHJ9kK2hDPx1n5gTEH+5I3AqnQbPHFDb/OOBumLfPPRPKkU+/VD4Qc7S3K6F5lnr1hrK22IeZkzf5lHGSekf2gqPBuJtMQTxPATkv1Vvvuc+3KsSOIEDa8CZK3tTM3dwuCIEUzjueG+bwI5zns/BgXTl7ZacEi8P46owFIvZnpS5Pb7TBmzMf/fQFc7cGvHe1wlxdI6wAchOohPI7BDBwVX0yBr/EmAzvhYtZDJc0+28xGgP0XvJ+9k2MiRYlauGVNpjlHNA1d9KssjY6FINBnash5vFZ4QRM688DFuMGnc1MlGJSi3S9iw8+6MKkNlrUFCCcXbY6u27mc7Ve1WJUVgm7MS8eajeE27H2o4BrDlvURL+94YmptaBKppyDw/La+fA rvakEphg s2umwUdDIU56Zi7yIDddG6C/UeDLn/ixuzvJ+U5IxUcoisqZXZHpiOTCKXxMgQGddWHDVZTfOWxbjMH5KBjZ1MDr5QmuKvp2eWmawxZOFvwdtUOP2JEmBaED0Htz7tRDRNRcSYSi4Wf1NKOyEF2apJ15pNa7qSg1cU5KC5QA479slxNTg/RLDBIRnA0onOkArxslm93KE8pER3/w/UREpAfxWW6Ljc0zdbOoghrBbUI6ZEqFNy9teDRMYK89QwkbhYPsc/UdVhkwqUb2oRLwlP23B+mWzCK3BkRVAip3/QAjTen3mrOcOdOs3ud0lG91oJ4B7xcIcpUZRVqy7pKFgjxW8V8RvDcAb9Gxn X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Subsequent patches implement `Vmalloc` and `KVmalloc` allocators, hence align `KernelAllocator` to this naming scheme. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- 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 e7b7eba84acb..2c1eae25da84 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -6,7 +6,7 @@ use core::alloc::{GlobalAlloc, Layout}; use core::ptr; -struct KernelAllocator; +struct Kmalloc; /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -40,7 +40,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. @@ -76,7 +76,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 Mon Aug 5 15:19: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: 13753713 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 8BB29C3DA4A for ; Mon, 5 Aug 2024 15:20:42 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 15CF46B0093; Mon, 5 Aug 2024 11:20:42 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 10D7B6B0095; Mon, 5 Aug 2024 11:20:42 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id F3E236B0096; Mon, 5 Aug 2024 11:20:41 -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 D7AA66B0093 for ; Mon, 5 Aug 2024 11:20:41 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 9F0261A0268 for ; Mon, 5 Aug 2024 15:20:41 +0000 (UTC) X-FDA: 82418553882.23.61F3B4F Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf01.hostedemail.com (Postfix) with ESMTP id 50B8240009 for ; Mon, 5 Aug 2024 15:20:38 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=EMxxVbqZ; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871178; 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=oIfNG5+EAdgpQkSpCBi98MFR4NgYWnX2/c6hwf14RYo=; b=mNltc4gbX/6cURniUSptEcNq+Qg8ndRzKmierKBG1FiNlCvCK13CnhMVz29bbMpOZl432l W4084V0CZ0ZmC8qDxzvf2X7NQSJrGrE51dyQ0J1T+XjvpkROjfULRahx23x+PmfWo9Bddj sAuewc4SER2o+tbGjsKwe4df34naFSg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871178; a=rsa-sha256; cv=none; b=06AU4uYcFijwZ7u40yo+tYBaZrEGUuD78114InTI0T4LVTAATfn3BwxulgUR9tKOVkk0KV I9NAQ8cIgFa+7huk2rYN4ejAbS9HhRI3m/ZN9X3cgiJcVDqhtAqc0OCjXvnI5SqRNAr6PN DWxha6EouSgxgr/f3S+0whLGffRIUSE= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=EMxxVbqZ; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 2DFB5CE0B2D; Mon, 5 Aug 2024 15:20:36 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 697CAC32782; Mon, 5 Aug 2024 15:20:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871235; bh=KUN3egAY7JyTXEWIOlIzv3zwwD5pg50NL+IK/lAWQ2g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=EMxxVbqZsYS6nje0qCRhq8ZjYYic641hDJRMsjp6Pa5Ba7wKckgxEzzaVkWT4c7E4 tY9hyufAZRqbEWsqp+jP1c0nJdb4JIGFs6/3mKu6g0HwA3prX2eDxZWIHeieyQ7zkw msTYgDTMoxrHx9Kfdysi8sOAVZmA8GbTMIvk/Gatky1A38ZHuV4WLGPyEQIChmxeM/ sdjY4dYgVjDkpONE5ArmejxyhKkv7F8zgYza4kcdEJpyQzUSNLaPCoiPAFpq2MqJK4 s5qsHODvwWTrJn3dJcGxBsVJWuLDQ9HO9Ln6kp/S5ofY9gnIuFimqfJCsRSx9VFpSO V4zwpKrFBpwrA== 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 v4 04/28] rust: alloc: implement `Allocator` for `Kmalloc` Date: Mon, 5 Aug 2024 17:19:23 +0200 Message-ID: <20240805152004.5039-5-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 50B8240009 X-Stat-Signature: racf8pgbxmxmnq1pham681naccaf9mbo X-HE-Tag: 1722871238-325011 X-HE-Meta: U2FsdGVkX1/Ph36oVe/yca6ER0UhkSVzddx7Fd7BCr9f0Ne6pzvB+u6ecl4rB3p7F7odqgn5FATkhgy/fy4ivMpg4wIdH/MDtD9CGanfRz5nD08up2dbw0LEmseFpTaGSmSYjjy82wXGcpCWojh7H6bDPtJTMjmorWO+ngXaVGRa8PPoknh+J85xsO012CP6kLZJcQTIgtBmoObvlx1pDkms5DS9TbkS5Ds9eKCN4wPjFUuYK0kGCEyHtmSPIoPFZ43ZNAfueZl/csYezrT4OnYzW7QiJw+tdZq6txwe+G2OTHPmUcFqsGbFVB1tYuKFqWFEgPS22K6cXo5ulKPeAFgKLI9C//jVY3qI8AezR5W90rU3Zw29l7Es4tPyH0wjNH/7jqsPystiXbqYgZ21EGI+8aHcieFGbXrSTmxYDaazZGOLQUMf3iTQhqhEB6MwvXDJGczkTst4YHa5mbv0Ca1D0RXcXHAleBXLRV0nQ1xL3B+W2WDHyH/f5qyj4zCEDv9flvUstGPX3zrvXdVzIpS3oH77NuPndf+uYpH4UpVobsDC50BRZrfZkitmHahDBeAJUc0tjFsLjRgqzM9dZ7oojvUExk8XAJ2k3CMJhVgLQ7DSBvwsqEr/38Ww1ugG0ExIpPNz+JdIUjxpRBlb8pupDlJt+TwSOj1DKPT/BW1pYEMHvWHbUGoo4eHUnCvf4LIf7OLOTJDTOGttgaOcrb/FA8ue+g5F7mJXIfwA1VdbzNoWuXP0D1r3DeTpi8Gz2N+ONZpeK1pW4PMxJDOnUIStMWGU63+wp6dU+DC8+40S9fFRGm8VeW+yzwOH6l7BX4zD0APn3PFiqZqMRQqlq+6mvMwOcNXse1LuiYmju7Z4oqmT8zKA+o+ic1Z/hgoYxei18nKWdArKDFVDuNCM4zR1rI4I4HzaPGnq26R2LKNVtlFlLvJ019wDkefc41Y1UedoXyv603wjxJjLuE1 zatIFr8l x/Dnz5aVAxbLuqD31c13NBremm7TCV5Cg5PDquay/1uELILHFEDN9+vr7ceMzM7TendXUqGggXwrYOp3YTZTHwzqkC06Dpk+0Q5L5kkgTPYBDA1aeevoRSDpfgyrp+fGKFFgOcaAzA+fksKWuuo9qeuT47lWcGpZ7m47c24iedlIECR6DGgQw8yfR8/Dbz8IAy2pbWBfERIB9kFZauJRDksUUf9nAewZm8Auvb5fHNOMoI7Co6oC8XCni53wQY1oCAbUB4CAVOXdWso2PrQreUBQQDfzUZacWNi4LF8YUrgcAlvuUhbhsQGBjqg== 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/helpers.c | 3 +- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 68 +++++++++++++++++++++++++++++++++- 3 files changed, 69 insertions(+), 4 deletions(-) diff --git a/rust/helpers.c b/rust/helpers.c index 92d3c03ae1bd..9f7275493365 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -193,8 +193,7 @@ void rust_helper_init_work_with_key(struct work_struct *work, work_func_t func, } EXPORT_SYMBOL_GPL(rust_helper_init_work_with_key); -void * __must_check __realloc_size(2) -rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) +void *rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) { return krealloc(objp, new_size, flags); } diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 8a71a589469d..bc01a17df5e0 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 2c1eae25da84..c6ad1dd59dd0 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -5,8 +5,16 @@ 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 { @@ -40,6 +48,64 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F } } +/// # Invariants +/// +/// One of the following `krealloc`, `vrealloc`, `kvrealloc`. +struct ReallocFunc( + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, +); + +impl ReallocFunc { + // INVARIANT: `krealloc` satisfies the type invariants. + fn krealloc() -> Self { + Self(bindings::krealloc) + } + + /// # Safety + /// + /// This method 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 Mon Aug 5 15:19: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: 13753714 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 9A050C3DA7F for ; Mon, 5 Aug 2024 15:20:44 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 37FD36B0096; Mon, 5 Aug 2024 11:20:44 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 308E76B0098; Mon, 5 Aug 2024 11:20:44 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1A9FA6B0099; Mon, 5 Aug 2024 11:20:44 -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 EFC136B0096 for ; Mon, 5 Aug 2024 11:20:43 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id A95011A042A for ; Mon, 5 Aug 2024 15:20:43 +0000 (UTC) X-FDA: 82418553966.26.6B2ED32 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf22.hostedemail.com (Postfix) with ESMTP id 1BC33C0006 for ; Mon, 5 Aug 2024 15:20:41 +0000 (UTC) Authentication-Results: imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MoML3ZgK; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf22.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=1722871192; a=rsa-sha256; cv=none; b=SUmb9HF1dbmSmGZNj855A2JiZtz5WcBoERyTp/h9O03zW+3HLLbN6HB7DWqY4V4dZ2wTKR QxIOgOZ1J6RgE3Ml461TMthm0IXk2r8TwiUxllN1lha9b1YPsj0EYk4ErAYY4jphQwEY6L 21U4cK4JauHjdAreQKq8WMletJojLYk= ARC-Authentication-Results: i=1; imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MoML3ZgK; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf22.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=1722871192; 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=1Tl/yfknUaCdVxWC9+TOlAZFtemlmU3kI8IoOJXIu0A=; b=cqfnk4gMSSVoq4Q1pddOLIw4tr/Lzpu2KzDXqCtwH2y58FsHBLePpQGNa7vRuNNB+VEOve wvjYd8zVoV4HtNqLloKfLdsTDlO+bLkdvp0mYyaMuC7Rgst+4fxnVAJd4W/Q45B0MU7mE9 w2uMzz+9Fo6wE3yB7stGfmXKW20VgwA= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 5D1B260C8F; Mon, 5 Aug 2024 15:20:41 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id EBDF7C4AF0C; Mon, 5 Aug 2024 15:20:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871241; bh=/7W8GCJx8ZaHy6t5I1ObMJj1vrI+veTwVNr/WbX4NOU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MoML3ZgKxFmsuOSbgCE56/itM8cvkuK//0MYyC4C4aunRsn7Dl8fWhcGWz2EqaJyp iHmE9IwsJtEQ+EHgu7FFHPV8ZnWnUXwA3+lh0gbW7Gkz97Saj+UQ1ofrBSyD+ZQUo3 pXNgjDlKvZFkzNmoyhI7ay9CSn95HVw7vMzY9GS8rJ39uNMYW0RinE+hhJ369gKnk3 K2RjcUnjvR1xVZL/IS3DK/iAjMJ5gw4T/18OQCFeghsNoP9FzgX2br/uRV43bDHpMv jIID+fqZFGd148UqPzOEokjka8CVFv71Ml3Ma+1USIivms//SQzAIrG+TPd8bivRVa l2P/zx6yd+lAA== 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 v4 05/28] rust: alloc: add module `allocator_test` Date: Mon, 5 Aug 2024 17:19:24 +0200 Message-ID: <20240805152004.5039-6-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 1BC33C0006 X-Stat-Signature: 68bxrgcsgbbuxedeynmzym5c9hhjnb97 X-Rspam-User: X-HE-Tag: 1722871241-144 X-HE-Meta: U2FsdGVkX19DwwG8SPhAEXpbdleztTeOWSW4l6PfX8xycKyCvYxG+wQEtXeLwhXIxJ722MuSrApJQTJ7KvpS2R8xYJ/6xEW0cc5Wotvnde2hqiKTxmCmcdaJfToFYQPY3OxjM4Bm6g5L48Evv+L7ZSZcZ+jeUXhB2njOS0G0YQYTr+5pMTJnPiaX201aElSDeAqyxBahr6ANWjYkUxb3D8hxq3XxGazEFU5B0PIYkCspQZRtbBop4c+oZLuUTs/4aflCVIAtA95raiv9fGWOeEk2oS0g3/QeZ9bII4oK+EyNZWxkLJSqJcm20FKYXaf8pkVOb5O4kTp14SsBalAgJF66TtwQr0it28NahkYnUIDsePrOjy7HBxijSD6W1SCKJqlmEIh1JnnJYJ2gRxK539lcPqRkN1bLzPN8ZO7g4MtV0qsU3mkLr6bgQYKmm2gNck+Jk3EaiPcro60YMsIMRu7pAVvENLNOFovnUrlHBXhACk7MpLUNNcCbdmVISNYXUBiRY8pQiNBSqXpkMB32jIw7z9jiBCPznvlxSx/r+qNwpVv0IcOq/KgfiG5FbRBQZ3weasXmVNPVoWjlVjIEEGcQ/UZtglvdRGQoEOu4kasg8271+Q0WyB1aIfWQ65bq96XyaeLj3EW/OGUgd88b3GVa6W6z3ww+T8RZYZQhZFIdf6mktFvSZz+QGHCVcJnPahhXC6OSP0+50EB72jstjik4g1W+JtqQvUKJhlBi8GMbIwsPrKOc1+Cm1pj1rFwWxfVKMcOoalXB0S2gX25BOAaa963NO87040d6zW4XZ2smDOtB2TorY4Apohv8uFgeKUCpdA15Q6JVNGlhOcqRIAW1ipnooO7csM94iG0pkhZqoQtUyS2zVGtE4VfbRPculBukwD/chHR122D7/BR3zDzw7YD1VqmayDlB5TBq1X9BhAw/z4jhI/j5taiRNNb5NYIdEP6gRBdaNYzPU76 HvJmxbtY R9Um66aiQnWKPmW0P8C7nmkzOvSGX4O3nR52/FMWydfeQ5rjOjhYiXb0x4NEWmfof4qy/kAhGLkTwC9Dgx0IBwQz/YH+AtDic3O6wQODlx5SBhbXjX2K8ksBDI9yrLnvoaJA9JPuzQ+aT8FR+PSFziPRMritKQCKBGC2eWAkD+MNrchtXWAFxKxOpY/vdeKjsIdyROPTGpgeYWBA7dL+aOLOB10Yy0RJe+K4LWnwYonupvjx8v7qOoe2qkRUpD+mCyqUwCLE1xHPewri6s6yX3FzfTRhO19sCWkF/yAycWLbf+oEF7mVgUvoeLLRbmjTMqJBpZeQUWqKPEboko+mEwWLPtwsbb7GCkZS6GzbIQ6Dbq+qoAo2bzi/MvHTZVS5s6W97 X-Bogosity: Ham, tests=bogofilter, spamicity=0.000009, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `Allocator`s, such as `Kmalloc`, will be used by e.g. `Box` and `Vec` in subsequent patches, and hence this dependency propagates throughout the whole kernel. Add the `allocator_test` module that provides an empty implementation for all `Allocator`s in the kernel, such that we don't break the `rusttest` make target in subsequent patches. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 9 +++++++-- rust/kernel/alloc/allocator_test.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/allocator_test.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index bc01a17df5e0..942e2755f217 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 Mon Aug 5 15:19:25 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753715 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 5BF8DC3DA7F for ; Mon, 5 Aug 2024 15:20:53 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id EA45A6B0099; Mon, 5 Aug 2024 11:20:52 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E53A76B009A; Mon, 5 Aug 2024 11:20:52 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CF46F6B009B; Mon, 5 Aug 2024 11:20:52 -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 B187F6B0099 for ; Mon, 5 Aug 2024 11:20:52 -0400 (EDT) Received: from smtpin04.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 562F7C03A4 for ; Mon, 5 Aug 2024 15:20:52 +0000 (UTC) X-FDA: 82418554344.04.16F6B92 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf02.hostedemail.com (Postfix) with ESMTP id CC4A080023 for ; Mon, 5 Aug 2024 15:20:49 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=oXd667Z+; 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=1722871220; 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=HAWPC78t7ZfsguX4kMtAamoZNbSBLp7VjKGba3QNS+c=; b=Al5ZvdYk87YkBlcr915OqG3EXTW1NjwBdnY+rAVrs8aeDqLMKUQlaEW6xHSe0np39zu6da jn5nh4JB26s5CKPxne6vHNiBFH1GleQGDyTJmR1/+8HUoUJOuqJ6DoP8siBzoKg1JDQ1/p 2CChn0v+dEKefCvqKQgLsthV8fssDD8= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=oXd667Z+; 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=1722871220; a=rsa-sha256; cv=none; b=PIIztRKsy8n6JdLUUefh/jAO6PAESyM1U+3JHNwfkmP2lkWkwKBQsCGGydkdewtnZnosQ2 raXxqxJKTVoozZ4sh7pkXHcyQR1UBI/pDnV6fr6B/XBYPoa1e5/zGx+fvKLg3+IeOxQPcq FX9ed8gVsUtwv1ZGSZkJ9NZyBfh1Ass= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id F35E4CE0ACC; Mon, 5 Aug 2024 15:20:46 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8143FC4AF10; Mon, 5 Aug 2024 15:20:41 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871246; bh=pL/2tk9r+RNw9Wnwj5An+62HaTNk3XqGiHLSI686pwI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=oXd667Z+v76rsJOSJiwugYw609RU4d6zvS4IpyxU3I92MkwzAqckdCues4v2T1H3A vkNdhCTwWgRMUDvgFaBOa4CrrpzOesoJFqdWJ6s5Ur+j1mSjOVvnC6CHSRNSy02wF8 1vz1ux3aD2y8DiGsV6Qy6v9tyQP7p4fpsN4M8C4TPWzqAxiQ5Ghaigs4Ib6+QGFBDY HwBY/mF2ukc7pbEUUFvR6HJnpCx4dqW2N7+r/MBeru8bfevLcarBnon3YJlxnqLRVo OFkXc6ZGL7uSiXg29DTUz8afCaANoREEuu2D9NqxQ8XEIYAb8hSoHDax9s9v8CgShz wB6sBGnyImjxg== 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 v4 06/28] rust: alloc: implement `Vmalloc` allocator Date: Mon, 5 Aug 2024 17:19:25 +0200 Message-ID: <20240805152004.5039-7-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: CC4A080023 X-Stat-Signature: yjtoushx47fab6nehtqx45azo11z98z5 X-HE-Tag: 1722871249-199535 X-HE-Meta: U2FsdGVkX1+3WJsC30uxX1Aib4WzQeIkwcT76iyfWwAK72zXjYjkqStH0ik7LsgqWJ2+nOQtjYbBm3yZb7kRr+ONlY+7URHmnLlP50mpm9Q1eHdtKI9DxbB76rS29+xy+nl8S1CFJ2RQu1Y0YRSTeya0NkzgxISf9/xWyqOvdPvtjk7cOWkWYn+hZ0ovGdPGe78gqnH0NFApg0N+Q2lyV9uMhhyfRjobhPJ/04vNazrroChURtgLRJKJZe7QHUF0AuTxyzezoVmj6QjsX+POCM1o+s0qYhJCZ7xHVPkqxeU1r74lIGFN9FDEN9nzvr2utSdvjYgkUJ08r+a/DfF9ZlL08vwzCeX2yzUZC+BlmSvkDKYWHISAI4tkfsPuQ4JYhhaZd/PLB8hNszroPIAQ6LQ0K1yeqdlEr95psIstowJNRz2Om526xLLTZkYGbP5vZp8D/5HxPbu5olE4D06Y67ASTdJBbq0bj568v/4YJggs6kz9mexTR1O6853wa8/nUk3rRRAhJi1tVFwhK0IfMB76QbuaJ2OldVTH9q4VXwkirQSbqVCdpf7lhzwUS9Ek6wIID/Z9z6f1OILfa4x7oZX6OdSNqqy9SeAa2x3935oPQXFoH9AGSweTMphV+oqn24p6RaA12mFSTvyKygrKsZfOtWrt5Q+WyHVbKEgaXbAaj8lZa5uCwJjJuMGjlTdS8Hcn+x2PY7gXAejEmeOduZCNR3pkExlBHYkKf14u9weq1KOhVF9LQ+6tSBe+efZ8WQws1O33fn6DWfoq3och4J+Z25eqfAvarP7kqxOvkIb6k+c5tGPsNSZsx2H6AwFShSLBE8DQHFHB+FaolR66f78qCWWWa8rHV6ldtVJB+Dj0/U6gs8HRu0eWisKRrQAxS072N0P4a4oFcF/gw/K3EkfiC3YIxv+24L0tUmphUyuYh5Xknm3D1Q+AydvOb0ihzDJtwdRJ4y/Lp9v4OPg 1k8OM3mD hEcw6UWeznD4P4O48ccWLECHCSKBVjpe60UAs5FpDUspj0SDaC8FvJR/m88zwOxu3LuuwPNcTLnN7y5o67FGQfRUUeZf76WMUZFhXeGEJ8ZSjol9u5LM1ZmcY5+C6W4csjdAAdIPH1+iCsZ/eaCephD3Yu9b4vmhvhZFOiixBr0XYCSlpJgMnQg6Uhl4EAY+TR/ZPtpMksgtHzRHkAmYVrWDyvSlvlW0L0etKhJ8nux1xb4fZsN97QOJ1fkp3jZxqbSzakzir1b3mmAsW0ZRn2Cvd4ZVBmYNS67BHpgwZR1z3ZwSsnWBA6ezL9RsLOblM640NRSVM5vzMjsQ= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `Allocator` for `Vmalloc`, the kernel's virtually contiguous allocator, typically used for larger objects, (much) larger than page size. All memory allocations made with `Vmalloc` end up in `vrealloc()`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/helpers.c | 7 +++++++ rust/kernel/alloc/allocator.rs | 32 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 40 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 9f7275493365..7406943f887d 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -199,6 +200,12 @@ void *rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); +void *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 c6ad1dd59dd0..bb55895cbd03 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -9,6 +9,7 @@ use crate::alloc::{AllocError, Allocator}; use crate::bindings; +use crate::pr_warn; /// The contiguous kernel allocator. /// @@ -16,6 +17,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. @@ -61,6 +68,11 @@ fn krealloc() -> Self { Self(bindings::krealloc) } + // INVARIANT: `vrealloc` satisfies the type invariants. + fn vrealloc() -> Self { + Self(bindings::vrealloc) + } + /// # Safety /// /// This method has the exact same safety requirements as `Allocator::realloc`. @@ -141,6 +153,26 @@ 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(); + + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { 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 Mon Aug 5 15:19:26 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753716 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 492CAC3DA7F for ; Mon, 5 Aug 2024 15:20:59 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D44966B009B; Mon, 5 Aug 2024 11:20:58 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id CF4966B009C; Mon, 5 Aug 2024 11:20:58 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BE3266B009D; Mon, 5 Aug 2024 11:20:58 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id A178B6B009B for ; Mon, 5 Aug 2024 11:20:58 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 48774141CDB for ; Mon, 5 Aug 2024 15:20:58 +0000 (UTC) X-FDA: 82418554596.06.7D03F9D Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf28.hostedemail.com (Postfix) with ESMTP id 08EA0C0020 for ; Mon, 5 Aug 2024 15:20:55 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GJAyHZFL; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf28.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=1722871188; 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=U1xTY9rjR9QlOfwvr690HS+T8JAy2CA/mTv5J1WCnXU=; b=nioRkAQospT03IKiQp0rICOKUwkAO26BDr0fZpHWm9j+BMo6R77Z9YRKJT9KcfkAr4eBpF eQgf/WMffNzA8qFBIEadcHje9aGaEg/j9jnJfuVEILyRCVEY88qXq2MQQyQ1/NnzJpY3yk RkxLeoVk+CuBm2MKb21RF++52OSySPw= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871188; a=rsa-sha256; cv=none; b=JjBA7XQUVSWpBLLK/73UR6qybWkNaR8zFpxOcnxKgtl/LWdgxe9CEapkfdFuznDQG3W1Nn ZLJwrFshu97MBrTjWKPdyeQVUTLfyVmXX/abe11VxFAFXhgcyAt996zXkuXwycGg4qEj+Q tTBgYxLugVxj4mPwMcJPJX1rMN/f+cY= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GJAyHZFL; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf28.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 E8502CE0B2C; Mon, 5 Aug 2024 15:20:52 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 13970C4AF0B; Mon, 5 Aug 2024 15:20:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871252; bh=4X9wSdLX4mWoeYIrAd5wlz1K/X7N03r6vTnYVQGkAO4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GJAyHZFLBa7Fe6Up0rMI4tOEodUpG6ICWZsYB2kS9icTwHsv0wtG66ktGFCoOjyxY pXCRPWZeor7R6vBE9LRo5MJNRiM4BLH8xXJI0PIBnIyvPd/YHQmtjyKZ9m/jKa8bTL VZd48fllVOFNugpuOyQOJWmnk7hjLZQPVN0ha/0JFtJrb6oF/A0kXmCcBG17FIZtWn 1xTk0MDC4qqfztXrPzUFAVOzBguUtCZHmg1pKUEEQCZqyIslqywKAbJ2MBEq+2ZAFG ZKjqokDjnAsjTlUD/6tbLaa5ffRzlKIlpoxxiV/EsMBdEOW2q5N3RO8OhT02M4Fvay jHkfPN2IYfWaQ== 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 v4 07/28] rust: alloc: implement `KVmalloc` allocator Date: Mon, 5 Aug 2024 17:19:26 +0200 Message-ID: <20240805152004.5039-8-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 08EA0C0020 X-Stat-Signature: yyjippfium8t614ph7iiiygjnwtabkmc X-Rspam-User: X-HE-Tag: 1722871255-437964 X-HE-Meta: U2FsdGVkX1++AZmJHhvCRzyV+K2hAJ4D5jfhwXbLJRcJO2CLlKofdz+8jT4HPuIgkZRP0LRw9xJCRLthiar4DwP/1FISqpORRlInSkqGMV+Gl9qT2AVzRmExI1vq5iqNMSC8F73lLIwAmNzOCBHENlw6OtE9Nlbe3mdpNWsq/zIBsR6mYF3HiUa6x3SLUSxutC5PM/13cF/uE2oShyF0kHFsO2AZEIFldewj5/KLLLYWsajfkBbASFSUokx/3bizdax7yjurZi6L9aIJeYgsGJ+Zo0UOB1NlO1IH3KekUDU0J45ujhAsM5W8YIhjAW/eFdDXUEY/HHyi0Luxsf4MOmVkghXR+0PoXqheUzBIZdY0aUfLni/HcqgFVRUwxEPELjyXRe9oPjRK3Q81EcC21hoqhbXAqtmQzmFbPEqYxX4NcbMifAfCxJsD8R67wiupXbiiF/oUOpwFYDZ88+4/Zwz4x8PR40aD7L1IBJtZADWFMyNEqnX0Gfiv/e4IuG82tFJYL9uJJirQtok9kdk47ZAn2MmgQlutBN7ZB8MhL0JhtYLon6MvBd7ICD7EdXXIsRHlY8//WyCrpQRB35P0EcKUT685PiLgDJeh2SOU6wSEekkOvEcY1TJRd4fhYSJImYte9mtKjDwbqwTJtDPg3JHHGvI3BJ5MbnyHAfwHrIcoKhEo5t+75Og7iotA6ELA5pQIWid4fuknaZL9HG8ApkWsWTEElGORQ4R+EPsbXI2MkcWJ0imS8b8hyODC89CaaAEEwkGga35yRPySdArrcbnhUfrHETfxnhKQIGYd9c/Z/adONaLfDWKJMpPSqgIkdPAyIqXJan7X/OBnJF+VPEzQWmEreuncEqQwVK8JIF7IcTHkz62ftBOkVtj5hgFianBXpirXlylOmKkx4ozHQrcB14rDGP4vDTjm9pppiS3XKV30okHDXi1S8e6P/sqyShCZHd3f/I3eBTqNxPW 2Is8XzeC 44wLuwd+ShcmQugmP7H3hYTXPkMi/HJQs39EoAdne6YwYJQJtov4LIuNZyqQnuPLT5ldvNMyOkJJ17IzCjIJHPFuNBIzAWbCKgs5tleQ5uRmY9B8x46d4GUZD+tX4/WngrT9G/VW265v/kvJiVCC6MGwUE9SGVN/8fhkch7BpjdBpHZf8o5QLUVIGVswT+/GKjJIrFBvu+hWBHzVUzOL4bq/Jlmk2Zc9udhMhtlNCzp4xOpSMMMjJ9YhoWzgpT+xqj2k6AMzffB6w5EW5LU9wvfQi+SlL78g79G6/orrUxehi/2s9QfkrKQwfwo2zUaHN57DZ5SgcvPMqZ80= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `Allocator` for `KVmalloc`, an `Allocator` that tries to allocate memory wth `kmalloc` first and, on failure, falls back to `vmalloc`. All memory allocations made with `KVmalloc` end up in `kvrealloc_noprof()`; all frees in `kvfree()`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/helpers.c | 6 ++++++ rust/kernel/alloc/allocator.rs | 31 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 38 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 7406943f887d..3285a85765ff 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -206,6 +206,12 @@ void *rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_vrealloc); +void *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 bb55895cbd03..91ff21372a8f 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -23,6 +23,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. @@ -73,6 +79,11 @@ fn vrealloc() -> Self { Self(bindings::vrealloc) } + // INVARIANT: `vrealloc` satisfies the type invariants. + fn kvrealloc() -> Self { + Self(bindings::kvrealloc) + } + /// # Safety /// /// This method has the exact same safety requirements as `Allocator::realloc`. @@ -173,6 +184,26 @@ unsafe fn realloc( } } +unsafe impl Allocator for KVmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc = ReallocFunc::kvrealloc(); + + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("KVmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { 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 Mon Aug 5 15:19:27 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753717 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 1A340C3DA4A for ; Mon, 5 Aug 2024 15:21:05 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A12E56B009D; Mon, 5 Aug 2024 11:21:04 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 9BFD36B009E; Mon, 5 Aug 2024 11:21:04 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8395C6B009F; Mon, 5 Aug 2024 11:21:04 -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 667E86B009D for ; Mon, 5 Aug 2024 11:21:04 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 0B8E71C565D for ; Mon, 5 Aug 2024 15:21:04 +0000 (UTC) X-FDA: 82418554848.26.016F20B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf24.hostedemail.com (Postfix) with ESMTP id 8C21318000D for ; Mon, 5 Aug 2024 15:21:01 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="cdxAs5b/"; spf=pass (imf24.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=1722871213; 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=7PFvN6+7DtHc+JrqwPEjPxGffSm5k3GRSxPndbOvRG8=; b=dIeGt73VV0mgmyxPszMkQmsVRJnJOzb9N4WJp4EugYIQHc2/ivZVqFKDMLOwmreyELag1I spywH/GOJ2hDdIfS74yuyPUgZ5xINac2Hm+GqsXipnxaMDN6wMTrEzGaJMP/OEnTKJFn7Z PZuxo5FUEL2UcXjmzVU8fIVm1ML9WhI= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="cdxAs5b/"; spf=pass (imf24.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=1722871213; a=rsa-sha256; cv=none; b=wJjIt7kpe7bcZX4ZwLLVQpiVPOBYVYIzexCKFMRVmOn1te97hb6wHeeqdbLUhMVh7QLk+T ZKtDtxRFoqUSaODtR7gK8ZOILgs9/1m/4pEccQtjt0A/E3p/lsr6+LbuQdmk3m+hFc8jW9 sEe34pyTDl50KuO9oqjjSyHFfWT2SCc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 6E863CE0ACC; Mon, 5 Aug 2024 15:20:58 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9C595C32782; Mon, 5 Aug 2024 15:20:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871257; bh=rMcjDrrKtW/xMLE5lbZxePxiklFMyzPsbOBl2rb1EqA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cdxAs5b/1Fe6xH8UKlGLdCCUCLDyjtSIBAnMG1ZUwkJr+9PDvew0haUEFRz6oVaaY +YuEuWuCcXfnTBKs4xHAToRDnUf+9uqy7/Flc/5TavUzriCPgQ6cE8RHHYwNVHox5S 8pOVIj6lILYgorP6kthArTsoN8FhBOSaAEkHfEuifWjQ2cAP3jhSPE6FBgDOyBazpN EmuPcKnqbrOByXqFZeoLTp9fUbm58JnaZdJwXpoDJKzCESgWuoaMkd217KtrD6alyI zO1Qajazexhllns3D4lxkOtexDp13fjM7Xg13mYjgtox/2+d8j9qU9gFwVKnI9P7X2 sxe2H+a2IgvFw== 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 v4 08/28] rust: types: implement `Unique` Date: Mon, 5 Aug 2024 17:19:27 +0200 Message-ID: <20240805152004.5039-9-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 7abpf96hgta5wbir9qexag6hq1awq5qh X-Rspam-User: X-Rspamd-Queue-Id: 8C21318000D X-Rspamd-Server: rspam02 X-HE-Tag: 1722871261-377741 X-HE-Meta: U2FsdGVkX1+bBuOlerBbBXv8x9IZuQJCVpKrhqcTawctMlMXszptN9xKEdc4DxTIPyobEpPZfrgg985gxsmUzg8+aL4TLLcyQRgYqcMxqVbqZ+t9AqJewoPxJEKpfP1RpSCrucBuLH8ygZt7z6GOB6K8KLs8nEpfJ91evlVw0C+PxTOOD8y1OUZWTdLCc8UHJv8PaLS0spJoWNRakRZDam+7May6R888Kz9tX+gr/0UBT0DGxAx4krGlE+z2yKwDbVeFgW3yll9eiFEMCMOps3T6CZ8hcwQy8IqqLwOORzs1XfEWaS7QsT4qtEc49Ukie9DaDNW+Lg6zGJzzOXYJm7AN0TTxY7VNa1W/KXL19zKZTjSvW63M7LE2quFJcCLb5Om5soCZ747ICnZ9qMnebJrXq4w7MVYAHw/aiAbmxOkwMa+bQ2/Qtt03ne4U11ylJ1y+dnC+b5T8ow5RFrdkbDqJQ9BqTbzH/BK+FJFWZxE5oW82JdmAshma5mqVf4NifWZm5y0Kq2KmoUf8DBvq4Q8oSufa9Jl2diCqzCJLIEciuZSb6oFOdBTN0US/YX7BHKzjXT+Eet9LB1BmugWjGAHfM7fmQJvQiFbm9dytKh3BXUDeKNPfVbq6hX1Dqp0CbWvUOh+RxePoFds4PKRK5HwRe5e6YG8uoRxmR6HeWVrNqbNVHjzggje0fGWgimgOkm/lhLKIT/QSTmFbUoRyUznUsK5HMvztS4+4YXBNvUCZEclbem60BAfTySjZyFehF9YJYobuDGbtNHn3JQIQJQdXCFcP2dhRnfTWRt/cZ5PTOZh3km0ZOpNu0pj9+2o5R9RXFe4nripEN+U2RqktaBDf/9a15oD23j1/yKQlvC/UWHRbLz7qUGIj7R9iujvd1JeD/Tu8hSa8oAbc7GNu6wiAR1VDvJDfT6WzmUx+ZFcdxiXNm5Ps7hDB1WgXTcMlJY+7zbTNrC6w7VHkgZz 4FuGdxNL EgTQCJDYVbt9h5JvFA5z0jDaWvAdxUCkusGkXek7p4sve/QdE8FPvWIvgx2bilhKUQwHyP+TS2L4xDw1Z8SLK/2RNZKpTPfUXs04pGgEVJyd2Z2SZVo+R/OI0YOOoNotPw1ZnwrRgBKKBIRarhmA2r6sfLkQxH0sbqpdX3pMTLeo9cBvTA/HckgJx0uxdnlJ86wUDpVVcHq825rT5gshUusY3NZK1/w3PL4GaEK5pqcDlXmyyjJxLjwJaNkU1dFwP7hSKW7u1PS42+5jDCqKgSWY64V5ugJgzbdl6n1eangkqDpWZ98OXJ9hCJi+fnWt4yWhvA8BOiUyNzSKFTa4IFXcRiTpg9Camvxt/ X-Bogosity: Ham, tests=bogofilter, spamicity=0.007542, 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. Reviewed-by: Alice Ryhl 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 Mon Aug 5 15:19:28 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753718 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 E92FDC3DA4A for ; Mon, 5 Aug 2024 15:21:10 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 79F296B009F; Mon, 5 Aug 2024 11:21:10 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 74F926B00A0; Mon, 5 Aug 2024 11:21:10 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5A2696B00A1; Mon, 5 Aug 2024 11:21:10 -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 34A766B009F for ; Mon, 5 Aug 2024 11:21:10 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id C9DC8160290 for ; Mon, 5 Aug 2024 15:21:09 +0000 (UTC) X-FDA: 82418555058.17.AE95687 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf01.hostedemail.com (Postfix) with ESMTP id 7A63940014 for ; Mon, 5 Aug 2024 15:21:07 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ge0Xaxvi; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871186; 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=YVnYPfr6pFUqfBgM0Lt/Xf7UvlOic93TEMVW8p+N9As=; b=D9Y05kuyoQH/vUbSERwLrpN0IOyB5ACdVuMlcnx1C2fdr2CZ2+2GO0Zd21cxja5a0jjuqx Yus9VnGQDC+MNKSjB218fFvmOlkG3R4FNzU6NiyODhV7vZWmlxmL2gk9cQdBf5zpLkaw/7 klcupgy6QH+vqfcCasvxEz3oyEZOGCo= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ge0Xaxvi; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871186; a=rsa-sha256; cv=none; b=SnToK0Gy8XdP9d57+4InFXbfZqSwNHDZfv/QgYjg6dZYXbM48+R7UoMeWL0EfkessKJMYG xGOar96d9dZNb/irEn2dqIIMjW0x3AMAeBIQuWgD3vP2Qe42nwLhzen5j4OcqmRyqJDf0z MCs0paTdXt+bZVgkmolCkzb9Oa3TgbE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 4B41FCE0B2F; Mon, 5 Aug 2024 15:21:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 338F7C4AF0E; Mon, 5 Aug 2024 15:20:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871263; bh=3qegzxF0CAqZElJOf/fc4vi4CYGZNhd1qrq8DwG4IkE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ge0Xaxvikgpg6uiVTL9CSOEiG0ZMde5q5iorlV3mzzxtuB9522yCoHvEra9TMh/la i8InoGWDWVn2GqE5XkTEJk1g9s3cimELmk6kxrJ8JsfCTy2JerBeH1aQAIWoVLAqKY cj/13OE5hWdx/D7RDfa1t3m5N1w5efVQl8//szQZ6p4XpORhTzZB3vTSIQKR4kTX0s IXxjKV5jzUr3qWtDu5pibl0djk6NIDJZ3uinepRykeeaMX0cn1WVAegsNQAhJCYnYG vT6w/pPWtPrTUCdm0gBLYBeCX+5C/JZUPmtJHb1YFE8jHacqc01fV6WEoxqButYT50 UCtNC59Ebnz3A== 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 v4 09/28] rust: alloc: implement kernel `Box` Date: Mon, 5 Aug 2024 17:19:28 +0200 Message-ID: <20240805152004.5039-10-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 7A63940014 X-Stat-Signature: zjqxjr3gu8175jf5jqef33p5taxnw1tm X-Rspam-User: X-HE-Tag: 1722871267-521631 X-HE-Meta: U2FsdGVkX1+Sz+oMybr1LNElIMzyff8EDR/o16RP4EjkE0SmSaS6dAyzuGIfUNYIjLqeKBV0tAXlwF63LNnCGQ3C9DiZBKAwRnrt0LQ8jB4eWGNXl4Mm8Xzo5rvhiGvtwjiS2HcYPPRVsdwDl/5hQZwyTFYKQ/FS2h4if1YC7uP7teYblY5MakXhbyJ59gOylHhalyrMxqFhN5V1w5zJigAu1et7pGPNc52jd0qh2UEbu6cW5EFWnrDONnP9lXq9FuSVoKroRpVq5SC3lxHPYV/g4IgS56MlDFIb2aur8mSWF1r8WyshOiUbB/93y9oavjFcqV6cm1b7ZCV4KZj/tBzyEsGGPcFd4GMHAbewzXAuzl1TfV+gjIVhYHTzJLuXJDxZiQJ4hdApdt/8+Aw/+8q2KJNCHVqL69cX361oktUQ3t3LWupUC1kzmB+KwErroeOCZ36bO3mLKXiFozKQxDYl7Cn/CQtUdz8d9qvTKMKIcKamwtZBGfogFq4eqekIWQrYo8EgTMx7rBgHpDSojn2AOnTs3aSk8+E2RjM7LqOxuRqnrcQjbZislWOTQpyfDF8aojha/eY0PTYIbV71D07nxSnbk2BBtAXn4BUe9vKOvx31fHg6pvCWW7Rar3/75YDs2jnvfdelxmEZDieAqYmoYF3+AWox5b0D38tIKmdFT98N7RMmSUfqx68gOFntCxaJM5qmgnEd/lIiJlQ/91fcY+mr1Cu+cfM6JoUWUl0Y1Ax/DXL5ksgtT8dORXFewsQFQiAkSAfdTk3yfvKWooDNBsuCbUnzHvGtt0hTyqg/CKb432LWYQ2h8qeqO0h402JEDuIRl+4sKNX/wgtK29kedEuZaflzy/kSVFh9kfZEjcdPTC1v26VqUZ82qQBy5KezhpYTafpEwH25ZTfxrM5cJdqTFDMJ7+8nH/gsrrM3bGlu5WYUeJ6mRqaQnA/p72vrPsSaW3ZLfUEWgFc 9CcMY/hI PrGZ7eqK2HxXe4GBG25deTqAPgALpsgmC9X6r6zr80PvEn5CGfj9ygkI6qmlnJLYq9zUpgW4cPrULItJVilvY58VUJDG/Y+gwNQ/NjPQdOnHXwF5qf/2WUEB+2Diy7oMRnrkoG0+wY5V0twQttegHpnfrBq+977HnCr6W9YTvE4TziufSvKobKLBHFntNl55z4pVAUMga6zNm+/4qffeF8z5Womi1eTx5DWnpVX4NyMRGbASh2EP7aqihUSEe2n/1jnMfIeE1Q3gTNEm/+I52msgxz7BTX0CZP7zx43zOQ2pSaJoxIwsWZNPDILsHNPSXAZyl+svHhp6E9gzkKdiu+2V1gw== 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: `Box` provides the simplest way to allocate memory for a generic type with one of the kernel's allocators, e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`. In contrast to Rust's `Box` type, the kernel `Box` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 330 ++++++++++++++++++++++++++++++++++++++ rust/kernel/init.rs | 35 +++- rust/kernel/prelude.rs | 2 +- rust/kernel/types.rs | 56 +++++++ 5 files changed, 427 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 942e2755f217..d7beaf0372af 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..4a4379980745 --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +use super::{AllocError, Allocator, Flags}; +use core::fmt; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::pin::Pin; +use core::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(raw: *mut T) -> Self { + // SAFETY: Validity of `raw` is guaranteed by the safety preconditions of this function. + Self(unsafe { Unique::new_unchecked(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 { + let b = ManuallyDrop::new(b); + + b.0.as_ptr() + } + + /// 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()) + } + + /// Drops the contents, but keeps the allocation. + /// + /// # Examples + /// + /// ``` + /// let value = KBox::new([0; 32], GFP_KERNEL)?; + /// assert_eq!(*value, [0; 32]); + /// let value = KBox::drop_contents(value); + /// // Now we can re-use `value`: + /// let value = KBox::write(value, [1; 32]); + /// assert_eq!(*value, [1; 32]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn drop_contents(this: Self) -> Box, A> { + let ptr = Box::into_raw(this); + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { core::ptr::drop_in_place(ptr) }; + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { Box::from_raw(ptr.cast()) } + } +} + +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: `ptr` is always properly aligned, dereferenceable and points to an initialized + // instance of `T`. + let size = unsafe { core::mem::size_of_val(&*ptr) }; + + // SAFETY: We need to drop `self.0` in place, before we free the backing memory. + unsafe { core::ptr::drop_in_place(ptr) }; + + if size != 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..9fe87528d129 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::{ @@ -9,6 +10,7 @@ marker::{PhantomData, PhantomPinned}, mem::MaybeUninit, ops::{Deref, DerefMut}, + pin::Pin, ptr::NonNull, }; @@ -89,6 +91,60 @@ 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 Pin> +where + A: Allocator, +{ + type Borrowed<'a> = Pin<&'a T>; + + fn into_foreign(self) -> *const core::ffi::c_void { + // SAFETY: We are still treating the box as pinned. + crate::alloc::Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + let r = unsafe { &*ptr.cast() }; + + // SAFETY: This pointer originates from a `Pin>`. + unsafe { Pin::new_unchecked(r) } + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Pin::new_unchecked(crate::alloc::Box::from_raw(ptr as _)) } + } +} + impl ForeignOwnable for () { type Borrowed<'a> = (); From patchwork Mon Aug 5 15:19:29 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753719 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 41D47C3DA4A for ; Mon, 5 Aug 2024 15:21:16 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id CCFF06B00A1; Mon, 5 Aug 2024 11:21:15 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C7F856B00A2; Mon, 5 Aug 2024 11:21:15 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AF9676B00A3; Mon, 5 Aug 2024 11:21:15 -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 89B506B00A1 for ; Mon, 5 Aug 2024 11:21:15 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 2B3AEC1C68 for ; Mon, 5 Aug 2024 15:21:15 +0000 (UTC) X-FDA: 82418555310.08.96F7632 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf11.hostedemail.com (Postfix) with ESMTP id C1EBB4001B for ; Mon, 5 Aug 2024 15:21:12 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GUwMSH70; 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=1722871225; 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=Ux06sg2b8GB27Lf92WMCQjqQPGdpajFZN8RC2F2+F3hm1gXUuMF0pekh5UxUcXqJsfAetM slHMt7kgXQXfIOFiehNnyFQ+YSLZ3xKphafT+rdsZ9DSgVVJktLdqUzQczFSa049F1n/0/ MtsgC1TlisIEaDs6beaNxhIR+bS7mWA= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GUwMSH70; 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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871225; a=rsa-sha256; cv=none; b=pYqkVPfN5ffZ7JagNdcy7WgYp7vCbXhf4GbB0jewfrZRrp+2mMLk1izsKgZEi+kQCIp1gN OmAf800QnAMubg4RFWLuJaaeq8B9CDe5bXJOoU+VSJNTdjAbxauKaur4/e9G155cliZYyH OHxbXFvOtoTMRb8D8xV2YuSzjlS1+Rs= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id C5398CE0B30; Mon, 5 Aug 2024 15:21:09 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id F1FACC4AF0B; Mon, 5 Aug 2024 15:21:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871269; bh=udM8gowoRtDWYZ1bTx/TqIq3PTvtL9tWCZwGcw+omGE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GUwMSH70agnUMAzx7yZkpnGV4nptO10VaFFsLrPUEo9muwql4SwsID1SRHjtqdjMT C44glyquZiQp/db1l0+rW8SwTL6hem0dQpXoLkSjdfwasdSOPx2zRyMnucGMEUdMZ6 64Nf/2sdgn00efWpO0BVhpmfdsJ2NMwIm2i0fBCzjkNh5DW3om4T5jcwKvijE10OaQ EPn6zcLNOndnIfh+c1sxOm48LB4p3c5Cb8I51bP+1bfI7PN7U5+Mk9HJfALEMwFw4q ZeSCHRQVX0HjkDQfYXUKmdelOG/CqxM0abj+OxoE1iAf/wpahqkSn7UDJnSD8oA4zl xO3c+2zA5e6Aw== 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 v4 10/28] rust: treewide: switch to our kernel `Box` type Date: Mon, 5 Aug 2024 17:19:29 +0200 Message-ID: <20240805152004.5039-11-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: mpsn96n9rnby4w31k71ea6oogakw597y X-Rspam-User: X-Rspamd-Queue-Id: C1EBB4001B X-Rspamd-Server: rspam02 X-HE-Tag: 1722871272-240731 X-HE-Meta: U2FsdGVkX1+43yU3x1ZiNjwJxx1xxM549EQJYOGzGgRKZ95jlTI3/EGnH07VufzVxvcjgWhGNwEZvRXPDaWBuuKTO4xhaESP09ipkyiGFSS1Du3lZJp1NFWKscxclCqxIa/ij2WV56wYMwQhqRegR6KVNxdAL8TOF0s5gGF1hGSkEvwatXxATt7J1zr2wzDbYsqm+ArBP71grEsJYl1spwQGQwGTc4pbojahWnfietbRyu0Pt89aTztvmRef3IK7mG0kdvciGysBr9UshkJW/cO2QT3IgRogxbdhaLTRNi1PWUnBVHYnEoLXonMEL9ZTuBXA8T0LXA5PlTKQA0dlHzZIXUMqp/f1QtoQT2E7q/+TW1m7Pm7RAQi01lSRwwRbqFZHebRp5jvAj+XXQWdaWu+gvMTLECOuONoyxAnsYABJQtwEqFucgomBKngORDkprmQz2Ab/nl2hGsB4PYk0hDakeXp2A0p+rCqLlswX+TVaorTmJgStIVY5b6/RAXwLeBeiRX+z21exSoWKowDcQf4pAG6T0S85RjUfUTJqUtxp1cSxDz1h+PAM1vnsuxUrCxDndTHHE/JEGjWkqIJLnxJ67JzEeqjL1g55FUW8W8/aA9+N2US6RSTVK23I2OIvgQ7H595Vwd8ZP6GRSHRt/ernzTEsv1tCKy2Np8UWTOmkq/hMnWGjebChZEPKPvchvvTJ2aNADTggk+++qEUr2CSayIMfNVGDjWqXxo99iWN5rk8/OVbmLxScNUK8lplpn6RkCzSi8JXjD8+rwy6AtfCFi+vXkGWIQTGlw5195JpJY0RPvKmA0LpXKJEDaMu+2sv6U5QVVQI2FsEJUDAOx+SvWpm8yhBWGv799Id9EdngqKUbY1VwQoPl6xrqp2okoACAdSWmpapB59QvTus/Vkej0tkY9M5V1saEdpMi/FOw5n0CxO6dwCp+iAi3ualzcGZylw0+2s9a20t2dSw 19ync0Np BiPuFoNFCLn/Rqe2gxBiwFNgZsAReAqQTflnobHzss0JhfN4IK2ODbSArIk71UP4SazbTGnz9k6GJyVR5m0XImzUpYdTmunwr0jLdMbuxfq++HhybqIu+L6p0Rlz0mKx9i2sE6IF05ZfPF//r8y1lzAP6nHzg4BNfzNxhfjt233Sp5UlWE+y5sPKarZSecWYNw36+uGHHyrXdiBjDzOrVsxjIeRdLQvk+ehb2f9jVOEFxBpqp0P6vcp3xhP4ri/ARNpg/SvzBTeMMy2BKpL/MoCCREJ05fHO/ONimI/Ss9FG7SwN7gqUwGA/q0dtFTs3mxLIVyJ3WJeMZ1GRwfjkpZD6968Azm33JWPdiu++sT44AI36giFFxXkn+L/oe3++TAxjhZw64t1yh71M= 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 Mon Aug 5 15:19:30 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753720 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 B9F56C52D6F for ; Mon, 5 Aug 2024 15:21:18 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 2BF3E6B00A3; Mon, 5 Aug 2024 11:21:18 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 222C26B00A4; Mon, 5 Aug 2024 11:21:18 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id F3F536B00A5; Mon, 5 Aug 2024 11:21:17 -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 CAEC76B00A3 for ; Mon, 5 Aug 2024 11:21:17 -0400 (EDT) Received: from smtpin15.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 8D94F1203DB for ; Mon, 5 Aug 2024 15:21:17 +0000 (UTC) X-FDA: 82418555394.15.8601348 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf04.hostedemail.com (Postfix) with ESMTP id B94524000D for ; Mon, 5 Aug 2024 15:21:15 +0000 (UTC) Authentication-Results: imf04.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=kZTuri7Q; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf04.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=1722871268; a=rsa-sha256; cv=none; b=dfoQkC6WFp+wreXO6cCoTrCSzPwGQGe6k1YuRoLmtKcaSFbPFReyxNDCLj9IsvPddYzs1v u5OWwu103Sfd2HnSQ/tyKja+BQYG7twrZjWjSKCYugM969f+dkkJAreP7dc9cZhyBLP4X4 PWQUKT5Rg6jmnJW5uSGdJekcMROI/3E= ARC-Authentication-Results: i=1; imf04.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=kZTuri7Q; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf04.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=1722871268; 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=3uCwkhuNT3MsNWUeLBA5xzVp0N5ZvPfIqG7gmp2zys4=; b=UqrQb6/uWWet2RSJWjb0Mom3tW5I1ITUJzQvvK5J+AUuf7pGRWX38hQLDw+R1GUeXmXk7I Hg9W9wiZw6EsPTap+c0md7zF7m8sVyMwvs+yue56f4tSShz8fXwrho873rux3vh129Zi3Z a2AMwuqCCP1d7+YY+jHaX4GRLs2exnk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id E73FD60CFA; Mon, 5 Aug 2024 15:21:14 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 82AD8C32782; Mon, 5 Aug 2024 15:21:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871274; bh=A4qZq0jLBGmSr7W8ys6nCHz+lSRSI4/dq4nSwiqm/08=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=kZTuri7Q9pVK1y336Rl+9BIudUi4Dtxb/4ueoJsMygn/Qz1UmoueAnLaQ1E+2sAuM 6oqjcTTXrSUYNa51oCpWuWi+hfQpB+GuoemZy1HgkSaH0wYq0x4J99m0urEdClI+LH EY53DYm9XTRkQXtkfI6IfByOK+ayHdZ+Wi6gJNlIDrLgmj9AfNDeemuPH0s4z6qHYV NgXmFBdx7MfhsmfkQ4nqJQhj51B/7w487MhEMBGnrsqxunuJ8QTZdEtFU5tpArnPo5 s9/W8DYH+oz5876dvkSxyl8WU44lxGVZpi0GEF8RSL9u8MvujKq25qCcpTp9aLE4La YQvQAMPOHV6GA== 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 v4 11/28] rust: alloc: remove `BoxExt` extension Date: Mon, 5 Aug 2024 17:19:30 +0200 Message-ID: <20240805152004.5039-12-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: B94524000D X-Rspamd-Server: rspam01 X-Stat-Signature: 1zuw4tjhaoj6qsp9jcyrfeye3d18d4n5 X-HE-Tag: 1722871275-779305 X-HE-Meta: U2FsdGVkX1/THT64sxL70EEW9d85rQWwNvmv+DM/vdDp9hEic+DcLKfebbqpPYxuvR3ks9PZhZDJr/Ns2CKpLtpe4iA8Mj3cRobPI3zoSg+IE0mWx6pv9p6hepQf35JzF/wMtAcDmvQZaFHrYzb7XULKX5MvdXSLJsrOLeQB31Q+LxLQue7onf56mw5MC95Y0VhnA5EvaoW07g8wi/z9p6QBhbtYnFKTyvN8xsnQIc+va1mFsTpjSSaN2yzVvpkLBMi/00Bdl7Gae/lPPuGoNjvVoWnUzVWmZZ28RW+T6ue0Sqt/fcd+EuuifRqscAs4xVw2ueQIAQclF7XNqJcqkxuMgHCT0aQVQuVwcUZrC1CdwywYFXdCzjersgZJMbaRWglwWuGVgVM1inzYhsdbjin462eLT+prVZypw6ngKnmfcuRQjqnLD2H3609fNBfh0eTApEAmaImZswhy7Te18Fn9rDidvxHKyENIl2mrzJryaI2gvvFp2toN/iFsNSsX5unL2Go0xzatS1k2H774d632ePTPV/UmM7sME0uNAWYgchj9wNdGUbrLBghhZEGZsUAS7iINjOzQXWqS/M8L+xgBYwh0pN0CBRucIbPrwanap56YNAIuYfmahwibEN+2fW6DPeHjQdZHlORqJ2Lm/HBGEbyzklQt7BTApdDhmgmo/RdtYFTNqg0vvvoJKMTmkVmjLNMj7bkFrbX3yb8W2HXZdQyC3Wb3C5SSqBTM7H74RU0Yt2qbPjtpSWmdin69nnzVfIVnZCm9h6hdUJbs0Di7YIMOObd5K1FmOSAoFEQrJxLbnb8t9h/JNXwpUyG4WynXFndNXKBLO/164WrIIDAHlCPZ7+eLTEJoLQHxeCtl9XDZbZ3YHTcV13EDyGdfCjkyTQeYGFyPc41QoH5bHyJBK+kMGbicxRJ96mCQbp7nscwMF0PzGSpUjI6HLYo8zAw6f7va/4FSCugsz+r uQ45eqEQ xaFp8cYIjgpYmelOp03VuQcIj7ECOO0MXbut2ymxterWlAaZUKZlZxQTwmJQ6n8QqmfN7RDHiXzBzDWSEcvvli8hcI2l6mVulw/ZlYyL10VRVTDji8uA5aL9cKg2cD8Wb6eiRwp1w7fE4bnA9ChTs5jVx93JepXA3+Vt4Ybn8MA4lhV3q5idOzOvifClM8as88N1OnwlGHnTQTv3KMqgokOpvSAly9fOLi1piCEc9uH8qz2O0zYAE6q+j7PucvYTcpUMxIaRsZ7sxbPZMKwB5C5BmCIJZfEQkQRZw+2By2fPNi0mX/muDwqCz3Xs88IFZu+3yfZFV/xSykgM= 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. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 56 ------------------------------------ rust/kernel/init.rs | 34 +--------------------- rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +-- rust/kernel/types.rs | 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 d7beaf0372af..f578175ff010 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 9fe87528d129..b80a3b2b62ac 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}, @@ -69,28 +68,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 Mon Aug 5 15:19:31 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753721 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 3A598C3DA4A for ; Mon, 5 Aug 2024 15:21:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id C5B806B00A5; Mon, 5 Aug 2024 11:21:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C0B846B00A6; Mon, 5 Aug 2024 11:21:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AD3346B00A7; Mon, 5 Aug 2024 11:21:26 -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 905A16B00A5 for ; Mon, 5 Aug 2024 11:21:26 -0400 (EDT) Received: from smtpin19.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 499758023C for ; Mon, 5 Aug 2024 15:21:26 +0000 (UTC) X-FDA: 82418555772.19.F7F9C0B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf12.hostedemail.com (Postfix) with ESMTP id 30A3240015 for ; Mon, 5 Aug 2024 15:21:23 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=FbMFBnAD; 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=1722871223; 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=eSROlH6ud/u1I95k9zcD/1iG5rIyFEPERrmcTVWEd4s=; b=t5N5XxFC4wKnYpB5sq3/WIdRCilWAGSPjDkVmS79OVOvzig4mdJ+uHkwfRnAKHKF8jKstB GnRCHR+7W2JeWzmluLE2S6qxfekqpMX7du6vw+o8UfWbqdUQm1fno2hXpitFNnqMuZO2JD XLsD7CnfFthR6KuYeINhaUjTprugd6Y= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871223; a=rsa-sha256; cv=none; b=GJjCrXQpRO2ZsNGl2XE4z047TqqVBUErIlo9XWTe0W47WKEOIGtIeV/UuPIVchVTNqJzFn uJOkTHyZg/HkG3Ki+ndjlA4epQ+1d9V0q41+REV0+nlVbomCMrI8+YHa0gRbqDzKpjjKjZ n5jjPfIRAXDA2L2tcQeIuoRzHCXBeKU= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=FbMFBnAD; 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 E4039CE0B2C; Mon, 5 Aug 2024 15:21:20 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1BAE4C4AF0E; Mon, 5 Aug 2024 15:21:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871280; bh=Z6ThON8OGnmMolEbvMDlA1wqJrU2Ykqt5/dZHEIEb08=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=FbMFBnAD+ONdyGOCxHDO68tIE5VH0ljFw7qk6sCE9LKSrEA9wwnt9OIhcQRVytJey UkxpPeVw0PTJpMDao+P/27nZDKGuWL5G1UOMe1vxrWCZFO5GYBJLtb5Jb/IGJu0iP2 b6ROc0rutdvuGbgr3jbmz2vlcc1+Ast709UwwCvlgC2BCs1dNiaFTyVHl/v3ViRxfT R7Wzps/B4vwrPUcspPvb1M3ze8H32abAV3r8+mHhsT2GuJ2MVXLrkcpXgEGIRZjKb2 f3b1nXbEbbNUpBurUduGALmQ/3efASeaPucqbUSzzSpWmBigo9rJ9fY5VCA2pvpoWJ QQsKOCQ12WosQ== 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 v4 12/28] rust: alloc: add `Box` to prelude Date: Mon, 5 Aug 2024 17:19:31 +0200 Message-ID: <20240805152004.5039-13-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 30A3240015 X-Stat-Signature: xr386pegqa3c6me4bs5tiqn3cc5b9tpy X-HE-Tag: 1722871283-276462 X-HE-Meta: U2FsdGVkX1/EsnmvUvFxgxQVAgfOUTXY4i15qOb3ZK/VNZM/cAMc8InxjPzOvd6WsOppA7IiRpHcMYK7UWl8+BX60Lv9KsMMKN3zBMoHpYVjMYAG/o7R2q6o4lHH5Nhf5LnL/SqLYRWkAjAEFhH2GFhCfMfeoIh7+N3bPgoWn9NScQi6933YjaXJYFxAwiOvkXIgOtm2YNyFOZJYY84Dfx7Cc5I2yI9x9y8GTkbh2fOhAKX0V95/af924WU7g4FchIxwtbQshvosAXpNlkUJ/9OxzIVmBDrOHpNMgoUQ0JwhjNhsDwMKpwXEjXQv+He0gr16ttFTRQ4kaS+vVevx8PXQtQ2s5a85wFg5DoZuxZ2MJUQsvfxfPXRckEqn0sl26r9UdTSwE6bNZ4jbRO/sE4q1cXNfX/4iQZ6xDXlqNS0eHImkfjnLHN8zjpn1JxW2A0JgG+yuDhnfp9OaPghanuGqg1HwTtnLvhU9n3EW2dWkdDs5Or9AW5yw3dFh2C9FlNLPFyvCld4CBajCK3HvPd8RFkL5rReCuYBgabrrByASm/H0/rEHTLSzzZ2D+3maqNa+XJZEhSnbv2pE+xY0s4alC01/dOrom04JBR+XOSEpnGXzgjiM9OlWPQSnB+hPbQWjpPGBmh4eU31MWOzRwJ+XV1/SHWWZtWMGAkd81nJ1V3UjU3amiNIZQm2varLYMDCNciWCzTU3tOPZN5X/nW0q+U1IouL2+zgjJjHCmRHTAHwN8Oye45o5JA08MB76PbpsUoJ6TFhuQwskaLoYKEvwgRhj9dM5qGnVSEQlfrbG5Pc8DxLcTYJI0fpy1vTdwJ5Gy7LoeUl2SHKZeZqQ7dnMDfLkRzkJ4zOGFJSC8xH9beUdDIelnlj0y1lHzRa8CAn06oELmwC2GPghFR3hbfEKm+maFNp/Z+X8VhusUQAWESMAIRreTFW8eazdw1kXVyCxfOPHEXN/5O4LEFO 1hh+5aZk ecn5vOT18pKoUpyY+8medSUDSbpCvGiBm/JAK4PtngO3bkRxwEDb59XYSMkyTAIr1iv3vA0+BfvZS+KN4kerK7DWFNQ1scDt8hZDrebwWIZvEuRWQ4O/FkeJVw2HeRf4yUoryb1FDM8y/mgGc14GGZRZAulAGNdmdFARKU/u62Kz77phXA+yHkyOAkFi5AJ8mq0oVkHJwRuI3Jen1SgfHbvZ5MkNbb+IjO3xhM2fanEvvAnHq7KK7ai4HUYHieHYlmAPVNpi0dGOQXHwQ5nsXSpil2eAuOlbGoK6OlKEkkVDpR84/PtlBE6yiAycJMukiIZqQn5neUIFVvco= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `BoxExt` and the corresponding includes in prelude.rs, add the new kernel `Box` type instead. Reviewed-by: Alice Ryhl 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 Mon Aug 5 15:19:32 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753722 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 A57DBC3DA4A for ; Mon, 5 Aug 2024 15:21:32 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 2E7CE6B00A7; Mon, 5 Aug 2024 11:21:32 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 26F716B00A8; Mon, 5 Aug 2024 11:21:32 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0E8D46B00A9; Mon, 5 Aug 2024 11:21:32 -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 E1AAD6B00A7 for ; Mon, 5 Aug 2024 11:21:31 -0400 (EDT) Received: from smtpin29.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 94DEBA6B09 for ; Mon, 5 Aug 2024 15:21:31 +0000 (UTC) X-FDA: 82418555982.29.8C1ECD5 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf19.hostedemail.com (Postfix) with ESMTP id 46C881A0015 for ; Mon, 5 Aug 2024 15:21:28 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DQYjAm2s; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf19.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=1722871240; a=rsa-sha256; cv=none; b=lFXnMJu9qvRkuE8/Gtn4rfuszGMGjjnxor0gpq7ELDsAIMnpcWgJkcqCjBNNk56GXNYytj hjSloXEzkavwUHuQhfEUM6Gb1zv4f+wxPcfWBoSdqHcBWaYnnCxfQC58Ar6i2FYuQrrmYW lpRtdjRNAa57/+1hhCmWnVDoUlVWkPQ= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DQYjAm2s; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf19.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=1722871240; 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=b75RPPaRKO6PTBp3GK4AfXTSCFaDnd5ZrMI2l87YSCc=; b=KJYgt9e4kRUg4loL7DABrue7+hiCRr/yANkFQ9hyCvGmDmoJLGPNGqr1gogiHKe4rXUYcZ b6Uby8rrW8DOsjEYJMxrOW+nwF0HlndBD5sKKKbgeMIwZjhS50Ini4Jfh4DdWnXi6fNQW8 NsGYGP+f1JOGB3UlBs9/ig6O4g3CUrE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 6E8A5CE0AD4; Mon, 5 Aug 2024 15:21:26 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A8145C32782; Mon, 5 Aug 2024 15:21:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871285; bh=pVB6WWQkYTknQoh+SglRWl5bEx9KaiouK24Dn9ENpJE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DQYjAm2sn0N6rVEH3rEmI88pOgI8cRwdDI2RVbhONdO8s774rHc+/ZyM38gA+TMDz O/mocm5GbuEzpZg9UYh4Uwo3tfa9QKVP5kxgGdwkxx/2Hvom/KgwaRf5pVIRcDUZ/N YtdkmL3LWu/gXveCzX1gQHv6V1pHg1AJwxZ+Njgnuq8lvmWDSetGbAcqgsArJAmgrN Q8O7wXU6pwrOYxUmXiKZFxHufxGJ7Vl3EHSde2TIC27WBazAjWKa7npwrVpWmxmqtq Sti3WOICk5Z7VUtMscEnq3sH83gFrz8TCDCqC8vn5tEk/WU2R4Ti+ANG/IvBqcYkAL sVr3GPTAsR56Q== 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 v4 13/28] rust: alloc: import kernel `Box` type in types.rs Date: Mon, 5 Aug 2024 17:19:32 +0200 Message-ID: <20240805152004.5039-14-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 46C881A0015 X-Stat-Signature: tp6o67x33ehdanfboqxo1pshwdgeuu5r X-Rspam-User: X-HE-Tag: 1722871288-980441 X-HE-Meta: U2FsdGVkX1+3/TBaUqBEkyQQ16utETeDFHdFdWeP1g5J1MMHMrCWK5+WVJuVJlzhOvvHRIAS6KJpHQ51ITa+ZuE2cSDhqGSIj0CJc8K7rV0cIifP6B+pD2niz2QV9odGVLofRxqR6W0h6+Fa6ksxnObdaSyMSxsMAQNGjLx47zFgb+htDuk/3nFtZQKtvSQMJJEs6uZNS2Qxps0shfa2RDttdZREqxglXN9XYYVHbBOLotROkuKZuEfjeyDGJJh6QJwd74D3r4VSv1mwxjIJqosEg5+19bUDi8ZH+afTsBbNxEq2Lw4tcVb2578fwBRslM2SLLcDvEVqyfYyaMGd+wS1CwQtnJUmW9cZNp9nUj4bze7pOEpOL/0tKJ3CzgmbQbPIy07AFQ3k85z2rNXPV1MzXeZj4JaUYQJlAdTr1DQVoaZFkxd0dpt17tnijisZiDAmlP3FhYaiNy4DZZI7s8T96KI7J6t2YDaJyt7KNk8LR69n1Y0PvMF7/NZHPBSzIbBpIBdysH7dWl/F4gdZ1VCeyG6UmdYnMa8Z7mXLWVGFWAs8z+c0eHc4mNCI16Y1d2iS4UDXmcjJUmrB/eDSXCmtz1uVKk/5a0SZWuL0AQtYsQsweCDSPgcZ2QlPkdgB6CIdnEToGQHyfn9dGU52HaPZ7fH9loWTJFNqpF3jBPbj4iBP2kCx7X9adBrRIupm+LxHVIIi+W7SACiaQCLwpnW/uMpqEgpCyaINWEVksdXJ/BqugITZtY+a+fe74/+K08TpPoOzrgxKqVR7xOUM4wtX0cZLgVcuWsA0QQK5eRe3VdM5f9GNFCzepxYgEVOihgW0l8SJcUGahVcEjIt9I1n6nScCbjo8NOiAB6/gHJZhOnPwnlpCOy6+WTom98X0NwDspt+RxyYK7BntbCoPXnTPlAO0Iz1g8KiIDD9fqzufkULFzGJ/k+hbOKZi8uxzp7zQXTs0+B19HWrz50m fbRjZmpB YagMAiKQUw6sGAqyf/s8MEeMiN8Yu9BUkJ7pAqs/jPUH8gnLVn8HUpMdaDOhzN0f/QJk30Ro6toap+ki/GoKkL+K8NwCZfm/U0b7GEZDy7yDyRKFcjRf005mQTZeQg/1ThWYrQBVWU+/uoQriU6mfE3syO0Ig60jqKo1nSa9Po+RdS9DcOtfOCyjDQ6kKNNHp5rtB2L3r3vAs+hLaElfeNPb9TplnppuR2dsE1g505nkWkTpODQE6GBUqL7FKGc90uOmXfP/WR6xhiJSY3MRsaQ8BTnMpFnPHtYCFerdyJO4rXHgcbzej+EJJHdS9fGKLhGjQd6sZgGrQuO8= 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. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index b80a3b2b62ac..25761da5a816 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, @@ -68,14 +68,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 { @@ -89,11 +89,11 @@ 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 _) } } } -impl ForeignOwnable for Pin> +impl ForeignOwnable for Pin> where A: Allocator, { @@ -101,7 +101,7 @@ impl ForeignOwnable for Pin> fn into_foreign(self) -> *const core::ffi::c_void { // SAFETY: We are still treating the box as pinned. - crate::alloc::Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ } unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { @@ -118,7 +118,7 @@ unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'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 { Pin::new_unchecked(crate::alloc::Box::from_raw(ptr as _)) } + unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } } } From patchwork Mon Aug 5 15:19:33 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753723 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 29AF2C3DA4A for ; Mon, 5 Aug 2024 15:21:35 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B26BD6B00A9; Mon, 5 Aug 2024 11:21:34 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id AD4366B00AA; Mon, 5 Aug 2024 11:21:34 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9736D6B00AB; Mon, 5 Aug 2024 11:21:34 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id 779266B00A9 for ; Mon, 5 Aug 2024 11:21:34 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 305E3A6B09 for ; Mon, 5 Aug 2024 15:21:34 +0000 (UTC) X-FDA: 82418556108.28.D182BAD Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf25.hostedemail.com (Postfix) with ESMTP id 733EFA0019 for ; Mon, 5 Aug 2024 15:21:32 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=O1oXHRoz; spf=pass (imf25.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871230; 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=UdyeIfTQAHA24KV5GBPEk2+Gwk2HBIVUmVSILtDmhlk=; b=of7LvaOxD9iqLvZ8NxtrxJYHDzzw5A264DVtorIF5MW3rYoisK6/v3wAlxO23JElxdUNNk qB5iHYANd62cIcRWO4hNDDB7kS3/A6W8UmOpiJBwWQZutC28iBlesTGsikC6At3DgnXC7v vdN4fmx1IYLIHloo6Gk4jefb9aGRODo= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871230; a=rsa-sha256; cv=none; b=ApddJMo/4xMZFmcrwvYBEhZWXv7jd75I0LDqx0FvSK5o3625gChwprXKIDykqScPEbgCLg 26zt/GYA39ZxPwPBk1GI2p0Mba/znmEyhktLf5zKl/tp+06jna+UVFzctcP9XCegLY4q35 9zFOUnYTYJu0xxvN2yT9U8vp0bHA1I8= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=O1oXHRoz; spf=pass (imf25.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=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 98DF660CEE; Mon, 5 Aug 2024 15:21:31 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 37E80C4AF0C; Mon, 5 Aug 2024 15:21:26 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871291; bh=Lu3sR+WGYMF1UUYzfkZ9j2xNETNWcnAc7sJFrR4A4JQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=O1oXHRozCxElqWOZx7zUrpBUJXCIC5CrgbAKeFrqcKlcOBNs9+XpKdfy265PO/e2n 0GUo+PujPXsi41M3hy94E7O07PgxZUBhl0OgrkJ0S6nULlWzvpKrgUIEBg0GWG7nJL E3mn/JFadLIHEbOEsL3MQWJ3IdCYLT0JfGQ6cj5mhTUxBnpdtJ14VGxCnUZRyUb4If 1HQONpQID/uAQoBZH93bhl3KmSVoVKgO5rLNsLNr5bwE8QvS1oMqiE/Xmuofhnq0fD vmMbWClGaZPm9KtavkN4Jyq2LQxp6+IOqM/891vzyrtx2CP/fH8mwZGZny4FXDatGR UEkMf7445vvKw== 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 v4 14/28] rust: alloc: import kernel `Box` type in init.rs Date: Mon, 5 Aug 2024 17:19:33 +0200 Message-ID: <20240805152004.5039-15-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 7uf4hd8197u7b45hki1bkz9a1y8s7rw7 X-Rspamd-Queue-Id: 733EFA0019 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1722871292-9911 X-HE-Meta: U2FsdGVkX18g4ZtcFqZKbSVO5m9zOeA6yJUYZInhVIb5e3uOiCLU+RpIL67ix3P/P5z4MglNtTTkNIh9f39TIfMnjWDRPOkqKIp8Q5DCM74HQ2ApyoWiCN7Kof8Ns8FzgTUBE/DPaZejeqlAb0LKLOYvnbYkhStOxmZGTKNIYWGSxKiBVwGw2Dpp4LIJfpzcb0jxXjcsZfUEs90Sjm5wIEIobBLB5F25GqX2L8znAJjkQlBdTadTkHZBXmFd5DK54WSytFHBRb1sQCh7F+2iNXAu4jvumoU1NYQvqL6YSoR4s41q/BcZo8VOLC5tR8+hgYu9/0eFUil/sf4wPd9S7PEQPkKB4ndZ1XrP8xD5rmLhSRdEZhStM6vB0IWNusEyK77EunRfyc+Au16JYCyLH59BqxQzw6ytDVyH1EvE464l7MtVQrg7LnvCAUdFgRfIMggU6KJerqYxrDPcrUbh2uNJmG8R8QxvX7D35KS978kOJ/0u9jY4seahp7M/qk5sBoL/LQBfH8dol5TnoXvRECqwjN8bV9oY4bjt8ICmvDdTPY159DIdsHyFUojKJf8BkKqgAq9QWYFBpW1vY2ADIWu2zgtjRSY4yk/NKnwp2TjiRPTZUZWiWnIxgox3PvU3BFqd5vNJ2L+H0mCtW98ChcZSot1fK+UlQRsOsEwN6RPVSwXgkYnmrBiyN3zkAbIcvjefbPn79Z+yEXRycm/7eyK4MZwUm8C3oduRagXd18hCRFAb6zp0ZnS83qW5PQI0Cz5l89+Dx0tjRESnNayZx1aBO4EAU+AHvjdxdSvRarL20pbc92s6xbJq+w7bEvO92rqOk+yGdgR7sGLTNDAACh11415SjNnjmcuSAzPQwcB4xxPE2j4ON2k4GiLmmKgcg6cNHkiqz/79qq4RZC6FYnBDesGZn05ioM5UXsyLxghjQzyKOjXKinzWIOnygIZ7lxbdQKy+VB27OqRrhv0 PzgSZvlj X5hg5OIeZ7LCPfrpvwz470qj5OIW6f8xsYjnG1LUM6/KmDr+hBAp5amE2eI6dwEILqEhUkRpJuPmDgcZo8SJg9FpvN2vvu/0N4flD6ou3Fk65TUuor6P0jrorjRSwiantADHF3/3MJHthsH7Nn+FbxdErszzdGOsRHkWue5O6rIKlD+h/O2QN0BBlhutr4A8C2B5r033LvypGhbpRG2YLH7W2Nr+Dvy+6Y+FKMZmb9Hrv2LlsKK2oTkcBAJ909R09CPAqQ6aDhMApr77b1fXH47ePaHJzux59ZIL6V46oIlpneeem0vfaN3k3fYIt8vCMEEW8HFtAzW8wnK4= 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. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- 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 Mon Aug 5 15:19:34 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753724 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 133BFC3DA4A for ; Mon, 5 Aug 2024 15:21:44 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A3A0C6B00AB; Mon, 5 Aug 2024 11:21:43 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 9E7D06B00AC; Mon, 5 Aug 2024 11:21:43 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 83BDE6B00AD; Mon, 5 Aug 2024 11:21:43 -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 5FD636B00AB for ; Mon, 5 Aug 2024 11:21:43 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 17853120350 for ; Mon, 5 Aug 2024 15:21:43 +0000 (UTC) X-FDA: 82418556486.25.B37430B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf01.hostedemail.com (Postfix) with ESMTP id 8F9BB40013 for ; Mon, 5 Aug 2024 15:21:40 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=l4TJfxzS; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871239; 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=J/L6S/76wGO0qYCt6t01UNdb+qFSblavWBY5keYEuFY=; b=oEnBSfe6tTf5+sFvhn9a0HSOws1QyOM8KAkrEcqCqxfcOP4P5OKQRxC9yZ5KG24ltS0eZ/ ykYk1qn6MM1ci7gkhkcAvh+x8AOx6MT3or5yVGyy6js5di/HRdCIkqHJaDvMGPhwb1U0Ac 5UdyZeiVXUQysrP4qvUeBwbnps4dAXI= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871239; a=rsa-sha256; cv=none; b=tX+VIMFEpq9jelRBA65UY8jUDubEV0Wmj62l54x52Y82VZkgnHyZZ/3IZpCg/xkq0lkO/7 c34qCXt82iY71rT81OhpfrwsihfmaJAsKKn1s+3t+SzWIEXGbLala/2iV5Ww43nqGsrq4s dvhL/yjNLHNcDxx66/xNmQRzaP5/lII= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=l4TJfxzS; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 886A7CE0AD4; Mon, 5 Aug 2024 15:21:37 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BF289C4AF0C; Mon, 5 Aug 2024 15:21:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871296; bh=cr1cmTv5QS3td1mUWLd800K7nmZjFcH5mHeUUy9c9lA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=l4TJfxzSrnWuBELuNzaXCR3jG4s6NRrfF4HaaoCv6cm1XmnJxVQakLiCZ6KbqQVCd 99iquM1lCTXB2mBYWf8dsl8jFzGclMZN93MfrADoZ53qy1qe21aatiT+sFe/AY2PLh +0NxNBgwbyeEwncwLs52xo97Pu//mQwfGguTZ7dyZUqSN5A/J6XoADAjblK3XOHoTd zG10MQf1UeAgqLTUoi2BJkolHmDeanktLVSyxTZLeWGJoDYzIBYQmvZErz2U7X6OTd dJt33WTRlT2+0QYwAbgd0x2Z2T3hGlbvzrVin/GxXr63bLmXkX16ibLR94JZx8hZK8 CclNjOl0oGTJQ== 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 v4 15/28] rust: alloc: implement kernel `Vec` type Date: Mon, 5 Aug 2024 17:19:34 +0200 Message-ID: <20240805152004.5039-16-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: sgqsjpj546g1q4ejwh4cby935bnjwq7w X-Rspamd-Queue-Id: 8F9BB40013 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1722871300-560884 X-HE-Meta: U2FsdGVkX193TkG1KMnHeP4FcvunopuI1V5tiAx8MXk5ZgNv/ReK8cO++v3v/4O8cqa9ki0ARa78ZKcYpnARGk3F8T6YBK77NnUTKR8a1nvWNBodxUG57jSSqzSTgmisdGkeHCqewYt5LMmYTosH7+UbRQta5VdwH26W2eFnbJC/ro8/NQyXDNXsTy2wrgXILNd16kfiBaO+iOoSgAfhgeTqItqPjiNNVSuWlvOoFVvWbgr7pjSglJFtIf78QsNbQwObdp4AnFwHCNUE0ChV6XBrSb5LZw0Z4EClNCYAyT9Qws/+O/oBXSsxmO9vhkpWyfOKQmtYPPXx6cuX4PqNTjst3TO+tm1gXb9OM9no5p8bV9/hVzTYxkrBVMXAAwdNOhdOL22R9jsLWNDSZILt1hHljwQ1ZzmGXZbWxKlzJgfHVTtt+vahwTE4MsRXo8jie4vnRkWLAfbdteL54/aOtLDP6DuwSMwZ5PrkftiJ6JfKJL+UmL7gOXnv3RnWmbPE6uzioMWe56JK7fVvnXp/YznXXm930dKW0bLQ7jXFXDk8wgjPmgmGS2lBVZj8LXV10pDiqgMMdE2MWu5E1icjSkXfNr1m9+wacm+xcu3MWfU6uQXbPNR5CJPA0Xd/xT/8BwKKdV66VVXad3TwZPa7uXLxzhPpxgiZRzUOkoF7brz3zA2fNNH8Vc1zihxUc3xwHKelPobVpHvom+HH+uv6Xh6LJfpj76fK4efp4jMboQjiNyX1DuTpGVxZMvuIphFEOSvFFq1zrwroDFdbCYXwZphKvneVvU7z7xmyRIn4EGPjwCnf7jrjBJ+j3yWq6ucLXjF7qaevT/U8U2wTL/QielfLLu+2gdEJV81hLtV1gHrNuYP63IOqj3ejF0DqXgO8F9ZAwJ203eRMyyzzZvxxzCkD5A9yHl6EamF7Qeee/HJcoEfPlcLZmpSdwh3LILCD1irHNUMXqXGIKxhjCst qexYxj9G loXWyBRD7JD83dCQYC0ENMah10AoVeUHVE7gkDedR9WMh5gKTspfogZhGdihriuZd5CKZ5NCM66iVe+awaBYayhw+5wxKM4WljWgaNBGgWIfj9Lisgaw3RjBj7LRIBPs14PcdkzBQE8txZbRYscONOy4AptnmtTE0z+NCRl0pw1ERaT8kqrxhnQTJLDYNVLdy3em4Fm+hU6P+GlOQhBRs7i+69scyvw7E1oGxBcT7kxQVi0563nSclTA7trx84MPpWbihLNzJ3r+31N8HeLeUZGDOG8wTXKRfDZ62osIpsh6IB0wdNMa70urHsocXWjrd9fx1d+dpcgTGeJr3wZvKS5FbzQ== 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 | 591 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 4 files changed, 613 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index f578175ff010..28c186906e1b 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 4a4379980745..02aae24edda8 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; @@ -150,6 +150,20 @@ pub fn into_pin(b: Self) -> Pin } } +impl Box<[T; N], A> +where + A: Allocator, +{ + /// Convert a `Box<[T, N], 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..6cf62e7dd36f --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,591 @@ +// 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, + /// Represents the actual buffer size as `cap` times `size_of::` bytes. + /// + /// Note: This isn't quite the same as `Self::capacity`, which in contrast returns the number of + /// elements we can still store without reallocating. + /// + /// # Invariants + /// + /// `cap` must be in the `0..=isize::MAX` range. + cap: usize, + len: usize, + _p: PhantomData, +} + +/// Type alias for `Vec` with a `Kmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVec = Vec; + +/// Type alias for `Vec` with a `Vmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = VVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type VVec = Vec; + +/// Type alias for `Vec` with a `KVmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVVec = Vec; + +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 of it's type invariant. So the multiplication by + // two won't overflow. + let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?); + let layout = core::alloc::Layout::array::(new_cap).map_err(|_| AllocError)?; + + // We need to make sure that `ptr` is either NULL or comes from a previous call to + // `realloc_flags`. A `Vec`'s `ptr` value is not guaranteed to be NULL and might be + // dangling after being created with `Vec::new`. Instead, we can rely on `Vec`'s + // capacity to be zero if no memory has been allocated yet. + let ptr = if cap == 0 { + None + } else { + Some(self.ptr.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(); + + // INVARIANT: `Layout::array` fails if the resulting byte size is greater than `isize::MAX`. + self.cap = new_cap; + + Ok(()) + } +} + +impl Vec { + /// Extend the vector by `n` clones of value. + pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> { + self.reserve(n, flags)?; + + let spare = self.spare_capacity_mut(); + + for item in spare.iter_mut().take(n - 1) { + item.write(value.clone()); + } + + // We can write the last element directly without cloning needlessly. + spare[n - 1].write(value); + + // SAFETY: `self.reserve` not bailing out with an error guarantees that we're not + // exceeding the capacity of this `Vec`. + unsafe { self.set_len(self.len() + n) }; + + Ok(()) + } + + /// Create a new `Vec and extend it by `n` clones of `value`. + pub fn from_elem(value: T, n: usize, flags: Flags) -> Result { + let mut v = Self::with_capacity(n, flags)?; + + v.extend_with(n, value, flags)?; + + Ok(v) + } +} + +impl Drop for Vec +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: We need to drop the vector's elements in place, before we free the backing + // memory. + unsafe { + core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( + self.as_mut_ptr(), + self.len, + )) + }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.ptr` was previously allocated with `A`. + unsafe { A::free(self.ptr.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 Mon Aug 5 15:19:35 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753725 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 D5AC8C3DA7F for ; Mon, 5 Aug 2024 15:21:46 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5A6D86B00AD; Mon, 5 Aug 2024 11:21:46 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 336D06B00AE; Mon, 5 Aug 2024 11:21:46 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 186966B00AF; Mon, 5 Aug 2024 11:21:46 -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 EBC296B00AD for ; Mon, 5 Aug 2024 11:21:45 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 55E24160382 for ; Mon, 5 Aug 2024 15:21:45 +0000 (UTC) X-FDA: 82418556570.17.380F64D Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf20.hostedemail.com (Postfix) with ESMTP id 9C0631C0003 for ; Mon, 5 Aug 2024 15:21:43 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=gYzOyUPG; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf20.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=1722871258; a=rsa-sha256; cv=none; b=69ZOamafBSk47+rb2QeOvOz1w36ri7wZCVmpCIwlaDuaMAZdgz/oD/5J/iN4vAWFnCxgqt ovL1lkgxjYStxJCYqEU36yAEUIXlTpWh52A7417WK7BMKm/F4hDRRZ50WLl7Nmddj21pxD 5reP+Kxsq5gDsK3eiyvpC4erAM0kRJ4= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=gYzOyUPG; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf20.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=1722871258; 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=Pn11VUbkvJ6GW4qxPbHU7GLU2uJVUSDKIUWvFado2sM=; b=LQW7D25iAz8yu6kR81oe/HUvBsbrmr6qhRssJkwkliK5lJZ6NX2NKgCL35xDSmtyz6EQ9P l13Gx2s0KKMMxq/V8Gn634ZrQ0BxsGIRQpJyRpquUrI5BxHzHM4rq8UDBI0zLoBUOIRQfH PwkFzetFEVNScz/TBeJn+vRAfy2Edeo= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id AB49960CFA; Mon, 5 Aug 2024 15:21:42 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5138BC4AF0E; Mon, 5 Aug 2024 15:21:37 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871302; bh=EOv825N2AZNtDITSBB60LhXsn2pwxBz/HyLjwhp7xNk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=gYzOyUPGGvzsiMCuH+V0ldzMfE7hiGbdGKAbK0Tqa6euhkVivoi0+hDENWQHThRWX 2w3a6tls/UCFaVEKHsLRO/Q6FcpFslG5N1YkJRZedT/KojKDdDCeuiEd/Xq5ddWU6r /Iis8UdRt68YDCxh1Agab0XRwfReNwszxWXPVnUoxXuigGnHnZa2i985IhIIqWqtTM UzhIiI6lhVyQ8iLU3RHkQAsSZlfUwQ/7VGf5ejaE1bFFHRvERoofuYrFSFeCxqkNFe 1vesmYCILN1fNzoBV69DgiNt2r/AcfQyaEAz3pCUSha/OFhcumt5MJUu+VIjUPcpv+ 4TBxhXiqojWPQ== 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 v4 16/28] rust: alloc: implement `IntoIterator` for `Vec` Date: Mon, 5 Aug 2024 17:19:35 +0200 Message-ID: <20240805152004.5039-17-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 9C0631C0003 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: zn7ok9r4pip5ryu8zpayhap1hoscmfd5 X-HE-Tag: 1722871303-967220 X-HE-Meta: U2FsdGVkX1/kjIo6wAuWkYrd++PyEJ3P2xa2ZmjwLD5QXZBIRvRUV18eHEsomrndf9yu+RiKyJmz9pBRQWkCcw+kVbbw6lYSHZxzJZADt1fCsf5SUB+pOQar3kfjMYX9C/qFwlGDo1sAZHD8kALamKifCGU3KIRm1xfCioCj8cG6HCXWYMJfPpKovO4f1Sw6HRRe6Zz7/38o4UuaBM6NybYLmCxYi+vGNlZqwq+5DlPTsM87VFmJ4mfiXdBI1MXQXZk4cuR0/Kx5wWxHf5LOlkQeUPqBS1nSaOGU27ntQlRUiMgN1f7tbpn++dr/s3NRhgNUStirB1VCu86ryPi9knPll0cJQdzCps5MwbubfQkLcWX0LlN3A4LEwVD/wZyxd0ezEqdE0lg7peWnMJcQ6y1/2WmW9NdU8QGL27ehGx0ytpeO6CCbaB/IMNaiV4F3/S1FNzBqgUhGWnZRyc5UhTJDc7HvfSukNxp2NsEqmZ6munYaMtn9aVZUfCut7BG6DOioNX3xrvz537BGzMgRWeTwIrkdZ0V5wk9+aS77IXPlZ7B9tpByKrusaZIxtf7SrW/B0+VOgkADt95BsdC3JHzZsbMPG/cfQermGRufZaE0ngKZYW1n0R5qh8tFNYQvpqKCgPD+R+3G0+c48BxXDp+1yEkyns/ViTqFSfOP5fo72gk6iliWDoof+UaNtwXc73VgUs7QWEAJzKnQ5CO7va+kyC5231vkp+B/9yfVzXGfGFGpFm9lnaOFX4bqEVAfpue3TfeuEcLVf8mnWwkee6IpI9XQQn45u8xeNcghhFPyy6rZ+8M5BU1JNRic2EonRX3msRLXX129qs2/1fCEfn7yiScHEg+IJMIeLUzu4m+XotTdjNqfuo9ayQ9NYdfQklsOnU6lwQ4yw/aDZFFtyTLk6gNkJoQ6TF8Anv6DukZGfr4labMgQrHONFM5X1Ljf67Bbc23F+gJGIP3e7x 7JKmTqHz 7pgh9biKIrU+8cu87IjOVFMdk60/dsMCbTmCEczaEIMC0IYCFpdwllAurwOYwA9nNWcvRX6gGUSVHGAL+NOFUeSWuWUwZStp4H6/Ya1k9qXPHG/DkLfZXg5ix/bK1j3GoozWTCFU9FjG//rIAjq5sCBR70/wm19vuNle2hayllTw9Y9J1NkUOqNzn24cUyyadOhHTvVPr8QNbNkMDqVGmXU8137RZ3up7u6949M/mXqFU0ccA3XAShD+vLdePdjezRmPWHLPA5Dxhzp/pe8dYO/5KdDX3hB53OEUMXeqN4rwF2f77y+N46/5HouadEHTlu5rCSEmJGyZGuPqU+BOs1hunRQ== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as `Iterator` for `IntoIter`. `Vec::into_iter` disassembles the `Vec` into its raw parts; additionally, `IntoIter` keeps track of a separate pointer, which is incremented correspondingsly as the iterator advances, while the length, or the count of elements, is decremented. This also means that `IntoIter` takes the ownership of the backing buffer and is responsible to drop the remaining elements and free the backing buffer, if it's dropped. Signed-off-by: Danilo Krummrich --- 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 28c186906e1b..86648037b3dc 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 6cf62e7dd36f..51426e0b28e0 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, }; @@ -589,3 +591,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 Mon Aug 5 15:19:36 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753726 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 C3E74C3DA7F for ; Mon, 5 Aug 2024 15:21:54 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 506FA6B00AE; Mon, 5 Aug 2024 11:21:54 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 4B93A6B00B0; Mon, 5 Aug 2024 11:21:54 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 358D26B00B1; Mon, 5 Aug 2024 11:21:54 -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 141C16B00AE for ; Mon, 5 Aug 2024 11:21:54 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id C82A3120316 for ; Mon, 5 Aug 2024 15:21:53 +0000 (UTC) X-FDA: 82418556906.10.5033C5C Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf05.hostedemail.com (Postfix) with ESMTP id 7DA4E10001A for ; Mon, 5 Aug 2024 15:21:51 +0000 (UTC) Authentication-Results: imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ID+VTQPg; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf05.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=1722871262; a=rsa-sha256; cv=none; b=QeELDnvqIzB70jtfHXzOcahk5DR/rBcSsB395oy5mJp8VbDUUvGWka7lBoLZeScwTyeh8F NX9/FuaszTcYqdtiGqYevuh1n2jyfPEA8g3fIwxMUBDPOIIDvbvl1RvAbED3D3KEqT03LI mJI9cNX0DFOwkMU327qrb7U++wll9b0= ARC-Authentication-Results: i=1; imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ID+VTQPg; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf05.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=1722871262; 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=yJbzbI2+Y87ayk8SDBOTkDSCjpAlw6Ll8sUTcXllnvc=; b=I0PN7UMUtoXkGjFGlrJOqPay0UJv0ncomMdu0v8Gt3OicN4hosJQ8Vw2pGMoV0L7tPANf4 oW4T8FVhVVmJD902tIYArjSi2xyoYnnrbJ3oR/EiQO8TZIzLFCWPrLw/iKIIrCdSntTAf0 HIB5neTzOHj/Y3uAgmc2HsxS5o2yLRU= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id A1FB7CE0B2C; Mon, 5 Aug 2024 15:21:48 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D1739C32782; Mon, 5 Aug 2024 15:21:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871308; bh=XOcjCrkdVgWqenxc2S4POpPouyHf3iALRM/oI15aNRQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ID+VTQPgxM4/fo/86PhXM8wRLmUNRAGD0AtIR9PtyYSxsVsHuIDvWngmOC+r+/vdl cIN5C0KpCslxLORbqND66Zfvihy6aQlgFRHQSOk+wpPpD6no4Yud3FS3rT5/CDIs+Q BXWO+4zgoIp3+nxfgwueV/3Up8duKjAUksUMzqgF9+qdt+ovvcXwaop8+MVbGixguk J37SZmf69xbVFHxg4sKet5BDZPN8wgDPz2zaed4SF2pBsXmPcOIYsKi3/lRW5i0dhD GYikD+tDejphoiiin0o0ZiQI8f3sVZyMcYBKWRWvI1mrEHnXAvU4qMpi8FZ/YZw/ab ZS9nCCDnFf1ig== 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 v4 17/28] rust: alloc: implement `collect` for `IntoIter` Date: Mon, 5 Aug 2024 17:19:36 +0200 Message-ID: <20240805152004.5039-18-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 7DA4E10001A X-Stat-Signature: nzz75p1979q81cxbjkgncemh8rmqpxmn X-Rspam-User: X-HE-Tag: 1722871311-538663 X-HE-Meta: U2FsdGVkX1+2pjFDBIKtmj/abBPcGU7gOXKfyCfTIV8XJ6o+xBmiUg/H8P+xWCcX18N7kW8ozOqV+iH+XipVtwNs5m4nIF8EdLgXcDLwP5onyumFXmTDcfHjplhMhVSpqaYaSbgVdpeEIJrluP9MVOTThAhhgJOqf5XnFxmMRu1WPwmf+1Nu4lClW1GdaoLcjNuJZ3pqoh67XOEpxFa31iGOLabH6jYYNm3x1wOmoI6p7yWTDB6d6lplftXiBzpklBdntIX8vqcAFokQNuCnGVsb49MnpOs2gia1oy+i3HSkmAeg46ZuHK8VqfFrDvMquQSZpEZi7Z8LDxFlGQLQdzVMSmq94QzBRAcjG1jymV2CmzU7QJ8h2gj3kSwK0a50OZFr4qgQE9WBpo36YwmyUjumbgrcpVchAOPcvBABEhC8Ggyanp0txzkkxdw7/B+m6wcF7HSBspRLQrX0kkNOl+6bJRY4fD1aeIvjm2TZM7RF0Nwgufo8HShkuTv7tHsUKniJWDngnG9r21jhNq4Rbc+APAidINNPxBvYF8hqZjbWaBJoslG62r2VpFvrN0xngNlOral9E+jSwJRxKY25CufKwIywKBfynBeJeLYezhrPS9YZ7jwmT1OkugQwenNIiLulzDwZ2IjITElCKmggoiUh3m6t+GSm+a+UsKCZpi0H7bbJFezpTdyiFCClTeX8LOQDn617f0akVMlbg/FeAx6vuvOnhCXRxXWMGAhp9Mc0TophTePZuhwmHLdYvxKUbrdKF9lwuie9YvDDpytSZIRVc5/ok1UquvLbNvxvD84rX8XvExXe/4OBSS0JqLn/dxN5mnvmtsglP+LiUCcjtSa0+eyFbeKdcKemr89RjpLMZoVn0EUKcWrD9+k6AAhBWPqq2+hkfXpWNDdpClWdhsatT9Git3yaXwb48x/84p8PBr1NYuIUXGVxFbMrs1FJNHKGo52eElBRWejecr4 N65qx1PV +aDoOz93Sw0eYLKnIbgqTS2uZH7UQka9P2l82GH8w1Jqh56UZ0Yk1SUWnBJtWyfvzfE9FQ5grjAg7NCcQFvB5Wmd4aFMkX1kcwKVKxfXTqnSmBRLpnOM2jXhmIru8r92XalNp4CH+K7tGf1VgMDrtpf1W/fq5iEZuoV8LNf14lbjc1svEWOXjRnxipW0ESktq3ajYtacOhee/Bq/y0XJPr9gLaPb0b9Gwizu4XCcVzzxMN/os9G5BGfweVR5naawJOMj9rG9enwGUiUy1In/aHvRkPjUgV24AzwHWR6zUeMXNOKL3Vx9kCOXFQurPP0iqQ0f3YVxXYMxpnrw= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Currently, we can't implement `FromIterator`. There are a couple of issues with this trait in the kernel, namely: - Rust's specialization feature is unstable. This prevents us to optimze for the special case where `I::IntoIter` equals `Vec`'s `IntoIter` type. - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` doesn't require this type to be `'static`. - `FromIterator::from_iter` does return `Self` instead of `Result`, hence we can't properly handle allocation failures. - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation flags. Instead, provide `IntoIter::collect`, such that we can at least convert `IntoIter` into a `Vec` again. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 78 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 51426e0b28e0..160c6b3868fe 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -644,6 +644,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 Mon Aug 5 15:19:37 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753727 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 6B869C3DA4A for ; Mon, 5 Aug 2024 15:21:57 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id EA63B6B00B0; Mon, 5 Aug 2024 11:21:56 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E555C6B00B2; Mon, 5 Aug 2024 11:21:56 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CF5F56B00B3; Mon, 5 Aug 2024 11:21:56 -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 AD1DB6B00B0 for ; Mon, 5 Aug 2024 11:21:56 -0400 (EDT) Received: from smtpin04.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 705A61A0304 for ; Mon, 5 Aug 2024 15:21:56 +0000 (UTC) X-FDA: 82418557032.04.BFD9B2F Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf20.hostedemail.com (Postfix) with ESMTP id ADD6B1C002B for ; Mon, 5 Aug 2024 15:21:54 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MkQ4E7lU; 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=1722871253; 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=UKZ9RAu8ebJNAVhjA9eapP/9lH0KMLQ4XSXutoY4puo=; b=mPjSuGWo6OPwaDYZDHOhRyBEuYNgriOmh+wfULanHC8t51361b/wZT0bvO9+bQMHc9jP6c 9r9x0ySEcdvdEelnOM3DErzSCURdmK7/a7/254MNvKeNxRLbhDhrx+gsFGF8fZ24qf1EAD NR1z3cTErC+kqZxuTmb/ThqBaib7foU= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871253; a=rsa-sha256; cv=none; b=kmK3u8x7Iq9DstAzreOFOnZEBSoZI1HMbur61Q8TFB7Wf4WxL2u2NmlLNCtbmbEr3oHpmh 4h5ohmKdwa5aXr82lzya6I5c/zMiT83pWhtZPpt7mZ3BQqn4jqThRNWUEjJ+8xPxeaFpqw iXivSfIMtQHmolgPGQiIb6GD/zuCL2g= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MkQ4E7lU; 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 Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id CB92560CF9; Mon, 5 Aug 2024 15:21:53 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6B1DFC4AF0B; Mon, 5 Aug 2024 15:21:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871313; bh=sdhZZznOxeJHYY2QktGYlgQTOZb5ZmWJzNbZi+z/9XQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MkQ4E7lUhaA0lmzYa1EHdFvKHEGKH3UaU98g02eHPsVkpZdobEUsgc6JS0S4ZeS7w 0OEYLvf80LOr0XH2SuWFHa650YREeChd5r+BWZdapI8e0XQarq9g0G4TCdCCafzNDz Yveqv1PSPCmyYHRfql+7X1bDpnOoCYH4OMQHrXYH/K+7Uazzk+gAga/H3DkSJQOGdq 587aaNTegtnnLZ8Cht4vWh+KJE0P6u4fmkd/qbAz24AqY7F2NoUjNdEsy+F5jwi+D/ VXFPCh4t4eQmfdJb8/5B3yD1nWZAGK+1lwvwIZoJP5sm0r9PS7YiLRz5JgJcnntiE+ bOpo61yC90QRQ== 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 v4 18/28] rust: treewide: switch to the kernel `Vec` type Date: Mon, 5 Aug 2024 17:19:37 +0200 Message-ID: <20240805152004.5039-19-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: ADD6B1C002B X-Stat-Signature: e9xcfqupbbcxik7zci7rjqjj4o9e7h5b X-HE-Tag: 1722871314-593830 X-HE-Meta: U2FsdGVkX19DihNK9HUsilXJqfaJKe9zH26xgDGGoFhVy934Pwqg/9BWJ8F246Cu2KgZQHiQmDUn2FQhsgcaQbn6SgvwfdEOS5ILVb6VMokjoIvAslTmv7jUmp6Kwb9ZtodLEcbQuPiP5o/x1dD8ZcSfZTjc3TIAgi0bxPHENqPVFWkES8Fwi6L95OwK/3ObTWvIk3XDAqMUWNzisBOpzNtLcPKXUKVE0adsuWFdHFeHMciN1bq3WJ90GJSOUQBIPmpZSBjOOI579lY5imCjkYZE87GA0/w4VRcCOsUxbbND9u5/vpyPDDg4i5SfRuAkGVTQzuC+bALr1EUk4F7ZTQrVJ+C3TED1lsU2Gt9/HHv5LvdBQ/Y2ahgswZyzVEhqjRcpXhkj5YOe8SxJJDpNYlxGtYQNk2Nlpo3TOTF4YTloE3cCwC1g2I70CxLg3uNO435DxHZUboj5VwQ1Rxmf0c5s/cx2/9g/ajz7Of7Y8KyoxnwJl/hxONcHCws9WO2CT4z2tAjXbyoijNyZqqgHmnkEByCCb/UgukanM312jhEncZ9tHjQQvgv8XvwJXQGtE70eU73/dDA2eTkq83zE6CcB+Me3S8hms9C8It2LWJzhecmKI1MyW4OmCY+3UWtFhi/9IKVfqJCJRJi2hDIBf7xoHcBVpSMXe1KK0lDEnHbFPY8Gq8YU7PsrD0oTi2znCKp5mjHHTlBt/UOT99nMYz94MU5qwkv/nD6gf9in6t+71x9Jo0yFVuPBk5f/IwK9u19/Xs2RgdbWhP2YkGbeHZz2JNiLmStQojUWWmL4Ry0t8Z8oENmr1IOi4RpYOB5WliP0t2c5LlHJ+ioWo97cWRJI98hM29WtLitDC2p+m90Am69nNCJOIozeNJyqDY+nq3Pfpgqr4vHJecYtGYDhrenSJj5h8EE3ft9kSuEmOtNkJfwTNLEiQpJm6ZTVNM1FUfAVdojzJafLm+6gkax 741GOhBe n/mgVWuYW4li5Mwl4xQFHwsT2hCKfzo9hhYxsXW8cddrBOCqqHvdST91bnERVDxGtm+nRr30j2BBkqz+OWZ6Agk/ap1vnVCQlzUwCNRjfu8NdI8vgH6D3i5fKwDOYE5dPrcS+y5yTfojEJwzEA6wJ0aP89xIalIRJYlgHHpWaA+Wj61UwXu6AhsdkPdgNs2tNIxJHIzhYzejv9rKCUWZKLJoM1R3JeO5uk2z1QY+6jgw11+u1i74zd9zTrDfWweklhNKa+IXdCYjJVC4v+w/uPq/DfPQlagdq5T0aU+mPoz3HGDvrbcfki2dn4A== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we got the kernel `Vec` in place, convert all existing `Vec` users to make use of it. 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 25761da5a816..25f290428c8d 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -188,7 +188,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 Mon Aug 5 15:19:38 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753728 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 B91ABC3DA4A for ; Mon, 5 Aug 2024 15:22:05 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4BB876B00B2; Mon, 5 Aug 2024 11:22:05 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 472158D0001; Mon, 5 Aug 2024 11:22:05 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 30B2B6B00B5; Mon, 5 Aug 2024 11:22:05 -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 11C536B00B2 for ; Mon, 5 Aug 2024 11:22:05 -0400 (EDT) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id CD4391A02FE for ; Mon, 5 Aug 2024 15:22:04 +0000 (UTC) X-FDA: 82418557368.13.AD6F214 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf27.hostedemail.com (Postfix) with ESMTP id 6BFCA40022 for ; Mon, 5 Aug 2024 15:22:02 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=vEdXdA7H; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871241; 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=8F+7W8UA/cLDJIsdDWd+MCIAi8y5Akc5eKuUMGzJLWU=; b=eAw4qOCCnkkR2j7lHsMspvCMSX7KB7Uy6B4YRmqVMxXbOlTgFqOze5Hrimjkws/wDy7V7J QiepsIBUkBN7FAqibTMIIHPqUz7M60zUbg80PZAdzy0vuVokZ49aWP7l6wDjS9GQ3i4MCZ PWGDIbs3tv6nlZthoS7Idsa5Z1+xURs= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=vEdXdA7H; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871241; a=rsa-sha256; cv=none; b=dN/XwF4l6yobvWf1JHQb3I7Fu74cnUzo3TEaf83Gqf2Cr5l/h0vqRPONLQ0GoK8Go0d+zi fxAg5OXMSVvNb5GfCQfuACXeluuoBqRKs+b/jD/X05+aLiJ2fkwRvzLX0ZCZnvD4C5CQg6 kXdME9wL94BjdwkOV/jSN2HZqa4zH+c= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id BF3CACE0AD4; Mon, 5 Aug 2024 15:21:59 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id F250DC32782; Mon, 5 Aug 2024 15:21:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871319; bh=ypL6fvsZDuvmX189rxd6X6uwkZYnuKjYNcyeZ7x+t1k=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=vEdXdA7HSshrjfYIce17wK6XwMWAxL5/nLqSzAiU/5cLytRr96oxtI7KOaSfS0RsO oSbmtmEyXJ+dKvnZBNHUa0PdVCxoOQxyHTf5obH45VXEvZMpJ9B1BkPekczRj8hMuE q24Aj+MKfpnljYS4ADNghs0T1tvARk+aMXIKthsops+ru9pwa52jeLuMgu0rcK/NZr Yx59pGZn64/lzczgduEr7+lfY55W+MjDyxNNUIXWAD/+c/OYNeWK7IQ3FdN0K7doHX 2LTX3nxg2DzkQNZ3PBmCYdAof2gRyaitYq2Vgd7Fh+Jkaay4eX7I0NepviC4ypI2gl qzWCOjBZxaIvw== 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 v4 19/28] rust: alloc: remove `VecExt` extension Date: Mon, 5 Aug 2024 17:19:38 +0200 Message-ID: <20240805152004.5039-20-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 6BFCA40022 X-Stat-Signature: e9kacpbdrkzrif4tpxd3muqrudu7fegj X-Rspam-User: X-HE-Tag: 1722871322-895038 X-HE-Meta: U2FsdGVkX18r/Jclzqve2lTluXs6HiUpJ8mvrAp785NtOHY01C1kQ/pThCCj51ZBFdRKhfsn+9TRSJZs09QxoIRzKhxC72GRfTQ6huv0/1/E4dGTnnMFxQN//B+CiZVy76EMQ/YXrh6f2qIalnFQrfx/ZONOlez0T6lohRJQ7AOKu+VcOyD0Mso5oeSAWFpaYKd5Oo/UBSkpoWrbS963iLPGOS86oAZshZOzB51DJnSZKeYE2kfg5fOpsNPBILhy2eLYoO5G1qIx9ZAG0nShive0uxu2GMlQEDF5SgKsM7mNOlJInMSJiiZBFcM14jYoIzo4nBTKvRKrVrAXNG1E5UBCCz6eYI0c3G4BvR40FVDiAlZYRz3DVtmh+T5H9EFR79NnHa2t8CkjG/ShJDGS8NkY6b3bo49OUelhyiO22Kqub+/J11OMzMZek58FadH1PJ4FVz+8zXALH3gbKhyQO/ktehJ3E7w9AHapTeYMnLnt3RLBBTWvWXbH+Xy7aL7Xd7PX97klAVTQbw8KI1BMHGHTVxe8gjTke+HJZVBFajNXtI+NaLPZKf8CE+bIR2tbfGDh/E4lY4+6RT3TTWZ4X+0NeXvqmxmEpk3YRx1RHHItGZ6yaD30X/EIMC9YtOexu7dh7HlsabVPlia5bVjW9KUjbXKdG6Zy8czAc9tWS5yWcz4wqctLcuxtoJk223v5caBTk/P6+07zI9Le8FFpxY7ktFb+dPpWTfCxRzUDM3kQTbkjweKLKLTnii/9jqo7gupcJzszyQPTp4NMdRw208U8nkFVZUBOh2vm84A5YuRXMxNg0YEDX/sDlcHo/7r5JWE/RlvhsdlGMoQsZ/9v6CjgjwXNruQEsZ6qV0DMMjkZ/Hv3A7sfSF+Of1FhNoW7MKmlMiVzkMwnEIFwYvNk5Ik2xbIoN72iW1+YKdOul7BkemAnaIO7Z/wURkf+FaSd5Y4/2qPhgQG7goxowJq 3Bfoytad mVi58xX6rYpZjP1DKrV0PIMD+/wcSRyT9MJ1360KTcNxlPwPLkML0lUI2eOlIxFgJVUDYpMGAGyOm16Cs2WrHdBguYtwxHKl+3aoWnHqUr4R3M+neLaYNeuL6wryg3RXvaBwZx+DiBlaCpHMasff+E6V7qrgcy7HDtmOE7G7wQMq5jO+bA/bRHvjC+anbF9iCEQzJr7uoFys4bL4F5WCpMoc1sjowvrFAp3ojFa0aaCnnNlOze4cjRAlLNPSLks3Vz72A8M6/SYPBButzFYCdGqjrqnLsTPKwX8iddk3lsYvW9gOPRP/SOLR/Sw== 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 86648037b3dc..8a1cecc20d09 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 Mon Aug 5 15:19:39 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753729 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 8DA80C3DA4A for ; Mon, 5 Aug 2024 15:22:08 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 15FA36B00B5; Mon, 5 Aug 2024 11:22:08 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0C37C6B00B6; Mon, 5 Aug 2024 11:22:08 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E7D976B00B7; Mon, 5 Aug 2024 11:22:07 -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 C85A06B00B5 for ; Mon, 5 Aug 2024 11:22:07 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 836E816034F for ; Mon, 5 Aug 2024 15:22:07 +0000 (UTC) X-FDA: 82418557494.08.3290F84 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf28.hostedemail.com (Postfix) with ESMTP id E7C86C0006 for ; Mon, 5 Aug 2024 15:22:05 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GiluqMtX; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871244; 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=obkndDpLRsuYrnq5naqJZ5iz/S6hb9izv0qpXTyopO5CROBQKdq35x4jA1vpqwT0cD/rvB uVcjp34cfpkzrYt2SM1HTUldW8hIwJSCfUmfK3Q9HEeNPLRUKQYZqhHsqx728G075/pLRN GNTfsujbIdmeOztGpU9/oEp9/9Qs4JE= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GiluqMtX; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871244; a=rsa-sha256; cv=none; b=v2UY4Qm8ERi7OmSGUenVGYHQJxuhmZ3bGdnrnnPHEc0K6UKtzq3cnrTe3qkkC6qlvOxLr7 wYu90Jeaub4vLdfRG+L3OhK/1mlLp6VQKwp3dFAIzQhVVQEOXUqvHUUK3Sdacp1gMoqueR iIT99tlU1B7MlTc6FrobLpK/M6u6kQk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id F061760CF7; Mon, 5 Aug 2024 15:22:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 88645C4AF0C; Mon, 5 Aug 2024 15:21:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871324; bh=x0JvvRfi87BBCBI94b39MtnQOfc5sS9njBcl08nLwWQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GiluqMtXdZRrGxd8njXJGzh/Cnf1XJFc2iZ23I6ziKDaiDjT0f3p1u4HPaC1G4uah l/YEiiIvjf0b4ltjN1ueSK3zylXBNT+K5g3kxc5BVTvZikzngFX62UcXk2YpAXbB0K MI7i5QKXgq/K8AEsUY4PueIhpjWMF69MREMH628K7zjwnNn0tHp+bGVhN1o/5K1edB XPtQDYlm69lFVM1TWny+/5dfby4rl7p6JyoEqgxH35gdvfGTk1MZNfQ5elSVOtDc1P +YkOJ0aKYgxQjOzrh5iu1d4rfGViA3aD/ymffHIe5ZVsmU6RqHWOj631lcpYfb/NEd ua2KgmEVCJ1gA== 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 v4 20/28] rust: alloc: add `Vec` to prelude Date: Mon, 5 Aug 2024 17:19:39 +0200 Message-ID: <20240805152004.5039-21-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: E7C86C0006 X-Stat-Signature: a8rwekckk6isdw6fxwniuyfuwmak16q4 X-Rspam-User: X-HE-Tag: 1722871325-282471 X-HE-Meta: U2FsdGVkX1+9LPXb5bMdiayYPVUzsrinLi7yw4v1nd5syiJr1Wm3rF9dk48rqYknu2OUXyj0JrKn/JImPnvShPGhPvwfPmGbruXI1GJ4jQn5sCycsUlcsruXnUufpxieRosegvshfEp1ErhCseSTK3Tq7cAtJwt+2NQidJaxKzW4+mC3+zMMWeU1pNQeNODC76LBv5/FZGgtHOSFvi8g9iT04QPq4T+/dOU3SZzuRYXcbyNqjX645Dh4it2CmsV6OgVD+Ctp2kbkkfFnwbFZJBQ9sW7sBRaZZzli5NK/qU3dsFYqWxhhRLcrZT8+jv0Ks/iFZvsc4FuA45ZeU1Z1IjzpVhQvMPGpI9GJ9j7UlS65I/s2VNx93Toljg5GFFyvMwz+O38x+JtJ5Zl2w/Y5/aZf+YTvA8SMIkeIy2AzJ1bMja+4QCUeqVm3wvSUK+x8p+vbQSlD9oF9ORNXsTHdYCkT+YkfSXk0amU8T2eFFyPDM8vGtXm3tFle661ITIKjQWWoqeFMpx7vK9GfjvH30+iWh8xC3MXIcWYfwH/kpnlJQvUXfkY+FH0+qHFqVN0usY7O+M3dFaZujNWztTRMrAdtmiYZtk7/tKNclzI7V570s1J39RlYcR4K5ra/d1zFvBb9+Vuv4ByjZGXrMeHbrjYc6cvu7HzjhshmhUn8sMYNbqgCHzMTdecMI5eDlQuSBLuLZ7KpzerbLEPKXn0oH2S941rO4G9Ao0JOr75IfAQXup9RMsLo7VmKl4BkxPlE+BDAK4yunAWi/3lxgrSifrgMMJERpwOACzjhdG7Aksl7c21QMPHAkAQwzTqjnJ49BRdV488YMWqAfH7EdlHiglCgBf4wywFrL/29dM3268uptxc2rxP06Qv4KMhBDwe1Bg6ThbAWUpCCz8sjUPsKhZh6cYjPPtHkaVJj/XGo6VeVlh2s/kHEBlUC427BF0Z7qQyRVA8+s+9LbVyhpMo XHjqluDg htAo63zEFEY/NPZ7eblUnI16Mi763MJr4/7ImIOtvYFqpyf7qlfNYB+291hwfo/W+5hBhWilDN8QowFJAko71Cr8Cn8+lN765bGjOWvcij6zP5Ok51Q/etHypITHMHc63znBhCpKy1VC+8rAh+gYVHmTD9klkD0vojcXwNGV/hkfgFoARDrTFqjmTfaIPUbTxH7MqJP1cHb4dV0K6rAXYtgBk2LfaM4QuSWovMRiRSE+BYXIuPxi/Y9AFrtg7IqZHe3McTVEL7t4OA05OJswGI2uMYEtWLX0+kwZ08RqBCtTHSn/RQQE7kq/aug== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `VecExt` and the corresponding includes in prelude.rs, add the new kernel `Vec` type instead. 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 Mon Aug 5 15:19:40 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753730 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 B5779C3DA4A for ; Mon, 5 Aug 2024 15:22:16 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 52E8C8D0003; Mon, 5 Aug 2024 11:22:16 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 4DED38D0001; Mon, 5 Aug 2024 11:22:16 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3A6DD8D0003; Mon, 5 Aug 2024 11:22:16 -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 1B67A8D0001 for ; Mon, 5 Aug 2024 11:22:16 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id D4F00C1C69 for ; Mon, 5 Aug 2024 15:22:15 +0000 (UTC) X-FDA: 82418557830.03.712678F Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf23.hostedemail.com (Postfix) with ESMTP id 9E522140026 for ; Mon, 5 Aug 2024 15:22:13 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="d/S0kpnJ"; spf=pass (imf23.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=1722871286; 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=IWR+1E/65mwo944n6uj+O8Ije9QTslyXqSepjeFgNOo=; b=7ySlhgbhaidkQRKuHCiV9At3ypRKUW3QczMDThB9spueSo6/CbKsM9kHKGANQPP2J+7VnL CKAG0B1dNpNbuuyggpUnhjTsBtMT1cqClCWegaKz+XbZ1r7o57uY9nL3tTCJlmTed40gwT ZFlKhLlWlXSQzNK6+bQ+ljWnBoCjlPw= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="d/S0kpnJ"; spf=pass (imf23.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=1722871286; a=rsa-sha256; cv=none; b=LhJAsRUYtRCBghyK96rCmmITTqE+TkuqF6G26Uwq96MSZNvFExc2iOBsSiL3MUn2P1ShRR s+5d/Som1nBj0S4WY6dY8L4Cg4ymUId0in9MwIcUladX1qxUAYhwznb9biq0WmsC3oX9o6 cD+K/ez87NSX30G6r7vPi/CuG7X5YVk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id DF7D8CE0B2E; Mon, 5 Aug 2024 15:22:10 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 22FE0C4AF10; Mon, 5 Aug 2024 15:22:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871330; bh=7OXF+mdH/VtP3EJJlqmokN5UjBwgO5IftFjHmEHegv0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=d/S0kpnJEA53HZxx/ByKgPAnMqA2hpXuuhUkXibFqKo49ZEoH76Oj4hJ8SqrD3aqT ohaViLeqbOK0gaZsi/YhrEPpZXklRe02xuggdqQSFZM7frZqBv26bR1J7bFaq3GfZr kCFuJqcRX6kpxTcvMNk1xoMkNxQpXXosWPQGfg/G4D24VbC0zsc9n3E1NFT6mukVqo TaHwHMYBskm5uZKwmvD4+BhLRnXthAhNxE0EtTCneiAwCmfULUVtNOZQpZ7/OvOZSz hp4bWiQFIIkrm7CnkC811aoijDzacgxc6d8ngbYyU7Kdo4HynY54SZYCf7p2cgxEBy Q1M+GE4r/RV1A== 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 v4 21/28] rust: alloc: remove `GlobalAlloc` and `krealloc_aligned` Date: Mon, 5 Aug 2024 17:19:40 +0200 Message-ID: <20240805152004.5039-22-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: za6g1aorb1b3pfj3offibqaafy83se8g X-Rspam-User: X-Rspamd-Queue-Id: 9E522140026 X-Rspamd-Server: rspam02 X-HE-Tag: 1722871333-484327 X-HE-Meta: U2FsdGVkX19fGc3K7NOhCy6q32JvTQO/S8o0pK7YlVzyss2wMd7qSpMHoBRY5CkRMM+wFUHLHeultxgRJqs3lW8USL1hqK7F6wn3V+5oBYMSetgfBBUTw5Vlzlg/jqvWQbAMBBsCgoW28ABeEJufD7aGZGt/DsuxtVu4m85qutGu3uxRHUC6mxtnaiR2OQTqjHMGMQXm94ULNUPIRqQE6TA8z2qNjjwNFc2w4KTSOJW+qQ0nYIa5I8aBkJgD2ehL7Xt+GFNYJRKwky41gnNw4ZofBkhH8onCIqTnLL1+nuqjChzDBVjpJ4VLBHiHa/13rWYfwSKGD9V/2xRZhLg8e9XGiNpv5rY8LIOQfSqTUVH2QBvCxJkrtBJozBhAlN5EGEVlCLpKFOlqfRSdhVqW6tuQozqWJXr2Vn7M9QbmvPIYopFmbcYFWBFxU/Xi/monsje6sY2Cj82+Zt3GkfaQQ/UDvUwKtost10XYY5GYb+5EqOVZTOxo1eLhb47L1PnQ5gNk/cTKVXst7l+wiMmgGqzVL5uxpr9lWoEUOBdzCC5LH/cmJmiuRhHhqYT4ghSmQnG6YbPBXeFLuLDeTJR88zGhp0ySTB5I9icUB4CCy8VFdeNauuLVQDinPc+l0umrZwgHCkuupdbzTC6oqzdSgqyFv22sIVRGlLxzsDxyhxi3rrlE8BAlAI25aLmos8LFeJpuGvSP06RBOqfoUyqx7MmJcvjJa6xid20CEsO37LEETI5RggLiVBEW96lLYAG/r/cckeKClnY7IkSzbx9NsjEXjvPBLUfmyFAAq8A+cdwdR84wqMyB8Ol+3NVu4/nloA8H1oa8tPCdqZ2pftljQqMGSZZiXF5WnmMMIJjKNFDYf1mBXXXn7nuzbl3/e7hOoNaUoPzWlrELgM8fE95I95gxMwIX2Nofik8TI/uAcjMog8UWqD4JhQgvrJ7DRF3CdoF08NJtFyhMOzcVw8H +3ingtnC zkGVkcU8aJFK8jNgpNTNlw7LdSeqlJ3qCZF26DjqQirvpJBXvruIV6o0t8N5byAUx53QupS6EhLb/lWMIkg6aCLq/xibCLGZVM1dakP4t+kFj8QgVQryv2To4lC3wYB+uBARPlZd6qMnmsp9qqow2hTRyjVPEVvlD3ka3LkMddE6MltdMQGRRRDf0XlKxxkwQyBUBdsSnKPFp16P3/KJkDUSO4A6/W9ET64KoqKXhS50ujGrG8FVP7XSj2alrGjHUmlRRycb8Xg9vUY4uc9w15dMPuUw+PASF5zyWCyfwnIj24FccylLdG1wm4QlN+FIDC67ZdNCCtAPhV82MUGBd2wuth8LtCbyXTXDHdVWmMhqKsYgQBtj9wV6hlUEWOPPL2THH 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 91ff21372a8f..6abd55694422 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; @@ -40,27 +40,6 @@ fn aligned_size(new_layout: Layout) -> usize { layout.size() } -/// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment. -/// -/// # Safety -/// -/// - `ptr` can be either null or a pointer which has been allocated by this allocator. -/// - `new_layout` must have a non-zero size. -pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - // 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 - } -} - /// # Invariants /// /// One of the following `krealloc`, `vrealloc`, `kvrealloc`. @@ -129,41 +108,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>, @@ -204,9 +148,6 @@ unsafe fn realloc( } } -#[global_allocator] -static ALLOCATOR: Kmalloc = Kmalloc; - // See . #[no_mangle] static __rust_no_alloc_shim_is_unstable: u8 = 0; From patchwork Mon Aug 5 15:19:41 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753731 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 A10CFC3DA4A for ; Mon, 5 Aug 2024 15:22:19 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 270A18D0005; Mon, 5 Aug 2024 11:22:19 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 220FC8D0001; Mon, 5 Aug 2024 11:22:19 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0C0FC8D0005; Mon, 5 Aug 2024 11:22:19 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id E3CEC8D0001 for ; Mon, 5 Aug 2024 11:22:18 -0400 (EDT) Received: from smtpin27.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id B01D0160359 for ; Mon, 5 Aug 2024 15:22:18 +0000 (UTC) X-FDA: 82418557956.27.ADE6117 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf30.hostedemail.com (Postfix) with ESMTP id E6A078001F for ; Mon, 5 Aug 2024 15:22:16 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fLVr7YbN; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871275; 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=H9OZQ5xsOD9gubXXkQQXhoCX68XVgwSAneS1UQY5TB06HACXZn8tSA9wS0GcO5VIi4DDl9 7oUiVqYRq0UNCHBZbEIK/M+fnPIccYchdna5BR4T/sTTQoXEnwYx1NCTZcJvhjElhYBQPK GNsGtu7VfslGx1jeNiXXESfyCty+RHU= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871275; a=rsa-sha256; cv=none; b=kXBKmLqjhhmoGHj0mHDTHUzc9GwkwbB/xjrEokDuOUAZBntPxLSZ/VEc1NZHlQDtOInebB SO0BN+u6ddeqwdaTrrD5VaLGEkFozimYS3QBH8gCAPPTzGetzJT5AVHbJK1GZnJH5HEVUh DR7CBORt0lV0W/wqb7jtXJvhSOofUlw= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fLVr7YbN; spf=pass (imf30.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 1AA0060CF5; Mon, 5 Aug 2024 15:22:16 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A8DDCC32782; Mon, 5 Aug 2024 15:22:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871335; bh=ifLa6ui520OxD4tx6GpOL1mZtUOCjuqJJxFCxi3qo5o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fLVr7YbN264rVMq6UBxDkj9mLkDKu+lSnJRLG7ZDHjikHSZtClMvS0zahZgkPnYnC 8g//sl6JDeyuCBMEHtPPyasEONse+pNBUhjzv+LJcoYMBSaH/8Dz2uwMj08S1/d687 gpXy+kODqrOIBDERW7L+MmgNouc+BgymUOc1ddUgOKnaNmndK6eQWQCy5IrEvrpGOf MAzoF3+bKOWT4uc1/CUC04cf119BepvY7K7jvxanIMQeDHIXUYk/iG+0TVUqUCE4mP fXvjpu/uQPXoBJeF6GCTy4zLnn3y7+EvbMgnsFG8kA4WfqgKwTg1ujG6yKE4SKvFZw kwgaUYAhHVjuw== 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 v4 22/28] rust: error: use `core::alloc::LayoutError` Date: Mon, 5 Aug 2024 17:19:41 +0200 Message-ID: <20240805152004.5039-23-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: cpsfwbfwjf3puep9wmq3dackhpkx3ceg X-Rspamd-Queue-Id: E6A078001F X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1722871336-623684 X-HE-Meta: U2FsdGVkX1/LCUOhR1WvnARzcxUpIPr9Mz6cSBck4XJcCQP1wcRBISqX+tNW3hCegaK5dsiCNeUXoiEiAu0hHnOXt2112SeGGHjwAUBqE03c0YRwwybFYDscFjUzYAEqLzwq3dAuxDkM48w3m6H/DROXdeId3Tx6RXJ/u/D8xNH99pTnknw2PWlilT+pNeCWwWvHtXVRPiVmdZmaze6sWC6WOVC9q5WwsgLl96qP59rILiWywaq/JbxaKhXGbwLnePwqiOMGy9hYh7aeWcL5qpv5jW1KyZWaXq7u5IBtc3H2qAHccV7dldI3Ol0vGKJgYxFDtsk0I3hVZHDpM9sg+K4lwICSkpqMkfwROoArnjBwBWhvIfD1ezqWIPGYA7ECKSp1RcSGPix/BZqIQi69XmhWtmS6zFnBT8LRgr7oX3FmGhsqTTpZ/l9y6RKqpsXuRJtRzA1/OoScUFWkKRM7h37iy0E3xrE12zak+3JYXW9rZFZtve6LvqMnMiAWeVdMkAG9bpvn5TCVkPGp0oUHnFG4ukTX2LMkbPt/zTfJJdsFGONxL6ZcKbq4s6sAkwaxiE6FiTV97jN9JpYoe5/tvA8FN0yFQox+FO53Vimb4SK23FtZyiyLWztZEcrmN7u7769RLjGWHOBy6egswA4vJxIF5FcdxtZJNnIf4i29daSvYPuHmLqpRapzCnwWKG4mQyc/5W8VMrAw/OhcNqj3eRo+jCCqUQhSVSw7uqyiKCWgBs836M93LCKwBqJSnSRVaEqQFCKdOpCgdWdI6Hq4rQKrAKCtyCDhzyzGy6OpMOzBl9J9UuI1ehAiLDSEdTXjJvr+BPyH676fLPfP3jlyPRhqgIHnOl17y83eLW89hmPInhhTq4UtAJC0EeiGJPNKpUwWsEByZwEqtfsg0meE3EcwG4kp9zpAFMetsIAH8lv/qaq0f6DNWqwAxvNsU8+XhGyQOfutVXVBjPu3Tus JaXB+FIe DMmBownurhzmRm0EaPuPLXxxodXnfMBBv/Dr/KuLCWzHTCZwR44W3FGcC2gcCHYHzzlEFUJ+dyFtYgKg5WdDQGAO2D096f4SSCvq9/DoWRhrdIxyvQhE+4EHCdv22ZX3wAbQFz2cW8P/SsnAI/8/q+3QuvVRbC49ZlxzJW4v7JtcF6pIZ0eNtS4hBP8cYtTAP25S8S1kYm9+QGYUMy8BDBcpnVcCq6wG9DiBkFGSTgXDCzPibvKbH8mAxf0fVFv3jIu9O2lZ785J885ILl6HMQxiAl9r3V2CaM4hqZuHNTLllfwNY7OOLWoN1rA== X-Bogosity: Ham, tests=bogofilter, spamicity=0.001449, 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 Mon Aug 5 15:19:42 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753732 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 96E16C3DA7F for ; Mon, 5 Aug 2024 15:22:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 222178D0006; Mon, 5 Aug 2024 11:22:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 1D2F18D0001; Mon, 5 Aug 2024 11:22:25 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 09A108D0006; Mon, 5 Aug 2024 11:22:25 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id E00098D0001 for ; Mon, 5 Aug 2024 11:22:24 -0400 (EDT) Received: from smtpin29.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 9863E160317 for ; Mon, 5 Aug 2024 15:22:24 +0000 (UTC) X-FDA: 82418558208.29.CCEC824 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf10.hostedemail.com (Postfix) with ESMTP id F2457C002B for ; Mon, 5 Aug 2024 15:22:22 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=vEmVFRkO; 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=1722871274; 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=Kg4rxZnToZCB8OB5w8nf/zd0zNrcWNsGfSrWrCZqegw=; b=pbbHJdxRqtrIQ7ktZuEbf0gFBzDtRX5cvJaKj0GcbIvPQQ3FSKyRMqSb4u3vyqrEwjB4D4 oCdZpjKHR9euy81zcyprKawC9q7PsEWE5m9QKMsXAdSNQjGhwlMXRjZbmnqiNovB4ds6Qz wg3PA4wa9Oc3V+VyWe0A+Dd2udEieWM= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871274; a=rsa-sha256; cv=none; b=oFYe+Q63VurKGPJidDG2pLRwmkVyJVPWzyQdSwG0xU3yA4LGvmhQDx9foEV+6dS8GigN9I O9OOlExFZoZeNwPoNXqJj1/BMDT4K/exHDRjpb4p6/KcqwRokFuOMT8pI6NVkAP1jv4CLZ i8prOI7xpLmDS4pfWQvSpubAAKm1NZE= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=vEmVFRkO; 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 1AD9960D27; Mon, 5 Aug 2024 15:22:22 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 42B82C32782; Mon, 5 Aug 2024 15:22:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871341; bh=EhvuU5VnVA5zmjTNVXg5lAn5aUpDsOgozY6sKUH/Zyw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=vEmVFRkOg+K1zHXflqDDLqMsFN5JV8HF2isrn3XG9SHLQENzOcT1gsu+4+g9o/IzO i1NcdMbFG58zjVRkRc8yw/6WVmKfBbia9zg9ZCiJXfUuQ3LyVj5VN/oa0PoAO1m01I MvEgr/p5ZsWrWwkny74Vk6sUqDTVENSSe4P7kEvbpyZHeukri9Abj45hY5u8CkXoCh aN2L+tN6VhYoOARZWnKwC/hxOobR4fqHcZaFq4TnhdsVuma4wHYELV1bVW+P3pV54S mAJX732Y/F1kZcbxCvivOKl4QFC3ef7HJjrVY4T7QgWrZtHUOWkFlOz0riRnp+tfdU 3D1Tn2ABbHY+A== 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 v4 23/28] rust: error: check for config `test` in `Error::name` Date: Mon, 5 Aug 2024 17:19:42 +0200 Message-ID: <20240805152004.5039-24-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: F2457C002B X-Stat-Signature: 1ocaha3ckqoio3yukhase74gi8gd4hus X-Rspam-User: X-HE-Tag: 1722871342-400135 X-HE-Meta: U2FsdGVkX1/nSaa7gZCs5A6BGgnic5/c/lP/YX24gwo0AQTMPsHQcZfejObJmGKpImFxz5wtIjGvV4xS1FcENapTFv6OlxfdHMqguzLVuvmD0vJSQFDM2kbJvVaJ559R3pkPuqiyooy8u13/Gn+SUs0iUv4pFIMUg1tYEZWD0//ZNH2akCGwj9Q0cIhacWTyEIekUCF98+9K28n8n+uBrxdV/EY2JLL9sp5AGYaph+g0jEne0mw2pnvDELAhX+OkIVAJ2Nyueggo1HuRVQDy2KSYTEa7FdW1QS5kFgFQzhqPcQQk19UrzsNiDnwKwsaxafMkXVFm4ivDBMJ1SmQr9gLmm/yb2Pv0+7un52xSWAV7fl6wqPRCjtf06pYRMKc+f1AweG/2pF4lx5LoR6KRTXUfTjvKpiAwNpjJQCB2Jn08WanuutinXrupChlrV4T25uZmjPv0xq0W7rktmSN+u8AmLbktZKRP5A9rrnJwhb7nEo2yguyis6zi1aaVupAMsxIWWTJ8OYWK+WhrfwONJnsBXzcsU+P113TVCT3Vswm5I6zzXl0Qw+SwjXeZNNU46n9RsQ4Vk7GFuVjwoYhVaY2HA1ePJWuWNYbXFdJ0EuqA7o204fwU+ZyT+6MCHX+pdi8Ue3lpvuAhqI+ffniEsO68uVLF2u3WApc5Mxg/zsc8/weeT967KalBdrPXp+/NGv2X4+J/+JR+iF1eMY5055dbS8TuqVzA7fw7AYMG0G66h27mwhsHNLtD/OHaDlh8rNvZLzY7i+QonYQ73lM8pu4bAUF5BUgLWrRHLqLueSBryai1kcWkSNrh1+m6BMK197saIZBBis3Z9FbkVCnIM9axwSZCFI2ZnmYRKun2ymdVFC1kFEg1BeIDMyXcjymyry5FLMQpnNF9pyZotrDnVg5LW1bBjguWSgl9karRBV3qBNU9kRqgBQXAlg4R9KCxLgElIC8f6o72xAhNRgB mXZ6RZbb S335fxAbaPxTfnY3eCoqf6ab8BnkBwFHiQe1AJE6XE5Pwcr/2zZnnRwt6hQmErHT4tXqUQYmaJHipVxva5v75kMkxg4VOXJakZWS6SXLybKzK5OTgNQcPUZEw7iz0wrZi0ZeWdU/f77YnYGzs/VbWqnGXoLC49MRvvnCygFb4o+1/0BsydjgBrsu2KV9QHH36pyNNA7TfNu38AAlRxJK8hNfe5Yd84vq2s1dv3By30CEbtP4i1P5lHLOZQVVqeq8DihrbJugWg52OYrP6pSnMm9JxoswF2w6pl1f30mfQ7/g5apOEyeqhXmWYjT5b9jz2kKFPov4bQ3/B+Qt0Xg4+IyyyDw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Additional to `testlib` also check for `test` in `Error::name`. This is required by a subsequent patch that (indirectly) uses `Ăˆrror` in test cases. Signed-off-by: Danilo Krummrich --- rust/kernel/error.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 2d012cc3881a..7adf889b9526 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -140,7 +140,7 @@ pub(crate) fn to_ptr(self) -> *mut T { } /// Returns a string representing the error, if one exists. - #[cfg(not(testlib))] + #[cfg(not(any(test, testlib)))] pub fn name(&self) -> Option<&'static CStr> { // SAFETY: Just an FFI call, there are no extra safety requirements. let ptr = unsafe { bindings::errname(-self.0) }; @@ -157,7 +157,7 @@ pub fn name(&self) -> Option<&'static CStr> { /// When `testlib` is configured, this always returns `None` to avoid the dependency on a /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still /// run in userspace. - #[cfg(testlib)] + #[cfg(any(test, testlib))] pub fn name(&self) -> Option<&'static CStr> { None } From patchwork Mon Aug 5 15:19:43 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753733 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 AAFA8C3DA4A for ; Mon, 5 Aug 2024 15:22:30 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3D0F28D0007; Mon, 5 Aug 2024 11:22:30 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 381098D0001; Mon, 5 Aug 2024 11:22:30 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 222758D0007; Mon, 5 Aug 2024 11:22:30 -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 F3DDA8D0001 for ; Mon, 5 Aug 2024 11:22:29 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id A9FE3A03A7 for ; Mon, 5 Aug 2024 15:22:29 +0000 (UTC) X-FDA: 82418558418.08.55E1500 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id F31EF4001E for ; Mon, 5 Aug 2024 15:22:27 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qoHEC5Ud; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.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=1722871340; a=rsa-sha256; cv=none; b=sy+47vJx1bM02aNXKio9YJTe70Ca22lYDhnq/MZvAi7yCFPg3TzJuJ5AgGbhuI75XnW4qF 4GyeDOBFv2cajZyp+vvcYPFlKWJaL4hPXPO/kP3AvZyB+afbyoTirobDGM1CrUCcp3jVyX tZDnNomrK/EgSOaz+hfm0bo/FYyuI5c= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qoHEC5Ud; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.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=1722871340; 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=Zk4L0WSfPI0qo4KV2m6DiBmtrizln3bZhkW+ifFdOro=; b=7ktMlMuFAalPROs57iIqEzu5zWJu7G5vSBEIyUoxfPbLPs2ypUVv6Ox4h5Hb1FTSOvCo2T fAf2birsLLFuLBGs6IGvQ8mqksYuoUodOS5WIrqi2tIgzq4POCIU4SDzfIwTZSJDN2HWpR DE9F7hwpdN3cVDIhO/Py1acHDZahzyI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 3EC0E6092A; Mon, 5 Aug 2024 15:22:27 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CE009C4AF0B; Mon, 5 Aug 2024 15:22:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871346; bh=Io2x+G7qKjrcvouOx2NWqdpFm0dKR4v0O7CzrkJKPPg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qoHEC5UdKarefAWF6zWNd2LvFyyq/4wBYNZgs6miJ6rFtPBVvOsC30fAeL88n+Gh5 uZQNESyqL8aEbnOBYoCjniO/U2YgYO2ZrKTcn/Iy6ZJrdJhFF3xntpiryK9mUD5Z+l O5+q1s6FdysGzpYj+MpoBf4qKrVa3yUjrwqvN8gepAUkriIFx8hfj58N0LJT1RRfv+ a/Ro1u7l7plrczaR2exu4kVSBXWVNl3R3urzO/Yn52zdjxC5SW2XcgZjzoixC0Ix7x SPxqv5DDTj8XOdWvdLo+wRTff1SDyK9iT5KFg9Bx//qbpsmRKsw9ZLtl+GHe8C0Lsz ym3ShTTtCvHmw== 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 v4 24/28] rust: alloc: implement `contains` for `Flags` Date: Mon, 5 Aug 2024 17:19:43 +0200 Message-ID: <20240805152004.5039-25-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: F31EF4001E X-Rspamd-Server: rspam01 X-Stat-Signature: 547rjfg6onf5d3uk3miiu7gay98kozt5 X-HE-Tag: 1722871347-922267 X-HE-Meta: U2FsdGVkX1/dugEGtaU9CMrk/KgHPqIdxvxR/lq6Jixr18p4uyCyqky56WiMDvYEGCGpZ3dB/eqWCdI5zGCD90NS0GuNnN4ttqs4YpZgT6/uC93exyhwp1bwrh+4wNtos8sbQNT89sBvq7A2DLJg+A180FANAV/wvj9E2OSzKHTr5FUaeV7aX7JUugfvG5LqKwDAplWKjMwifJrmXQkDbk5S9eNmvQqKoRjM2XuRxphdNlDSTx1IWvxj8iXyDQ+QHGB/HiOoo8U3QEL5WaSMMcXTrt7gppwKrjqP9AOvpg3EdI9bMsaOC6opBv8wpqcAKbDtgt+A9CLPLC8GvpRy4VfmO4iRaiS8/ZScr1mduiVYXDbDTYxl6UqyWCJ5CV0FQL9TwRjj2wY5a3w8eqHpFQ5bJcDCMENUEHPQMXIyP51P94aTfpn/2mdkCn7PGawf2qqRtCOlKondL9kwTF2niL2wg8qOuoJ1F+DgwR2hs0fgLiTP1M5UCYmOtE/k8VMYJSruwwvUGyCxJSK6TjnoNtRiYFSykXlKs5WCL7kToa0YK3rvd0G42yM9LbJoPQWfqAdTaMJn5RbQ5CqdZ+ifbvCAVJ5UgcAltXXn1qOxs8rNd+/DO0xUwhBq8yFojDlop4bpAjzwfnR5XpvsIH9XAys54HxiGr+pjaL1fHYPiS9bSSxxOo/4cTk09Krj2WaUBHnH4vgbVpAThqCDd7Ri66ZEtwBTdoHn/eLyCy89538DENEIFMCQ6w/vsMRlCad+oUzn62IGsSW2wTX40Upaslqdsi7SxIVHeAlBlAj7e39FSxCuT5H2AwviFj+tR32MuSOlDa/+aqJDj9x+xayQoBdjyC4yZVmIaGdnvQiiaOv1I6+BWNyog/JPS69vLOxz2McSyqIlmUCn+tDUJL6KGzegsZDhnqvVjoOusIjADrPu1yFrJC1EIbHVs3iSUZ+xKxFaR+O7DxZDxMrtJ2Y i7/fi1uM i92ZC2c5hI/s54yMewYF7lqGyVOuDanO1aj2wDLxLVgm+L/uDpzRPkuY+e5hmw2xFXFOAwqcbOtHqal2GTi4GG5xBW9rKxmea4j1GN6BbCOFG/jcYcjJYU4Ht6zQHcSpSvW+EdHvb2WGhADJSIfop6E6lPC2NJTXdDHJGGc2w7mh72qt1aQCw5FBPuwC5UDHbcFKmgZ5RNyOVlZQzpwSx1yQWQ18+L9V3gwwTbLHtfu1RCIv29N8cEUS2TZSL53BqAJ1Evnk9R6g+y/P9bgCZyfaeP6Vub9J1dGX/OB3yfE6ufJ0UyPDv0jfV9Q== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Provide a simple helper function to check whether given flags do contain one or multiple other flags. This is used by a subsequent patch implementing the Cmalloc `Allocator` to check for __GFP_ZERO. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 8a1cecc20d09..615afe69d097 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -34,7 +34,7 @@ /// They can be combined with the operators `|`, `&`, and `!`. /// /// Values can be used from the [`flags`] module. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq)] pub struct Flags(u32); impl Flags { @@ -42,6 +42,11 @@ impl Flags { pub(crate) fn as_raw(self) -> u32 { self.0 } + + /// Check whether `flags` is contained in `self`. + pub fn contains(&self, flags: Flags) -> bool { + (*self & flags) == flags + } } impl core::ops::BitOr for Flags { From patchwork Mon Aug 5 15:19:44 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753734 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 3DD84C3DA4A for ; Mon, 5 Aug 2024 15:22:36 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id C35378D0008; Mon, 5 Aug 2024 11:22:35 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id BE6418D0001; Mon, 5 Aug 2024 11:22:35 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id A5E8D8D0008; Mon, 5 Aug 2024 11:22:35 -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 870418D0001 for ; Mon, 5 Aug 2024 11:22:35 -0400 (EDT) Received: from smtpin30.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 456981A02CC for ; Mon, 5 Aug 2024 15:22:35 +0000 (UTC) X-FDA: 82418558670.30.991EE86 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf09.hostedemail.com (Postfix) with ESMTP id 967D5140020 for ; Mon, 5 Aug 2024 15:22:33 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=LZruvTTd; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf09.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=1722871308; a=rsa-sha256; cv=none; b=d0lIJYD+EfUhaEm10ruX3mysGtmKHtJNiaev0VE9VU/Jmdmu91bhGwBvokN2GjkMK74bR0 MBHEGtdLcqt2O3of09Ug6z4KBvorxXlWtFzn32NRyNTlStHdsdRai509Gblxbf3oyDVHlE MbcKSJVEx+rnZeJ9Q/e5tRmTp7ZfOMQ= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=LZruvTTd; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf09.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=1722871308; 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=SHvXsSdvR8gV9nOi7FMdYpjEUU1d+21ihBQXbQa3SRM=; b=NHuPwULxiMie2qqk/KiEEAYKZHwFrT8MICp/N7V6obENGYlq1YqvCCs5a4HgDQG+y2T46K skED3avHAtMqc7Y1aad3fvDnE7nl61ymeQLrBwhEcsVh/7XZmQX5oWV8N0vZQ4A7Pt/qS3 QwjkYMuPHvuo2MG7DrN4cYxClR56JM0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id C85EB60CFB; Mon, 5 Aug 2024 15:22:32 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6509BC4AF19; Mon, 5 Aug 2024 15:22:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871352; bh=iMS9KiH08GatcQmOb0IQ1b8oJCGscNUEkjpp2MaItTs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=LZruvTTdj2MIMJkKEyIhRIp90mWSRe8963+FYjpGWG7TDpKeL61kjFpJq6XTHRRsR eJ+XQFqJGJmV7k8G/0tlaqfID7YOd2M4FckoJbAm9lYxR8q2AapulfeMNA3ncLjQ2k 5olemvFRi749j1zdg6uxd6KavaIYdMpYze3FXFv1vsJ8vaKPX/KNZV+yL4qJFAnhlV NnWSpoAORm9LM5eYLguKloPcUkXwkZsC7f52Oyu0NNzLc6HjUjgsfIsUqMIlQFIUOk Qfr5K7Sl3G2P96mhhtgNIOu3QGl0TmfOI8HUNePueD1JH5f/4tRXiodHg4fwi0eNd9 rczgS8BGkBgxA== 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 v4 25/28] rust: alloc: implement `Cmalloc` in module allocator_test Date: Mon, 5 Aug 2024 17:19:44 +0200 Message-ID: <20240805152004.5039-26-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 967D5140020 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: x951t1mjb7fu3fipqfd1perwnqxpcwdo X-HE-Tag: 1722871353-795570 X-HE-Meta: U2FsdGVkX19GRsasn5XWVkkBLVgaFzoQZgbf0vA4bAdaRBTJBY13ieG8/sKkXKKK8L4RanICwnYRXWMlWV/jRGZjRckybFO0JLZr4Mww1iMcibwTHDPAf6jXKhjOfHcYf0ubYSoWm6B9M3c1mgK/5VtYCmSjCdBMOtzlomrl8Aj5x49osmW71SIEUhp9sHyfi2YdJJGlQwwWvI5Yn0sqnj0kBTbAGlMthdmPd7qOPXFUtgypRfV9ToHT5R6/EuUtqENAea4+ZPkFjIuUa4MfTV2p72PZiH6hNew2qvEg5kLYWNi4A/NZCLv5a1+3WB79zTHhGxspkuImyZN8OAg7wlEj/CXlqbUdbBRcXcwXWTlp5epakK3xn04PPrCdugnNEkYlh/lfdauBdUIuOnuckUmQuP9cgWUsW13WyNyLfNyPpZZBBraQghkdI4jFRFzMRwfREp+ZHXYlVmnONfaMprR3X7HaFlfRHFarnN/GVQQ46fK2gwvmxri09L2p1xCwZPQWR+AW/cQ1jAMA2LBnpwsOAnBZTNmX9/msS2+w4PGPJ421WZsDtk2rdeu4kUjCnA7UNKEOhCNKKT0IgK1TPOdvzCXwiek/qSwwi6c4GbaTLcyh9aOPgzVmO9/bhI6Zkgxrr5xXYB1xjB430I4wVVZwVPbNVTxUqfPo0qmadA9uk2+icsXp8DdGGeJRmJ9U3GpoyR14+teSMjfx/1+DxU17rVexIhglX+HUJfrg0MsID8j66kZ+JtPWkmDXQXmHvDmv1z8NvAW8IunQRjzxdGJJ/0594RJdX2KGfHwNFpdXn/UYG9YmZWHg3pQbvID8cq7euBSuvWdgHFs+tdsTuZ/mbjfzXA0iYLARVRqndvijLOJzmgYfB3TUTGvROHEXqiLl+hp0TTfM04KsnK+WhlLa3NiIZewieiDWJgLZT+xL8tpTBZlSvb1ehbuw6H4VBFdDyzTwBNVsuBYUw22 vdsPNUfY WLCEkT57ONTpi6rooKB92nU8sdKB6DlRy3RbOug72giGQPA5x43oUETnA46WUL8N9WxANT9BEVw/V6xvpkxuB7Ou27zCW9rodcWt4S6NHKzUSnLjNA7JKqaD9rjocTkdkNX6llYFe1ru1866qcXM6tEOLXcPrPbF4gMy6oarhEU/NYI48p2WNqSUTaUSZjZJF0935lo+hvFymuOB1kq3l6ofabv+2kgB+nYvPHi9JIkO585vdfS9fvj/5tbK2PNrFkItByV28b9oSf3KRcBt5bNkVlqYr2DFExzHLE+fH0HggJ+hzNnFoIp9mF1Rxk0h1B4CnQEpzCbfREIYMdTLFGabTAzAnrWJo3HjQxNBa/V5yzIA= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users of those types (e.g. `CString`) use kernel allocators for instantiation. In order to allow userspace test cases to make use of such types as well, implement the `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as allocator backend. Signed-off-by: Danilo Krummrich --- I know, having an `old_size` parameter would indeed help implementing `Cmalloc`. However, I really don't want test infrastructure to influence the design of kernel internal APIs. Besides that, adding the `old_size` parameter would have the consequence that we'd either need to honor it for kernel allocators too (which adds another source of potential failure) or ignore it for all kernel allocators (which potentially tricks people into taking wrong assumptions on how the API works). --- rust/kernel/alloc/allocator_test.rs | 91 ++++++++++++++++++++++++++--- 1 file changed, 84 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 1b2642c547ec..05fd75b89238 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -2,20 +2,97 @@ #![allow(missing_docs)] -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use core::alloc::Layout; +use core::ptr; use core::ptr::NonNull; -pub struct Kmalloc; +pub struct Cmalloc; +pub type Kmalloc = Cmalloc; pub type Vmalloc = Kmalloc; pub type KVmalloc = Kmalloc; -unsafe impl Allocator for Kmalloc { +extern "C" { + #[link_name = "aligned_alloc"] + fn libc_aligned_alloc(align: usize, size: usize) -> *mut core::ffi::c_void; + + #[link_name = "free"] + fn libc_free(ptr: *mut core::ffi::c_void); + + // Do not use this function for production code! For test cases only it's + // probably fine if used with care. + #[link_name = "malloc_usable_size"] + fn libc_malloc_usable_size(ptr: *mut core::ffi::c_void) -> usize; +} + +unsafe impl Allocator for Cmalloc { + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + let layout = layout.pad_to_align(); + + // SAFETY: Returns either NULL or a pointer to a memory allocation that satisfies or + // exceeds the given size and alignment requirements. + let raw_ptr = unsafe { libc_aligned_alloc(layout.align(), layout.size()) } as *mut u8; + + if flags.contains(__GFP_ZERO) && !raw_ptr.is_null() { + // SAFETY: `raw_ptr` points to memory successfully allocated with `libc_aligned_alloc`. + let size = unsafe { libc_malloc_usable_size(raw_ptr.cast()) }; + + // SAFETY: `raw_ptr` points to memory successfully allocated with `libc_aligned_alloc` + // of at least `size` bytes. + unsafe { core::ptr::write_bytes(raw_ptr, 0, size) }; + } + + let ptr = if layout.size() == 0 { + NonNull::dangling() + } else { + NonNull::new(raw_ptr).ok_or(AllocError)? + }; + + Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) + } + unsafe fn realloc( - _ptr: Option>, - _layout: Layout, - _flags: Flags, + ptr: Option>, + layout: Layout, + flags: Flags, ) -> Result, AllocError> { - panic!(); + let layout = layout.pad_to_align(); + let src: *mut u8 = if let Some(src) = ptr { + src.as_ptr().cast() + } else { + ptr::null_mut() + }; + + if layout.size() == 0 { + // SAFETY: `src` is either NULL or has previously been allocatored with this + // `Allocator`. + unsafe { libc_free(src.cast()) }; + + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)); + } + + let dst = Self::alloc(layout, flags)?; + + if src.is_null() { + return Ok(dst); + } + + // SAFETY: `src` is either NULL or has previously been allocatored with this `Allocator`. + let old_size = unsafe { libc_malloc_usable_size(src.cast()) }; + + // SAFETY: `src` has previously been allocated with this `Allocator`; `dst` has just been + // newly allocated. Taking the minimum of their sizes guarantees that we do not exceed + // either bounds. + unsafe { + // Always copy -- do not rely on potential spare memory reported by + // malloc_usable_size() which technically may still be sufficient. + ptr::copy_nonoverlapping( + src, + dst.as_ptr().cast(), + core::cmp::min(layout.size(), old_size), + ) + }; + + Ok(dst) } } From patchwork Mon Aug 5 15:19:45 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753735 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 C1E40C3DA4A for ; Mon, 5 Aug 2024 15:22:41 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 494158D0009; Mon, 5 Aug 2024 11:22:41 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 443798D0001; Mon, 5 Aug 2024 11:22:41 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 2E5A38D0009; Mon, 5 Aug 2024 11:22:41 -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 0E39B8D0001 for ; Mon, 5 Aug 2024 11:22:41 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id C3BCD1A0297 for ; Mon, 5 Aug 2024 15:22:40 +0000 (UTC) X-FDA: 82418558880.10.7026818 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf02.hostedemail.com (Postfix) with ESMTP id 31EF98001F for ; Mon, 5 Aug 2024 15:22:38 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=uc9cVv7E; 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=1722871351; 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=TNMHTiQPDsOotoqPWiY+akbD6XzPr/Jtnfk/mP8IDw4=; b=diz9w+wUDfkHuZofbkfIBnpesNAdDeT8whumsOgotuqPWq0aSlc8iFYocEo5dXeRUjKecg MXSNMZowLPlQUf15jh60WQFDiGAY/NlNZFe8+xK8HrIQOSTSQhLvEr6xWgVoMeqBSle/fj HXvwbfIg6sMNWQKbNgDjhl8WcTSGJLM= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=uc9cVv7E; 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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871351; a=rsa-sha256; cv=none; b=0EuUs9OrOTZyTFmtuUmXhZvps47fWHnwiuAIb+N7AHmoFisdu24MX+XxVdYgz+zQDTHLy9 X28EbvIhq4KlQdpPPKfurSOpRm3LLYAX0MLXpCgsV2nDw+NrFdg3nnSEUrr5V6erXNEgdc v2AsiRvoQSzF90M1Zj2kSfHOux4NKNk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 56A8660C8F; Mon, 5 Aug 2024 15:22:38 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id EE08AC32782; Mon, 5 Aug 2024 15:22:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871358; bh=6dLN6QohX0ktcU4cWe7TRCkIGusnQOXkZAPpBQ1FLWU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=uc9cVv7EEGEFQxjC4dwhg3zVwyiZ6SxOToMFUCRbQVqM16pUaXc+fZlyaIuu7Frtu NDJPcUyyZsri9m6uxCaouTJDUyTn+TWuVOk9yGLqOPI8Hv8+Fz9y0bT5pvkaO4Q92u N6maC4dN3Y+PW6mixAbH4phOt+o6zomDCYBcUaUyQc0VZI+BuzVDShLPiaoTLNIxPA ADzFXCXhJEV/3uBxq0mK01Cm43A4x58uvAMs0f0RqRGngixezRZG+Ib22n4Q1Wfstm 4L0sh3jjULPRSEozDeAdICVRsE9LtDVeLSGocoEd0pjyL+E/2FdsA88HTkU86M33oG oXaa/CY92g80g== 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 v4 26/28] rust: str: test: replace `alloc::format` Date: Mon, 5 Aug 2024 17:19:45 +0200 Message-ID: <20240805152004.5039-27-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: tekt46je1r16xz5zw4y6f5sn68rker13 X-Rspamd-Queue-Id: 31EF98001F X-Rspamd-Server: rspam11 X-HE-Tag: 1722871358-573118 X-HE-Meta: U2FsdGVkX19Hji1OTD5VRwwANC7RR9nPXglX0SFI5wnhiwCA5/SG+X3ZZgMubIMcp0/JMbOQCO/zEbqQ7rNFrsed2YamkS7KN+EPERH7R97sYCa0UIKx02A5ZnErcdPCV3OJTXBUDL6xR9JV88f9rFDLS/d1ThwEjToNdxX9zDPkQ50REUF6w2gvLVz9MO9UHqa3ocZK/OtPhouGjnWcbFOTfVmFhNaGWsAdY/SuttxEPijXWdRCmUx8bJZxE0L+ULOENxLzzzSIr0HAqCW+ddexsYcUSnP+PQnpvU2Fpf6MX8LXIjN0y7FInM0R48ypLFpA4Gz8MfCPhU8SRT0DEx5QiptxMmHwkj6CTpVm4y3AbIbXJMzgaNFZ6MmLI1VTK8YUBo3BwWOkjjuqi7nfrm+uQT/J5SR/F7+ud8s+iLllz3yMtiqJ2KRPVtAJcQ5kpGdixbupd91B2bYnTbqfpnECuvowjuvzyDFlRK1qIfBZvx4DO+S413AlKb+7dJVf6nm1uwYDYgWw84uy+MAJ6uuU8VuQG9SEOm+a4dV6wdScm3rGSTbjPONeA3infdMzXc+fdlcWhXr1XadyXqZAyB2lcV/suzsZuZZF50iMNFMa5Uu9Q6Qy02RMKduOMnwFOI5VLhtc7s+1WDUF4DLonFGBaKi/mupfEX9EZ9C3/+SWQyhExpCgZJQZhQVEJ1Vu42Lcew0sM0R7Xe2Q1JUUIbpMDjvVq8rwguQWNWJ/O9mjkS8ebs3iw36nuVa+AnD7Vn6MdHtUWZo1jaEI/Ns9iPiZKz+sLY5hVMCF2RBn0Ej+O6EN11hKIeVpDL6gq6NPArjB7rNCAOxjxXhj2mD5JqDaFwGHSMUgMuRvKTM9wCtqz5SIlk0WbGPHsIx9I40SEFRMH+yGV0c4klHTqbB0l6mRGUJocpPPy0Vy1xedzTmmhLnY8USc02jnecpM4hJpozMJmiv0TS2CUsJGI9G OMDE10K3 jhzdVdikMjEpvzsn8wu11vaeRfYp9qUAi11+FJaXMY6+ECKgyIVrEF7wLgF14mraibQb5TE2xCMUBQAp6pLz/2wtjIw1sdbBbLVGZ9E82DVS3TyV34Fwq+q7CypMhE1u7OqgN+37QyHAb/oxMxYBDla/xqT0Q9eXgjrHOljI7Fm+jT82BQUre+9mU8vFGr05Pwc2S038WcA19HrdMXDtEsy9GYvzbD2F7oAkEoonvEw7uqXkUp53gvT0zao2Gtn80/jHnYClXW4h3SgXXNW7CoNp6zSKqve7AJSr00+JrndBOl4ZBXcTGfST9ng== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: The current implementation of tests in str.rs use `format!` to format strings for comparison, which, internally, creates a new `String`. In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement `format!` for `CString`. Note that for userspace tests, `Kmalloc`, which is backing `CString`'s memory, is just a type alias to `Cmalloc`. Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 0b6ffbade521..8f234224cbf5 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,28 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; + + struct String(CString); + + impl String { + fn from_fmt(args: fmt::Arguments<'_>) -> Self { + String(CString::try_from_fmt(args).unwrap()) + } + } + + impl Deref for String { + type Target = str; + + fn deref(&self) -> &str { + self.0.to_str().unwrap() + } + } + + macro_rules! format { + ($($f:tt)*) => ({ + &*String::from_fmt(kernel::fmt!($($f)*)) + }) + } const ALL_ASCII_CHARS: &'static str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ From patchwork Mon Aug 5 15:19:46 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753737 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 30E41C3DA7F for ; Mon, 5 Aug 2024 15:22:50 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id AFCFB8D000A; Mon, 5 Aug 2024 11:22:49 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id AAD888D0001; Mon, 5 Aug 2024 11:22:49 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 926E68D000A; Mon, 5 Aug 2024 11:22:49 -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 68E958D0001 for ; Mon, 5 Aug 2024 11:22:49 -0400 (EDT) Received: from smtpin09.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 24956A24AD for ; Mon, 5 Aug 2024 15:22:49 +0000 (UTC) X-FDA: 82418559258.09.2F843F9 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf08.hostedemail.com (Postfix) with ESMTP id 148A3160012 for ; Mon, 5 Aug 2024 15:22:46 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=bYI9PdiH; spf=pass (imf08.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=1722871319; 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=baBUngev5932gzvPp3q3hm8ogzZpNcJ2flFSVOgHGcs=; b=tl/kwBP5KeNN/cn3I/lMzvRkOIWmSvsWJnVThvTpYFBNb5xffpWBMIvBDIsqf/tUif11Dr aNFuNG8VayaW/dQnk+OEwqJnww8i77FA0v0FUbBCzTjjEQF598WhaNSFQSHlN9mY4P0vwc TAPrQi2aY68+Ninf0qZLIiJF5WjMFso= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=bYI9PdiH; spf=pass (imf08.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=1722871319; a=rsa-sha256; cv=none; b=QmQFTJt4prQulKj7vjrheE1sN77FWyOkWsPrLQhO84451fy1nr8iYu8TmU4/vc44j7FaFJ K2GZ+KG0ApKjUeIiBzm3Sq2sX+ftftaZT/Kk8DMon1y80ufvkD0m99P6OijadJrO9iJXPj TmOEYxcVtu/TtPS2lKOAff7wf6i7H5Y= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 70ED9CE0B2D; Mon, 5 Aug 2024 15:22:44 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7B800C32782; Mon, 5 Aug 2024 15:22:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871363; bh=yqZfDZklljbN0uO3lQJvfzXfJFBboT5n5ZoqxzlseQQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bYI9PdiHMEa6z+y4a49v74LXqpDE47khUkbXxwkn7JYJYv/DZQXc3MSTZ/urywyFv atR7cWe7kP9ojhrrPjeXzdwpLW5B2kqLlZV4q3SWIiqkRhYsDlXQk8VOhHar7GSrul OEJ5fsIxT7PzlDXt9Qhf6ElEZjeBGlY9ucX75YFzAN/lCYSU71WbrPUOHriRCkvNJh jHsqsqgSPK7T1H7fJqIabk5l4385QPeLFQXDP/EFQSg20ALuU3yAOU6hy1H70UMRj0 5AeKx4fuuC9Ximy7trO2gaPMkBbXWTijm+t/VfnZpLpfZlUuDmitxWYYoCS4Nq4CI2 vpc0lH5iTtJsg== 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 v4 27/28] rust: alloc: update module comment of alloc.rs Date: Mon, 5 Aug 2024 17:19:46 +0200 Message-ID: <20240805152004.5039-28-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: ounba8n7ducekkere1cfrbwh94xsdsgk X-Rspam-User: X-Rspamd-Queue-Id: 148A3160012 X-Rspamd-Server: rspam02 X-HE-Tag: 1722871366-835234 X-HE-Meta: U2FsdGVkX18f5NPy1mxjpmYXvv9gRVhP50qf+8Es17zmEpmR7RBZ18I36IpCwpMA4cVlndiC3otTzrsCqpH743scbhyIh1Mt2BCC+RLot4HhC7X9UDom6LfQ6jXCCWwX2txFdlfd6WlZD7UHzP80+f7iP5diyPDhvC2xyMRzdzmkHVP2YkPIl9zNllcXeTw1nO2dZ0k31fd0eC54yrSArxE4ygYK26m8v/IO5xTFni160rRbDjpUn62VgK7u7zYCV4xpnSiLScWDDdTeb4YE2+N7mSKJkxjJTeD/CEVeHpcGMtX/5GU0ktgUTBR2D76iZBDgfpJeVhyhAaSC0K82FFcveWrjzoYnN5jakT9zCSNm7ei72VhyvSkBsSsIGWRdQ3hmUEC2CGNPcURmwDsnluC9BxaYj0h12zUQhsjZM/eJkp/uhTD2BWFvEGx6eLhV/ZWAaqT/ALZMlzO35Y0mJXu964o7k79+82HBTCMfPGGAGoGOUcdq80+n+NSAZeISbf9Bv+tNvfWGP+mH4ojabcADsR9/W7KoDf4G7BSE3M0albuAisZ3HXh9FIZyNg2ZFogSJW28UFoEdl/dsibl++SiUCKFscbrMb8xZb7a1h96sM5QlbMroQmadzpD/IE18dM+8TyRiXJi93FuiKIzMA+8kYTioHq+gfmFKgNyESVloiH1KDLu0eMnvrOq+EVG17Q1OR/V1okVJsAMp2+iJW6KW419a5AV9eWEjwXzj9wFV63J4GidyxuKmbklCrqr9t1kzcBRV7/H9k0mqCMI1MlrSaD+/hM5DHiOq145BrL/Upre/vSMLuCZFlUgoKdEKwL90xewdcHvW0flP25eNNdAqUUyfaC2vrfbSzVwecAiTiQIqnOPqdEZESsd7vG0OtMM1jXbb8pzvOpBtGdbgWBGCUcwneJngz9LYqhVDwRQ2xJOOJiL7x9szr8PIbFHxLztPsswu9ej/lHohNB v1PB8EWW d7GQZgX/qxAz8tmKgYxBSi/JZmyhtrrScOf4sbEOg+yt4ommUQHd5WNMDIIv6S1ge/YISYsr3KiTvZF5RS51r0mWfEdD+6U/i3a/Cjxy0HK2C4iePd58MPQ4Z9QP3dxqWjRy8K6Gm+sfV+k6fTL3Tq63uJPnq/pLuirCgeYankRWN2xznaPJUpQvHiTvl8olOoohc8+IsXZncqWY2aNTbUjGu9QKOk3vXWa7lTpXYPmPH8RjYJlnh4EADue7j7E/I18wjWOPEMNq6etCTI48avZRQwZ6Gm70WS74b57UOXKgN/4X45ZH+xEUYqxEgXuvUbnjOa5wifz+QSTw= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000134, 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 615afe69d097..ccb9f5ddc4bb 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 Mon Aug 5 15:19:47 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13753738 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 24D45C3DA7F for ; Mon, 5 Aug 2024 15:22:56 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id AFD796B0092; Mon, 5 Aug 2024 11:22:55 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id AAC0B6B0098; Mon, 5 Aug 2024 11:22:55 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9271B6B009C; Mon, 5 Aug 2024 11:22:55 -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 6FABE6B0092 for ; Mon, 5 Aug 2024 11:22:55 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 1DC5A8038B for ; Mon, 5 Aug 2024 15:22:55 +0000 (UTC) X-FDA: 82418559510.25.2062EBE Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf26.hostedemail.com (Postfix) with ESMTP id B9308140005 for ; Mon, 5 Aug 2024 15:22:52 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=pl2BM5uH; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722871311; 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=Cio5LnlfPHw6IAiTfcjUJ+K9u3n2LhQtC/Z76VwkqnJlRQAOzSAO8nC2jKECPxEsS5Dx0m rt61B//7eacThV219V3/9uBK+DGbh3L7wC4vHnidpXUu1G6pu1dVpvVMaTwnnwbDUCop6+ MH1X4lURZycHAgw2/ar26LrSk4CTK7M= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722871311; a=rsa-sha256; cv=none; b=0R/MG2+0qppQzenrrQIqAJfcGBptKps5jArkSshg4ARRVRnNl+bPxR6yQkd4jaMwpAiw+F LW15OM6ypgzGTw7RsFr32d1qFk02uV4ltyzrF32LVfP0jGtrXPUPygJZnijzW1HMgnQ7BB 9wrSxDyjh6LhUCyEM0oAtI/W+rGQJiw= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=pl2BM5uH; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id F3246CE0AD4; Mon, 5 Aug 2024 15:22:49 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 156FEC4AF14; Mon, 5 Aug 2024 15:22:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722871369; bh=BnmAT9t/c5IIktW7mx1EDTKEy8RKB4RK+wsZKxEJOuw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=pl2BM5uHuxVh2a3ewPaeBnItwpN6qT28JvjVi6r0MOje8zHSfXRetvnJLWC6T49A8 rwdcD1TSgUTpp1k2MqPPot84sHMYLF12u1EsPNcc6ClTtsoU1MmFSFBnk1ZOsGE0hf 1xqdBj5O1ox/Bd8l8Uco5iMJLT5irpSKsbgEBXPmqjxtTdlb5ca+o9AH9P8qwmtm9W +OoTPTk6xDVV6tNUBK4PzZSZ7A5d1QyQhrWiUFScIxMwYDaPy8l+gYHOiJb0laa0Qa YzBbQm4ZoyG2rZ3XfiYe+WPNG6t+hU6hfFCQ+z55H5oVI1/drRVmyrhiGb4focDIAg OCLXWBKdlIKjA== 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 v4 28/28] kbuild: rust: remove the `alloc` crate Date: Mon, 5 Aug 2024 17:19:47 +0200 Message-ID: <20240805152004.5039-29-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240805152004.5039-1-dakr@kernel.org> References: <20240805152004.5039-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: B9308140005 X-Stat-Signature: ug9krmr7a571pqm86fon3o6hxffp3jte X-HE-Tag: 1722871372-679476 X-HE-Meta: U2FsdGVkX1/UIWiArbZ53tCwDlynvA5gbGKjLwpbdk6C+W9QCIMbyJaR2qFk9NJtrSV+VlSnEB3r62EI+fkwHWOrZ/b1+PrBaIbp7r2u2oLW/nVEeMHtCP1UQpClJvAY+ngsT4lIA+GRCjMoAooApb8UDyc3gGIT7gEuqirWYpubGVYIXkoY4X1Nir5KTwADxK/EMSu+HUjdK/TtFoAxZZeTRcmh11renxXJeZ+el7UcTeqNocE8pO5GmaZsbXrEbhclp/7wdcmE+tFAFvIWHxhcQ7jiN8rYipW7a7TTadbB4ZSRHVZFMBQYiqrbBz4S+yRKet+hPWt8BYjt1jE3RWHyLKvww51urB7nWGKxz37lmpjd4u6OGxueHb/BgijRf3et/yXfjv9S2w+egmtwJZrpoBfQdzxVxKgJqcNMAVyA5Og00HoWWqMDgt8NFIgr8DqwP40nfMVd7j7oddJtImDlHSM0xeZ7AJOzHSfAMOcBGOFnk75E5Y9pMefTiRGZx2sragVU+AiQxCJd/2PoWPr5J4I1qJDAeDa0YXRCUXd69BEE9n9xnCJcRRRFOOg3o9qjryly2er9UnPM+zIN1y7U4VYPn7gbH7x9o6uCwxIQhma/bTQDa7hNnITUpb23CdIqIXh/JAU2Lf9LZzPH4iBKryBT8/pg1nnsh/DG1hN4k4I8T6bAA4DLAPPHSgmzjUOCN7TCBjsP4aRkH5f3n9kgd7GJyluQsGpN+lGAs1aYZmVEVGp6f1Ae5Bec4eGgRQinVDr0AnRQxKFx8K21uXD7xA2ER4/Rd+9oVeuY49awjW6cDHPOY8cmWOctWcUcS9hEXCfHA8MExFavSUcqC6nKxqjkKTfwjN7s/W1z5vlxFT0+yFZmQkrbZ572FEqCdmHnVVL8jEhygJOQDl6TL5euPnhAF8IdkkYTSVORRUP1LIpo5HnAkmgXhh+dYOI4JFd6ydbXe03LaEpJ3et q+sMxP+U CetDzY0Ofw2dZKKYzTLeiyYgSb/4hLG5DDba0B04MwxrigLyUI0YPSL03XOBKhh+BZAUY21pvnGL5vz5MjifGJPtQSiEwadswIxC+LyxuKgQ69Pi5/fbnJUbD3FMuej8jKXnMi+PNUlVp7DeVYR7/wXGUKAotMrEAFQ/FgzBR0A+EH52qlQe3tavi6isUVdWbzGMlig6exJLA7z0Orj6LpHVJmdL0ecBfzHAx4nODn61hDt0ymAL2iG3sJCx3IW0hgXhNFFrBVzrDZhWKjKHLRX776F7lG6+OYE1JI8fA+FEKW5z+blKNIqv+dQ== 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 \