From patchwork Wed Sep 11 22:52: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: 13801174 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 4CBE0EE57DC for ; Wed, 11 Sep 2024 22:55:10 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D1AAA6B0083; Wed, 11 Sep 2024 18:55:09 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id CC94F6B0085; Wed, 11 Sep 2024 18:55:09 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B1C686B0088; Wed, 11 Sep 2024 18:55:09 -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 9097B6B0083 for ; Wed, 11 Sep 2024 18:55:09 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 0A0971A169A for ; Wed, 11 Sep 2024 22:55:09 +0000 (UTC) X-FDA: 82553964738.17.FFDA8FC Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf12.hostedemail.com (Postfix) with ESMTP id 65F3640005 for ; Wed, 11 Sep 2024 22:55:07 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=PP0oko47; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf12.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=1726095279; a=rsa-sha256; cv=none; b=Pyij96JKzD5P1P9ha+TdfZWjJYmIHhVs7JuSeBh8naabmwfbTolM+m9BuLSQraopQyGNHm qquTExV+p3/wdn+VBPEXUinvVWShyAwP1lzgeLOpV1RvO/zpyIqJhW7O6M0uGKwz/dr47B pWtWed7iJeqqXwo//d37FjlKDzzBxRU= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=PP0oko47; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf12.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=1726095279; 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=Q97hAHGH5VeVGoTtt7KcJOGjV3cwmvFaa2f09uCny5k=; b=Mwv1jNZY/PqkPw5k+saNjvnXvIRg2KjMVM5W3WIuOtMUDWx+3/HDWrl5OX97XSCZSqs8xL 5sa3XSJEd9A0HGPh8YMZk6n63vL/uRFXVro7hVjwfquvPac9anlgSltqmMPAUD0gGEXMBP Ws68msaqbs/K04l4nLY9KsICfHQGjDk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 0F8355C076E; Wed, 11 Sep 2024 22:55:03 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 65187C4CECD; Wed, 11 Sep 2024 22:55:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095306; bh=YJ+3Hmuf4lg4RSyjGhOmEDyEN9eOYFpIUvOB6gUqpsA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=PP0oko47af8i3c5/Hy4kVN84YWSFkT4p5u/bF6oMUDUOZRQfFG0aMXubN+SNpeYQl cctwMTAnRRXh1rDSCnD52PpqzOTQ8w3HGFwhoqSWbCCXY6aeRmN1FhE64VK72pQ2j5 ydR9BBdGMz8nUgJnI5R/AVyqMLrm1FRRz3vPpsyXc0byHV2UD41PKjPn/A5YR59pLq JZlF/t+zbfPr1eW0CAOx1/tMzOxJl1uF5rGQM7OdGcNzE19DB/60OCTs4r65NJkf87 KT1UlGA/9BV/3iuLjtUoQTHY49o5fI3MBDBfB5Mt+5RXpSYXbJKaq6fMc7wKLgnoAm 9dA6oIh6GatmA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 01/26] rust: alloc: add `Allocator` trait Date: Thu, 12 Sep 2024 00:52:37 +0200 Message-ID: <20240911225449.152928-2-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 65F3640005 X-Rspamd-Server: rspam01 X-Stat-Signature: 3ofsopxk3n3bqh3e3gg591mpr6e67141 X-HE-Tag: 1726095307-803865 X-HE-Meta: U2FsdGVkX1/ODrrzTLGQtahVaEJocbtDa50E2Smm8XLY5VcnAljyaNLGnuNyNFqimue9jDCcCqce4iC4oJ9yJb6Mlbm9GboMpT8fSfjTPs4KX2RNsJ8yd6EZmtbwbluwqsrzA/5fWP8+foXYMsfolynA4vPvvqtWVUNuj23Ez6x99g25owraUKvxxgf7GMmAAOQ3IE1byWfL9bXnZrxwPeoOjDZ96VLaWWGQQSk31r9begjz16sj1ve1V3TuRD1g7E2wuh8mk/S74hNQoisbnFGZ1T8/Jy+FeoZ4UhxuaFbBtQSoSKePnDygbJ2VPBlQAx7etUddXvC4BsTsNz1JWOQLUW4UV3dwqMp5Pyg3jZjkw16n4Ga71Y6uSlBN8ZAXsrmBN4vg+EcOL24gKkmBuAE/eiMlLUU+d4hSuIazsOr7OCB3jGxjM3aNDVICNX5W7g3i44tHpjuOu4KQd+UdZEzFGx21RGmP9s41Nq99pWtvqCizCi3EdGkEtGdnWtrztspFIPlQkAz/QG99bi+Y/IHziezl6KUhZ+zjXsXnbOFRUwVH+8utFPJVm0oUFqjsZ0dANzQgq16ViuPMAB9vrWeEw5tURkRUSzVboOs1mN6WRvMNQP89ivvzmBcYYGoT+i069ZPS/cddtu1EhX8YCZSNj0s9dEN5FtQY1sJu59kTxY7cIbeqoND11R3SosEA3k3Yrprx06NLTZkGgISAPATrWAijbPGtca/Cuwl9CESc7OhnjoEnDeTWG+Lf5sxKn1Xm6ZWSQ/4PrNg6FnD3DwyZuWU7B9gVvwdEu+98UR+7Mgwyam+hBZpjhHtHB/gMUQJ/5EVPeeO/bO73pSkmPi67fQVU1czfrTlz7MTWzD0knBdUdC64ILoIOZC9w9Hodxc5RACuw6BfnpuIJGmDnU0rUsBPxTQxX1vav4LgfyRHDr+Yj74HfdSwCR0lfloxakU3MGKwN0Zs5wEzp1/ LdEjWd5D OBrVWcVUPlHtj9cRzsmLXN+7cVPoj/mKUkTqRQgELp5qWWxKeX6DHgj0LvdKsa6BnKknvJ+UBFQnalkdBM5qobUKv5j991cZJznFZn06yIZuStMwla3TD60gggbvnq09k/IaqUtumSAzdQfCETAaqszDjNqm3VnQoTaXZM3HRSOU2+aj+CHUuEe9OcKZJmhC6rYHAfoP9uxgHxvuyC6HCe2lExDggBWawTD+SlbVX+TPzPyHWVBJIXGtxOgz366OjWyq9k/A8olmxyyRgO894JFRVe+DaqD/RfvIJocx+YpmUB+R0uKMBziUmx2oQI72y8yGq3sGtcR1hVMHbcEtQ/zmhORgqFlJE+1if X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Add a kernel specific `Allocator` trait, that in contrast to the one in Rust's core library doesn't require unstable features and supports GFP flags. Subsequent patches add the following trait implementors: `Kmalloc`, `Vmalloc` and `KVmalloc`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 112 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..6c21bd2edad9 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,114 @@ pub mod flags { /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); } + +/// The kernel's [`Allocator`] trait. +/// +/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffers described +/// via [`Layout`]. +/// +/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on +/// an object instance. +/// +/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design +/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind +/// of `self` parameter. +/// +/// # Safety +/// +/// - A memory allocation returned from an allocator must remain valid until it is explicitly freed. +/// +/// - Any pointer to a valid memory allocation must be valid to be passed to any other [`Allocator`] +/// function of the same type. +/// +/// - Implementers must ensure that all trait functions abide by the guarantees documented in the +/// `# Guarantees` sections. +// +// Note that `Allocator::{realloc,free}` don't have an `old_layout` argument (like stdlib's +// corresponding `Allocator` trait functions have), since the implemented (kernel) allocators +// neither need nor honor such an argument. Thus, it would be misleading to make this API require it +// anyways. +// +// More generally, this trait isn't intended for implementers to encode a lot of semantics, but +// rather provide a thin generalization layer for the kernel's allocators. +// +// Depending on future requirements, the requirements for this trait may change as well and +// implementing allocators that need to encode more semantics may become desirable. +pub unsafe trait Allocator { + /// Allocate memory based on `layout` and `flags`. + /// + /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout + /// constraints (i.e. minimum size and alignment as specified by `layout`). + /// + /// This function is equivalent to `realloc` when called with `None`. + /// + /// # Guarantees + /// + /// When the return value is `Ok(ptr)`, then `ptr` is + /// - valid for reads and writes for `layout.size()` bytes, until it is passed to + /// [`Allocator::free`] or [`Allocator::realloc`], + /// - aligned to `layout.align()`, + /// + /// Additionally, `Flags` are honored as documented in + /// . + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + // SAFETY: Passing `None` to `realloc` is valid by it's safety requirements and asks for a + // new memory allocation. + unsafe { Self::realloc(None, layout, flags) } + } + + /// Re-allocate an existing memory allocation to satisfy the requested `layout`. + /// + /// If the requested size is zero, `realloc` behaves equivalent to `free`. + /// + /// If the requested size is larger than the size of the existing allocation, a successful call + /// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but + /// may also be larger. + /// + /// If the requested size is smaller than the size of the existing allocation, `realloc` may or + /// may not shrink the buffer; this is implementation specific to the allocator. + /// + /// On allocation failure, the existing buffer, if any, remains valid. + /// + /// The buffer is represented as `NonNull<[u8]>`. + /// + /// # Safety + /// + /// If `ptr == Some(p)`, then `p` must point to an existing and valid memory allocation created + /// by this allocator. The alignment encoded in `layout` must be smaller than or equal to the + /// alignment requested in the previous `alloc` or `realloc` call of the same allocation. + /// + /// Additionally, `ptr` is allowed to be `None`; in this case a new memory allocation is + /// created. + /// + /// # Guarantees + /// + /// This function has the same guarantees as [`Allocator::alloc`]. When `ptr == Some(p)`, then + /// it additionally guarantees that: + /// - the contents of the memory pointed to by `p` are preserved up to the lesser of the new + /// and old size, + /// and old size, i.e. + /// `ret_ptr[0..min(layout.size(), old_size)] == p[0..min(layout.size(), old_size)]`, where + /// `old_size` is the size of the allocation that `p` points at. + /// - when the return value is `Err(AllocError)`, then `p` is still valid. + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError>; + + /// Free an existing memory allocation. + /// + /// # Safety + /// + /// `ptr` must point to an existing and valid memory allocation created by this `Allocator` and + /// must not be a dangling pointer. + /// + /// The memory allocation at `ptr` must never again be read from or written to. + unsafe fn free(ptr: NonNull) { + // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this + // allocator. We are passing a `Layout` with the smallest possible alignment, so it is + // smaller than or equal to the alignment previously used with this allocation. + let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), Flags(0)) }; + } +} From patchwork Wed Sep 11 22:52: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: 13801175 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 054ABEE57DC for ; Wed, 11 Sep 2024 22:55:16 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 8FB536B0088; Wed, 11 Sep 2024 18:55:15 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8851F6B0089; Wed, 11 Sep 2024 18:55:15 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6FD856B008A; Wed, 11 Sep 2024 18:55:15 -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 4F80A6B0088 for ; Wed, 11 Sep 2024 18:55:15 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 88920160AB3 for ; Wed, 11 Sep 2024 22:55:14 +0000 (UTC) X-FDA: 82553964948.23.F7A562B Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf24.hostedemail.com (Postfix) with ESMTP id 0558A180010 for ; Wed, 11 Sep 2024 22:55:12 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="D/WgSl3S"; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095236; a=rsa-sha256; cv=none; b=VeCf8ArWd9r3DJjErMF1zzQWgGfpDf8VwwE1kRTCDYJ4/iLysxxfN1B0JQrL+iNA1+Dv6s 89OaUgMPbc3JmA3V0eRpsjnQH1Y+L4/2EI6eJhd5rKx1204+OwHedy8CobW4gEK1vhFbx2 2TBfixqKxlTAVgMjvhpXfiINHF7zsVQ= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="D/WgSl3S"; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095236; 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=pmgYwt1xqnnNHM3FNr1fcsHPTRYEOoEUaJzx3PaKkEM=; b=DqL/tGYDUTw4XLx3Sl5LJMWbj6OWuBdDuiYbTA6jzBv5l/Xxpk7pHBHxw8pdpt0OjAlfU8 fS8R36mtifRhmCnjPtW40oya5A4WF/LhI3ANoWu6jEPUZTJ62BT54F+kXm6FUd+WQH9Zcx w5ni4aHjKOE/RWt+FDcn6fYh2XQccuY= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 53737A45533; Wed, 11 Sep 2024 22:55:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B5D95C4CECF; Wed, 11 Sep 2024 22:55:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095311; bh=KguwORfCY7YFKN8ylS2gRnroFHbMzQZYk2Q9X4DUkvo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=D/WgSl3S/dVR8lPldARNWqtzBxXX0S7eYokMIzvH+tUsNddrFOKgY8H7hg3IL8v7J 5v3sEjSAvsQtbpDLlySeaWqNttFjmU7ML31CGvfUsC/plF1j/aqfY37ymrpz7dLwr4 m8SN45KADpIY+l8OIBaofroxoa8zToBc0GZpMJXQ/2HCUq50F82aulAVsB08GbMIFM FNi8Phjw2JIHJl0FBTLH8aa4ZAiEFoRbkkVQJyW3tWl7BSKy9ThyabCKX9zCaNhquT vId+Sd/uYzs29X0EN8pG29Xhh5iduiyOOXP7EIzE8u8Tqx/zcgaocb/94BA3Zze16h aGi5EIDGU9qFQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 02/26] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Thu, 12 Sep 2024 00:52:38 +0200 Message-ID: <20240911225449.152928-3-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 0558A180010 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: u76aj9e9rw6sdfrmtdym14s58edx1o78 X-HE-Tag: 1726095312-529505 X-HE-Meta: U2FsdGVkX1/WmhHzu56h+pGXvRKyVHKoV5UwH5Zzr/FAPwZ6h5p1kwurG2kcdCeVxZqY8ZA97NS8yRQLx7lvxmuUhzsKiwfDxaS0PgmBu5qm4YZiFyt87pEtrRyxwCQadSMuJKlMog4oLHvQ9mctkydlTA44rfGFI1qgD9BvIahvDsxTXAskTsKN+Be80ILFoN4685XuEqehLDM2hFtm9CXnJPz8VHdI+6NgKXVg+BuzGDaSH9CjEYGloTO7kQPPuMRI7TS4Tfws0K7h3sp90lbuNwuBSYWzR1NHePQuWt56+KmaP87tTZGQ3WsI/q0blKI+/Vw/gxpFVGFIhNVl1XWaHnQf1iZgZBncmajOhLWSDBoowY4QJCunlROXa5AC8PGZowc+WO2JljfmECyEchf6BZlvIYHCjG3Po33ge/f8O4Mz0gRq8p4V01a36PE9+SU1WWgA8ja+c349Iag5KmZ9w08lZgH8732RDnhtNTkNEYk3tTuYon8yRSAPjS1m8TB7LyT4MRpr54RjcasFLCeEEpZXiGKNj3zZBekfeQYpcTgYEN8+vfDnqh4NXAPXN81FESvXKN28zD7mgSwHNxTEehIv/bcDERlYYX8nlsUu7Unj7XhC3F3mVMTg2a7V1gBPvFsu9QaOmZ0bhZKU1yZPXHCI+Q6ZTvwwW+beaKeOdQfGBPAnHT6yCu29+E1P/nQ/fkQP8W9z/URh+j+KZoRrQH4J+WEIzD2dr05pm3uWuX5H2Y+hBaowBmGfxwG3Wc83m/gGYNfFfiQNAq/CwUYLSUO6Axt1j+N7BmGf2F6TV7lrIMrXU4LIPumX6edmdZNynXxs38EUphfqs39b0Km5VZXOj7gtiaXUGu3gKuxknzhsMD0YBnWs/nn3/mXJIvPIlP3XOcek7Mj2CWJvtODHHydkllzNxaDs+reJZgbs7yMjixwLgg4iGaBhpd1H7tqQvjlgAN4+21i4O8a ghjCVVnh rw3s6OhNh1sXfaTYYBReSADNvrUl8v5rbA1tvtRve3y667Z46fkfzpbqrwslBN+Nv2joOcSsqaFN/8gN5dkxr568fgLOOXzYmefRJNPAZ8LOYhRdqF3UtcjajjsbyB/BgavG7FqYKfpPDpsa3j6l58JOn9eKwErGa/CRXipM34zIiQs2CsISbt/dwSjGTW4cA/dHbyEBRpI/7HQHZ6hxgCjVjmTsvOnEyUCVN7TL6xKGIeaiWzPO/BMjyFm8/8E7nAfUuHuS1MbFcaBSPkSrkzhC1+CqcmJS4GwKJc9WZaA2fYthudK40X6KrhzzAlPcmeOkMEA1zXYD0PbIlaYg9opJeQAeCBNCLkjYcMyQ17ZsMhfCPMj4naRK44T50bg/X0+Ug8/G6sV3SkCloE5U9gDuP8l2T7sZjZ0ZK+Fp1SNP3yCm2fIDvYgcngA== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Separate `aligned_size` from `krealloc_aligned`. Subsequent patches implement `Allocator` derivates, such as `Kmalloc`, that require `aligned_size` and replace the original `krealloc_aligned`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..c83b6dff896d 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,6 +8,17 @@ struct KernelAllocator; +/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. +fn aligned_size(new_layout: Layout) -> usize { + // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. + let layout = new_layout.pad_to_align(); + + // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` + // which together with the slab guarantees means the `krealloc` will return a properly aligned + // object (see comments in `kmalloc()` for more information). + layout.size() +} + /// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment. /// /// # Safety @@ -15,13 +26,7 @@ /// - `ptr` can be either null or a pointer which has been allocated by this allocator. /// - `new_layout` must have a non-zero size. pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. - let layout = new_layout.pad_to_align(); - - // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` - // which together with the slab guarantees means the `krealloc` will return a properly aligned - // object (see comments in `kmalloc()` for more information). - let size = layout.size(); + let size = aligned_size(new_layout); // SAFETY: // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the From patchwork Wed Sep 11 22:52: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: 13801176 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 98637EE57D7 for ; Wed, 11 Sep 2024 22:55:20 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 244506B008A; Wed, 11 Sep 2024 18:55:20 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 1CF356B008C; Wed, 11 Sep 2024 18:55:20 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 06DF06B0092; Wed, 11 Sep 2024 18:55:19 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id DD2926B008A for ; Wed, 11 Sep 2024 18:55:19 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 840F1A115C for ; Wed, 11 Sep 2024 22:55:19 +0000 (UTC) X-FDA: 82553965158.23.9F10974 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf05.hostedemail.com (Postfix) with ESMTP id E9D0A100005 for ; Wed, 11 Sep 2024 22:55:17 +0000 (UTC) Authentication-Results: imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KCGcTqnl; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf05.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=1726095241; a=rsa-sha256; cv=none; b=Wg3WR1D4wd8ZMq6khUrqgVPs+/eR6tDcWxJEJjEC0TsHd3Te6QYk9QhdjpIEdNNgc9gsMP 25JaNG9FgLE0dUQDlF47WtCljo0j79wIdrvgGj9KluCc8ZYsRKtttAfrrqtPAMVsbrrhaI rfaiSLrWfcx8FVZgmhs8e71sC3MqcOo= ARC-Authentication-Results: i=1; imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KCGcTqnl; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf05.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=1726095241; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=mTEK4ewxpHHdTJ0KIUOEQy2oIL8O9c+6dlpP59lW2IM=; b=C7QzQaJWqMyMPrtnBCAX8C/MSusribDCPEsG2R6Z4Kx3+LAks5Vi2X5ZufX/7tEGO6oHJh uz0p/1misbvwG64qoe9LUmDKueY+2NvoPY9UrzwvHQoMBWG6NUMJhvLZ2ZRH9Qfq2jgQwB m11vPmUAd7tEorSpI2QKJyIkGJn//DQ= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id A4BEA5C06C5; Wed, 11 Sep 2024 22:55:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1039CC4CECE; Wed, 11 Sep 2024 22:55:11 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095316; bh=Ul5b1CTJ9tob+sYMI0uOwgqpbhRR4cA87hpBjRrp3KM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KCGcTqnlJVTcLOAmbSEUKqOazK/xR4SmyhHf6E6yLxfNTUBqg888J/jQNW3zoXMsW BI7/fwKW0MKhxs3jEBmYWCiX4BhCu3aKf0fLOGyIKRsM56Bnyr3XrrFXy62AfbCpLW 8UF1PfSA3yeN2oduAomH1dIhBJa9dBiM9jJu8L/NJ+IvW3gY6y7K6YmVvjs0Wkm3Da 7EZiR7QheKaarwwp8Fxdn7RjH/jtPFM9neQDEJW/KBl4n37/fZAZM94WAfK9n0Ka8B 0vTcbjzPGHt2Hv76tpvxptGeMIwheH2dMcELkpMpl4R7rMMGQd0pYO6WbbhSgsk/34 zCnCFGDSpWd7w== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 03/26] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Thu, 12 Sep 2024 00:52:39 +0200 Message-ID: <20240911225449.152928-4-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: E9D0A100005 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: yqqgxsb4rhj3wyaei96yq6intqfgx7dd X-HE-Tag: 1726095317-685431 X-HE-Meta: U2FsdGVkX1/N6tylnjzc9j1wrxttRW0c/BznXQNdTxGPG+3Y2yTtkmUiJ18iXhVgTNaLPsXKO8aeEDwi25dbcgyH2LOb+20PHcddW2n2QGkmrI2EQMVBJBz4mD9devUphAHV22E6gGssrkr2fFRr/pKbWK7g9Pg5hzFrOFQA2jt0RUDj6M4dL645jYiZ3j0b1GEAgrLJHJtMwNXIeZdS/HgXic8Ku3pLyvPkJfQIocygWVst9bxAxTyFSUiehrPr3SkjSUPXotyea4hFqswBJS0/aAs4Ke/eI5GkY5HhzTDYtoT85iODcBfNk9BPexybeMUhQ7gW5GpPzL++z+yBJR5xSNrpw8cUViVtr7wLyb0xERttH/4KZNiW4KSPtCUiq777eSBFD+SgH8dCPBWWnFCBZnR/DHdT9676xiksSwU38alFo6+1yCAbHo1aCwBMlOb/lXOb9XO/C9ov3CW9EcUtInzVkvd/qVtpqr/Uw/5JRqXZXP1cX4u0N9j/5cR5nnbono6Z3w2JWZ447qE5IeQThiJf+Wq0jfia3S1ijMHM5dLKN+O936eb+ijBrgXxsV26xBSiabmmiH3alpQD9UFSugZRVnCENugHU8GeKJe/7sSJ2/4uB9yTqWKktVqc4i/87FhQgAfEpDsB/Av07NmPlAWUDXk11vRLtOd8Kazc7qXw4SU8ncBaA0ZnIbHDGwUnIrvUr8HZqMyazdQZrH0t5Dl7I2jBsgWjUIm+SiwgJPxHxuJUfPUOLBFUgBvwnf9b+JV8PC3js0KuRM8mQkm4U075bHX55kkA8kNUBhK/bmQDkvhphUGBI8PV/dlCQC9aiLRfncEbNynUgqklrF3kJE03OONrYVCxQSIfWXlkSodrHELE/TmJwUGUqOea0ok5lJTRbGvoVX4y+u5APve9hBqKnurO/seBPnORp9Qo3VtlELtIV3w5buM5jmGhTEPS+beQAKr3YilikvN QycF287r dixyV/eCLjTQT1X7bdcDjUHN6xrdCq1xemWLPxb5BlsdaQHWmpUrx/wbN8S6Omrmin3Tm4COEl/h681Veo2Gl66q/N26bwf0WS6ymg3JQDGuFr/8LzFJ62ECm+giiqPaE2AkeTDA/YEcgf0b4jUilLI8VNYrL0uFFC/xaA3p8ShGvgyKrCV/N63G/HONe+yIT79wFTe4LaYh4luQ0oczH3HuZvWx6Wd3HCMUpRIYdQNRRIQ4Ukw4/n+haoVuupxzCchGezykz9giEH2jnse3Kybt9pp2SRszSGVLikcgOhJeyv/0o3SonE6FeJEAA82gIk1YUUjQDvNsz7R96+SXB+Z+xJeNrYT0rrm/CripHaoPwxPHJwCZvxkABi628fUv9g3SQakouBpSl2c+/o2C/mcrXYyYUFSPh1GN1 X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Subsequent patches implement `Vmalloc` and `KVmalloc` allocators, hence align `KernelAllocator` to this naming scheme. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index c83b6dff896d..e32182f91167 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -6,7 +6,7 @@ use core::alloc::{GlobalAlloc, Layout}; use core::ptr; -struct KernelAllocator; +struct Kmalloc; /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -36,7 +36,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } } -unsafe impl GlobalAlloc for KernelAllocator { +unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety // requirement. @@ -72,7 +72,7 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } #[global_allocator] -static ALLOCATOR: KernelAllocator = KernelAllocator; +static ALLOCATOR: Kmalloc = Kmalloc; // See . #[no_mangle] From patchwork Wed Sep 11 22:52: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: 13801177 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 0E584EE57DC for ; Wed, 11 Sep 2024 22:55:26 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 998F36B0092; Wed, 11 Sep 2024 18:55:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 921AA6B0093; Wed, 11 Sep 2024 18:55:25 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7C1A26B0095; Wed, 11 Sep 2024 18:55:25 -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 5C8396B0092 for ; Wed, 11 Sep 2024 18:55:25 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 1E50BA9FE6 for ; Wed, 11 Sep 2024 22:55:25 +0000 (UTC) X-FDA: 82553965410.20.F3A3BE6 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf18.hostedemail.com (Postfix) with ESMTP id 6B69B1C0004 for ; Wed, 11 Sep 2024 22:55:23 +0000 (UTC) Authentication-Results: imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="g/+6QwRq"; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf18.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=1726095238; a=rsa-sha256; cv=none; b=neTrzhzlSsSd6sxuhk2dF4LZ7ljJ91n1GO/et3i12AWyPqr7nNFcAqs29QqKlm/Ct/I8r0 mmnudwQNDkVGJn99EoHHH1hsyFbFAQYK+CMg6pXRtckS73MeLtxILlJmYNwoG13toRCuym BtzTNDhYosE3xVHSeAOShlPyvhrysNM= ARC-Authentication-Results: i=1; imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="g/+6QwRq"; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf18.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=1726095238; 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=YguptbdFs2WNhKF5RArha1tcuaogtFP0wa/nw1tX0Bk=; b=HxZtT901Py9K3eFQWJqaQafCg4zXkUcQh26eg+B3FkzgnZLGQDT0+r1qyuuKSu0ogSjcSr YkoQsUzhBDAjnSgzAuecWtKEKH0iPQunZwKr5PY9cpnonmWlX70NICYpHbIBG1n7xYszfR jxnX/5EWCZCA0oF22N8QqnA9dvmjmHc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 000635C0655; Wed, 11 Sep 2024 22:55:18 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5E35FC4CEC5; Wed, 11 Sep 2024 22:55:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095322; bh=lbiLQnErRGDrQbj4pxfkEOD42vZ0I0vTG1uGJ1op8G0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=g/+6QwRqD1gJeXD0nTRAi39kPwchUeku9kzbofccjkCxU8yKJ5xJQ9NbBWGzIY1J7 9bJDgYS9aUM5Kt1EmpIupw1BwMb8FinYpT9XninnRN7iEZEWbNW2TysnpXm+OukEZx ZuZ/IbeVMnIEZXNXgxVoCjP1tM91eAhZrdpDSq0CRNFAv/gKPqJs/6WbtW0xrFEJOs pr8NENuo8oo+1kjNBNQeVnArUGCnEjf4wxB+KRDyGNa17RP0LqHvduThVsdqPJMDLT x9NQtar2HyN8X5z4mqq6zfCPrH6DElkh9WCtMtjG8kcWiEEs/UhfpS/gCeJYmZxwoK Q2wE3EZLWULFA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 04/26] rust: alloc: implement `Allocator` for `Kmalloc` Date: Thu, 12 Sep 2024 00:52:40 +0200 Message-ID: <20240911225449.152928-5-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 6B69B1C0004 X-Stat-Signature: we7qfjfwmz9nmusz8a47wdy36c5o75mx X-Rspam-User: X-HE-Tag: 1726095323-634979 X-HE-Meta: U2FsdGVkX18Qj4+slumM4rcZ7R5bVR1Wxla3cWdmPkjGDeu2cXp4nB1kvS0ge51WRP1G6a8dAty/drV95WJdu8F7NXbh+NmpDTyg6dDNEdKNEgFZx7COdNZlDZozkCk2vHCV8Y3KuMbRv02ityvUnczNa/Yj4j9chaNSmH7tZnXhEEMBAXHKzJ7swR2klpZW/VCv3+HpJz5T7Og8N0EMQom6n23u6P8fpXhjQpeJvolEA1GnUAF4qUbkbIv7GIx9CSgX1f+hBGuy4ipqCx1aP8Zy5K7sLUc/CnrhBgXODrQJ0JStpWAVaMX02sDkIA1AyMMIrQ8DhSIW3Rzwa+fpiBxm//TruIS+acXLrt8nqWHyhECHgH+2a62Fu5s8URCAYMYWt4Ab00qbV4kDEfdf5PeNR/XmvEez/brgxQTcd1uLxQMEALwqXGwgibyOolTulvgjRi+E7z0N1RUcn/RPd9h1d07s59vtBTnAd56NcUvBdrTgvOZmPoTneoH7Qhi7O7ZUFrj1ybC/+FQC96oEDq933sLBq0P7ks8S6cucnHxPdizvEWQlPHp6WRrGfsX+xEyzoOS4mpKQEq3MGV7QBXbBxjQ7Fo94FFjF6D4kUJ87nC3zXUR3v3DKA1f8/jJjhFCbi4gLG+xkNwtHaYUNXizHowR68BROijYYGgZcx3hCmg3mpxV634oH1CAim3ek3N2QL7CibuF2NONvXV4Z8pKhjDPsv3Ep+L6uHJGJO3yjjRAxpS2hNRo229TMKfI+9FF6H1T8rJCCzcY2/MuIKnhWpS7JlfsgknH3K/GqiFQchHEYsL/T+OVvMro8UQ51+5ZX9q/3JMQq1f4qnXrlpomNaVzDcps/PsqRrPMUtoIcOiakYAugh08nZk+6XWGl7OF/74Q9mojtHpOqjK+XbyeKb51fObPqwzyRYr6PAzljkFfoXYN4A8QMWXDHDoMwnFj8qxU8DKN94KeDSCu dwff2IkK Qwb2kruXy2HU94B399NMT6K0Y8uRYckjGkMGpzBNBBpVJ4qmp1xhsnoOonOlpFuQTkSlbe3XCAzAv5IfkQU+pW3JV2CY5BFNEMlC9ciTOnV7liYKidyP+zsdwkDYEcJjzF+fBP3/V2w2FCg9jtLB+2max5pxu3r5vGKiJd1PymPbA249aydpQKJiBC7/8hPh6xm4B/FpdGlSmDqYtFA0qZ6Db+M2OdKF+HwfFaeNAkz9FfT3dm1F1KSAt3S0ORwgN2A7nQrvO1s3SQyAFs5gTslOG5p7HJvKKKcKCcyCYSkyL3A/36JUEW49KS7zIUPg75KHaVjYS+4/BtRqD7g74N6p4Zg== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `Allocator` for `Kmalloc`, the kernel's default allocator, typically used for objects smaller than page size. All memory allocations made with `Kmalloc` end up in `krealloc()`. It serves as allocator for the subsequently introduced types `KBox` and `KVec`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 89 +++++++++++++++++++++++++++++++++- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 6c21bd2edad9..535ed1527034 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -4,7 +4,7 @@ #[cfg(not(test))] #[cfg(not(testlib))] -mod allocator; +pub mod allocator; pub mod box_ext; pub mod vec_ext; diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e32182f91167..7a93442187a1 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -1,12 +1,28 @@ // SPDX-License-Identifier: GPL-2.0 //! Allocator support. +//! +//! Documentation for the kernel's memory allocators can found in the "Memory Allocation Guide" +//! linked below. For instance, this includes the concept of "get free page" (GFP) flags and the +//! typical application of the different kernel allocators. +//! +//! Reference: use super::{flags::*, Flags}; use core::alloc::{GlobalAlloc, Layout}; use core::ptr; +use core::ptr::NonNull; -struct Kmalloc; +use crate::alloc::{AllocError, Allocator}; +use crate::bindings; + +/// The contiguous kernel allocator. +/// +/// `Kmalloc` is typically used for physically contiguous allocations up to page size, but also +/// supports larger allocations up to `bindings::KMALLOC_MAX_SIZE`, which is hardware specific. +/// +/// For more details see [self]. +pub struct Kmalloc; /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -36,6 +52,77 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } } +/// # Invariants +/// +/// One of the following `krealloc`, `vrealloc`, `kvrealloc`. +struct ReallocFunc( + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, +); + +impl ReallocFunc { + // INVARIANT: `krealloc` satisfies the type invariants. + const KREALLOC: Self = Self(bindings::krealloc); + + /// # Safety + /// + /// This method has the same safety requirements as [`Allocator::realloc`]. + /// + /// # Guarantees + /// + /// This method has the same guarantees as `Allocator::realloc`. Additionally + /// - it accepts any pointer to a valid memory allocation allocated by this function. + /// - memory allocated by this function remains valid until it is passed to this function. + unsafe fn call( + &self, + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let size = aligned_size(layout); + let ptr = match ptr { + Some(ptr) => ptr.as_ptr(), + None => ptr::null(), + }; + + // SAFETY: + // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc` and thus only requires that + // `ptr` is NULL or valid. + // - `ptr` is either NULL or valid by the safety requirements of this function. + // + // GUARANTEE: + // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc`. + // - Those functions provide the guarantees of this function. + let raw_ptr = unsafe { + // If `size == 0` and `ptr != NULL` the memory behind the pointer is freed. + self.0(ptr.cast(), size, flags.0).cast() + }; + + let ptr = if size == 0 { + NonNull::dangling() + } else { + NonNull::new(raw_ptr).ok_or(AllocError)? + }; + + Ok(NonNull::slice_from_raw_parts(ptr, size)) + } +} + +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same. +unsafe impl Allocator for Kmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // SAFETY: `ReallocFunc::call` has the same safety requirements as `Allocator::realloc`. + unsafe { ReallocFunc::KREALLOC.call(ptr, layout, flags) } + } +} + unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety From patchwork Wed Sep 11 22:52: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: 13801178 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 7D532EE57D7 for ; Wed, 11 Sep 2024 22:55:31 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 0E6696B0095; Wed, 11 Sep 2024 18:55:31 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 06DED6B0096; Wed, 11 Sep 2024 18:55:31 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E51636B0098; Wed, 11 Sep 2024 18:55: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 C4E8C6B0095 for ; Wed, 11 Sep 2024 18:55:30 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 6C85F141343 for ; Wed, 11 Sep 2024 22:55:30 +0000 (UTC) X-FDA: 82553965620.26.2D36604 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf17.hostedemail.com (Postfix) with ESMTP id BFD5A40009 for ; Wed, 11 Sep 2024 22:55:28 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="RXwms/Q1"; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095300; 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=5oPPMmxauRhXV8pigZ+6XeLCWIciB7fh8ZmFec/R0tI=; b=qncYBW1QjHW+DOEnYv85Mc9TPurEM4fCTmgblAkUgtx8MRUTDiGJAz4e6x8pAqYdsJNEy0 8PQBmY8MRSUFCIkq45AJ4mfRTQqV0vR+gw6TE7bQYOmeG+MZIQxoo4JaJenl0/SMCPX1af PqTgGJ0kaeal95eI2KzFnw+tuYQEzDE= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="RXwms/Q1"; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095300; a=rsa-sha256; cv=none; b=YxgnQ/cdW0oh5uQm6UOVImP5AAA9Y98TzqXOX0zsc8+nnkoGLBJocbGsJsLd+UjcrFR4Vm LmjRtUB8yU7at+BCy6875z17fFDCE0xQFN8R2Iz50AXI2iWXQbFDAirX0SCitVbeKf9k3O yaalWhCNJD4lzlkLWpNpuxKtJ1bQ3jg= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 502C55C0532; Wed, 11 Sep 2024 22:55:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A98B6C4CED0; Wed, 11 Sep 2024 22:55:22 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095327; bh=6UhtPHghMdWoDtF9TGoHZC9u3Z5IdMcvwYnLuoTa2qc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RXwms/Q1IYeTrOVyS8N6rmwVkuedlR7RrzOdigur1Nqg3fVvLpdjdpt87ycrYgBak UL4Us49SUfm6lzmfl286zvwwQQ6+fZJvTwTCQOoT+Rmc98EoIWGzN9YVgQd9GRJQj7 PjiLKvK5hZ8yXT4bPvuwFG/9I7iyeWLqE5RN8Ij81osBIQ9csfmWVxmb5HyMvzjAvB Y+MhH4C9XSnTyz48Ul81QJ092J0832DhYYkhm29zar+vQO3eVBU9nHURmuXisch9zy bb4hNzvrwTD+0uwAH36Id9zHlpN3/ayuyyHlhEvLDHQogD8XYcVbHi96wwOaChS528 frujahViF8gvQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 05/26] rust: alloc: add module `allocator_test` Date: Thu, 12 Sep 2024 00:52:41 +0200 Message-ID: <20240911225449.152928-6-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: jngmcb5amz5epn7rfubfkgyh7sszjtnm X-Rspamd-Queue-Id: BFD5A40009 X-Rspamd-Server: rspam11 X-HE-Tag: 1726095328-16210 X-HE-Meta: U2FsdGVkX197jWZrn6pg4TgMHB4C53gmp+q86I35wK3GJNhJSVF1nac351/wCzY18hfMNtIhAdD011oK/uO2vBTWNiJhCU1WeyVreo/Wg4KenJR1QHKWx9gTUagZgC9SoeDg3PfK2+2Kpq9g3BAtDZdwKqVm+OCMxQqvjrPeQJK7bvtYxw1MtNMdTrGlpEO1FJUHJftEnkIfTgaG39Ln7NChSCWryCbvTDIQ6fOvW/W1f+uI33iojr21khHt1deIldlLycLgCwCdxg9eL7WQcEipRVvjPL0vBtTDbrW8qdPGku2jFPtijG4H70LSOFyqsEMXUAKcEaJeUImBKJ7lEhmq6G8cH9/EyXqdVtbVJ2e12AGSmRzx36lvNiqQUd5F//Nz99j5dws2SNvxpl5iq1eZmcFA7+u5+LyPIGjMzII/i2tookpOhGXSLRPNsHDv5HW12exJX2LTSF7g0vZgEhZLHYArBR+jnnu3q/sHhu8CODJPm7iNjBNsfSQ0cm1D7VwQrSKyeM1szWXft/jR4S3kEM2YrxeMwJ8h0UChUvCn/gsK13vQAryXmjOMXhtbx/Pry5gM0wDO8VLY/outAAade4W9OxzTh7EUZDVN6/5Ol5WSK7oHyxmtM6mefHquiS9agbO0fa/y2vifmV2/4B60J796U3BK319YKc0jKByPMdBuczvOuuy54mSlJsFp4xs9DiiCdtYB4gaHOGCnQJS+VX28YN04TMczcNY6QSW+6mRnDuv4+3/F53NZT+yAILBTht8ldadc2L9QWukSdl3E/thqclf+6zfHbb3CueOQz9Un4sIJ6koo5KSTuvMeSpit04pHFL1DFASComCmSxswA4ri6IlWLuZdfFQie9HHZCygr7og2RP9BaEPQMx3IPx6g0mC6frpIu0cISdvx5L5jD3rCRzNuxWmEdxIEyDSr1nFjYwQUeKynn9pK8kAR16PBYmIpO3Z8UBbvVX 8ZOx+x6S M10nm2MmviB9csqtkKex+EHoYAvhtIpltsSZlKWZ6NVB9MuPdt4YEaFrRMMBdpQ9gxgygKrAwYg9rBEg+4tTS9ZE5gcD27G1ctnc0vSQ/2bWtg5WBt5R2dMkYazdm/ySAhc89pIE9kFeNZuiYJuWW5DrMHIbTKXBV50OK6mZRN6B/3FdgMZEm9B6aClAn5FPnsy3Tfvn4oY+M4vmb4OOzXsYWrtYThho2vlpFqiMxRSpF3vve5jlZQGrumJVPIPDkwNTqAcZAy2/8sSakj0vx7c9D3VNOTvnNrsWvoJENn+HjtbYITJrBNioz2xuMf92/zlrtzvpQ343Cg2jcADGASarwstZgeezCJQ7891zYOKhLO0OOajFB9Dta+wAHd1qKHRy/kM4H+lpdQPQ8FcVESF8AloaWgKCw/TzZKIuSOfysQngFIrHwgvfRYw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `Allocator`s, such as `Kmalloc`, will be used by e.g. `Box` and `Vec` in subsequent patches, and hence this dependency propagates throughout the whole kernel. Add the `allocator_test` module that provides an empty implementation for all `Allocator`s in the kernel, such that we don't break the `rusttest` make target in subsequent patches. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 9 +++++++-- rust/kernel/alloc/allocator_test.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/allocator_test.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 535ed1527034..da025faf07f8 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 Wed Sep 11 22:52:42 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801179 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 0AF0FEE57DC for ; Wed, 11 Sep 2024 22:55:37 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 997116B0098; Wed, 11 Sep 2024 18:55:36 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 9477A6B0099; Wed, 11 Sep 2024 18:55:36 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7E8BA6B009A; Wed, 11 Sep 2024 18:55:36 -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 5E8496B0098 for ; Wed, 11 Sep 2024 18:55:36 -0400 (EDT) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id C5FAF1C5AC3 for ; Wed, 11 Sep 2024 22:55:35 +0000 (UTC) X-FDA: 82553965830.07.C7FC571 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf21.hostedemail.com (Postfix) with ESMTP id 2C6F61C0007 for ; Wed, 11 Sep 2024 22:55:33 +0000 (UTC) Authentication-Results: imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Trml8k+n; spf=pass (imf21.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095229; 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=G4t4ll0XQ/1sZ5Wy32FUdKApuxrJ7TdCMxelFkR6R4s=; b=lwVsjOUEaTdrSSRUbbMzbJ+MP2QKAm8IeEuTNf1VRYDGN9J3qHPbIaQiE9746M+pgzRDtA 6H8cTYUvvAcsW6dw3ysWTxUiCKez6g3MXNdTZR/0Hb5SjgNRggblYolUEywHYST1BpncYt rNhVJg3QuyQ0dZ5RoHlFruYSAl1Yzdo= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095229; a=rsa-sha256; cv=none; b=SHwd10fxuichnflo+QADJIeb6F+oD6tXUTDzPGF3XS8GR3n7rE3H/jkTJXUTGeUWpG385A EKJORpLWMC8qU3IB28TBYr+XPNwjaSjaXEYoBvrMuykJxG4REoKOPPIeV/YHd25NwxZSAn NnDj8Ni3/SfoDhxSEEUNzd8ZADo1E2Q= ARC-Authentication-Results: i=1; imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Trml8k+n; spf=pass (imf21.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id BBCF95C0775; Wed, 11 Sep 2024 22:55:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0846BC4CEC0; Wed, 11 Sep 2024 22:55:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095332; bh=kZOIx3Co/Hq0ECAauxmLflkd+d0Tj2aHN+O0afOlvOc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Trml8k+nqKDeTUNPT+Q0B0wvV+B+DWgxGKE7UnVOvVcv9HfLKATNF6fhsj47h9iXV nrywaauzGj4lgxa7f7xhiOeXOhOa4jhrhk0aJbt2WS6uE25MeEEb7ECReBtdm3z5V+ Ghk+wMz+UjV+GGyGsr2rDdhFuUsui+3bn6x0M3o5H/hSH0WPiIh7e1qQJuC1D7eLkZ NtvqlCiNNBLhQsJxc5teRL1Zt83GIbrLUF67Cp2BFree4q129nsPVzUKeBg55kn5zH Hv2jMnY9qjlGlbH4yr5yCJJreEwShKO/DEWm2xC+eWRG4VjsvB5JBP7aOayJ0bq+ZT zfV95Op4i3MLg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 06/26] rust: alloc: implement `Vmalloc` allocator Date: Thu, 12 Sep 2024 00:52:42 +0200 Message-ID: <20240911225449.152928-7-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 2C6F61C0007 X-Stat-Signature: o6emg7jwwdh75d45yi5y3bfgph4swujm X-HE-Tag: 1726095333-542022 X-HE-Meta: U2FsdGVkX18MXuxCzD/eQsfjESxe8DzBLCsMDqb0w2BYkzevDKDd5T+U5g9Rz2siKc/ETpJXugc10xhA+bOQ4Cjk8uMyaEu9PDJuXg8SksEaf84UH8Rna3f0bTaWbbVIrEHuGkuaWKvqhktn4yhQfYaYAv7MaTJ4zJOLXFkzFMlnlXhoo+fer/e7YnH6ZwlpZACFsnrpH2hd/OXNX1XdpxoBFcvE4e0RpRtuaqcpFCs7OsH+79aFPd6WpAq+1XRvZrz9EO6OA2dpmxdhe45CtBvLgeWUKsND3IMxuF1c1uuWVWO6XnComGmRKByNwI1ykKN6GRIY/sYz+nH1f03i8VHkCaIydFWk/wAaAC8BK2ycTaYv7wTRy0IMwncifLvb2j+ujhzEBvdwQY1rOnfNLFPCuKfs7FLm+h/mcvCRy38obi88yT5dP0cx/5QuEgtZINw+2OIzaWp4VUU0tRXWXJZMvkZ+JcrB6sSVlN+Im28TyukcSGsWTBccH9kI6hPciwdZ6iPftozWHsPvMPGWf+B2yQqWX95JtRZ80joaJ+4yyrr1RNnAcfaoodSn8uEM/d1HBsf944VPDuW8qDlHEWAT+7BJ5Oy9mFi3SWRPJMT1AVlGke1esnbCBLl1XG1f4lprHXQQfKacivn58wJoXHnobhl28pLvtKBTFY//jxQ3WquI1s9L1FbJ23JEEhBJct26I4Tf7tJAOd2MQ3jXmwOLMXEhZ7gKZ6VxrQ/zm8wNWi06jgejUAEtLPGZiMuXIg8e5M3Z3gicaNq1ruq9sqw+B9PLHnGjmNiBKKNs6bCRVTWvRYiYEXLL5mX1sSZ9HYeMfwG0n4FyHFuRhBKyOWPnl1lFKM40V9e/7sEWYcLC0CfIpuyM2rjqQBdKWcV2+qEW+4xSpYSTu9G23rqlqJ1QPHrrIAmh9co+tzJ7YI2bapsMxqPWkpChRmPYe2g2k0eTOwbX+mPeC0n8RCh pD0GSTTk mQW0t1nxTWFGvgZvKzOdDmxLu5r4baPcY98OCG7bFZipkFdlKQNpCT6WR94RqiuISa+UC7sPCoKRPheQLBXHw/jgveu7uZQ8zRpr+urdRdcXWvnW4rJaMUhdeBubsGWMfK0aauW6l13Rpkvpwg6CjmjRUQ8EkDdu7f1EEhOS32zAfqIRf78rzBn0k3QKhoQ7ra4xiL4NW3M9lW5qCyYwDN5Wx6d7+xVc4BUfkER521I56QQsS23OioAe3iyEwMs/0pA9wN3uf5Lu8cfcHOimxIZ1QJsFoIPPzOAZ9zKRcvohsfNOCyiCVDjJVVxY/gOSU1CdZpzicR00idTw= 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/helpers.c | 1 + rust/helpers/vmalloc.c | 9 ++++++++ rust/kernel/alloc/allocator.rs | 36 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 4 files changed, 47 insertions(+) create mode 100644 rust/helpers/vmalloc.c diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 30f40149f3a9..20a0c69d5cc7 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -22,5 +22,6 @@ #include "spinlock.c" #include "task.c" #include "uaccess.c" +#include "vmalloc.c" #include "wait.c" #include "workqueue.c" diff --git a/rust/helpers/vmalloc.c b/rust/helpers/vmalloc.c new file mode 100644 index 000000000000..80d34501bbc0 --- /dev/null +++ b/rust/helpers/vmalloc.c @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +void * __must_check __realloc_size(2) +rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) +{ + return vrealloc(p, size, flags); +} diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 7a93442187a1..0f2bc702e8e4 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -15,6 +15,7 @@ use crate::alloc::{AllocError, Allocator}; use crate::bindings; +use crate::pr_warn; /// The contiguous kernel allocator. /// @@ -24,6 +25,15 @@ /// For more details see [self]. pub struct Kmalloc; +/// The virtually contiguous kernel allocator. +/// +/// `Vmalloc` allocates pages from the page level allocator and maps them into the contiguous kernel +/// virtual space. It is typically used for large allocations. The memory allocated with this +/// allocator is not physically contiguous. +/// +/// For more details see [self]. +pub struct Vmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. @@ -63,6 +73,9 @@ impl ReallocFunc { // INVARIANT: `krealloc` satisfies the type invariants. const KREALLOC: Self = Self(bindings::krealloc); + // INVARIANT: `vrealloc` satisfies the type invariants. + const VREALLOC: Self = Self(bindings::vrealloc); + /// # Safety /// /// This method has the same safety requirements as [`Allocator::realloc`]. @@ -158,6 +171,29 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } } +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same. +unsafe impl Allocator for Vmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::VREALLOC.call(ptr, layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc = Kmalloc; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 4785efc474a7..e7bf2982f68f 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -7,6 +7,7 @@ use core::ptr::NonNull; pub struct Kmalloc; +pub type Vmalloc = Kmalloc; unsafe impl Allocator for Kmalloc { unsafe fn realloc( From patchwork Wed Sep 11 22:52: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: 13801180 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 EF971EE57DC for ; Wed, 11 Sep 2024 22:55:41 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 8AD016B009A; Wed, 11 Sep 2024 18:55:41 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 836586B009B; Wed, 11 Sep 2024 18:55:41 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6D69A6B009C; Wed, 11 Sep 2024 18:55:41 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 4E7526B009A for ; Wed, 11 Sep 2024 18:55:41 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 04A7A1C5C8D for ; Wed, 11 Sep 2024 22:55:40 +0000 (UTC) X-FDA: 82553966082.16.628BF9D Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf26.hostedemail.com (Postfix) with ESMTP id 5CC79140013 for ; Wed, 11 Sep 2024 22:55:39 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="sh382Oa/"; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095311; 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=xpCyIIItvhaSWCjWFHqWOk5Js5blwh8hFjcI+6KQiYA=; b=gCwOhgf7TZFsgMbb5ZnRNM9X8bPXOnTVqvhB+cQD6ER8Zw42ZIUlyWhRG8ajjf7tLFaTPH zD8tfeCEnE2RnWQ6m/KgACB6Jh2xwzteQgp6ycXyahg5E7G0UFW9bmyw+xvuh7uzsNk7Zk goGP7hbPylJTIU9w8znrlkx1MVlpdUw= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="sh382Oa/"; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095311; a=rsa-sha256; cv=none; b=VfCabHHDp8yeb3G9T7CQp+Jr7jkajkjdCw/3F51Gje0KMbLgzrfwkbhK3XH6XD5IAD7WbA xCmbKrLAtZqz1Env5lGEeiJeldRLqbEnLtLzCronaP36nBZcXYvSZKmicyG8QBt1JAXjma cY7CrWM3kRBUyao1bpmupPe+CXZxF4Y= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id E9B395C0532; Wed, 11 Sep 2024 22:55:34 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 5A1C7C4CEC5; Wed, 11 Sep 2024 22:55:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095338; bh=7ud9iFBT5EcUDGEvKd041Y+gvEKEu7RxRlS2eA0UCRA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=sh382Oa/l5uE2UTx21wKubJ27EmXt/WljM5TDLCvic0zWfZUvcq0zujcO0gwtq8UN frSY8H4qkNT32280yR8hCKXi+tJGkeGY5mHW8l5aOYU7V8gfphjJJ6SzFh3O7D/j4d UEgK+aCBsDu+hr6gEL8aTYlWF8nBFRgQaAsgPEnw2kJaHBgWUB+fyqREO+OOM0I+jY mV50Hr2ANdJESRoToUkBIfUIggcAVBckovKxkAdC4hTFOLLzCn75rA54hGe/eF7wxp H6JsuRM16TZWPBhgK0nnGbrkA087+fbnAGT9hNcDPE2UU1L7Y3IY/+sfiWnwIIUTdx 86+gU0pe6L42g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 07/26] rust: alloc: implement `KVmalloc` allocator Date: Thu, 12 Sep 2024 00:52:43 +0200 Message-ID: <20240911225449.152928-8-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: i884dwrw59epqb5tg56p18cpg6q7rbmx X-Rspamd-Queue-Id: 5CC79140013 X-Rspamd-Server: rspam11 X-HE-Tag: 1726095339-899807 X-HE-Meta: U2FsdGVkX1+9I+AoY/blMGmDzzVRjyDsYa91vwVbXNPif5009GcpdL5AdUB0TD3RNrUiu4HeeFffJI3oCVipqswvtT7XuWdglOaYgub28er2x47YITiXJ9VBjsuIE7l3VQAAMNUpyuEIwN0hScrID6GUnky9wxW7eMJE+JhJCtWVW0rtXBuWVQ72dKyfWrKBgOOOkRCDwWPU5vUntFXBQqh9Iyjpo+qgCdgogrK8eea6FK9JKzs+jD+a9N2p79C2lyX0fM3Sz9B4NX6Rlw8NiQyniIHbfqsRk+axiiaBTZZdskmUFlypzQ8AfhI/QxRZiYUYJx/MediKf0+y+8oE/b8fZOyA6xSnu0NLRqunvj7FkFMQPTW3GVpt48G5zA4My4A2RXqlhZ2DA36p5HghUwX4OoTla9fIJ87M6Z3iJK+6sbe6SSaGA2yZZ+MDa/WYahfend1YGLtJTRHN7dZuFFnVU0Kqz8Szdy2gXCFWPisXzeM3BXgN+NzeBEUSolHBzC61EU5skH+qeb+m65g54Yakv/xZ+R5lnArM+G3eRjroKfJH68WHc+oWr1dusHRCx0hClwf6dLRNDM9qll9g6d2F12QId0x8kWicPGdbDpswNingDCBzwyQwzw5KUNWOe3bSm/LWMRVXKGMmEWr7DpMqjGDkSEaIE8+ltsJwyM9xfEDZXtJYxilXO39rxmocqGtdulPrnTsOW1+C5LTb7SI4QVzRsJ0oaMJeZcJhIfRabXcDxyY3S19jpdbKy54Uw3OU7fI7T5A4DHuXFa6uIwuEpJcC5lOUrx0phxsJBa9iS5POF65l/QWMhDXK1Sp3+HjACGMfldKN0PD3zFg+QGMb7BXekUBgwvWu1a/tGkk0Pd+cGTFa1DIqm3VbK6KkyfB6Zho9pQbwqs8ftzsZaVZSoGtkvW7NuS4oWNIvkScddlX5WHIxc+T84H7SDHwb7s1IcSYr+2Oc4ChK3fo npyKhXCB 7oYe0S2SMBNwsBVPQF+opUrJBG6kMlImkdhAmEn2FwbzpWaLdElTSUjUv8Gym1Ga9jSJuKrMqbLUPx9MKbTuiIcMKyDpFQlUOVekaS8IUK0PNJe1Y5zua/6CTRb+fPoG+orBHidREywhCx1GYPfKQLKkhYg4xedFPh3vBn5QD3jxtH32DbrVjlRMJ/PG6T/hBRA8USB5vSnI/yt9OyW4B2ozyYRSdvCvDgwVoesX04Gc7l7gj2wwbbxGODwKFCEyAL5Mh93JEQCGQbYSfCUjQQ3jXI9oT4iL+YxaGGdVxY+XUwPzJbbxfuAero03bVwphHieWzRyZYQZHFNM= 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/slab.c | 6 +++++ rust/kernel/alloc/allocator.rs | 35 +++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 42 insertions(+) diff --git a/rust/helpers/slab.c b/rust/helpers/slab.c index f043e087f9d6..a842bfbddcba 100644 --- a/rust/helpers/slab.c +++ b/rust/helpers/slab.c @@ -7,3 +7,9 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) { return krealloc(objp, new_size, flags); } + +void * __must_check __realloc_size(2) +rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags) +{ + return kvrealloc(p, size, flags); +} diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 0f2bc702e8e4..a5d7e66a68db 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -34,6 +34,15 @@ /// For more details see [self]. pub struct Vmalloc; +/// The kvmalloc kernel allocator. +/// +/// `KVmalloc` attempts to allocate memory with `Kmalloc` first, but falls back to `Vmalloc` upon +/// failure. This allocator is typically used when the size for the requested allocation is not +/// known and may exceed the capabilities of `Kmalloc`. +/// +/// For more details see [self]. +pub struct KVmalloc; + /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. @@ -76,6 +85,9 @@ impl ReallocFunc { // INVARIANT: `vrealloc` satisfies the type invariants. const VREALLOC: Self = Self(bindings::vrealloc); + // INVARIANT: `kvrealloc` satisfies the type invariants. + const KVREALLOC: Self = Self(bindings::kvrealloc); + /// # Safety /// /// This method has the same safety requirements as [`Allocator::realloc`]. @@ -194,6 +206,29 @@ unsafe fn realloc( } } +// SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that +// - memory remains valid until it is explicitly freed, +// - passing a pointer to a valid memory allocation is OK, +// - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same. +unsafe impl Allocator for KVmalloc { + #[inline] + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("KVmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc = Kmalloc; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index e7bf2982f68f..1b2642c547ec 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -8,6 +8,7 @@ pub struct Kmalloc; pub type Vmalloc = Kmalloc; +pub type KVmalloc = Kmalloc; unsafe impl Allocator for Kmalloc { unsafe fn realloc( From patchwork Wed Sep 11 22:52: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: 13801181 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 9752FEE57D7 for ; Wed, 11 Sep 2024 22:55:47 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 32E516B009C; Wed, 11 Sep 2024 18:55:47 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 2DEB96B009D; Wed, 11 Sep 2024 18:55:47 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 17F726B009E; Wed, 11 Sep 2024 18:55:47 -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 ED1336B009C for ; Wed, 11 Sep 2024 18:55:46 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 7B2971C5C8D for ; Wed, 11 Sep 2024 22:55:46 +0000 (UTC) X-FDA: 82553966292.11.64206E0 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf11.hostedemail.com (Postfix) with ESMTP id CD7AE40009 for ; Wed, 11 Sep 2024 22:55:44 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QPvCMXFp; spf=pass (imf11.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095241; 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=bkSQM67IdFsrXjQ4lzr33DtOqD4RTup7jocShUepuMA=; b=EHKR8JT0YExsgP3piTfrGnMd+pnb8boVgwgD1JKgnAFof5JN/pIiD83YMwZwmCPV7wPAaP gopNSJ0Jk/sbXUBHPmVA2e/eMtqw9WD1lzy3uwbvon/wb1+TKsYhTpGbSlL7hJ5U/AjDTm AVK/aqQQwc+xCjawQ5vQ2VVcCY0k2Bc= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095241; a=rsa-sha256; cv=none; b=Gtu+4Ef50k23fo4zpMJ5xPyPX8iWhj3bHbbzKijujAxaezG9UjoywegyzYMKMb4/IsJvzX aSyr1UF+Y35iVjKR3evK4TaR+sthHJ35BNtXCEPGfRdZwCpAf15mb/majGwgqaeWNS/USc uw9BxvFyy97rz0CEAg2Tp+zJqARu99k= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QPvCMXFp; spf=pass (imf11.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 619F75C0131; Wed, 11 Sep 2024 22:55:40 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A63D1C4CEC0; Wed, 11 Sep 2024 22:55:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095343; bh=cw4d7ozoaPZp9ThW0IiXPabVi14FeEz+TkCXge43sLA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QPvCMXFpIwzfoZbpxM2gjuVdmtZUL2+Yc6GhKLt//9t7CDDcaB8AgbIiSKcHmTb0C x3EGE9ZzTqaLvqTvzVZYjvTAg13F3eEJnh3cJJEWio3yD+JN8s3DsYCmcMLD9Yc97W A/GUrN62DQFaaEosXHom6aUqb6ujSOgzzIhn+XhM/km6w65C3We22AI9nBIBuXuu/5 L4MD9j0pviw9fbRrP/07HmRhI3G5Zllhkjf4P9q9vlqmXaWmXUuzLzM1PyTb8m68c9 3xPHmt7Mu/gEjvkGoVc4YPmFE+GRhsiPEmyJRhGJ6rKl7lsXMWukOy0DuYZ/aXCFf6 o5h4yzR932z0Q== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 08/26] rust: alloc: add __GFP_NOWARN to `Flags` Date: Thu, 12 Sep 2024 00:52:44 +0200 Message-ID: <20240911225449.152928-9-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: CD7AE40009 X-Stat-Signature: xfwipc9zufs4cp8xg5qmdmi47iuizbry X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1726095344-65324 X-HE-Meta: U2FsdGVkX1+aIZDhUCBlA0yEF8Jw90ppCJ0dkKHqL4h9hIgwpYF8lZOJlYj1Auo5vLDY4KuH6+sWmJgODXPvv+JpfZCHrf/4cYuUO3SisXZFHvDbN1fedSriJxSQ6GXrOqK7U6m9LllSBRxr8VpBc+/ogTiTzaOU9xBbeONQErQjhLa3nEv6bq2H0ixoaV3riRCkJgx8y7wT6Jyp1pWVzuY1LsyTy4Zupk7fBaLWKc66nSD8dEKu9p2DBa9R6osIJqhI7YYqv0Q2wE0jZXoSN6xbtuwoA63OalRwb0+hYqdI1mjQMmABc5jukZM1TNCYm1qmcSnl+l5ilf95ntMjtIrwdc8gVXnbgKlVD/QeHc/bT11MY2xb1Z4HllojHKI8rzfyQPwCqFJVrODXEoe4J/0Lqoc8FqA86W0ZdRwjcoywKkU6gTn1Su7hUGu2t0+11g3T8bEivrDmIDzDiL7gVOclkzM84ZBMMJIn2tk3shEOC66JKrNEdDckZcVrK4ALUQFInEEBYbLnC/6STy0RSQpg1DFRTX6iII7JdTQ7T27yYvBaHfhFQlQplJCGNsR78LkKls8fOXqKoKj34NZjQtQ1XQok1XHYz7LTpYiZufbE4tmaNTBsY+cbmEF3ZS3hB+btllzaxtswZWS++rz/mg3CJZJ+sFzSkA30UMvjtiKuVCxKpotxtwbSdJf+nzlzRHDhMEGnRQF+igObTeDa23kpiXzBtSIwBz85GWGTkC6LIu35Gro/Jq75REir73Z9C39IOPledkU6+5z/w+PRuBdHX1BN2T+mAUXjXM6SIcCQiSGNEX9kCj3nLGS8YepAVusl/rG+T6V2dT+lLcrf/qv06t2bKiBUIsF4XhpASplD8jEv+VjRYDgKMA+2NJB5KLN8KpDfJXDe/Ng0TMJNAe2ADAui7BHQmc3f0L0ur9iPLTLN8XDzhRSRJvYeeqkLQSKjK4ay1sfxMbf7ecf frq1aER+ sA6KkdRrYMSUlL3XYoDqofwBgcfC2i9kLdlG0c9XPuyiH7q6BipFBKSyfskIqOj3bnOfJprUawBROpiv0up2rDjKyppQH9QxkkMbrcBslLNd5zouKSvaSpunL8pBAwMQDcMQA9qDspZCCTlh6QBOaqnZJNO/6HS0pZ2ROYF11n5Wxv+3fFXJYJ0gS+QDqPqcbus2YxbhYwyzMVHnqdmsE3LC792soVIutlwCcM/eBXuFEDyb9ERRPpwW27o9UO6uGdr+3FLXr0Hco1WyTi52ZB2IVALCB++Jcms4RuQ9JJP4oQrE1x/27H4eYKgfgTO5urNdCImS3Oj8h0vOinkFUrYsCCIossXsmGY4u29dXsZatAKFEZTQXtiYjQg== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Some test cases in subsequent patches provoke allocation failures. Add `__GFP_NOWARN` to enable test cases to silence unpleasant warnings. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/bindings/bindings_helper.h | 1 + rust/kernel/alloc.rs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index ae82e9c941af..a80783fcbe04 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -31,4 +31,5 @@ const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT = GFP_KERNEL_ACCOUNT; const gfp_t RUST_CONST_HELPER_GFP_NOWAIT = GFP_NOWAIT; const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO; const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM = ___GFP_HIGHMEM; +const gfp_t RUST_CONST_HELPER___GFP_NOWARN = ___GFP_NOWARN; const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL; diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index da025faf07f8..7a405d6f3034 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -91,6 +91,11 @@ pub mod flags { /// use any filesystem callback. It is very likely to fail to allocate memory, even for very /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); + + /// Suppresses allocation failure reports. + /// + /// This is normally or'd with other flags. + pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN); } /// The kernel's [`Allocator`] trait. From patchwork Wed Sep 11 22:52: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: 13801182 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 9E5E6EE57DC for ; Wed, 11 Sep 2024 22:55:52 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 37C896B009E; Wed, 11 Sep 2024 18:55:52 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 32CE96B009F; Wed, 11 Sep 2024 18:55:52 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1A6AF6B00A0; Wed, 11 Sep 2024 18:55:52 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id E269F6B009E for ; Wed, 11 Sep 2024 18:55:51 -0400 (EDT) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 969084111A for ; Wed, 11 Sep 2024 22:55:51 +0000 (UTC) X-FDA: 82553966502.13.40403AE Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf03.hostedemail.com (Postfix) with ESMTP id E654020004 for ; Wed, 11 Sep 2024 22:55:49 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=eUiJEiIQ; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095297; a=rsa-sha256; cv=none; b=4RSINb9AIczWbSOC8tqxO6KFertTL7ucWyYgUE8BdFyUG1DIm/jaUh/vWcrfxrXA99jInr 8mDYWUZDa0EzUL2SMuL7KOxMdqClzLYs8zwAyerHDryBoxtQd7+kBcQX+S+pSDKUGhfqtQ 55nftXh57VAZNZwFqR/q+QagGAZH2XY= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=eUiJEiIQ; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095297; 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=fG6b/Lg67wERNrdw1Z861e40PtepZsYSu5XWjexXJ1s=; b=caGOmHmQpTZ5jF78wm+psmtbFzlLB2sEp9ZjFIe7adsNjcGaD3ViyX8aJzmucQZNPLljSM cDhJ/74qU5LORyFidSnjhyuAvZNTGIb0w1VdltXkaAwgsCpAAhKSHtKZ11BfmtqAAXsjm/ onP9B+oMqnK//cspdGqO8Y1VEbOvzX8= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 6F2AC5C0592; Wed, 11 Sep 2024 22:55:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 00C2EC4CECF; Wed, 11 Sep 2024 22:55:43 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095348; bh=ONKVPueTm7R2PEVvV8+tCD9cNcEk3jCly02IRQlQKQg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eUiJEiIQGC8VjeuVStZGt08/gecMgGbA6/Fo846oN4XZsN1GacSC0O/e2hdwKqY4I V/cQVDeymgAllj1Ey5mMJHQl1F/GC7GV5Yt6Q1WeU4iNzkMzP+exjY7BAlreNrqbUd MWGJRxchhyh+qHR5c1CfTeuEUPL7RisF07YbyWGuaf8Ts0N+wzLm6Elp7VP/BNdyxf VykicW0iKU8O1umLdSKlIc8xTXa3wMnlJcDo37urOPv/YBpi5lcq0oyK5wK6Jca5Sj MiWZz7aL5NKXkn6LUXRrA2xKpGHMG3t/s9RmYdje9xUVzoo3EomMT39Xfa064Lmy0K CcQPMS1RGnEUQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 09/26] rust: alloc: implement kernel `Box` Date: Thu, 12 Sep 2024 00:52:45 +0200 Message-ID: <20240911225449.152928-10-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: erraq419t8insw1cnft8acddwh7uo711 X-Rspamd-Queue-Id: E654020004 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1726095349-622548 X-HE-Meta: U2FsdGVkX1/cQNw51e5yhdpGMbeOxi3HZb/fg9jYWrO6aJ5UqEfZTiRl5JJ3jDwMTUA/BYkvf6P5+kZSI/efSh0aq4GZ7FZ0zrX9DrbSOhgFgKbmpEpWL57aqkBV3+ksn9Uk5CM1dI22jnoBmXhVr8sbhlduPyTtZyFW1XTP9DKOiqU5luMgtbMmo+ueU5RlMLMw74AwsLz0Fv2Dxmn9U+ifaQ3z9V29GVIyJuNSvM479+yqA7FQiDWfHN0gNvqZiGrZlkxgw9yqzzRA/7sJexqlXTikn2rY2IXSUm7U9bxNy+iJkCU9Mhf74m8GXA7l49MbzbpOE4ed/HMwMh6RvV3xpz5x/zB0UaGQ64OREUYWbeneqJxpLfZfnJUCfz8U/dCBKOCkSQwIsEH4tBaJ9CzIS7ds+pqUlGQ7zqYP1eC8lOmMbDTdq8RCkfHJNahfnOQL/BBjGMtyuna0avzHY+sV3Jz7S2NF3u5+BC6R15vCpEJoaDftdlxW/ZHo7BC5Kls1Xpm1u5lSZ4ETZ7+mMDnLd2y8/x5cwTuxF0X3S2baKDfx2eanPjpSEKWXiS7NHQeOG/xfa4yGBFk8H11PFVwuCLOuKrmLrYpSzruX0p4XCW11k/EIgtkDMY2MHPN4IdYbWHichlVxiegRpZ+t8f8hVDASGN7F1m2djO0YexMq2kKN2rNhOCIPnM0it4eF+ODNwz9AG+9I+G6t31S8VzBpWggyK8nFhTzJjyuiCm6kA4IHj8xsG2YIzdH2sx8MwaOxQuVLJ84UcmJ1Xfs3fWczWKIXg5NsaCTJS9iDJ46zfnMtQLamBnnYgNrlEmUSjQG8HEctch5mamrVODQrIrME1yqz87aBsy8cwF2LLPGla2/2IFXOmFo0P+KTIVIi7IgOVyyKXDuuEnNEFyu7Ol83+GgGdgc/QPU2D2hIUBTVdvhh8FRmSkDO0l4x7obuDtVCGyB1Q9tReqBu8ip jzXRwsx8 sVV/UAltCUCdRpB7WpYkyVerIMuAqKlrgZIFLZxxDN/GEyuOi+Dv+go8qp6jgVKGyhei+57aBltoNEQoH9KZYqDG++ERDoSwR6ZogwhxW1jJOMTigumwr3raJ9UG4Ifc15u2Zq7bQEjjIZK/kd5okbHI4iA2gzuRSkRFS5vfI6mwmmF8FlVLc1uA6Hh9t3QUv8Cz3ud6AepYhdUgagtvdnIXgzA+gJp7IJF14SgevpvUK8CZjPQxBgpzRdvwFd8cBI6x1HB6rtlefMHSn2M3xeQ/081XUQNYu51oYWzP4CjcKNBxf7SH/dP7uyg== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `Box` provides the simplest way to allocate memory for a generic type with one of the kernel's allocators, e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`. In contrast to Rust's `Box` type, the kernel `Box` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 465 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 472 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 7a405d6f3034..b1f28334b27a 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..6188494f040d --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,465 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +#[allow(unused_imports)] // Used in doc comments. +use super::allocator::{KVmalloc, Kmalloc, Vmalloc}; +use super::{AllocError, Allocator, Flags}; +use core::fmt; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::pin::Pin; +use core::ptr::NonNull; +use core::result::Result; + +use crate::init::{InPlaceInit, InPlaceWrite, Init, PinInit}; +use crate::types::ForeignOwnable; + +/// The kernel's [`Box`] type -- a heap allocation for a single value of type `T`. +/// +/// This is the kernel's version of the Rust stdlib's `Box`. There are several of differences, +/// for example no `noalias` attribute is emitted and partially moving out of a `Box` is not +/// supported. There are also several API differences, e.g. `Box` always requires an [`Allocator`] +/// implementation to be passed as generic, page [`Flags`] when allocating memory and all functions +/// that may allocate memory are fallible. +/// +/// `Box` works with any of the kernel's allocators, e.g. [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`]. +/// There are aliases for `Box` with these allocators ([`KBox`], [`VBox`], [`KVBox`]). +/// +/// When dropping a [`Box`], the value is also dropped and the heap memory is automatically freed. +/// +/// # Examples +/// +/// ``` +/// let b = KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KBox::::new_uninit(GFP_KERNEL | __GFP_NOWARN).is_err()); +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KVBox::::new_uninit(GFP_KERNEL).is_ok()); +/// ``` +/// +/// # Invariants +/// +/// `self.0` is always properly aligned and either points to memory allocated with `A` or, for +/// zero-sized types, is a dangling, well aligned pointer. +#[repr(transparent)] +pub struct Box(NonNull, PhantomData); + +/// Type alias for [`Box`] with a [`Kmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b = KBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type KBox = Box; + +/// Type alias for [`Box`] with a [`Vmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b = VBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type VBox = Box; + +/// Type alias for [`Box`] with a [`KVmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let b = KVBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// # Ok::<(), Error>(()) +/// ``` +pub type KVBox = Box; + +// SAFETY: `Box` is `Send` if `T` is `Send` because the `Box` owns a `T`. +unsafe impl Send for Box +where + T: Send + ?Sized, + A: Allocator, +{ +} + +// SAFETY: `Box` is `Sync` if `T` is `Sync` because the `Box` owns a `T`. +unsafe impl Sync for Box +where + T: Sync + ?Sized, + A: Allocator, +{ +} + +impl Box +where + T: ?Sized, + A: Allocator, +{ + /// Creates a new `Box` from a raw pointer. + /// + /// # Safety + /// + /// For non-ZSTs, `raw` must point at an allocation allocated with `A`that is sufficiently + /// aligned for and holds a valid `T`. The caller passes ownership of the allocation to the + /// `Box`. + /// + /// For ZSTs, `raw` must be a dangling, well aligned pointer. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function. + // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer. + Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData::) + } + + /// Consumes the `Box` and returns a raw pointer. + /// + /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive + /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the + /// allocation, if any. + /// + /// # Examples + /// + /// ``` + /// let x = KBox::new(24, GFP_KERNEL)?; + /// let ptr = KBox::into_raw(x); + /// let x = unsafe { KBox::from_raw(ptr) }; + /// + /// assert_eq!(*x, 24); + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + pub fn into_raw(b: Self) -> *mut T { + let b = ManuallyDrop::new(b); + + b.0.as_ptr() + } + + /// Consumes and leaks the `Box` and returns a mutable reference. + /// + /// See [Box::into_raw] for more details. + #[inline] + pub fn leak<'a>(b: Self) -> &'a mut T { + // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer + // which points to an initialized instance of `T`. + unsafe { &mut *Box::into_raw(b) } + } +} + +impl Box, A> +where + A: Allocator, +{ + /// Converts a `Box, A>` to a `Box`. + /// + /// It is undefined behavior to call this function while the value inside of `b` is not yet + /// fully initialized. + /// + /// # Safety + /// + /// Callers must ensure that the value inside of `b` is in an initialized state. + pub unsafe fn assume_init(b: Self) -> Box { + let raw = Self::into_raw(b); + + // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements + // of this function, the value inside the `Box` is in an initialized state. Hence, it is + // safe to reconstruct the `Box` as `Box`. + unsafe { Box::from_raw(raw.cast()) } + } + + /// Writes the value and converts to `Box`. + pub fn write(mut b: Self, value: T) -> Box { + (*b).write(value); + // SAFETY: We've just initialized `b`'s value. + unsafe { Self::assume_init(b) } + } +} + +impl Box +where + A: Allocator, +{ + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Creates a new `Box` and initializes its contents with `x`. + /// + /// New memory is allocated with `A`. The allocation may fail, in which case an error is + /// returned. For ZSTs no memory is allocated. + pub fn new(x: T, flags: Flags) -> Result { + let b = Self::new_uninit(flags)?; + Ok(Box::write(b, x)) + } + + /// Creates a new `Box` with uninitialized contents. + /// + /// New memory is allocated with `A`. The allocation may fail, in which case an error is + /// returned. For ZSTs no memory is allocated. + /// + /// # Examples + /// + /// ``` + /// let b = KBox::::new_uninit(GFP_KERNEL)?; + /// let b = KBox::write(b, 24); + /// + /// assert_eq!(*b, 24_u64); + /// # Ok::<(), Error>(()) + /// ``` + pub fn new_uninit(flags: Flags) -> Result, A>, AllocError> { + let ptr = if Self::is_zst() { + NonNull::dangling() + } else { + let layout = core::alloc::Layout::new::>(); + let ptr = A::alloc(layout, flags)?; + + ptr.cast() + }; + + // INVARIANT: `ptr` is either a dangling pointer or points to memory allocated with `A`, + // which is sufficient in size and alignment for storing a `T`. + Ok(Box(ptr, PhantomData::)) + } + + /// Constructs a new `Pin>`. If `T` does not implement [`Unpin`], then `x` will be + /// pinned in memory and can't be moved. + #[inline] + pub fn pin(x: T, flags: Flags) -> Result>, AllocError> + where + A: 'static, + { + Ok(Self::new(x, flags)?.into()) + } + + /// Forgets the contents (does not run the destructor), but keeps the allocation. + fn forget_contents(this: Self) -> Box, A> { + let ptr = Self::into_raw(this); + + // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. + unsafe { Box::from_raw(ptr.cast()) } + } + + /// Drops the contents, but keeps the allocation. + /// + /// # Examples + /// + /// ``` + /// let value = KBox::new([0; 32], GFP_KERNEL)?; + /// assert_eq!(*value, [0; 32]); + /// let value = KBox::drop_contents(value); + /// // Now we can re-use `value`: + /// let value = KBox::write(value, [1; 32]); + /// assert_eq!(*value, [1; 32]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn drop_contents(this: Self) -> Box, A> { + let ptr = this.0.as_ptr(); + + // SAFETY: `ptr` is valid, because it came from `this`. After this call we never access the + // value stored in `this` again. + unsafe { core::ptr::drop_in_place(ptr) }; + + Self::forget_contents(this) + } + + /// Moves the `Box`' value out of the `Box` and consumes the `Box`. + pub fn into_inner(b: Self) -> T { + // SAFETY: By the type invariant `&*b` is valid for `read`. + let value = unsafe { core::ptr::read(&*b) }; + let _ = Self::forget_contents(b); + value + } +} + +impl From> for Pin> +where + T: ?Sized, + A: Allocator, +{ + /// Converts a `Box` into a `Pin>`. If `T` does not implement [`Unpin`], then + /// `*b` will be pinned in memory and can't be moved. + /// + /// This moves `b` into `Pin` without moving `*b` or allocating and copying any memory. + fn from(b: Box) -> Self { + // SAFETY: The value wrapped inside a `Pin>` cannot be moved or replaced as long + // as `T` does not implement `Unpin`. + unsafe { Pin::new_unchecked(b) } + } +} + +impl InPlaceWrite for Box, A> +where + A: Allocator + 'static, +{ + type Initialized = Box; + + fn write_init(mut self, init: impl Init) -> Result { + let slot = self.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid. + unsafe { init.__init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(self) }) + } + + fn write_pin_init(mut self, init: impl PinInit) -> Result, E> { + let slot = self.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid and will not be moved, because we pin it later. + unsafe { init.__pinned_init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(self) }.into()) + } +} + +impl InPlaceInit for Box +where + A: Allocator + 'static, +{ + type PinnedSelf = Pin; + + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + Box::<_, A>::new_uninit(flags)?.write_pin_init(init) + } + + #[inline] + fn try_init(init: impl Init, flags: Flags) -> Result + where + E: From, + { + Box::<_, A>::new_uninit(flags)?.write_init(init) + } +} + +impl ForeignOwnable for Box +where + A: Allocator, +{ + type Borrowed<'a> = &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + Box::into_raw(self) as _ + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Box::from_raw(ptr as _) } + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { + // SAFETY: The safety requirements of this method ensure that the object remains alive and + // immutable for the duration of 'a. + unsafe { &*ptr.cast() } + } +} + +impl ForeignOwnable for Pin> +where + A: Allocator, +{ + type Borrowed<'a> = Pin<&'a T>; + + fn into_foreign(self) -> *const core::ffi::c_void { + // SAFETY: We are still treating the box as pinned. + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + let r = unsafe { &*ptr.cast() }; + + // SAFETY: This pointer originates from a `Pin>`. + unsafe { Pin::new_unchecked(r) } + } +} + +impl Deref for Box +where + T: ?Sized, + A: Allocator, +{ + type Target = T; + + fn deref(&self) -> &T { + // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized + // instance of `T`. + unsafe { self.0.as_ref() } + } +} + +impl DerefMut for Box +where + T: ?Sized, + A: Allocator, +{ + fn deref_mut(&mut self) -> &mut T { + // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized + // instance of `T`. + unsafe { self.0.as_mut() } + } +} + +impl fmt::Debug for Box +where + T: ?Sized + fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Drop for Box +where + T: ?Sized, + A: Allocator, +{ + fn drop(&mut self) { + let size = core::mem::size_of_val::(self); + + // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant. + unsafe { core::ptr::drop_in_place::(self.deref_mut()) }; + + if size != 0 { + // SAFETY: As `size` is not zero, `self.0` was previously allocated with `A`. + unsafe { A::free(self.0.cast()) }; + } + } +} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 4571daec0961..a9210634a8c3 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt}; +pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; #[doc(no_inline)] pub use alloc::{boxed::Box, vec::Vec}; From patchwork Wed Sep 11 22:52: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: 13801183 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 0E7BEEE57DC for ; Wed, 11 Sep 2024 22:55:58 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 923076B00A0; Wed, 11 Sep 2024 18:55:57 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 8D25B6B00A1; Wed, 11 Sep 2024 18:55:57 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 725826B00A2; Wed, 11 Sep 2024 18:55:57 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 4D5D26B00A0 for ; Wed, 11 Sep 2024 18:55:57 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 13BE51A169A for ; Wed, 11 Sep 2024 22:55:57 +0000 (UTC) X-FDA: 82553966754.14.6F00E68 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf26.hostedemail.com (Postfix) with ESMTP id 3B5F914000D for ; Wed, 11 Sep 2024 22:55:55 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Qmmsw43W; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095278; a=rsa-sha256; cv=none; b=qNCzU+WRNZ8a1A7awbDeBnmZo5mEaeld4/QDX/DxZsPyMKQsM1StVIN9oMol7RkLq0BIn8 02NdEdLvfZgy/pRQdbVMonAfLMtpqmbNiyGkugSERmzcp8cta8iEmT6WUomfhp8q1UZWMV uN/wzZsq0NVlFK4npZrLeFw0nTcvJ1g= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Qmmsw43W; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095278; 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=1pIoVp/SC39zlIMVQFG1hbNG9e37ynFdbTAr+kyp8fA=; b=WNEg0LQGS0T1PnyK+WJUX175BgbFrOM7bR0CMoJXwZX5PzWxop/5Oj3ykotFfnEIIi/jVj uhwR6+o7Ez4G8hWlDcrcSpvgSmsLUyri2BbxklDIQPbXrutHGWJUuNCjzZi1nQBMr3t9iX q5w32NNoajB8bGR9IYaBA2Chw8e/q/s= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id B6BEF5C0131; Wed, 11 Sep 2024 22:55:50 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2539AC4CEC5; Wed, 11 Sep 2024 22:55:48 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095354; bh=HeNALPSOjE0/n20+LWU+GT6yCUL8iOTLWac/bFqoeV0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Qmmsw43Wnal8FJjiGoJbRtDfBnn+XXk9RxQCjiU1kb+2Kj7ZpJ1pkKck1wI7NS7GF s5jREs6+svc8czMLdyk0FQlAJNa7vytaWS4bB/TuP2zeGRSJHePnI54F3GEttJRbFw YeN6TBLLvtlNIyc8+mBPovBljl9dpI/r8X3mEWflpT5CBUNvIt6KQuXdXnaoEx34/i O+jsL2mWEhLLOUpVlZjHa9dGCwN5gWEVfHRPdRIyFBFaNE87TYZ0s8RIQryEEBi4mV DJ+nDFg+YMlJeG7B/4kbnMX+pXB+AoNhyp630lI34XcMey25irWQoT3vtd5w6CFiw7 pyenSvRj6Qk3g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 10/26] rust: treewide: switch to our kernel `Box` type Date: Thu, 12 Sep 2024 00:52:46 +0200 Message-ID: <20240911225449.152928-11-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 3B5F914000D X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: ew5p6zxc49f5e1qzrgqujt9qktbth5tz X-HE-Tag: 1726095355-693902 X-HE-Meta: U2FsdGVkX1+0WDtcnLiWDhhPNuw7U0tbMtVL/coXbR1aWBlUWkxiGOYXvDbn43NG5TDsQRcdUuh454PVK1BiLYJzmDAp/43sLTEwxGR3SYhArlUaDF9FMKpZmnPj5xw/RP6UM910idMZRi9afmfpzoOHrO3k9tfqIZHt22pkIHgs/MKg5hQ8EmRLrPswkl2lZy7V/TYqU2m116FoK6pQwdDG9gwc6WxXr/r6wap0uFe67YjCs7urVeOPqG94/Iso2VN9M26KuL2+HOLGWR0WkDtHWSDclLbxB/SxwcprNQ2fbF4XZe6noJQscn0DwlI4svLL1o5Vswii2+DT8zVJDeZrxVK86FpvQbczb/Q7OnWLHibVQwd2kLTp5eIHKIyT6Hs75KhPZGMjeVoi6TXwVsR5Kb7OLfEX6uo4FLREI61FIvnFs7rrMqproVU+CfdkcjayURrLJ72Yv508+ZlazVxw8Y3RJl6lWgjOfmK4UGWprkMSVLq8MvDRaL9IBe50R25dtd8JllPR390VWcWfk55DlUCHQjcXAsUI5z5MmDDpMTu3aJ7P05nnbaYfIXp68atF6eorV68qkAWBlrqFJSwhLdD8tDwaEP3C0yohHnguNzjHLK6LlgtGdQUejRTNBgXybtp0eiWEIEUQ8TADmyS2m4EBhWwjOgKg8a6PYKxQecksYdwS6VWDgvnqYNw79tJRUjKhAK2oMKLxgeTME539z64O8teAtEePiOTCJfMZa/Yw4kH8Yssn4JswmqPyaamdHJG3PlXEsLOJJsxwG4bEnovuyco+J7zKZG18tQDIrgDN9zPp4eVUvvlTpgLPDrPHsOFyQyKV3JOr41QULsbaQM0B7LeTQPFdMpWQk/ICZyCBzBKTIEO12zuKV9yZvTDDhLuC2n6xqIHFjrqyaFqUs+eSP7EaKU8XxjusbFIlUvcIiGPw1acS2PiYvOa6oCMWmbfiKQU4tRS0N6P ffrqRxDY JggD/bd4B19EGibMqkF86gM0YvzKqyazZOBGNsHYF8v4qEkwDHO12kYxdA+jvq3m6gRzFdgHFlVtfPCXsCIn2ejaHU+hDU5a8vzrOGp1zyJSOXnGGHekTFYh/YHhQiNomj0qSccsLJLpwS8P/VLslozgj5JJdBqcMehGxo6SS4qrTTAtfvXoZRhAJzZwjGTmTinOoR+zjuqoESHnK7rugKFUZwFc22CtrGB84HAuTHGcH5RtLJ6/lKo/WLHyCwm67xIwVYmEYFcE8yY0KbLAcJzaW0lIzocZvsBaGmibq5NfKXwKa+hOaWnHfrg2zWzk+sdOxIg/gAFXhDNJ1/nUMgy7tMtP8wtMWnyqJsfcQ4fNGNZIeJwYyIWWkUDPddmouz/vWBXLuJcqQ8zlXijFLL0RlrwgdFEF6qd3sN06JM7FY0z1AK+ZL8SE6ylk6rHHoHvTP X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we got the kernel `Box` type in place, convert all existing `Box` users to make use of it. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- drivers/block/rnull.rs | 4 +-- rust/kernel/init.rs | 51 ++++++++++++++++--------------- rust/kernel/init/__internal.rs | 2 +- rust/kernel/rbtree.rs | 49 ++++++++++++++++------------- rust/kernel/sync/arc.rs | 17 +++++------ rust/kernel/sync/condvar.rs | 4 +-- rust/kernel/sync/lock/mutex.rs | 2 +- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/workqueue.rs | 20 ++++++------ rust/macros/lib.rs | 6 ++-- 10 files changed, 81 insertions(+), 76 deletions(-) diff --git a/drivers/block/rnull.rs b/drivers/block/rnull.rs index b0227cf9ddd3..5de7223beb4d 100644 --- a/drivers/block/rnull.rs +++ b/drivers/block/rnull.rs @@ -32,7 +32,7 @@ } struct NullBlkModule { - _disk: Pin>>>, + _disk: Pin>>>, } impl kernel::Module for NullBlkModule { @@ -47,7 +47,7 @@ fn init(_module: &'static ThisModule) -> Result { .rotational(false) .build(format_args!("rnullb{}", 0), tagset)?; - let disk = Box::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?; + let disk = KBox::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?; Ok(Self { _disk: disk }) } diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index a17ac8762d8f..e057b374f255 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -13,7 +13,7 @@ //! To initialize a `struct` with an in-place constructor you will need two things: //! - an in-place constructor, //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc`], -//! [`UniqueArc`], [`Box`] or any other smart pointer that implements [`InPlaceInit`]). +//! [`UniqueArc`], [`KBox`] or any other smart pointer that implements [`InPlaceInit`]). //! //! To get an in-place constructor there are generally three options: //! - directly creating an in-place constructor using the [`pin_init!`] macro, @@ -68,7 +68,7 @@ //! # a <- new_mutex!(42, "Foo::a"), //! # b: 24, //! # }); -//! let foo: Result>> = Box::pin_init(foo, GFP_KERNEL); +//! let foo: Result>> = KBox::pin_init(foo, GFP_KERNEL); //! ``` //! //! For more information see the [`pin_init!`] macro. @@ -93,14 +93,14 @@ //! struct DriverData { //! #[pin] //! status: Mutex, -//! buffer: Box<[u8; 1_000_000]>, +//! buffer: KBox<[u8; 1_000_000]>, //! } //! //! impl DriverData { //! fn new() -> impl PinInit { //! try_pin_init!(Self { //! status <- new_mutex!(0, "DriverData::status"), -//! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?, +//! buffer: KBox::init(kernel::init::zeroed(), GFP_KERNEL)?, //! }) //! } //! } @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, error::{self, Error}, sync::Arc, sync::UniqueArc, @@ -298,7 +298,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -307,7 +307,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Result, AllocError> = pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -324,7 +324,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -333,7 +333,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -392,7 +392,7 @@ macro_rules! stack_try_pin_init { /// }, /// }); /// # initializer } -/// # Box::pin_init(demo(), GFP_KERNEL).unwrap(); +/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap(); /// ``` /// /// Arbitrary Rust expressions can be used to set the value of a variable. @@ -462,7 +462,7 @@ macro_rules! stack_try_pin_init { /// # }) /// # } /// # } -/// let foo = Box::pin_init(Foo::new(), GFP_KERNEL); +/// let foo = KBox::pin_init(Foo::new(), GFP_KERNEL); /// ``` /// /// They can also easily embed it into their own `struct`s: @@ -594,7 +594,7 @@ macro_rules! pin_init { /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// ptr: *mut u8, /// } @@ -602,7 +602,7 @@ macro_rules! pin_init { /// impl BigBuf { /// fn new() -> impl PinInit { /// try_pin_init!(Self { -/// big: Box::init(init::zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init::zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) @@ -694,16 +694,16 @@ macro_rules! init { /// # Examples /// /// ```rust -/// use kernel::{init::{PinInit, zeroed}, error::Error}; +/// use kernel::{alloc::KBox, init::{PinInit, zeroed}, error::Error}; /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// } /// /// impl BigBuf { /// fn new() -> impl Init { /// try_init!(Self { -/// big: Box::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// }? Error) /// } @@ -814,8 +814,8 @@ macro_rules! assert_pinned { /// A pin-initializer for the type `T`. /// /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use the -/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use +/// the [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. /// /// Also see the [module description](self). /// @@ -894,7 +894,7 @@ fn pin_chain(self, f: F) -> ChainPinInit } /// An initializer returned by [`PinInit::pin_chain`]. -pub struct ChainPinInit(I, F, __internal::Invariant<(E, Box)>); +pub struct ChainPinInit(I, F, __internal::Invariant<(E, KBox)>); // SAFETY: The `__pinned_init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -920,8 +920,8 @@ unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { /// An initializer for `T`. /// /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use the -/// [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on this. Because +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use +/// the [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on this. Because /// [`PinInit`] is a super trait, you can use every function that takes it as well. /// /// Also see the [module description](self). @@ -993,7 +993,7 @@ fn chain(self, f: F) -> ChainInit } /// An initializer returned by [`Init::chain`]. -pub struct ChainInit(I, F, __internal::Invariant<(E, Box)>); +pub struct ChainInit(I, F, __internal::Invariant<(E, KBox)>); // SAFETY: The `__init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -1077,8 +1077,9 @@ pub fn uninit() -> impl Init, E> { /// # Examples /// /// ```rust -/// use kernel::{error::Error, init::init_array_from_fn}; -/// let array: Box<[usize; 1_000]> = Box::init::(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(); +/// use kernel::{alloc::KBox, error::Error, init::init_array_from_fn}; +/// let array: KBox<[usize; 1_000]> = +/// KBox::init::(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(); /// assert_eq!(array.len(), 1_000); /// ``` pub fn init_array_from_fn( @@ -1451,7 +1452,7 @@ macro_rules! impl_zeroable { // // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant. {} Option>, - {} Option>, + {} Option>, // SAFETY: `null` pointer is valid. // diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.rs index 13cefd37512f..b31f498f4f8e 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -102,7 +102,7 @@ fn make_closure(self, f: F) -> F } } -pub struct AllData(PhantomData) -> Box>); +pub struct AllData(PhantomData) -> KBox>); impl Clone for AllData { fn clone(&self) -> Self { diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index 25eb36fd1cdc..a63d4b0fe485 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -7,7 +7,6 @@ //! Reference: use crate::{alloc::Flags, bindings, container_of, error::Result, prelude::*}; -use alloc::boxed::Box; use core::{ cmp::{Ord, Ordering}, marker::PhantomData, @@ -497,7 +496,7 @@ fn drop(&mut self) { // but it is not observable. The loop invariant is still maintained. // SAFETY: `this` is valid per the loop invariant. - unsafe { drop(Box::from_raw(this.cast_mut())) }; + unsafe { drop(KBox::from_raw(this.cast_mut())) }; } } } @@ -764,7 +763,7 @@ pub fn remove_current(self) -> (Option, RBTreeNode) { // point to the links field of `Node` objects. let this = unsafe { container_of!(self.current.as_ptr(), Node, links) }.cast_mut(); // SAFETY: `this` is valid by the type invariants as described above. - let node = unsafe { Box::from_raw(this) }; + let node = unsafe { KBox::from_raw(this) }; let node = RBTreeNode { node }; // SAFETY: The reference to the tree used to create the cursor outlives the cursor, so // the tree cannot change. By the tree invariant, all nodes are valid. @@ -809,7 +808,7 @@ fn remove_neighbor(&mut self, direction: Direction) -> Option> // point to the links field of `Node` objects. let this = unsafe { container_of!(neighbor, Node, links) }.cast_mut(); // SAFETY: `this` is valid by the type invariants as described above. - let node = unsafe { Box::from_raw(this) }; + let node = unsafe { KBox::from_raw(this) }; return Some(RBTreeNode { node }); } None @@ -1035,7 +1034,7 @@ fn next(&mut self) -> Option { /// It contains the memory needed to hold a node that can be inserted into a red-black tree. One /// can be obtained by directly allocating it ([`RBTreeNodeReservation::new`]). pub struct RBTreeNodeReservation { - node: Box>>, + node: KBox>>, } impl RBTreeNodeReservation { @@ -1043,7 +1042,7 @@ impl RBTreeNodeReservation { /// call to [`RBTree::insert`]. pub fn new(flags: Flags) -> Result> { Ok(RBTreeNodeReservation { - node: as BoxExt<_>>::new_uninit(flags)?, + node: KBox::new_uninit(flags)?, }) } } @@ -1059,14 +1058,15 @@ impl RBTreeNodeReservation { /// Initialises a node reservation. /// /// It then becomes an [`RBTreeNode`] that can be inserted into a tree. - pub fn into_node(mut self, key: K, value: V) -> RBTreeNode { - self.node.write(Node { - key, - value, - links: bindings::rb_node::default(), - }); - // SAFETY: We just wrote to it. - let node = unsafe { self.node.assume_init() }; + pub fn into_node(self, key: K, value: V) -> RBTreeNode { + let node = KBox::write( + self.node, + Node { + key, + value, + links: bindings::rb_node::default(), + }, + ); RBTreeNode { node } } } @@ -1076,7 +1076,7 @@ pub fn into_node(mut self, key: K, value: V) -> RBTreeNode { /// The node is fully initialised (with key and value) and can be inserted into a tree without any /// extra allocations or failure paths. pub struct RBTreeNode { - node: Box>, + node: KBox>, } impl RBTreeNode { @@ -1088,7 +1088,9 @@ pub fn new(key: K, value: V, flags: Flags) -> Result> { /// Get the key and value from inside the node. pub fn to_key_value(self) -> (K, V) { - (self.node.key, self.node.value) + let node = KBox::into_inner(self.node); + + (node.key, node.value) } } @@ -1110,7 +1112,7 @@ impl RBTreeNode { /// may be freed (but only for the key/value; memory for the node itself is kept for reuse). pub fn into_reservation(self) -> RBTreeNodeReservation { RBTreeNodeReservation { - node: Box::drop_contents(self.node), + node: KBox::drop_contents(self.node), } } } @@ -1161,7 +1163,7 @@ impl<'a, K, V> RawVacantEntry<'a, K, V> { /// The `node` must have a key such that inserting it here does not break the ordering of this /// [`RBTree`]. fn insert(self, node: RBTreeNode) -> &'a mut V { - let node = Box::into_raw(node.node); + let node = KBox::into_raw(node.node); // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when // the node is removed or replaced. @@ -1235,21 +1237,24 @@ pub fn remove_node(self) -> RBTreeNode { // SAFETY: The node was a node in the tree, but we removed it, so we can convert it // back into a box. node: unsafe { - Box::from_raw(container_of!(self.node_links, Node, links).cast_mut()) + KBox::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }, } } /// Takes the value of the entry out of the map, and returns it. pub fn remove(self) -> V { - self.remove_node().node.value + let rb_node = self.remove_node(); + let node = KBox::into_inner(rb_node.node); + + node.value } /// Swap the current node for the provided node. /// /// The key of both nodes must be equal. fn replace(self, node: RBTreeNode) -> RBTreeNode { - let node = Box::into_raw(node.node); + let node = KBox::into_raw(node.node); // SAFETY: `node` is valid at least until we call `Box::from_raw`, which only happens when // the node is removed or replaced. @@ -1265,7 +1270,7 @@ fn replace(self, node: RBTreeNode) -> RBTreeNode { // - `self.node_ptr` produces a valid pointer to a node in the tree. // - Now that we removed this entry from the tree, we can convert the node to a box. let old_node = - unsafe { Box::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }; + unsafe { KBox::from_raw(container_of!(self.node_links, Node, links).cast_mut()) }; RBTreeNode { node: old_node } } diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 3021f30fd822..d7adbad7d3b4 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -17,13 +17,12 @@ //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{AllocError, Flags, KBox}, bindings, init::{self, InPlaceInit, Init, PinInit}, try_init, types::{ForeignOwnable, Opaque}, }; -use alloc::boxed::Box; use core::{ alloc::Layout, fmt, @@ -204,11 +203,11 @@ pub fn new(contents: T, flags: Flags) -> Result { data: contents, }; - let inner = as BoxExt<_>>::new(value, flags)?; + let inner = KBox::new(value, flags)?; // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new // `Arc` object. - Ok(unsafe { Self::from_inner(Box::leak(inner).into()) }) + Ok(unsafe { Self::from_inner(KBox::leak(inner).into()) }) } } @@ -401,8 +400,8 @@ fn drop(&mut self) { if is_zero { // The count reached zero, we must free the memory. // - // SAFETY: The pointer was initialised from the result of `Box::leak`. - unsafe { drop(Box::from_raw(self.ptr.as_ptr())) }; + // SAFETY: The pointer was initialised from the result of `KBox::leak`. + unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) }; } } } @@ -647,7 +646,7 @@ pub fn new(value: T, flags: Flags) -> Result { /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. pub fn new_uninit(flags: Flags) -> Result>, AllocError> { // INVARIANT: The refcount is initialised to a non-zero value. - let inner = Box::try_init::( + let inner = KBox::try_init::( try_init!(ArcInner { // SAFETY: There are no safety requirements for this FFI call. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), @@ -657,8 +656,8 @@ pub fn new_uninit(flags: Flags) -> Result>, AllocError> )?; Ok(UniqueArc { // INVARIANT: The newly-created object has a refcount of 1. - // SAFETY: The pointer from the `Box` is valid. - inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, + // SAFETY: The pointer from the `KBox` is valid. + inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) }, }) } } diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs index 2b306afbe56d..2081932bb4b9 100644 --- a/rust/kernel/sync/condvar.rs +++ b/rust/kernel/sync/condvar.rs @@ -70,8 +70,8 @@ macro_rules! new_condvar { /// } /// /// /// Allocates a new boxed `Example`. -/// fn new_example() -> Result>> { -/// Box::pin_init(pin_init!(Example { +/// fn new_example() -> Result>> { +/// KBox::pin_init(pin_init!(Example { /// value <- new_mutex!(0), /// value_changed <- new_condvar!(), /// }), GFP_KERNEL) diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index 30632070ee67..f8f6d530db7d 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -58,7 +58,7 @@ macro_rules! new_mutex { /// } /// /// // Allocate a boxed `Example`. -/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spinlock.rs index ea5c5bc1ce12..a9096a4dc42a 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -56,7 +56,7 @@ macro_rules! new_spinlock { /// } /// /// // Allocate a boxed `Example`. -/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 553a5cba2adc..94318472507f 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -216,7 +216,7 @@ pub fn try_spawn( func: Some(func), }); - self.enqueue(Box::pin_init(init, flags).map_err(|_| AllocError)?); + self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?); Ok(()) } } @@ -239,9 +239,9 @@ fn project(self: Pin<&mut Self>) -> &mut Option { } impl WorkItem for ClosureWork { - type Pointer = Pin>; + type Pointer = Pin>; - fn run(mut this: Pin>) { + fn run(mut this: Pin>) { if let Some(func) = this.as_mut().project().take() { (func)() } @@ -297,7 +297,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput /// Defines the method that should be called directly when a work item is executed. /// -/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be +/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`] /// instead. The [`run`] method on this trait will usually just perform the appropriate /// `container_of` translation and then call into the [`run`][WorkItem::run] method from the @@ -329,7 +329,7 @@ pub unsafe trait WorkItemPointer: RawWorkItem { /// This trait is used when the `work_struct` field is defined using the [`Work`] helper. pub trait WorkItem { /// The pointer type that this struct is wrapped in. This will typically be `Arc` or - /// `Pin>`. + /// `Pin>`. type Pointer: WorkItemPointer; /// The method that should be called when this work item is executed. @@ -565,7 +565,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput } } -unsafe impl WorkItemPointer for Pin> +unsafe impl WorkItemPointer for Pin> where T: WorkItem, T: HasWork, @@ -576,7 +576,7 @@ unsafe impl WorkItemPointer for Pin> // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. let ptr = unsafe { T::work_container_of(ptr) }; // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. - let boxed = unsafe { Box::from_raw(ptr) }; + let boxed = unsafe { KBox::from_raw(ptr) }; // SAFETY: The box was already pinned when it was enqueued. let pinned = unsafe { Pin::new_unchecked(boxed) }; @@ -584,7 +584,7 @@ unsafe impl WorkItemPointer for Pin> } } -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -598,9 +598,9 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily // remove the `Pin` wrapper. let boxed = unsafe { Pin::into_inner_unchecked(self) }; - let ptr = Box::into_raw(boxed); + let ptr = KBox::into_raw(boxed); - // SAFETY: Pointers into a `Box` point at a valid value. + // SAFETY: Pointers into a `KBox` point at a valid value. let work_ptr = unsafe { T::raw_get_work(ptr) }; // SAFETY: `raw_get_work` returns a pointer to a valid value. let work_ptr = unsafe { Work::raw_get(work_ptr) }; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index a626b1145e5c..ab93111a048c 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -243,7 +243,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` /// @@ -252,7 +252,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// @@ -282,7 +282,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// From patchwork Wed Sep 11 22:52: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: 13801184 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 218A8EE57DC for ; Wed, 11 Sep 2024 22:56:03 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A35046B00A2; Wed, 11 Sep 2024 18:56:02 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 9BDDE6B00A3; Wed, 11 Sep 2024 18:56:02 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 839066B00A4; Wed, 11 Sep 2024 18:56:02 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0014.hostedemail.com [216.40.44.14]) by kanga.kvack.org (Postfix) with ESMTP id 5B6CE6B00A2 for ; Wed, 11 Sep 2024 18:56:02 -0400 (EDT) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id E72D11C6056 for ; Wed, 11 Sep 2024 22:56:01 +0000 (UTC) X-FDA: 82553966922.05.1B81199 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf20.hostedemail.com (Postfix) with ESMTP id 665611C000C for ; Wed, 11 Sep 2024 22:56:00 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=iepKWa5w; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf20.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095283; a=rsa-sha256; cv=none; b=dkQht355op//rk7Myonfetd+Abw5qVATZYsuPisOohlL89fo4t7O+Hl5cp+w014NLkUsLh O8anGLH4cnjb6u8cdgkz+Uz0toHEsktCRV+2AJu48qRbZp6mvuldztPaHwTnMJHGwCYLcd N8JJf7fyVvFjlkUJrVr1LcwmTi+Ud1o= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=iepKWa5w; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf20.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095283; 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=WCtvpOJEwcfSgFSwmOKYTk2UHHktNY3FjhDRUcZyenU=; b=h8uVVa3L92xGXg1lpHeMBdPMfw2qpWFTwL3iF31RT/5WvXZlIi7uyPezLLs6m2m5mDYmjz E+ZHWOWD6mITHTYtjPtQ3QCMmiWlray5yZUohJfU6xESd4lEI1d7ING3e8EVj4p1W+FO8r xn8gikKkgrgtSddHEE3g2sL8L6CqFfQ= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 14B9CA40BDF; Wed, 11 Sep 2024 22:55:52 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 73E08C4CECF; Wed, 11 Sep 2024 22:55:54 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095359; bh=bmBk92HB3W03D2BfbbW7zaJgdP/ajBEnHftULDObyCA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=iepKWa5wL+zjAHwn6N6ep2yRpx+Zw5Ctq/woW3R5wGUhjZzx+SQDdSg2o8dfIzFt+ 32g34oKYqB4yFGI/VtPCV7JntljTb+jT86Fa8wlNZq8LUt8x0tPgxQ6OXTfCMXQBBT xYh82wtRgOVRcgc98HG0I0aBK8AXnJ7F6oLXb/tBvegoXiqkM0dUTQBCYk34iGzdHg h6c/r7HnYxpvN9fdXGHdCJ+7PVS7ixUHC8d4oOPQjV8ITKUPrv3Bx+O44p5jFbz7mL jkbsGqG3Uspl/oMAIlboYdmOccZRmsHiiGchGYYTXItjxZqycSz9QgchbyPdCyyyh/ 0s1nfxn7/Dkrg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 11/26] rust: alloc: remove extension of std's `Box` Date: Thu, 12 Sep 2024 00:52:47 +0200 Message-ID: <20240911225449.152928-12-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 665611C000C X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: iitif8gpu9puztt9wqr5s17m73gcd3ge X-HE-Tag: 1726095360-998517 X-HE-Meta: U2FsdGVkX183y4q81br3TthkRX3LPdyDr1rmaC+FfQjjYakOs+PwmyzSC/9dmnXkJeWi5yMFkkTfwWnsVaqBAJRfnKXUIr9yeB64WUWz0poSKaeYPejZKSHyXRN1kmHvbYgQd0gPPFJY8oNZ1vcH2ea+BeR0qEcP12o347592Q91Mva8t/XkmoTpSFv3Vq/cZdBg6i0VJZkCJyJJMJ6LPzoMTkq3BCmGmFqkTDsDBd1xd82qwrM/7AIPQ1idx97p2SVLxTHDCTPm5qqe74bJs86+RPpR7AHi70Ntb76cSNU2LutnA8enWtWE/LJxmZFkIvnNojmdOJ3bV4NL1hFIp79++oroNxeCRpRNns0FqhUPve2UQSQbGmVJey+6snM2u+coB8I0ol0DokrVMgquEdE5s8Djxq/EkhIrmBZhykTEyf7YGFstmiEZcWNXifBObbRtEuw51OoxjqHbiNqI15sxh9qaTTqQhkaX9/zxu1baMOQlp/6fsGpBd8kPEmXCRk3g50m88fvYgiwbIbrIZX17315puts+zVuDNvmh3hkd7diF4qBwAw2WM7BebVq7el3jnjImjrjE4w84ccAkXGZaOiec2lxC/oNzQvJvFEVdPuxW5BQiXbdvKb5b9q76gLnFtQfAqoSWie+UHN48UamwAje6nzTBM2nwM0I8A6uUBzQ5hcDLEYHtBPkCXhR1Tj8b/U8KFIpJT1/wxpHmmwx1s0gNrN3XwXPm/hjwudyP2HObJlNIpawsm9BOdLHv9vgoZO5KiO/fvI+iddWZUTJRt/lJQExYOrtxLQ5x33mdHFGU5/xbZlyN3gaFG2ZPWGmldHed9epxnARAMEbh1++sLh2S9bPtmXjNKUp4FSIAVqnNoAFZOkcYa492kMQkZSsyW3EpdMaCF/dRvICHeFP6uB2khAiTA/1wFgP/M4Zn9tczdn5ASnKjP8NB36JNJ7f0hM5tbvq23nfSJJy 5eFrxQn9 wFPDLHnM83aTR11F7nR9AmAu/O0HXvYrb7i+EbEDy4XCK1ei4LKNimlJ9fRtz2QEmO05wZVBhAI+uSfUrIro04D3HOf4pJMZiXqwEBm/xDl/zQUciMFI6ZEHjHcWBiNXOAT0UKtFlFX1HAptq/RkwLGeXNarw0xIpgwfhqCz1ARMN5yyPI4hiPR9QFLpkwiqKG70j/w88QHU+AikK9QHWcGkxn3qUftJKWNWKv73eKRXjjqYfuvRXdwlL/Q5Tv9dol9eG5Qi1YDc603qM05+10s/NITyFGmZQW6klZjU4bG+CQkSvU6zFcSL3dcYM0dAi9HSHx8QKoscmVAnGh57taAbOgg== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that all existing `Box` users were moved to the kernel `Box` type, remove the `BoxExt` extension and all other related extensions. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 87 ------------------------------------ rust/kernel/init.rs | 46 +------------------ rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +- rust/kernel/types.rs | 50 --------------------- 6 files changed, 3 insertions(+), 186 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index b1f28334b27a..1d0cb6f12af9 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 5b1550d620fd..000000000000 --- a/rust/kernel/alloc/box_ext.rs +++ /dev/null @@ -1,87 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Box`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::boxed::Box; -use core::{mem::MaybeUninit, ptr, result::Result}; - -/// Extensions to [`Box`]. -pub trait BoxExt: Sized { - /// Allocates a new box. - /// - /// The allocation may fail, in which case an error is returned. - fn new(x: T, flags: Flags) -> Result; - - /// Allocates a new uninitialised box. - /// - /// The allocation may fail, in which case an error is returned. - fn new_uninit(flags: Flags) -> Result>, AllocError>; - - /// Drops the contents, but keeps the allocation. - /// - /// # Examples - /// - /// ``` - /// use kernel::alloc::{flags, box_ext::BoxExt}; - /// let value = Box::new([0; 32], flags::GFP_KERNEL)?; - /// assert_eq!(*value, [0; 32]); - /// let mut value = Box::drop_contents(value); - /// // Now we can re-use `value`: - /// value.write([1; 32]); - /// // SAFETY: We just wrote to it. - /// let value = unsafe { value.assume_init() }; - /// assert_eq!(*value, [1; 32]); - /// # Ok::<(), Error>(()) - /// ``` - fn drop_contents(this: Self) -> Box>; -} - -impl BoxExt for Box { - fn new(x: T, flags: Flags) -> Result { - let b = >::new_uninit(flags)?; - Ok(Box::write(b, x)) - } - - #[cfg(any(test, testlib))] - fn new_uninit(_flags: Flags) -> Result>, AllocError> { - Ok(Box::new_uninit()) - } - - #[cfg(not(any(test, testlib)))] - fn new_uninit(flags: Flags) -> Result>, AllocError> { - let ptr = if core::mem::size_of::>() == 0 { - core::ptr::NonNull::<_>::dangling().as_ptr() - } else { - let layout = core::alloc::Layout::new::>(); - - // SAFETY: Memory is being allocated (first arg is null). The only other source of - // safety issues is sleeping on atomic context, which is addressed by klint. Lastly, - // the type is not a SZT (checked above). - let ptr = - unsafe { super::allocator::krealloc_aligned(core::ptr::null_mut(), layout, flags) }; - if ptr.is_null() { - return Err(AllocError); - } - - ptr.cast::>() - }; - - // SAFETY: For non-zero-sized types, we allocate above using the global allocator. For - // zero-sized types, we use `NonNull::dangling`. - Ok(unsafe { Box::from_raw(ptr) }) - } - - fn drop_contents(this: Self) -> Box> { - let ptr = Box::into_raw(this); - // SAFETY: `ptr` is valid, because it came from `Box::into_raw`. - unsafe { ptr::drop_in_place(ptr) }; - - // CAST: `MaybeUninit` is a transparent wrapper of `T`. - let ptr = ptr.cast::>(); - - // SAFETY: `ptr` is valid for writes, because it came from `Box::into_raw` and it is valid for - // reads, since the pointer came from `Box::into_raw` and the type is `MaybeUninit`. - unsafe { Box::from_raw(ptr) } - } -} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index e057b374f255..2f562642e9a4 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,13 +211,12 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, + alloc::{AllocError, Flags, KBox}, error::{self, Error}, sync::Arc, sync::UniqueArc, types::{Opaque, ScopeGuard}, }; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, convert::Infallible, @@ -590,7 +589,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1244,26 +1242,6 @@ fn try_init(init: impl Init, flags: Flags) -> Result } } -impl InPlaceInit for Box { - type PinnedSelf = Pin; - - #[inline] - fn try_pin_init(init: impl PinInit, flags: Flags) -> Result - where - E: From, - { - as BoxExt<_>>::new_uninit(flags)?.write_pin_init(init) - } - - #[inline] - fn try_init(init: impl Init, flags: Flags) -> Result - where - E: From, - { - as BoxExt<_>>::new_uninit(flags)?.write_init(init) - } -} - impl InPlaceInit for UniqueArc { type PinnedSelf = Pin; @@ -1300,28 +1278,6 @@ pub trait InPlaceWrite { fn write_pin_init(self, init: impl PinInit) -> Result, E>; } -impl InPlaceWrite for Box> { - type Initialized = Box; - - fn write_init(mut self, init: impl Init) -> Result { - let slot = self.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid. - unsafe { init.__init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { self.assume_init() }) - } - - fn write_pin_init(mut self, init: impl PinInit) -> Result, E> { - let slot = self.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid and will not be moved, because we pin it later. - unsafe { init.__pinned_init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { self.assume_init() }.into()) - } -} - impl InPlaceWrite for UniqueArc> { type Initialized = UniqueArc; diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index f10b06a78b9d..eb5c593acfc0 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -14,7 +14,6 @@ #![no_std] #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] -#![feature(new_uninit)] #![feature(receiver_trait)] #![feature(unsize)] diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index a9210634a8c3..c1f8e5c832e2 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,10 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; #[doc(no_inline)] -pub use alloc::{boxed::Box, vec::Vec}; +pub use alloc::vec::Vec; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 9e7ca066355c..53d3ddc0b98c 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -3,13 +3,11 @@ //! Kernel types. use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, mem::{ManuallyDrop, MaybeUninit}, ops::{Deref, DerefMut}, - pin::Pin, ptr::NonNull, }; @@ -71,54 +69,6 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option { } } -impl ForeignOwnable for Box { - type Borrowed<'a> = &'a T; - - fn into_foreign(self) -> *const core::ffi::c_void { - Box::into_raw(self) as _ - } - - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { - // SAFETY: The safety requirements for this function ensure that the object is still alive, - // so it is safe to dereference the raw pointer. - // The safety requirements of `from_foreign` also ensure that the object remains alive for - // the lifetime of the returned value. - unsafe { &*ptr.cast() } - } - - unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { - // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr as _) } - } -} - -impl ForeignOwnable for Pin> { - type Borrowed<'a> = Pin<&'a T>; - - fn into_foreign(self) -> *const core::ffi::c_void { - // SAFETY: We are still treating the box as pinned. - Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ - } - - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { - // SAFETY: The safety requirements for this function ensure that the object is still alive, - // so it is safe to dereference the raw pointer. - // The safety requirements of `from_foreign` also ensure that the object remains alive for - // the lifetime of the returned value. - let r = unsafe { &*ptr.cast() }; - - // SAFETY: This pointer originates from a `Pin>`. - unsafe { Pin::new_unchecked(r) } - } - - unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { - // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } - } -} - impl ForeignOwnable for () { type Borrowed<'a> = (); From patchwork Wed Sep 11 22:52:48 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801185 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 2D8F4EE57DC for ; Wed, 11 Sep 2024 22:56:08 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B1FA06B00A4; Wed, 11 Sep 2024 18:56:07 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id ACE486B00A5; Wed, 11 Sep 2024 18:56:07 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 949446B00A6; Wed, 11 Sep 2024 18:56:07 -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 743A56B00A4 for ; Wed, 11 Sep 2024 18:56:07 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 320C31C5F33 for ; Wed, 11 Sep 2024 22:56:07 +0000 (UTC) X-FDA: 82553967174.10.C55F795 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf17.hostedemail.com (Postfix) with ESMTP id A201B4000C for ; Wed, 11 Sep 2024 22:56:05 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=dpmfrHai; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095262; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=GAN7ymDWp8Lz5o35DG2vhzVY2kNsSLZxuib0MTJ4byY=; b=gUaJPHmdr+2A6/R6lEZP8BSdsqMv41UTUrydT+USJgL2K8Ur2spFhagCVIkSGIaogEc8rO xmQNzLZusiqUciGg/Mjs0B4/XfD1zYJ4Ymw31bfVMHjkJlYaeZ+8yQ9ihlyTT79blo8Nk7 qJ4OlKnrJ8YB5ShUT0f6yXDR0MQ3w28= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095262; a=rsa-sha256; cv=none; b=UA9heqrO35egsCTKD1VhPD06JKXRiwri630PqSJhSwW8Xwj/hXwQiYH7WOZ2RXbmZD8fZ8 Dcci5dqYn+rlLVNogotwBJpBnoLPA7W7mKb+jxxY6p9zoaFhjtd57zGyoLh0J6I6aRX3Np c2643A0ezgjbS40amt4iqQxNN1IEdPM= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=dpmfrHai; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 6BBD3A454C3; Wed, 11 Sep 2024 22:55:57 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C7454C4CEC0; Wed, 11 Sep 2024 22:55:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095364; bh=cG7LgUDIz4/c/n6Pe+TTApJnhkzb0osvgtaCA8JUOxc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dpmfrHairLbF/WFnDc9mCRxFc4TWwJtNuuEBCQGTkA5kZgRbz9m1xhG6wVnWSHl7n 2uKwNsknq2qHLD42rJOMTTaEIAO4x4rTO5oyVA/GB0PKQA7f5Rsk7c0YVYOJaAIWkB cNR2TzQoSm7yK/KzjDPPgoCJNab3xr7ixisMOEfwCP6E6Vm5IQV23FzTWf8u5R+xcR BGxhGzckFXGnU/hNP/qIfREYZDRN9Nf0+LB12qJmQ8WZcQe+CpIbljlzgG+fB0x3W4 /ffi5ETohcuJd+MD8CdRhsRo4bjM0doJtGkEWioO5TnDqqf9r4piOpub9UcrlZofuH pvuLLxS+bnJmg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 12/26] rust: alloc: add `Box` to prelude Date: Thu, 12 Sep 2024 00:52:48 +0200 Message-ID: <20240911225449.152928-13-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: A201B4000C X-Stat-Signature: kyzjnkbmgm99zdyp1ytbf58cctey1578 X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1726095365-276677 X-HE-Meta: U2FsdGVkX19CtHEbXcKEVw5wdrVXOoOHF8YWA6xHH9HkaoT57aQFOGR01Nxe+BgmcCCq8LQBhJRdgtGHskZStTKfeieLwe2D3XGAZH42Ubsr7q/oRwEM0FQ+nSVVntFLDuDKPnfaIvCcdtFjRziE93xcdaI04+tcFtrknoCT7IhfZzGzt5Zj9vUD8RLFARLCWO9LRLFKr8tWhjkHUBXUPi8EaMvFcjhHPfkl2Q08ennkooyup3UBbN/ACnsEcAZ6eTGUSNNNNt6yFKtgLZxD9xSQLFKM5tXDl6tHQHtsl1B7sK/cN65MiutWy02iobL7o2XJDgaHmg/uWzCjrll6njUZ9CE4Mfh/q9eojhgk/g7aG7q0CLwNb5Z6iWCRgJuZ1h2GvXiADqMy228gmEVZS4tkynvZN5Pa+/NhEtzy7SW5rrm56wF4Jw2wFCOeYMHaZOdhs1825mx+7kcSNeO7Lq2r/+rVLA6yGTueDQ8PKzetylX/E1DGpF2oZjxQtvCu2o06befoTNAPOZLGYaKovnJvPuYAlZRZ1QfvAqG0RHmLXCpnBSWbjn9nnNfIXk43/ftnvTr/CX4K1N1ms+c+wIEIvOCrZQ/uQPyMghpEnIxKHK2rxSDi68sPqonTpgjdYY2JSMMg72LSImjn44H1+JNPXGD/VZEPs5UOR2s2loJQYU2ljibUVIksIpj38M6invlzz6SfYG4EI8WqZlFVx+W13cLSyIwe57bJBNyO34+H6eG4LJ1fNCLHq8zVzJgkZOUmMo8KJQHPSs4M9wswE0WFRo3+ZveZJZmtGO7CVVOMu/kofBdv9+mqFY1wx6oT7rSxl36gvlaw35RVwAJ8LdU+/T+FMeW62pgSmF4Q4SX8w6OIY4Ot6mOc+ghpr1O7wZndfUzpq2xWpKfxLtnUlLgDqVZmUhaIO5Hlx5D1gzvfOw4APGqX1xHUj6sggUc6a/X31wjrMZGSolBIllx dPwsKWEh HrCTushTztYZA9KMGgymYEqIGiwZU+fz4vghNEiyb2tj/6Hdsnz/4+X13Tz3Xpz+cJNPRwjHVPb53RN5weSJEBuUeaQzOwS20p4EPCtjQz/pdAIC+1D5HIFwQDKeXWra/k7KyZQndc8VuuJaL+jNwBPxps6zWIbm01rNktZv7g+Ez5QnEZ6XCMryXCXIRltUWYBFFmBkzCMRAwARR+RfjzbZ+JXOPU25RDWs8J4K5oTLf067p1FeDTHQl24Y2NBWodZ3SKoSz/RAbxoyBrugYFThFmNZbZyR7zNRezpBtEC2tLYW6TU7rNubItBqxNE2pENHcryKTyl7MxZM= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `BoxExt` and the corresponding includes in prelude.rs, add the new kernel `Box` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index c1f8e5c832e2..d5f2fe42d093 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox}; #[doc(no_inline)] pub use alloc::vec::Vec; From patchwork Wed Sep 11 22:52:49 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801186 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 07DC5EE57DC for ; Wed, 11 Sep 2024 22:56:14 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 88A196B00A6; Wed, 11 Sep 2024 18:56:13 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 837A16B00A7; Wed, 11 Sep 2024 18:56:13 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 689706B00A8; Wed, 11 Sep 2024 18:56:13 -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 419726B00A6 for ; Wed, 11 Sep 2024 18:56:13 -0400 (EDT) Received: from smtpin24.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id EF744A074A for ; Wed, 11 Sep 2024 22:56:12 +0000 (UTC) X-FDA: 82553967384.24.7178254 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf01.hostedemail.com (Postfix) with ESMTP id 5466240006 for ; Wed, 11 Sep 2024 22:56:11 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RP7N2kn8; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095343; a=rsa-sha256; cv=none; b=kgPRCTkA/xSZiXbT5zODmIuYY6YwFnu33pOYfjSiJldPHW+cZdMPDH45kCwYr3Bs0qgk5L 33CMN9MENopIQRfoRuKtmigzp7QZckkKCYQayr4Cn5jxRRQb9kogi6U0FDIyLC4FPVA2eS s21e+htpp+X7LfQU7e8OCe5Ex1tqYGw= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RP7N2kn8; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095343; 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=UPcvDeCeoX3EkBl4J4aqYFKwaSO6oT3zOd5aFvmDKCs=; b=eXk2z7qx88R2K/XnjGt3IBDBJ5TNH9RxUtV+gJM3AT/ON0Y0vicP5C6lNK4ARQwzkWn5Y1 i2Gj8Q1lwPok5lPEWnpSKbr6iqoMSbFbZk0XD8fYosJ0ACDRAJoB5JdSwZx771YOdNSbgP dlDc4oXqbplhFcayC5oJb8bmdZ1MuBA= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id BE07BA45532; Wed, 11 Sep 2024 22:56:02 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 2C10EC4CEC5; Wed, 11 Sep 2024 22:56:04 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095370; bh=KwoehbhzPcxrEmOIZIyHuxsvPUIruBJfFaLK+8sOSio=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RP7N2kn8A7twihnr9wgeDk6Qtz3Ze8f5dhG9oP9w057T3zPImZU68n533d86lDYMO gdcbpvzAFN3g/nLWetza/mcUDV6PsR7xsCxnPo3douEKp5wmZ+99iqwds+rvDQ3YWL VDKxgDtX6LSw2CVtLx1Z0cUW7f3rnvlj0AOu83IftlH2RuqtFHkdXCQ+vZOJcVOaye Pxk5IXrNCDQeVmo/I1imlQlSWhnDKgxANpNGkvbgzNU4N9wfLAf/WijkqsbP+d4r9F 0gnMr677kSFYFiru37n2xPtb5ujPEyvBfbIEsSE8C/IUBRhYh4aV79r++jZ9k+bI9O +MKeTydyduBPw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 13/26] rust: alloc: implement kernel `Vec` type Date: Thu, 12 Sep 2024 00:52:49 +0200 Message-ID: <20240911225449.152928-14-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 5466240006 X-Rspamd-Server: rspam01 X-Stat-Signature: mzk7hfy4n4j4q89fxh8keyidh334yzno X-HE-Tag: 1726095371-223096 X-HE-Meta: U2FsdGVkX1+8/I6jvhxPnzSlsfV/uGFiXdEoVN60cVvZ6SPc6TowFaolPavZOcdPviCkl/jrnwLxKBWSXhhiWmm34LQN/ohXpFHHlm+hFmmUg4F0QtLimjYpaNbu1vF0Bm5l0kjFoLV3qDt/7nXlw3VaTFl9n711VoWOT5EB4l7mU0jC+objNjCoaAA9ai3oeHYlcXQd8cxF/aRA3XzbEyQsA+F1CUSrchMyc4QUYcYU5gw6Ptu/KIKID7iNsbUrX4W7xFiVhRwecUC3dzvIIjBOyXjtnD/g7pOD0yB5Mij0xu/edmm0bBjrhlXjL++B+NI2z7QE8Bw1Or2OGGpw8Mg4uw8NE5+rjgqXkthw1wWEJ8n1fB4mtaL31BIIBSi9dlYaQuFd4F6pr48fvDYUxeuRCFUiIvJb6RCgOk+82oM1cWdI27ED+WdfJjwqyTARcby4kdEWSXxP6Ft09r1ZsYEV8hzYk/FRdMyS3+3zyOThXjSVJZsz8OsAKKtZyWXXZZaMSSw1KX5pxYXfQH6PXTDh3A3sG+s9rMknMzAAby5pNWmzsIehjtRyM7GXKO1SiG9G4tpYsDJDzVznFjzRaJPDfkZ6+wJQO+vwe8sZ88+qjd+hFvjn67H73zb6LPAMdV39rSrTjWkn1/3z55p5jUKZ7dhECj9KiTK6btgEkqZ0XM64r+i6Tu0qlWizBaS8RBxbgTuswC2hrA88fXGVeBGU+73sgr8V0vqVwokcOj+Vyc/JpMmLLGymul2TbyrEIqgKBdvZeNGHR8/gLmsLHM3a4pJBnjG3L3niTAkyAagibEKclLQ2k9o8E3KU+GqELVhKa6acqOYMYNOtB0PIl2vlEsFkQT7iBoZJKfNJvKGHS+LED8GMh/jhqmCmh1joqO2LHRc4l3j33ffIVQsXtmjals9UhuWGxV0mPH0BOGzpyyRT0NeyNsMRhY/Ry7HpC4sk/SSvMF1JxTP++Ub m6mmYrfy vyBTs2ogA1CupeIf2uftgwF8FikKulBxQ+O7ylllptujKEDU2bR7kDa1FCYox1x4yWPHWeHEPmToKFBb9S/WcDYhI138pp3sPhQVv6/geVa/lueUfzZlwtzA1bp/Ui+SxRszonWB6bjK051qLBKed4ZYu796TlKsLOwr8z0939Opg5O/ZCal6vwQZ9iPG/3ZnTwY+4nAKHEIAWSjkZn450/wXTwCuAp0L5ahr5QHqbj3O9kQrg6IEDOSwbro+UAptApBA7zujN7Dl3SSRwxumbW4VGj7nhI0Lha8pHvc2UMLCltFhQHRFQyECnfvJ3FWikV+t X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: `Vec` provides a contiguous growable array type with contents allocated with the kernel's allocators (e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`). In contrast to Rust's stdlib `Vec` type, the kernel `Vec` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kvec.rs | 638 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 645 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1d0cb6f12af9..4fb983b63d46 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -5,6 +5,7 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; pub mod kbox; +pub mod kvec; pub mod vec_ext; #[cfg(any(test, testlib))] @@ -18,6 +19,11 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; +pub use self::kvec::KVVec; +pub use self::kvec::KVec; +pub use self::kvec::VVec; +pub use self::kvec::Vec; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs new file mode 100644 index 000000000000..631a44e19f35 --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,638 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{ + allocator::{KVmalloc, Kmalloc, Vmalloc}, + AllocError, Allocator, Box, Flags, +}; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + ptr::NonNull, + slice, + slice::SliceIndex, +}; + +/// Create a [`Vec`] containing the arguments. +/// +/// # Examples +/// +/// ``` +/// let mut v = kernel::kvec![]; +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(v, [1]); +/// +/// let mut v = kernel::kvec![1; 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 1, 1, 4]); +/// +/// let mut v = kernel::kvec![1, 2, 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 2, 3, 4]); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[macro_export] +macro_rules! kvec { + () => ( + $crate::alloc::KVec::new() + ); + ($elem:expr; $n:expr) => ( + $crate::alloc::KVec::from_elem($elem, $n, GFP_KERNEL) + ); + ($($x:expr),+ $(,)?) => ( + match $crate::alloc::KBox::new_uninit(GFP_KERNEL) { + Ok(b) => Ok($crate::alloc::KVec::from($crate::alloc::KBox::write(b, [$($x),+]))), + Err(e) => Err(e), + } + ); +} + +/// The kernel's [`Vec`] type. +/// +/// A contiguous growable array type with contents allocated with the kernel's allocators (e.g. +/// `Kmalloc`, `Vmalloc` or `KVmalloc`), written `Vec`. +/// +/// For non-zero-sized values, a [`Vec`] will use the given allocator `A` for its allocation. For +/// the most common allocators the type aliases `KVec`, `VVec` and `KVVec` exist. +/// +/// For zero-sized types the [`Vec`]'s pointer must be `dangling_mut::`; no memory is allocated. +/// +/// Generally, [`Vec`] consists of a pointer that represents the vector's backing buffer, the +/// capacity of the vector (the number of elements that currently fit into the vector), it's length +/// (the number of elements that are currently stored in the vector) and the `Allocator` type used +/// to allocate (and free) the backing buffer. +/// +/// A [`Vec`] can be deconstructed into and (re-)constructed from it's previously named raw parts +/// and manually modified. +/// +/// [`Vec`]'s backing buffer gets, if required, automatically increased (re-allocated) when elements +/// are added to the vector. +/// +/// # Invariants +/// +/// - `self.ptr` is always properly aligned and either points to memory allocated with `A` or, for +/// zero-sized types, is a dangling, well aligned pointer. +/// +/// - `self.len` always represents the exact number of elements stored in the vector. +/// +/// - `self.cap` represents the absolute number of elements that can be stored within the vector +/// without re-allocation. However, it is legal for the backing buffer to be larger than +/// `size_of` times the capacity. +/// +/// - The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer +/// was allocated with (and must be freed with). +pub struct Vec { + ptr: NonNull, + /// Represents the actual buffer size as `cap` times `size_of::` bytes. + /// + /// Note: This isn't quite the same as `Self::capacity`, which in contrast returns the number of + /// elements we can still store without reallocating. + /// + /// # Invariants + /// + /// `cap` must be in the `0..=isize::MAX` range. + cap: usize, + len: usize, + _p: PhantomData, +} + +/// Type alias for [`Vec`] with a [`Kmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVec = Vec; + +/// Type alias for [`Vec`] with a [`Vmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = VVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type VVec = Vec; + +/// Type alias for [`Vec`] with a [`KVmalloc`] allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVVec = Vec; + +// SAFETY: `Vec` is `Send` if `T` is `Send` because `Vec` owns its elements. +unsafe impl Send for Vec +where + T: Send, + A: Allocator, +{ +} + +// SAFETY: `Vec` is `Sync` if `T` is `Sync` because `Vec` owns its elements. +unsafe impl Sync for Vec +where + T: Sync, + A: Allocator, +{ +} + +impl Vec +where + A: Allocator, +{ + #[inline] + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Returns the number of elements that can be stored within the vector without allocating + /// additional memory. + pub fn capacity(&self) -> usize { + if Self::is_zst() { + usize::MAX + } else { + self.cap + } + } + + /// Returns the number of elements stored within the vector. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forcefully sets `self.len` to `new_len`. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity`]. + /// - If `new_len` is greater than `self.len`, all elements within the interval + /// [`self.len`,`new_len`) must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + debug_assert!(new_len <= self.capacity()); + self.len = new_len; + } + + /// Returns a slice of the entire vector. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Returns a mutable slice of the entire vector. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + /// Returns a mutable raw pointer to the vector's backing buffer, or, if `T` is a ZST, a + /// dangling raw pointer. + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + self.ptr.as_ptr() + } + + /// Returns a raw pointer to the vector's backing buffer, or, if `T` is a ZST, a dangling raw + /// pointer. + #[inline] + pub fn as_ptr(&self) -> *const T { + self.ptr.as_ptr() + } + + /// Returns `true` if the vector contains no elements, `false` otherwise. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// assert!(v.is_empty()); + /// + /// v.push(1, GFP_KERNEL); + /// assert!(!v.is_empty()); + /// ``` + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Creates a new, empty Vec. + /// + /// This method does not allocate by itself. + #[inline] + pub const fn new() -> Self { + Self { + ptr: NonNull::dangling(), + cap: 0, + len: 0, + _p: PhantomData::, + } + } + + /// Returns a slice of `MaybeUninit` for the remaining spare capacity of the vector. + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // SAFETY: + // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is + // guaranteed to be part of the same allocated object. + // - `self.len` can not overflow `isize`. + let ptr = unsafe { self.as_mut_ptr().add(self.len) } as *mut MaybeUninit; + + // SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated + // and valid, but uninitialized. + unsafe { slice::from_raw_parts_mut(ptr, self.capacity() - self.len) } + } + + /// Appends an element to the back of the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// assert_eq!(&v, &[1]); + /// + /// v.push(2, GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 2]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { + Vec::reserve(self, 1, flags)?; + + // SAFETY: + // - `self.len` is smaller than `self.capacity` and hence, the resulting pointer is + // guaranteed to be part of the same allocated object. + // - `self.len` can not overflow `isize`. + let ptr = unsafe { self.as_mut_ptr().add(self.len) }; + + // SAFETY: + // - `ptr` is properly aligned and valid for writes. + unsafe { core::ptr::write(ptr, v) }; + + // SAFETY: We just initialised the first spare entry, so it is safe to increase the length + // by 1. We also know that the new length is <= capacity because of the previous call to + // `reserve` above. + unsafe { self.set_len(self.len() + 1) }; + Ok(()) + } + + /// Creates a new [`Vec`] instance with at least the given capacity. + /// + /// # Examples + /// + /// ``` + /// let v = KVec::::with_capacity(20, GFP_KERNEL)?; + /// + /// assert!(v.capacity() >= 20); + /// # Ok::<(), Error>(()) + /// ``` + pub fn with_capacity(capacity: usize, flags: Flags) -> Result { + let mut v = Vec::new(); + + 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: + // - `other.len()` spare entries have just been initialized, so it is safe to increase + // the length by the same number. + // - `self.len() + other.len() <= self.capacity()` is guaranteed by the preceding `reserve` + // call. + unsafe { self.set_len(self.len() + other.len()) }; + Ok(()) + } + + /// Creates a Vec from a pointer, a length and a capacity using the allocator `A`. + /// + /// # Examples + /// + /// ``` + /// let mut v = kernel::kvec![1, 2, 3]?; + /// v.reserve(1, GFP_KERNEL)?; + /// + /// let (mut ptr, mut len, cap) = v.into_raw_parts(); + /// + /// // SAFETY: We've just reserved memory for another element. + /// unsafe { ptr.add(len).write(4) }; + /// len += 1; + /// + /// // SAFETY: We only wrote an additional element at the end of the `KVec`'s buffer and + /// // correspondingly increased the length of the `KVec` by one. Otherwise, we construct it + /// // from the exact same raw parts. + /// let v = unsafe { KVec::from_raw_parts(ptr, len, cap) }; + /// + /// assert_eq!(v, [1, 2, 3, 4]); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// # Safety + /// + /// If `T` is a ZST: + /// + /// - `ptr` must be a dangling, well aligned pointer. + /// + /// Otherwise: + /// + /// - `ptr` must have been allocated with the allocator `A`. + /// - `ptr` must satisfy or exceed the alignment requirements of `T`. + /// - `ptr` must point to memory with a size of at least `size_of::() * capacity`. + /// bytes. + /// - The allocated size in bytes must not be larger than `isize::MAX`. + /// - `length` must be less than or equal to `capacity`. + /// - The first `length` elements must be initialized values of type `T`. + /// + /// It is also valid to create an empty `Vec` passing a dangling pointer for `ptr` and zero for + /// `cap` and `len`. + pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { + let cap = if Self::is_zst() { 0 } else { capacity }; + + Self { + // SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid + // memory allocation, allocated with `A`. + ptr: unsafe { NonNull::new_unchecked(ptr) }, + cap, + len: length, + _p: PhantomData::, + } + } + + /// Consumes the `Vec` and returns its raw components `pointer`, `length` and `capacity`. + /// + /// This will not run the destructor of the contained elements and for non-ZSTs the allocation + /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the + /// elements and free the allocation, if any. + pub fn into_raw_parts(self) -> (*mut T, usize, usize) { + let mut me = ManuallyDrop::new(self); + let len = me.len(); + let capacity = me.capacity(); + let ptr = me.as_mut_ptr(); + (ptr, len, capacity) + } + + /// Ensures that the capacity exceeds the length by at least `additional` + /// elements. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let cap = v.capacity(); + /// assert!(cap >= 10); + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let new_cap = v.capacity(); + /// assert_eq!(new_cap, cap); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> { + let len = self.len(); + let cap = self.capacity(); + + if cap - len >= additional { + return Ok(()); + } + + if Self::is_zst() { + // The capacity is already `usize::MAX` for ZSTs, we can't go higher. + return Err(AllocError); + } + + // We know `cap` is <= `isize::MAX` because of the type invariants of `Self`. So the + // multiplication by two won't overflow. + let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?); + let layout = core::alloc::Layout::array::(new_cap).map_err(|_| AllocError)?; + + // We need to make sure that `ptr` is either NULL or comes from a previous call to + // `realloc_flags`. A `Vec`'s `ptr` value is not guaranteed to be NULL and might be + // dangling after being created with `Vec::new`. Instead, we can rely on `Vec`'s + // capacity to be zero if no memory has been allocated yet. + let ptr = if cap == 0 { + None + } else { + Some(self.ptr.cast()) + }; + + // SAFETY: `ptr` is valid because it's either `None` or comes from a previous call to + // `A::realloc`. We also verified that the type is not a ZST. + let ptr = unsafe { A::realloc(ptr, layout, flags)? }; + + self.ptr = ptr.cast(); + + // INVARIANT: `Layout::array` fails if the resulting byte size is greater than `isize::MAX`. + self.cap = new_cap; + + Ok(()) + } +} + +impl Vec { + /// Extend the vector by `n` clones of `value`. + pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> { + if n == 0 { + return Ok(()); + } + + self.reserve(n, flags)?; + + let spare = self.spare_capacity_mut(); + + for item in spare.iter_mut().take(n - 1) { + item.write(value.clone()); + } + + // We can write the last element directly without cloning needlessly. + spare[n - 1].write(value); + + // SAFETY: + // - `self.len() + n < self.capacity()` due to the call to reserve above, + // - the loop and the line above initialized the next `n` elements. + unsafe { self.set_len(self.len() + n) }; + + Ok(()) + } + + /// Create a new `Vec and extend it by `n` clones of `value`. + pub fn from_elem(value: T, n: usize, flags: Flags) -> Result { + let mut v = Self::with_capacity(n, flags)?; + + v.extend_with(n, value, flags)?; + + Ok(v) + } +} + +impl Drop for Vec +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: We need to drop the vector's elements in place, before we free the backing + // memory. + unsafe { + core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( + self.as_mut_ptr(), + self.len, + )) + }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.ptr` was previously allocated with `A`. + unsafe { A::free(self.ptr.cast()) }; + } + } +} + +impl From> for Vec +where + A: Allocator, +{ + fn from(b: Box<[T; N], A>) -> Vec { + let len = b.len(); + let ptr = Box::into_raw(b); + + // SAFETY: + // - `b` has been allocated with `A`, + // - `ptr` fulfills the alignment requirements for `T`, + // - `ptr` points to memory with at least a size of `size_of::() * len`, + // - all elements within `b` are initialized values of `T`, + // - `len` does not exceed `isize::MAX`. + unsafe { Vec::from_raw_parts(ptr as _, len, len) } + } +} + +impl Default for KVec { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for Vec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Deref for Vec +where + A: Allocator, +{ + type Target = [T]; + + #[inline] + fn deref(&self) -> &[T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } + } +} + +impl DerefMut for Vec +where + A: Allocator, +{ + #[inline] + fn deref_mut(&mut self) -> &mut [T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } + } +} + +impl Eq for Vec where A: Allocator {} + +impl, A> Index for Vec +where + A: Allocator, +{ + type Output = I::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + Index::index(&**self, index) + } +} + +impl, A> IndexMut for Vec +where + A: Allocator, +{ + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + IndexMut::index_mut(&mut **self, index) + } +} + +macro_rules! impl_slice_eq { + ([$($vars:tt)*] $lhs:ty, $rhs:ty) => { + impl PartialEq<$rhs> for $lhs + where + T: PartialEq, + { + #[inline] + fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } + } + } +} + +impl_slice_eq! { [A1: Allocator, A2: Allocator] Vec, Vec } +impl_slice_eq! { [A: Allocator] Vec, &[U] } +impl_slice_eq! { [A: Allocator] Vec, &mut [U] } +impl_slice_eq! { [A: Allocator] &[T], Vec } +impl_slice_eq! { [A: Allocator] &mut [T], Vec } +impl_slice_eq! { [A: Allocator] Vec, [U] } +impl_slice_eq! { [A: Allocator] [T], Vec } +impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } +impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index d5f2fe42d093..80223cdaa485 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; #[doc(no_inline)] pub use alloc::vec::Vec; From patchwork Wed Sep 11 22:52:50 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801187 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 D6FBBEE57DC for ; Wed, 11 Sep 2024 22:56:21 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6B6648D0003; Wed, 11 Sep 2024 18:56:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5ECE58D0001; Wed, 11 Sep 2024 18:56:18 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 418D08D0003; Wed, 11 Sep 2024 18:56:18 -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 226218D0001 for ; Wed, 11 Sep 2024 18:56:18 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id CFF6E1A177E for ; Wed, 11 Sep 2024 22:56:17 +0000 (UTC) X-FDA: 82553967594.08.4590949 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf24.hostedemail.com (Postfix) with ESMTP id 465FB18000E for ; Wed, 11 Sep 2024 22:56:16 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=IRpiFgQp; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095299; a=rsa-sha256; cv=none; b=Q5TLNKQwh6UaXBmR23eFiAdAyw14s+e+it92Zfms7B3wvCKMmBfI1LbPy2BwZbzQ3oVjbF KH62m9v9CZO7iIqXNOhxs1z1DscUoBpIK6eIKVPQ/eYysfJ2fO1K8F9Uv/3RgIrCf/iTBZ UCefrMJ3YPDJevARSm9iyl9p0HdhLMc= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=IRpiFgQp; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095299; 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=8RYQeGDo1hQgLLG2wpET2mGLcp8B0DfQePTl7gx3Uos=; b=sEzsu/M3db/9nWKHBfGrB9i4Gms5SF7tYDovNNug1SXi7+BABDjzfrKGqDjpim88en3tO4 gMapghIBkI1wR0WdHVCPHQADe4joOx7dIJhJw2RKCZgqJAgH+Ca2wecB8pJWb7dkH0lZIO sg7VNFwfbW40ZK2kgdYbvCuyjmFsZrg= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 1A25CA40BDF; Wed, 11 Sep 2024 22:56:08 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7CB19C4CECC; Wed, 11 Sep 2024 22:56:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095375; bh=aLDdES0o6RDAOJEjGLFT1eKKbvsH9kq1wWFmHyySuYc=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=IRpiFgQp9WwC2xCKc1aDcSeNN12nD+GShRbakKlDuGMWhi3GjwI+uXBKLL1jQIdbm QE2NbWO/lOI8KRM7Svf2gz/Z9mvaNRDH8/eEyVNvsinjSYS4k3cA2ac8ABB8Tnimfw w3XYcJeORuRs+NrHWD3UBYZhdYf7VAVg53hUr9bv1R82NYriI8OPKmq5gQfTpzEceL iVdQ85KiWl+VZHVWaMll71MQ32Zlv+nn1Khu6+jrIAURDNl/RDzgtlk3vzubC/Njk7 m4fr+jhaMvgefyfbBM/wKub+78OgiSGAEwLdN4jf6pM9TQPMbINCd0VluGuv6xQYZK MKwer9LnsErWA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 14/26] rust: alloc: implement `IntoIterator` for `Vec` Date: Thu, 12 Sep 2024 00:52:50 +0200 Message-ID: <20240911225449.152928-15-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 465FB18000E X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: oc4fc4difsi1hpoezymezt9ca8eed1od X-HE-Tag: 1726095376-20358 X-HE-Meta: U2FsdGVkX190SY/u3W4dRrLaVipkkT/Ukh6RmZNniVJpLIFpcDnEOTeZ2nIkQpGtDrVMl2+k60mTnOVUZl1q/pOJDOeZ1M0uYf8bdK/AaguEAsb+tQlhjdAc5MNLd7O827IKw7mqcBOV4GSBCn1n/FKei1HgtPIJj7xZX8GWlwQeIwUmCZKUHSR/xn8SIGFoKV8gcNn+/wn/rKheCh7QiuhNtfY+PgFmWqq69XjzhENivDe9/eEoUqT/LeAhzkjrgWwcuPUOhC9z28V8BQcvkD5RKzv/vg33LZJ6yWwU8TNlvpruRai/maaI3VHNZGKleRt87kAlZRYzVNGFR0vrdIPf4rPIDnrAMxvfPgF8FzduptFHcrLDUdJ+Kck80Ytu6+Jt8W5zSSlLAVgFb9Os4IpaOoRoutDgNYamihwcih2fgMYHzpEIAV/6w2dnI0mCXHqPPn2DebNqIgb5H/z+N7c8sPYgDEr5cBLvSIC1lcO64ySJ5QixLiEkMmMDSi/lpHtSPeodOJ5mJVckgr6Dl+0JCOJk6xLSb7mv60wQ+GOEtiVH5cpbnz+YZPFGfA1Uu0MR/zEnydWy8sfXs/1ZnibsXFboseoim6YTKp2VhiM5gEzicQra/d7q1hKiTNWdxdrPs4VpSxD0zpqUSN6g48lb3ht3iPxDk6KS66GIgstM/Q7jtFoo24wfwWxPM0rbeBG/05ZNK/HaS5NIuDlf0npp39gPJVpwYrl8a7uGgfM6/WOLhpHklS6rv7UNikyOjH7+W9gR+KvRqmTeUsxLhq3BEdRkXclm5xgvwvI9u38JaW6ESP3ZZQgJ6+g/L17vJs3i82JlDuSaTeph5jaOX4bXiaAKPCVVJ3exPM/2HmEblHTGiPXkP/SezFdXF8Z4ed78bDKL17DObQcdJxVyxLrMp3q/qbrA2TgfYaMNIMLMGkJ35ZLTlFMggjbc45kx/cltLq80gzqGqd2kLkp nxDS9uu+ uAF+dR1TGoG3NALAjkfwQTQ4ehbIO8zEDKLiERHjN87fYH9mPE8fxq1V+T7TZ4PztdjKOdgtCiwdoTf56SXQQDGOZE3OQydiJTkjTuTeqtL9fqJz3SU6AREA8dUkUUA7heX6avC2oYpuwkhvbzsznnj+fddJON7pyAUs6QTsMwGyScPh/eLsc9eilRzSbmMZPhptYE/Dz1+msEJTgWi80XpiEID76vBLtFbPVFjWRX8PNTrc/RCFLmsCv/VRjZniWXYLMCJVfZ1gxnpTcQuOe47Z89BT/g/TnzAESPa7pKoBNg3BIG3ZoSPgMatKc2ebqNp2krgbpCjPMXvg= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Implement `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as `Iterator` for `IntoIter`. `Vec::into_iter` disassembles the `Vec` into its raw parts; additionally, `IntoIter` keeps track of a separate pointer, which is incremented correspondingsly as the iterator advances, while the length, or the count of elements, is decremented. This also means that `IntoIter` takes the ownership of the backing buffer and is responsible to drop the remaining elements and free the backing buffer, if it's dropped. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 181 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 4fb983b63d46..e8fbae2adadb 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 631a44e19f35..e91761c5c52d 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -14,6 +14,7 @@ ops::DerefMut, ops::Index, ops::IndexMut, + ptr, ptr::NonNull, slice, slice::SliceIndex, @@ -636,3 +637,183 @@ fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } impl_slice_eq! { [A: Allocator] [T], Vec } impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } + +impl<'a, T, A> IntoIterator for &'a Vec +where + A: Allocator, +{ + type Item = &'a T; + type IntoIter = slice::Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec +where + A: Allocator, +{ + type Item = &'a mut T; + type IntoIter = slice::IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +/// An [`Iterator`] implementation for [`Vec`] that moves elements out of a vector. +/// +/// This structure is created by the [`Vec::into_iter`] method on [`Vec`] (provided by the +/// [`IntoIterator`] trait). +/// +/// # Examples +/// +/// ``` +/// let v = kernel::kvec![0, 1, 2]?; +/// let iter = v.into_iter(); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub struct IntoIter { + ptr: *mut T, + buf: NonNull, + len: usize, + cap: usize, + _p: PhantomData, +} + +impl IntoIter +where + A: Allocator, +{ + fn as_raw_mut_slice(&mut self) -> *mut [T] { + ptr::slice_from_raw_parts_mut(self.ptr, self.len) + } +} + +impl Iterator for IntoIter +where + A: Allocator, +{ + type Item = T; + + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// assert_eq!(it.next(), Some(2)); + /// assert_eq!(it.next(), Some(3)); + /// assert_eq!(it.next(), None); + /// + /// # Ok::<(), Error>(()) + /// ``` + fn next(&mut self) -> Option { + if self.len == 0 { + return None; + } + + let current = self.ptr; + + // SAFETY: We can't overflow; decreasing `self.len` by one every time we advance `self.ptr` + // by one guarantees that. + unsafe { self.ptr = self.ptr.add(1) }; + + self.len -= 1; + + // SAFETY: `current` is guaranteed to point at a valid element within the buffer. + Some(unsafe { current.read() }) + } + + /// # Examples + /// + /// ``` + /// let v: KVec = kernel::kvec![1, 2, 3]?; + /// let mut iter = v.into_iter(); + /// let size = iter.size_hint().0; + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 1); + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 2); + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 3); + /// + /// # Ok::<(), Error>(()) + /// ``` + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl Drop for IntoIter +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant. + unsafe { ptr::drop_in_place(self.as_raw_mut_slice()) }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.buf` was previously allocated with `A`. + unsafe { A::free(self.buf.cast()) }; + } + } +} + +impl IntoIterator for Vec +where + A: Allocator, +{ + type Item = T; + type IntoIter = IntoIter; + + /// Consumes the `Vec` and creates an `Iterator`, which moves each value out of the + /// vector (from start to end). + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2]?; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, Some(1)); + /// assert_eq!(v_iter.next(), Some(2)); + /// assert_eq!(v_iter.next(), None); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// ``` + /// let v = kernel::kvec![]; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, None); + /// + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (ptr, len, cap) = self.into_raw_parts(); + + IntoIter { + ptr, + // SAFETY: `ptr` is either a dangling pointer or a pointer to a valid memory + // allocation, allocated with `A`. + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +} From patchwork Wed Sep 11 22:52:51 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801188 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 31C00EE57D7 for ; Wed, 11 Sep 2024 22:56:24 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B1F578D0005; Wed, 11 Sep 2024 18:56:23 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id A80C68D0001; Wed, 11 Sep 2024 18:56:23 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8FA628D0005; Wed, 11 Sep 2024 18:56:23 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 71FA38D0001 for ; Wed, 11 Sep 2024 18:56:23 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 39D6F1C6376 for ; Wed, 11 Sep 2024 22:56:23 +0000 (UTC) X-FDA: 82553967846.03.AAAE845 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf14.hostedemail.com (Postfix) with ESMTP id 9F39410000A for ; Wed, 11 Sep 2024 22:56:21 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HNs5tm92; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095265; 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=3EJIaQOVxknEqZYdKuXN3g88B/BL47pO9NfuJlE1ZQo=; b=tCPqCcBS3+kRQqBzZVqcjn3zgLHhPpiILnfM3fdVj/tJuhJNTe7wu4Y8WzO2a/DreMSHwr Ro8EXLy5I0rnngLs8I4FIcK84rytXp2s8orQIsvV9ovYJ7SW6fedkS4KsaIkwoVDzB8Zy6 IAWqzYQhs3Zp1CpuMqn8Kwlgl6S00sg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095265; a=rsa-sha256; cv=none; b=M36ihiu1K2Pfxbi7dAETREn9ZTiWe30hfyKDhUKWKxwbsyldFP9UCSut/tUYkKUSWLSPyo pQS4echdcuN3XDfmlIMsuxIRyfJ346srgFrfTy+dHoFGdes23QSf04BRUTm09MIb/hVmot MLqo29AzARmEgBlD7DUTwlAQ+DXUE4Y= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HNs5tm92; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 6528FA45527; Wed, 11 Sep 2024 22:56:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CD080C4CEC0; Wed, 11 Sep 2024 22:56:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095380; bh=d0GTO9ovdr9mLJZ1kH3EJFt21UVQxchmojeAlHWWgj8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HNs5tm92QKne4wWPulUe3fcINVeehDTsWYP7OKbBuDAFJioQkoDs4xtPbMxWiphQb PZ2Xb2cE86reASaruvlmCSipU1rMPqObS0eRNUwsW3pQIH8bTigMxzP0QNorxbtwi8 hKr2oRBWsQAcxalCvk4SXGAdIuxQQwKJ55ChGFBQ9wdJEpSw8/TByF2JJfW8LlU+vH CAmR/f1U71SlL4T+Om9uVQWQFDPHSwlZ/trHlxvTVa6bmYEB2DMK7/UVMEpjm0Vexc Svc8EMpnLgkW2ZbarbI+b/qasorJz8jaeNpZWcGpm/AUYy3l9X/e/y/DOhuqfGCJKZ t8uAn5K+Ub5pQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 15/26] rust: alloc: implement `collect` for `IntoIter` Date: Thu, 12 Sep 2024 00:52:51 +0200 Message-ID: <20240911225449.152928-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 9F39410000A X-Stat-Signature: riduqjgfmq4p3owrpsqmwzfkfi9m97rs X-Rspam-User: X-HE-Tag: 1726095381-511750 X-HE-Meta: U2FsdGVkX1/a7QIoIAgtBoFIvNcaodVeW72+Xz+RnzkHvDhD5V1W/XNhxPIL4ZDRgvvTGaLGe+2lLmScgGrs/hOqbF3F+aDLdKeMfKOXkE40OgjL9fXuBkO7PZmDuaSUKb3b7SnxpKDnB+RRxmmx0tKuYj5IoCkiWAkknO+xAINaXGFNAdzaFYRZdbc0+lFcEqTe+JdZPt396AHMIM0NO1igVraXdQdztUDQJwRkzqW8+3ieOstaKjx5Ak3K7MfxAb3txDRy1QqlUItX1Yjeo6iZurWIFljYAtlQbyHSaPGOu1UNCaENVHz23vd5rXtKSrF7+ys4/wYcfQzDrjygVSwNgSmQ6X6ylDxOiLMeExI3qhfhkduSA7aZ3xQchfzX5c+xK9BfSgCkvZ5Xx0uI0Jrxlj2QOgVLkSrSlkd1fYiDSpnyb5GDI0W82RoBGTtYWazqk8Mk3r3VivL9H9B1k7AO1hnt9fbPkJIwMlaJRPcv/uSxhs1ocnqQ+9EHIzCJcUTjJDqJe7GWAvpcaUO3UtOeM7W9zqHkH5M6aoFgCpMLjxceYZ15AVLDKs6OquvMBSgzeVlHe4A8SECMi3k7Er6fjXsPWPVkQ7xj72N+dj+upC+SWc4nyROUy8qo0znSBojsD6RoyWqwk+Iav5AonuFyOXaIXCa3yi6uK3dAzkN2Jb4cRVb8nbq1OEBxSC7p+yONmLJ39BrariUescNSlGnc1GMYHSM+7bnrnF2b/4tlZoSPZWcaqyPgxtpD3U1O8wWEGC6ba4WuSai6h8jA+G1dl0+S8kO2IE/S7dP5pGGcMdZ4uh+B6Op37bCborx6J6mt3X/wDDMyOXlMFjrGYBZZUg3xvwu6C2KxZSENA4htRHPLOqCWdlHxPmMpN0pDFw4zHYhhqrlqoZu9fM/nL6MjHUe1t+gQhzXgvefw7FNyIxmOQYI0EZBTjpTtOt5x1sq8qeAtnDMTYf4n10a JppQuhcs bq8M2+IIFFzdxZHlLZ7Md5k1+AQgXd/eMavB1TKUt3VXhueif2WqfOa+Xn42Qlla3X4Y5N4JQNBhVvxanfHNtC1CQJpKn5nei2P4h9nlxaIUEJ7iyuDkI9ruaYud3bLbbOtpfnVNit8GmKcWxnEy0ObrLar1QhqsoQz4knGrOPwqi2Gvwi44r5gB4C6ntEY8zIyiQPlfwyC/OZdnxNyvnQ57ihq1i1SXQWIB/Wbaj0WBq4rbRZ/cRn4ZrDOZ9GjxaZ08VkJhGhVedMkumQSxFgoSGvsC2CreUg90wFyFEtno8BTLWgpseUrPwqekyEctgsVv22hWPyFrIPVE= 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 | 86 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index e91761c5c52d..686e969463f8 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -690,6 +690,92 @@ 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`. + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// + /// let v = it.collect(GFP_KERNEL); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// # Implementation Details + /// + /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait + /// in the kernel, namely: + /// + /// - Rust's specialization feature is unstable. This prevents us to optimze for the special + /// case where `I::IntoIter` equals `Vec`'s `IntoIter` type. + /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` + /// doesn't require this type to be `'static`. + /// - `FromIterator::from_iter` does return `Self` instead of `Result`, hence + /// we can't properly handle allocation failures. + /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation + /// flags. + /// + /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a + /// `Vec` again. + /// + /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing + /// buffer. However, this backing buffer may be shrunk to the actual count of elements. + pub fn collect(self, flags: Flags) -> Vec { + let (mut ptr, buf, len, mut cap) = self.into_raw_parts(); + let has_advanced = ptr != buf.as_ptr(); + + if has_advanced { + // Copy the contents we have advanced to at the beginning of the buffer. + // + // SAFETY: + // - `ptr` is valid for reads of `len * size_of::()` bytes, + // - `buf.as_ptr()` is valid for writes of `len * size_of::()` bytes, + // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to + // each other, + // - both `ptr` and `buf.ptr()` are properly aligned. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr = buf.as_ptr(); + } + + // 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 Wed Sep 11 22:52:52 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801189 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 1D3C2EE57DC for ; Wed, 11 Sep 2024 22:56:30 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9C2D48D0006; Wed, 11 Sep 2024 18:56:29 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 96E778D0001; Wed, 11 Sep 2024 18:56:29 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7C6148D0006; Wed, 11 Sep 2024 18:56:29 -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 5A7928D0001 for ; Wed, 11 Sep 2024 18:56:29 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 1E99440949 for ; Wed, 11 Sep 2024 22:56:29 +0000 (UTC) X-FDA: 82553968098.17.88DE0C3 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf23.hostedemail.com (Postfix) with ESMTP id 83B2C14000D for ; Wed, 11 Sep 2024 22:56:27 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MfPaagSK; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095359; a=rsa-sha256; cv=none; b=Xwapja8/qdiUO8Su/4Q4jx3NQuek+oIADspF0hgtTQK+DvNKVkam+PCX5jIYGZl5gQ9Yac eRLbeBA+H/MUOCYgPcm1KVktygr1daC1VSEJJzROLVjuc8IkmufL3IFfNPEcmTMXWu8Tjc s8ZeuqXv/+VsZ2hRsNne0/rYAQ6x4ls= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=MfPaagSK; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095359; 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=8g+ils7+MPSmz75Qtw6kV1XuBgCcSVycGHepbQ6Hs0o=; b=FNgv+317FDSXuJ1lihBZRr0xpEexSM3OAMc/T3+iXvj3rs2C93aPdf3kHx1ohWqD1IX7Wr GcCz2zCIV4QWtXxcD15TynVlfvtbfcuNEM/vNajYceuaKwKwZJ0aqEnHjNttCuUlIZq6VG okI+xeAbzPXFCvjG0GXMZM3f8/rAmp0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 43769A45531; Wed, 11 Sep 2024 22:56:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 286CCC4CECE; Wed, 11 Sep 2024 22:56:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095386; bh=kh3bW2oqiftIhCysHX0r3aVqtVie61GOoy8er6t2mxM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=MfPaagSK3gG0avIvoa7NTT1obNqCvyu1MQUNPJ1yIpApc6/6hGDGyQ2whd+2QIDQz ryLdIIriYcECe39Cp22B80psQZJ3Zj4cWTLC7VZnkdjXMc0gvuExAFmuvZXB64rFof tHPByXCEX0kCWJ3KGNDXf/cShE5cJ6Om4a1ehEPqAmu4araOocZEKYj0X9wLWyvK8q d8VffI02SEIIZ205Bxor8Aq4QF4yQNwSjXMDTjlMvDT0U+0Umtc1loYSpLUMqh3PdP wNODrTDo0/Ww3yTU5sxNiTn2EPWwioQ8PuPW/QqX/NXSpVeGynQOESApvVKWY1GM0a pEWwq8VYIQduA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 16/26] rust: treewide: switch to the kernel `Vec` type Date: Thu, 12 Sep 2024 00:52:52 +0200 Message-ID: <20240911225449.152928-17-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Queue-Id: 83B2C14000D X-Rspamd-Server: rspam01 X-Stat-Signature: 3xrbu9dgn7wx4cmq5ujixrsyzkf4ih4c X-HE-Tag: 1726095387-234374 X-HE-Meta: U2FsdGVkX19P89UbmSjzs4EjwiMnEzdE7M3psGYAjEZkkYRyDTgfQFnXSouAVrw72LeFSEUMDdIOIVnclHRxxuYBksFY7hrXOS2KyV9iz4aA14CP53xwMTvzaw0RXdgQU1WwUQLjUpmM+SdWIsbR8H2B9YJgKHpNy4Saqk7fBY/KJNJbzqUfXBWHMDspJkWlrWDrGwsVABTwC+QtugtM0tUcHqhf1XcQ6hznhnXPFotlo2GqbMbn1ymlVIqqqfWFSS+3w4BzwQPBQTMEW5U2XRrl2z19NiKRih80GHCE0z8GsEgSL5FLKhdybKdoFKSIM/Isw06axX3Ck1gQ9uYD2d8Z/YnQNhW5CgOwLvwnxRUlOmG7i+wd1scqTZ+6GlNF03jmrVm8keuyTF7LM2ExUQOhMkaxgsZINIQnyFrWSFSMmyhuhNXbelPohtV7m6bL3O1AKrlvKqfKQmRgO0qv+I2vshAFECwEbPj+/GD2zLkAbQog6b2gtOlKOZJZTY2H/9suP0hyKIvOTPRO0NYOOYPxHUKVDY+Zuc21xJ6qPc06uA0b9FZuAjJEyMZlYQe6Cn7/YJJxeA//F/D0knVT+1C3vc9Xd/vEsDfRHmYMjR9NvukP8esvMf0WC0iJR7RnV8q0LlBDWSP8OytU/Ml5umQRiyfeS/UT2XgOqlKgtM4yEmvo8afuE95EWMfD6J8Ns14bUqdRpT9n1WlKoP2BLpk1Lmb7L6hPfuqgnPPh9rAyQ6PRldA2qtlqG9w2zIdAxeAxd70OXOr1cCLq8uMO6XcVJqrklNcZu1+wGtFbuMBWRw6onEmjlqtxMo/Hdh8+DprRZM1urI9fWeait8fowUIIQavNGlfeRTswq5y4bKYE/aMZQvSGQYYdAGQSA5S5DQy++xJGaOV0Blb7pxoM9K+G+WHk3EE9vfAe8otuJvASL5Soj/qrpdQvYcOwFc2Groy89AXkf3lgdvm+36t ZE8umww6 Wp+7Lv/fZsO0SUJvCnSI9GaSS/m+SQIRKs8G78Uc4Mf/FIkVQmoTUnw/p5S9DrlXipG0xq+6BoCMkJ1BBVY8Li51F73XrnctRGg367/nmK7yIuhnx+uHkInxwTX442WEe2tkV5vbV9anowA0ZRxD4A8JBtBYUlcOyjS6Rlocd+0P9Cxek6os40Xg5obDKjUKKT/6zbqnLeOktMYgP10UvxNDGLGjfm3lqIM0z65tdVcdg5Ky/LMOiWTL46Uq+L9aSxfBAZAtt1OCf7EgFqgVThLY2CtxE180Svf5LyrLjoHhQBwyzqfWty3MBW/D7AYEO0HDJApAIPHfpvAEg0kNmw2m/Sg== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we got the kernel `Vec` in place, convert all existing `Vec` users to make use of it. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- rust/kernel/uaccess.rs | 17 +++++++---------- rust/macros/lib.rs | 6 +++--- samples/rust/rust_minimal.rs | 4 ++-- 6 files changed, 19 insertions(+), 24 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..209ad1bb1a49 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,8 +2,7 @@ //! String representations. -use crate::alloc::{flags::*, vec_ext::VecExt, AllocError}; -use alloc::vec::Vec; +use crate::alloc::{flags::*, AllocError, KVec}; use core::fmt::{self, Write}; use core::ops::{self, Deref, DerefMut, Index}; @@ -790,7 +789,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result { /// assert_eq!(s.is_ok(), false); /// ``` pub struct CString { - buf: Vec, + buf: KVec, } impl CString { @@ -803,7 +802,7 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result { let size = f.bytes_written(); // Allocate a vector with the required number of bytes, and write to it. - let mut buf = as VecExt<_>>::with_capacity(size, GFP_KERNEL)?; + let mut buf = KVec::with_capacity(size, GFP_KERNEL)?; // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes. let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; f.write_fmt(args)?; @@ -850,10 +849,9 @@ impl<'a> TryFrom<&'a CStr> for CString { type Error = AllocError; fn try_from(cstr: &'a CStr) -> Result { - let mut buf = Vec::new(); + let mut buf = KVec::new(); - as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KERNEL) - .map_err(|_| AllocError)?; + buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?; // INVARIANT: The `CStr` and `CString` types have the same invariants for // the string data, and we copied it over without changes. diff --git a/rust/kernel/sync/locked_by.rs b/rust/kernel/sync/locked_by.rs index babc731bd5f6..b94517231fcc 100644 --- a/rust/kernel/sync/locked_by.rs +++ b/rust/kernel/sync/locked_by.rs @@ -43,7 +43,7 @@ /// struct InnerDirectory { /// /// The sum of the bytes used by all files. /// bytes_used: u64, -/// _files: Vec, +/// _files: KVec, /// } /// /// struct Directory { diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 53d3ddc0b98c..bf1a96d5e1f8 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -135,7 +135,7 @@ unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {} /// # use kernel::types::ScopeGuard; /// fn example3(arg: bool) -> Result { /// let mut vec = -/// ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len())); +/// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len())); /// /// vec.push(10u8, GFP_KERNEL)?; /// if arg { diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index e9347cff99ab..bc011061de45 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -11,7 +11,6 @@ prelude::*, types::{AsBytes, FromBytes}, }; -use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; use core::mem::{size_of, MaybeUninit}; @@ -46,7 +45,6 @@ /// every byte in the region. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::Result; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -54,7 +52,7 @@ /// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> { /// let (read, mut write) = UserSlice::new(uptr, len).reader_writer(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// for b in &mut buf { @@ -69,7 +67,6 @@ /// Example illustrating a TOCTOU (time-of-check to time-of-use) bug. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::{code::EINVAL, Result}; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -78,21 +75,21 @@ /// fn is_valid(uptr: UserPtr, len: usize) -> Result { /// let read = UserSlice::new(uptr, len).reader(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// todo!() /// } /// /// /// Returns the bytes behind this user pointer if they are valid. -/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { +/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { /// if !is_valid(uptr, len)? { /// return Err(EINVAL); /// } /// /// let read = UserSlice::new(uptr, len).reader(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// // THIS IS A BUG! The bytes could have changed since we checked them. @@ -130,7 +127,7 @@ pub fn new(ptr: UserPtr, length: usize) -> Self { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(self, buf: &mut KVec, flags: Flags) -> Result { self.reader().read_all(buf, flags) } @@ -291,9 +288,9 @@ pub fn read(&mut self) -> Result { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(mut self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(mut self, buf: &mut KVec, flags: Flags) -> Result { let len = self.length; - VecExt::::reserve(buf, len, flags)?; + buf.reserve(len, flags)?; // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes // long. diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index ab93111a048c..8d4ac914b48b 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -242,7 +242,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` @@ -251,7 +251,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } @@ -281,7 +281,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 2a9eaab62d1c..4aaf117bf8e3 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -13,7 +13,7 @@ } struct RustMinimal { - numbers: Vec, + numbers: KVec, } impl kernel::Module for RustMinimal { @@ -21,7 +21,7 @@ fn init(_module: &'static ThisModule) -> Result { pr_info!("Rust minimal sample (init)\n"); pr_info!("Am I built-in? {}\n", !cfg!(MODULE)); - let mut numbers = Vec::new(); + let mut numbers = KVec::new(); numbers.push(72, GFP_KERNEL)?; numbers.push(108, GFP_KERNEL)?; numbers.push(200, GFP_KERNEL)?; From patchwork Wed Sep 11 22:52:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801190 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 2C435EE57D7 for ; Wed, 11 Sep 2024 22:56:35 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B1F498D0007; Wed, 11 Sep 2024 18:56:34 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id AD09A8D0001; Wed, 11 Sep 2024 18:56:34 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 9700B8D0007; Wed, 11 Sep 2024 18:56:34 -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 74B118D0001 for ; Wed, 11 Sep 2024 18:56:34 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 011551A1785 for ; Wed, 11 Sep 2024 22:56:33 +0000 (UTC) X-FDA: 82553968266.14.1886248 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf11.hostedemail.com (Postfix) with ESMTP id 7379640006 for ; Wed, 11 Sep 2024 22:56:32 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=a1fzmL5S; spf=pass (imf11.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095339; a=rsa-sha256; cv=none; b=wLhEOOvA5DINrEqA7Elluay/bnlHEhfygE9FcDB0OaQJohdm/uhveUh+x/4atGkcY5iCL1 FnfXMlIOR4qmaYoZMiobNLimTWjjNoyo9sZOrSRT6V7Bj/mBSOvhYOPmVemJo5mPu485zo 91oC6UQdyxA8q64GfidcoNDzeSnllZ0= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=a1fzmL5S; spf=pass (imf11.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095339; 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=XPv4q99W0SpMjmVjBR6ZwAGhf5b9W0K/9xMTDZ3LbJw=; b=PglugaCaLhCXEJBmNySZuigr0HR8L1elZtQjP/yvtbhBbkEIxAec3APqyFdbl5k658TwxR yHGn+iLgCI5i0sfRDE6iwYR+S1mtfgW9SUMpMhqqts4Nb9v9ozuRKcGhVQEnHpJBBtzG9I 7VHLrjH9N7tmuPqD41Uyl98xjs9qrk0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 1309AA45527; Wed, 11 Sep 2024 22:56:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7BECCC4CEC0; Wed, 11 Sep 2024 22:56:26 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095391; bh=yPcuj3XtLEYkObWgOAn3jFjUUb0DA9DkDjwxMGFkw5M=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=a1fzmL5S6iQ1G+qZ/fN386/6hhCpMJfzoO9SOlVZn5KWJLa2HfFxIt/w+Egnv8h3h HT9v6Q4SB7R+/+VZxqKo+/mJUS8O5xSciW0sg0UDKyqsRAG95oE8dVfrI651/vMT3R 0CTJ8r8yu3xWu87nlJqaryIV/oHJw8vbFyAtw8jtF96eULb3Ayho627G0dEbAmbv9t 4FhTcE4hv82Bg/AFGixyp5i9hY2KTtp817gsJ2zWDNEwj2GMR5yboGekSAbBRoTIHd m6sscVy1W6eWekGQhiBraXqn9lrX4GELtYvqB4lcb/36In7HZgYYidyW7dQRKLE/lC v1nbUA14OqFgw== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 17/26] rust: alloc: remove `VecExt` extension Date: Thu, 12 Sep 2024 00:52:53 +0200 Message-ID: <20240911225449.152928-18-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: w1wo9e8fqu7mygiadp7pkwof3erc4znk X-Rspamd-Queue-Id: 7379640006 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1726095392-811728 X-HE-Meta: U2FsdGVkX19Xw7mKz0K5QBC4l+Eh4OgbNoGW7ERfbmR1IBaT8n9JN5VVucSEpDIfgSVkGPuoFFR1Dr7NJq9aay++0Rl1KsQ6DG5VgMlvvZotxiV7Qt59vgdcV1pQ+q3dAK+ICgAMC7cnUAB1nqRWHOm9F7VFhJKbqnq4bm58hZprAQYUDl6hmL5t0K7uDbWppy6qwDP1LbTOfKWHJ+1tbsTLzxtpXJlBPJuvK+0BJq+8SxQREs7+zsiyDw+7oYloRImuN7aO3Lgb1oaLnWpthcES6bfFpDAh0c1nDnLknYuqGQ+Zhx/2hxcZvMB4j5GwBPr5s6HOHqoWXhr575TjQjJLgHBVJv9PDMeNjl7ZGnmceMpZ/bO5/AbWbPdX4KPhdmLHCZ9hzcSw27zLN2aCC+W/EM/N9k9BwhT55rkB9/KuiFNpfk0mMycvuIU3JPalH3MYjec60wj1XmT+eDS7+oaOFxcZwluCwugSbo2UTlem7lfiTjB5dN2slIrEJEPNbWNV0u4j4DsXwBomNzcEpR3LgtZefBwQ2jqoGYlNPcJgFTVVbsDVmpkn8UYtMf7EAkzD/DfKN/xXq0aY+Mb+f04BnkUTjup6EYpY8vuEd3lWP1/YKxGweT0kre85FZrMZ21Yr+oACfVyowTipOtN+yEQo1ih0t7bAxM1YlsTaW/AqZ1ZfR9+1giZ7FXfjJspM6lLAP3fIWmdCSDYpJ4bxitXNCcHvjQ1UWyJoEd0GuiYjkTeQOhpyFitKcdLoqjsUqAL8lvJRD7WiQtpnNJUXV2v7ZmwtoFrfiGZTCirZ8RVZKGV+hmrdo4hjzLVD9a9+YEX9jmZcStEoEY9zmRCq5Kai5uokbqGfhVYOf2W5TZv9peRLWKB5jZe+6imqcs5CC3GzA+xtAIeXKXnJfiuUFByKQkNOG4MGQb8R4p3R/SFOXLJuvu+hpfGiauHXmVHjS/+l3RzLHyy4HoTsAV go3wdEBD uoEwLnK3iryrytk1yrjzUyRvS96qYFTpDm340A+/JKMLTv3KbLRElWjx0HSx2mqMaKzPp6A9wiCGO24tEP4Triz6dBW4TiF0o0ddr0QF0K7eyDH2tS3F19wD17j8HnBuz16CijmTv6mOWeZ9WDSM5RmosqoGrQ9/usDERl/bPucRQ0caff4irw3k9hswKBNwNfkDjmtYbNOsYRuTTv45CY8PSOPgpMR+cIYlxHaySFoVb53e3GRugO2d5Mjt+qTrboT7fjm0QID6GhCB2qhbfs0QsmH3h1rQe53gZSsz3VYTFeiX7fDPHXl8he7wti4EPG6za22hfQqFkPQo= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that all existing `Vec` users were moved to the kernel `Vec` type, remove the `VecExt` extension. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/vec_ext.rs | 185 ----------------------------------- rust/kernel/prelude.rs | 5 +- 3 files changed, 1 insertion(+), 190 deletions(-) delete mode 100644 rust/kernel/alloc/vec_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index e8fbae2adadb..aabdf80e4f7b 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -6,7 +6,6 @@ pub mod allocator; pub mod kbox; pub mod kvec; -pub mod vec_ext; #[cfg(any(test, testlib))] pub mod allocator_test; diff --git a/rust/kernel/alloc/vec_ext.rs b/rust/kernel/alloc/vec_ext.rs deleted file mode 100644 index 1297a4be32e8..000000000000 --- a/rust/kernel/alloc/vec_ext.rs +++ /dev/null @@ -1,185 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Vec`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::vec::Vec; - -/// Extensions to [`Vec`]. -pub trait VecExt: Sized { - /// Creates a new [`Vec`] instance with at least the given capacity. - /// - /// # Examples - /// - /// ``` - /// let v = Vec::::with_capacity(20, GFP_KERNEL)?; - /// - /// assert!(v.capacity() >= 20); - /// # Ok::<(), Error>(()) - /// ``` - fn with_capacity(capacity: usize, flags: Flags) -> Result; - - /// Appends an element to the back of the [`Vec`] instance. - /// - /// # Examples - /// - /// ``` - /// let mut v = Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// assert_eq!(&v, &[1]); - /// - /// v.push(2, GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 2]); - /// # Ok::<(), Error>(()) - /// ``` - fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError>; - - /// Pushes clones of the elements of slice into the [`Vec`] instance. - /// - /// # Examples - /// - /// ``` - /// let mut v = Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// - /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 20, 30, 40]); - /// - /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]); - /// # Ok::<(), Error>(()) - /// ``` - fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> - where - T: Clone; - - /// Ensures that the capacity exceeds the length by at least `additional` elements. - /// - /// # Examples - /// - /// ``` - /// let mut v = Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let cap = v.capacity(); - /// assert!(cap >= 10); - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let new_cap = v.capacity(); - /// assert_eq!(new_cap, cap); - /// - /// # Ok::<(), Error>(()) - /// ``` - fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError>; -} - -impl VecExt for Vec { - fn with_capacity(capacity: usize, flags: Flags) -> Result { - let mut v = Vec::new(); - >::reserve(&mut v, capacity, flags)?; - Ok(v) - } - - fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { - >::reserve(self, 1, flags)?; - let s = self.spare_capacity_mut(); - s[0].write(v); - - // SAFETY: We just initialised the first spare entry, so it is safe to increase the length - // by 1. We also know that the new length is <= capacity because of the previous call to - // `reserve` above. - unsafe { self.set_len(self.len() + 1) }; - Ok(()) - } - - fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> - where - T: Clone, - { - >::reserve(self, other.len(), flags)?; - for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) { - slot.write(item.clone()); - } - - // SAFETY: We just initialised the `other.len()` spare entries, so it is safe to increase - // the length by the same amount. We also know that the new length is <= capacity because - // of the previous call to `reserve` above. - unsafe { self.set_len(self.len() + other.len()) }; - Ok(()) - } - - #[cfg(any(test, testlib))] - fn reserve(&mut self, additional: usize, _flags: Flags) -> Result<(), AllocError> { - Vec::reserve(self, additional); - Ok(()) - } - - #[cfg(not(any(test, testlib)))] - fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> { - let len = self.len(); - let cap = self.capacity(); - - if cap - len >= additional { - return Ok(()); - } - - if core::mem::size_of::() == 0 { - // The capacity is already `usize::MAX` for SZTs, we can't go higher. - return Err(AllocError); - } - - // We know cap is <= `isize::MAX` because `Layout::array` fails if the resulting byte size - // is greater than `isize::MAX`. So the multiplication by two won't overflow. - let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?); - let layout = core::alloc::Layout::array::(new_cap).map_err(|_| AllocError)?; - - let (old_ptr, len, cap) = destructure(self); - - // We need to make sure that `ptr` is either NULL or comes from a previous call to - // `krealloc_aligned`. A `Vec`'s `ptr` value is not guaranteed to be NULL and might be - // dangling after being created with `Vec::new`. Instead, we can rely on `Vec`'s capacity - // to be zero if no memory has been allocated yet. - let ptr = if cap == 0 { - core::ptr::null_mut() - } else { - old_ptr - }; - - // SAFETY: `ptr` is valid because it's either NULL or comes from a previous call to - // `krealloc_aligned`. We also verified that the type is not a ZST. - let new_ptr = unsafe { super::allocator::krealloc_aligned(ptr.cast(), layout, flags) }; - if new_ptr.is_null() { - // SAFETY: We are just rebuilding the existing `Vec` with no changes. - unsafe { rebuild(self, old_ptr, len, cap) }; - Err(AllocError) - } else { - // SAFETY: `ptr` has been reallocated with the layout for `new_cap` elements. New cap - // is greater than `cap`, so it continues to be >= `len`. - unsafe { rebuild(self, new_ptr.cast::(), len, new_cap) }; - Ok(()) - } - } -} - -#[cfg(not(any(test, testlib)))] -fn destructure(v: &mut Vec) -> (*mut T, usize, usize) { - let mut tmp = Vec::new(); - core::mem::swap(&mut tmp, v); - let mut tmp = core::mem::ManuallyDrop::new(tmp); - let len = tmp.len(); - let cap = tmp.capacity(); - (tmp.as_mut_ptr(), len, cap) -} - -/// Rebuilds a `Vec` from a pointer, length, and capacity. -/// -/// # Safety -/// -/// The same as [`Vec::from_raw_parts`]. -#[cfg(not(any(test, testlib)))] -unsafe fn rebuild(v: &mut Vec, ptr: *mut T, len: usize, cap: usize) { - // SAFETY: The safety requirements from this function satisfy those of `from_raw_parts`. - let mut tmp = unsafe { Vec::from_raw_parts(ptr, len, cap) }; - core::mem::swap(&mut tmp, v); -} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 80223cdaa485..07daccf6ca8e 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; - -#[doc(no_inline)] -pub use alloc::vec::Vec; +pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; From patchwork Wed Sep 11 22:52:54 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801191 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 4A4EBEE57D7 for ; Wed, 11 Sep 2024 22:56:40 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id CCDE76B00A8; Wed, 11 Sep 2024 18:56:39 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C7CB66B00A9; Wed, 11 Sep 2024 18:56:39 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AF6DE6B00AA; Wed, 11 Sep 2024 18:56:39 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 9060C6B00A8 for ; Wed, 11 Sep 2024 18:56:39 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 4719914194F for ; Wed, 11 Sep 2024 22:56:39 +0000 (UTC) X-FDA: 82553968518.02.8258572 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf29.hostedemail.com (Postfix) with ESMTP id AEB3A12000A for ; Wed, 11 Sep 2024 22:56:37 +0000 (UTC) Authentication-Results: imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=eXYbBBOq; spf=pass (imf29.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095344; a=rsa-sha256; cv=none; b=ElfpeeXumZlmIWsNmO4j/1wb+dhPTKM5fP1Qcsbg2UsHPzmFAK5hnfwkyNG5rJ3tOZkAtt hPnrH65TTva4HALjfEUwtOY1rTW3n5ISawEWWVtNdMZZPvnJfiqjxuS+OAxEO966CzGz95 6ANBV0h7udh8wR9e5a7hAatE10jLHX0= ARC-Authentication-Results: i=1; imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=eXYbBBOq; spf=pass (imf29.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095344; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=u+VoiLFAetgzpXhJGAFpXoxUqUSb5c896RWORtIY3q4=; b=f6WJO5wcDwI+cLmlxEgVC3obwPZo8mY81cHvj8Uy4oHgaUkxGjdSeu9d4Y75IJN71XW1Rg GF3XmwTlaIZmvRyG0eVouoh61kdwF9GhxjkOus56blHojra5HpTyaovv13ieXHV+Mrw3TL hZcPwo2jjAnj0zD6FbeRyunw6g2QSZY= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 6747E5C06D5; Wed, 11 Sep 2024 22:56:33 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C8FF2C4CEC5; Wed, 11 Sep 2024 22:56:31 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095396; bh=LpXBgctNj+tjXHis1qyn9ZWQx0pllgQA+Wvf8FmkV/A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=eXYbBBOqTcZi/ck3nmSLuIo/cm3vH9ZCqqGY7cMR6byy9TvrFUZF9Ko0BLAU0XK5n IQcydTIGaCpDd1VdWShtJHNIhuSKbBiu8fZmbLNPk5V1FstGPSiHU4mlPiZoudj+Ar PQl5lIHYYx6DN9XopMPbbPArq5yaSmpw8e5IZ2fxZOyDV03qYVJXOkOnSQ34Apk2Yr hjSWUuaP4yKr8zeAshhWErn5eS5YnndvNZIaAYFOQQvXLhap2aMHNHVfcDtaJG21zB rXWNnxDqHjf/D33ZosFzBveNXrQC+Lla5IZg1w4nNUswcNQSYDii1X8IXBQYZjmjqo bqTnlXOfLpGWQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 18/26] rust: alloc: add `Vec` to prelude Date: Thu, 12 Sep 2024 00:52:54 +0200 Message-ID: <20240911225449.152928-19-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: patdq3s4gt8oq3upctwj5u73afp1zidk X-Rspamd-Queue-Id: AEB3A12000A X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1726095397-881048 X-HE-Meta: U2FsdGVkX19Z3hFOe3sBwdZEonbIsZ5mEY0xxf8unMYCnFB5SSGr+LfrpRjQweaFXdpCUP1RqNGI78RCumKHAkg/ACr4d5BRfbGKwKWCIqdGNt6v+XXykIIk8pKhqTw7QbFqJ6jp/u3GwBr+7SYCQ76WCjedF88/diKNOs07HKXbC1+yh8DeN6Ljm0ZN049j8RVaFHANSEWQB+wmT6yG7iWzUpTetTOXISkJyc7xa9x6O0vIGa/7j9l8CX/tE79Oz98gWjbdyLokq/rwBM+xtMi9RvtE56IrOjYu+mavMK+1nYHOEnGGI6rnVsCN1QaddHebg24a0l9zRmgfMUwNe904suWMspLLgsGvglUCiWOeI/kgUt0ovqwCRTtfCdzA3C8TO3RRyKg/BJ2GXXkoLpEnJkhJvAa8zmtVVAKg0pBNCvyLRw1qb6EFmjMb1Fx32C+g89Lbp0JOOZbqqPjCMtplG2LHjvIVczoCqGWaPFbWW/KLymRkFXLsvXUcXSDc5LMD3i7XK35HFhzGvmtygkhc9ZXvhuqOxTuPjpRWdQsfTqEIgzzUuPGgbP5NsnPmfuwjASD+6mqh6oQGWiT8l+lEvhK0rZN2XPeqMK/rssiq9mXNEQFwPh7XBDLS9J5Y3d2oAm5Mbjfu5CYEHcdvVa7JGjpImG23hLN3GkEa4XDbhcsLixIeJiESMpHyF0nvkIw680c4CV5PxdnhMN+HvrT7SuLnV9dEOfxClmlPKfs+JyKY37dlREuzpFYW7vvSltrQnUVUNHtbnlZjxUYh5xTZtgsvyb8Nutdzwn4i2KrYnwYI6y/XnKHGlDRU18EiwcAr/qTR/J8XEmhiLr4hnlmZFjZSLvuwZ+XqJ/uOq07vqy0EoSk7fiklWwFN2Jw/62R781uJqSFZQ4t4hJcsLnq52qiBL/6kb/ssazYLB5XSoQev+/LOS22FLRdO+HrwHBVZPp9GH17gqpu6bCI 7f0pbaqa AKXcZOeHWgXez9McEPuVD2jGqXhXjymWJUJ5jupamlT56hEEINRHB7ZOiG9jO7vNhNFj4rsolIfNQasdht6m00nxcEVENxtBYLo1AWutFwg+X5S59VBAnQ0I7o9NvCUg2+25Zq8IUDPPkGGzNBC1pEvHExiZIDBlPYlWbqtTkVjx2UWSrQRYdLYJA0njzSd+QJVjnlGzArhVkXfRyxahd0umMM6w1bFWtrUZcPsBCcwb7KB9hgOa/jbVjsEhjF5nVDVyhbLRG0JE8vVm2unYd054rFHOswfyY0PojxhePBqL+bpOgHrQjg2vWLHo4N8PF5rFgTSJRv1ykEPM= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we removed `VecExt` and the corresponding includes in prelude.rs, add the new kernel `Vec` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 07daccf6ca8e..8bdab9aa0d16 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; +pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec}; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; From patchwork Wed Sep 11 22:52:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801192 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 CF608EE57DC for ; Wed, 11 Sep 2024 22:56:45 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5C83C6B00A9; Wed, 11 Sep 2024 18:56:45 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 551566B00AB; Wed, 11 Sep 2024 18:56:45 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3F2D16B00AC; Wed, 11 Sep 2024 18:56:45 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 1EE726B00A9 for ; Wed, 11 Sep 2024 18:56:45 -0400 (EDT) Received: from smtpin29.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id C7879121999 for ; Wed, 11 Sep 2024 22:56:44 +0000 (UTC) X-FDA: 82553968728.29.75F9DC4 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf22.hostedemail.com (Postfix) with ESMTP id 2773BC0009 for ; Wed, 11 Sep 2024 22:56:43 +0000 (UTC) Authentication-Results: imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=bjxA++Nc; spf=pass (imf22.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095350; a=rsa-sha256; cv=none; b=OKNgXke3dLz1AAhqII/1IcaDV+PRLDtbmeIFULJsd3R7NmwY0WCYycjSxwr/nIs8oleP7X S6VECcxtTa3lwKrEFgiPyYdaKv9JcyCkuR7fjmERqY5yHMfDZRneJkjqRFlnDDoUCE5vVY moIrOBN/c49griIrxu+SythB74wfHYM= ARC-Authentication-Results: i=1; imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=bjxA++Nc; spf=pass (imf22.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095350; 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=YPf94ZBAzQPt0v6cdu22K1ft2lIOQIrp3qc34OYRfbc=; b=U0OOgGsEKGj0gaDb0TF/4nNdCzHMBDm5w+S1oDzjT4vhh5C++YEfQblRJA7Y6Sm6gLtfrf UkaVd/715JsJZeNOE1nwulh1O2NiiYDhtnQgbZPqj0RpkOn513ysqgV+FlRzbiHR4lnh4G b+tA2sqhKzVYd0SaGPvSwIofloT5tQs= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id C07925C0532; Wed, 11 Sep 2024 22:56:38 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 21E5DC4CEC5; Wed, 11 Sep 2024 22:56:36 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095402; bh=XnmkIRl7JMA721xzQ642zkLKaoztfCsGi1LdCRFqGKk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=bjxA++Nc5MWL3sYzSRC3CUdU6XlAZO+gTMbQlko/UFgVcABHnYcNL7X9oc9V8vXF1 16vDpXQcwuoVs8tLa8s8vS5OnpYaMML3OIuqzKOEHWtEL1G+Sz/KLpUwi3ga5c6bmP KtLlbSLmlGTCIRqd59l9O1xupERtI+YcthuBihC53gXR8dbNDUv5PKxeWeLvwGbsi5 NBtqMO8aZ0bWn9mVwCQYdiD5bjMTxIOGB6vsIdodaNMTVcFActNXTjqsEkDvO/i6Ls LsfPi8WwdizJlorAXL6qfea+gIBx1mk024CrhBQrnqxq9bADxq4Rqg7nSdlkMUtbkh 0bhjMNs4vhduQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 19/26] rust: error: use `core::alloc::LayoutError` Date: Thu, 12 Sep 2024 00:52:55 +0200 Message-ID: <20240911225449.152928-20-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: gr3n3ssuem6kpxkeqz84iqc7ksgzg4s3 X-Rspamd-Queue-Id: 2773BC0009 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1726095403-870558 X-HE-Meta: U2FsdGVkX18fwuNmCT5cU+UgCWNhaYtD8ZEMjc1AsaSzxBe4q2V4t1o4gAGxMSQL/VzTNMwX7ZUAPABL/+WMtC6dKAzL/iOUUjtP/mIPM7WRyU+jKcbbQwzOSCZPnepUHTeIivO9rOMaVZQdEwIfDKBa7FlLBCAUlgsVk3cjNRZQ2ewXlW+PkoebcIN+BL5u1xlxm/g6qpNIOR3hMVWQEth91VHOFVkrNToA9m2pPe56RfDIvnZU/1ExxmOsMYnD2n1V8dHc4pWTo/JsmLAdZtsGalR/+SSLLObna5BpbPM+zxPaareuVaZzVkafpNa4x6ZmgK6x+OZVKDaKffXZKgPxF3WLa8zuQEGm2+w2NVYiFpPwq/KIWCehEjQZmVXnjOg54pGDgmKeSkvZxz+sJSNvgd/4FnQZnHD2h3KbUYa+aINBCkW4eLQATEe3ErUhbUH2fL+4OqwrYOi5wp+o1IenbQR6ZQenK1Vj/Lttea6WfmwkSSG6Ch4dG8fhW+qok3May8zCUq2TjoXxZlLNwn+MjKc5AOxC9rDrcA+L79/YWw7B9uFSHfKA70fc7ErkksCutvPy3lBugkAUrS/UAeqBxo0eDkJdcehbJoQMBHbfdNB2R+e9aXPmMWG9CKWBrKpgkvniPO1gr83GtOBT0umfrFeao9aIMYiyae/6Pn6mDXP2nwBkikpgMdzbSyqyqx0bxNY7HYaIplRn3wq7e5PecKliEDfh1vDJSTt8+5bkY7/mzmGOv+aDKcuvpT4aNeCZLSaOeo1k5XS7q1XDC9o3gj+xrUCb5hhJKOCv+PpVF+qtrLSuMLN0U8qlXa87lk8Ithwd5LSvau5EYYV4VtxmEJAcci19ibrenfvRAlnQS775I1qhH+4UOOkBF167SQnlTUFFbFxMFgZZecTGjgHVchQ9BeXOQLal4VKxv/fmwBhv6HYotm33gx+WPkKdOn+GL841L+m1Q0BPfUT YJ3m9b/e AGqSO0JiB3iqC26ntU5I8Ase8Onpzp1p/w7YP4cmcaILxuv/6MT7iVKQnY2sP8EpHAg+3ElJTagkBk/4FuJVXufdBUL+VL/hkNcsYNvvr+X44JDQ7awyH7h2derMeo+TRQrNkZ4GvyzYw9iwskIGmu6jmluJZ9QI48X1Qi/Wk0xcwpCDvtxtJQScNCXPDdqb2gcpFkCmhH0dQcZbes1XYi/jaiAuOn7Rs+HJ6/zmAnm+B8lxyzxQZTEzZd3ZaKgPHvf5OMKVJCpytomvN0ETiixDh7oi5gLLmJbeZuJOUtJxz6oT/pWxcTEkB71+UMpaUAgQezDkVLFkJbKU= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Use `core::alloc::LayoutError` instead of `alloc::alloc::LayoutError` in preparation to get rid of Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 6f1587a2524e..81b4fc5cf21e 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -6,7 +6,7 @@ use crate::{alloc::AllocError, str::CStr}; -use alloc::alloc::LayoutError; +use core::alloc::LayoutError; use core::fmt; use core::num::TryFromIntError; From patchwork Wed Sep 11 22:52:56 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801193 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 6BE73EE57D7 for ; Wed, 11 Sep 2024 22:56:51 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id AA9E46B00AB; Wed, 11 Sep 2024 18:56:50 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id A58D06B00AD; Wed, 11 Sep 2024 18:56:50 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8B63B6B00AE; Wed, 11 Sep 2024 18:56:50 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 6B30D6B00AB for ; Wed, 11 Sep 2024 18:56:50 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 2CFE5C16E7 for ; Wed, 11 Sep 2024 22:56:50 +0000 (UTC) X-FDA: 82553968980.25.9FD4718 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf05.hostedemail.com (Postfix) with ESMTP id 8B8C9100002 for ; Wed, 11 Sep 2024 22:56:48 +0000 (UTC) Authentication-Results: imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Hlamu4iR; spf=pass (imf05.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095304; 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=jfo4V10e6lOjfznTpyWD06S1WMnImc8oGefa3gyzVcQ=; b=6ZzZjUDGJBh3oAERFNfuvDu1boNwEByuzik77pUHzR9Ho9uRVcdCTy0K7kqW2FlLJhskwX 3zsc6kawndet9hWGNX+i4lI/0Fy9kavyF/vxJliyDO3HFILmj3gDf5l6rKwm4qQ46/z6qC mtBuZxSiVUPkHSbZ13bNonVQJ53F5vs= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095304; a=rsa-sha256; cv=none; b=bdkXFP5et1YMwYizyGjqL0shEsW1p5JV9/5vkesvDmxOparrSxJnfGqEuArXIL1ZKm1/yT DxWXUL0X+WJJBuR7hySH0zUNKEM7WAdwEx+2d+P4QhxvubVmJK8rRH3IhFgZuLXwF9YL6O j1ypI8OJcn2B4VUd5wugrXffFSRw058= ARC-Authentication-Results: i=1; imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Hlamu4iR; spf=pass (imf05.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 234EB5C076E; Wed, 11 Sep 2024 22:56:44 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 77EDDC4CECD; Wed, 11 Sep 2024 22:56:42 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095407; bh=F2SiwlBtvDarApJOsx0M5Yh8m55DamKxmrKOHUpHf/A=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Hlamu4iRv8xXSCkHAmar3KUNSPO3lkPYrPcPHu4IrAsbykCYVQpH0HcvRJJRZ0DHz XKpcM0mxEYFkl5S5WNATEcoL7Xs/iePmQhT1297x1nCybn3BwHGf9F8MwGHo1tF/re jyta5/E9VxSboNN95jYSIk5Krd7cpYjbyH+ePtE8st+cbUKNNS0G7EBY91R3VXZDou lt4MjcfAfxT2vFOVb5ZZaCHOvI5mp/oVMw5lME9XhehHaThcjPHWBshnWqF+FvwLUL zGZpYuNdVNupA6fpDQh6MD3xpcFe03UbJdkstToGDU7BpmtfXiTsnv2BjmKcVnv7f8 zi2EzgqaloJFA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 20/26] rust: error: check for config `test` in `Error::name` Date: Thu, 12 Sep 2024 00:52:56 +0200 Message-ID: <20240911225449.152928-21-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 8B8C9100002 X-Stat-Signature: 1rxkifti1zta9gkbjjdhkpkp8upo6c45 X-HE-Tag: 1726095408-791033 X-HE-Meta: U2FsdGVkX1/vNNYMhIb2K683PhKmuG6rADL9ny27NssD9py7ASqI2vu+X+NqB1bscmqmn3El/8NRO4s+hLAXRUkKrHpbtucNTsVzNwbf8UfqouTditV3x+RHIrVWdFCA7Eiv542aGfuLfIRp7iGCPllbsPzOQYL3osujUypIge9f79wkF0EOaG/oEAPrA+MTN7L367qMReboUQ5jTLhAkydicXqw5wPILmqhWrHvC6FmG8lMhVZJ0mQ0hw++equE5ehQowE9OocTaoFHaEcVLNY2tL6HP7YGA9Gj6tHkoKXnYmifnQRz38zoqQHMqAG8+Dfpd7gMbrn3QT194SJ5Ldb7Bsm5mRKZJdNAkk4kYikhDlPoksBkr8ddtBDN65u3aYAx1OvGWcCwnE7aG4FDoiOEEfCDg3oPL/H99bTd4FPu+4Qfuk9YftztqUjQrFKdrRCNl03Jl5j/5Rx1LDu/s6uUM8FtwY7fjtVzt15SfY12je/VDlG1+OvGlEFaq2hpNY2VRZIZSTOQomJ1ipD50w2hwU0QYdcOLK3aA1oRHcGSJsPOWvt1HyFdJBHtkG77vKAN7DujLSlk/nncE8um+/6VMhMrCTlwZg8GH56nE/TMbZKy0WCmKa8Irsfqe2OmvX6pNEZjVJznTO1MGSPbvmJ4MLi0fg3yuduvPrV45mR3/FzTBQXQnd6lLeQ1kNvbEWespwzADMqgPTni2egbOMbey4CWrQyl9GOVowCrgvv2SrNESB05JkCYkwE8oZeX1jLMwUoU3anc40Qke2Rul6qerOMfZj6E3jxjnLoh2qxeUwZ0ISsDGkcT1npalRlMkr67NKdFEIhXCo98icd93TooXFf+3oU9FDN7XTzS7WayoMGb7ojTRQ1LMKR86dGTGLixLxpOM34tVVgpEq/TiinnWb7tPc+/c+q4Ej9VGwIlhvYQpTXDggdbNv3AtvP9mCKr017mVkA2IyLBeXr 2Gk9YMSK GLUSQIIYxmVTP/7U7HBlCcP6Jm+4CXaENIVwptFsss3Mk3ui9/60ijBU751btn+xrAzjwH1OtFEwQFi9S+1a1Xb1Gt65O1YMuwJ6g/HZCoY+Sek6XvR9w1nQJf66i3YOOIZqBGopO9n07lCq4e/mnTMWX3zs6pKKdmIqRVEVqHWywZZPQxJWtAuG9Jm/VtrTAtqJVZRAB9wijSQIjmox4N0OTgxw1rWnx/Svtdsg33ZjAB5eEWk63clJj+eo+7xlLpbie0XNrMQPNRQqU+4GGk18MK24vGqrRJG9jm87Q8dbJc1JXDtTRBhk/IWNGOWtKSX8uqtTXoXhU6a0= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Additional to `testlib` also check for `test` in `Error::name`. This is required by a subsequent patch that (indirectly) uses `Error` in test cases. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/error.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 81b4fc5cf21e..b71fdd0f54c2 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -143,7 +143,7 @@ pub(crate) fn to_ptr(self) -> *mut T { } /// Returns a string representing the error, if one exists. - #[cfg(not(testlib))] + #[cfg(not(any(test, testlib)))] pub fn name(&self) -> Option<&'static CStr> { // SAFETY: Just an FFI call, there are no extra safety requirements. let ptr = unsafe { bindings::errname(-self.0) }; @@ -160,7 +160,7 @@ pub fn name(&self) -> Option<&'static CStr> { /// When `testlib` is configured, this always returns `None` to avoid the dependency on a /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still /// run in userspace. - #[cfg(testlib)] + #[cfg(any(test, testlib))] pub fn name(&self) -> Option<&'static CStr> { None } From patchwork Wed Sep 11 22:52:57 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801194 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 62214EE57DC for ; Wed, 11 Sep 2024 22:56:56 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E06216B00AD; Wed, 11 Sep 2024 18:56:55 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id DB4F86B00AF; Wed, 11 Sep 2024 18:56:55 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C56F96B00B0; Wed, 11 Sep 2024 18:56:55 -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 A30CA6B00AD for ; Wed, 11 Sep 2024 18:56:55 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 597CC160AB3 for ; Wed, 11 Sep 2024 22:56:55 +0000 (UTC) X-FDA: 82553969190.28.D0820F4 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf03.hostedemail.com (Postfix) with ESMTP id B399420012 for ; Wed, 11 Sep 2024 22:56:53 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=pnKBHrnc; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095309; 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=V3AfaQ6IrC++OfKloqSZu9fg84uCu6HgILZZet6SJcA=; b=WR/sdQfovnZSPyN1ey5vYT1vqw7mROiSUuK6fuVzW8ifA+tBYO9kikK9V2yiriMBnULB76 TQxsuMn1EACt4yYBU7+zH9TVyQzOQd1frwaGp3QiS07J+udeqdEYY9wzRoSTfbi3xoi4u0 sALFlUXX1NIYuNL2xkvSzHEOD94eYkU= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095309; a=rsa-sha256; cv=none; b=oiSGotuXN5PS8zvWpgtvH7jsBvTyj224z335wR6hwBKsN9tGmV6n8vNEU9tfe0z1x72ZvY bo7SwjZcRIyteFt20pqm6FCZnYOYfWLPLxWEPWz/bc2H3TlDlQ17zFFbab/uHYtKDrBAnJ k7rsIJN+l6ioz6CWEAInwIN+pJObUPo= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=pnKBHrnc; spf=pass (imf03.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 67BF05C06D5; Wed, 11 Sep 2024 22:56:49 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C4980C4CEC5; Wed, 11 Sep 2024 22:56:47 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095412; bh=BuRbAjKmy40vmT3N1pF21OHcKiAzSp8OEnKFLe420pQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=pnKBHrncLFslJd6q/nHuhtzqz1+1TBPq4XFiNkHyvx2teZQ09/rGvMq0rkZmjaUBQ Lbl4cpf4vZTYynneRL3vdFi1Bfzk//roOP+ergED0hIoIvTi45n+mq3kqjXJBmtOIE 2TUOfgMT/w6x7qTIrzC8BUSB0AsHIbayljpcYeLVt29Kz+Z5MdCntUZpOmeys+BJf/ +U0AYlUBKLQjbjODoG/ESll0BCXm0zsGtMDWqGWYJ0vhDiGDgL7bZP03DwWiqctj4+ qO7e62LiIaAdh3IGXN1jfezc0FpgcGxB/ZoBVQ43AZLRbGXi/3TLRnAl1HraDUiSRM p61kKYP/nDxBg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 21/26] rust: alloc: implement `contains` for `Flags` Date: Thu, 12 Sep 2024 00:52:57 +0200 Message-ID: <20240911225449.152928-22-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: B399420012 X-Stat-Signature: y8eiucpnwjcr7c7ja15brsdmtad8f8rp X-HE-Tag: 1726095413-413301 X-HE-Meta: U2FsdGVkX19ies8ZbudbcF7rxisp8vkKt0bu2IrySy2lT32laEZqV6+9D+/c+IT5Bhywlj74FrWw8XcJpc34EWi8tLRgg0stvWPEjfag87A0zWFtuXUi+LEDkER8Gv8CYd5bleAwKJcIZ7cqGENBZac6hMqSxxNC7Ey19pX7STLy3mYwjJISHo6LKONedGEPHixHPZSUaCN1VCGQDHb74mhcLyaHMkgliE0th1VyplrzmQFDrV+y3jON5NJMTxUaIExleA4dfB3l6bmH34yxRZcvKDeuOjIpVHT+xlxH7jfzoywWkXsl2AgfgGPzwsPEDA0oRSkWH6ZHo86BAOCBrEdou5OtS42gWi2LqvrEI7mITS1pGCDEByRMs/aOH6vre6/m/gmaWW+pAVyrL0u46G4JL82XiCMZ3Rs3EFJSbaS60VqFNQzPVE8V2QDWREcRGAG6gJtOApYy0lQp+rxCQlAKBSp/EuLEqjgJExiyK4Fkj9bBGIlp9XEEvNtHBDygDteq/P7APLhN/ueBZjG+y8EYCjaPWvCwm1YklYpfstj4kr8gch/RxaGSPpbBALeM8SP7bCdqY2/QgrvyDJ5jq7dBlvvENpMP7SvcS4I/+yoGfn47ceF+33dIbS3poxHEl1FH4g1GeXSW6LesNlBxlLoh3Uq+w4vJKzUIikItlcEtXRgWPR07azy21utXDILJneNA2R/HCW7pWuc27Y+DxEMG9FYiwmVDLQM1nT5av3o+o8N/72FuVnn3oabGVieutPBCSAy0UmxX4MXdSQT2bdIwiCWhhP5bXYd9n4HVNeibo5UooSzV125ahBm7p4fHbwcYDTE/8XlavncWn61Jfn4BWF3s8WjplXj4zMDQxcIcqAgKjEU5tHTKC7wgS618wQ2BRIyUdHAH5x9VGLNrci1Rr1yiu9OpJmyLM2C/Wgild9ioy2vJeVhVYtuvfOPSPAgyuZXuptA/sm5+E/0 vxhDC5v7 rkoAb+vrE3eyEkt3SGf5s71d6wKXEaM3/1aGEemqcZLDig4bIxcJqyqS/hCrGdYQZ98ojQR2FPBkffHSidu4UzVZ1P7ERXnqxv/aHoBqEyLcQ39MhQAFvGAw0KL3wqHJ7smJgS9xtlNUQPN4eN0GmPOIQNr4oahdtxR53i7K9Ti4Mi2i8K9CfQBebj/7mlr0MSNDB7gDIt77atSqIuJ6oNXKBTs6lJI8Xixe4g8MxcWoGkyPNiSdP6p4cCd8ES0HsaIxaalXO7WbZMjNehaOhUXLdbNdXQU8T3fvPSE0FY1vfS0HlA2tuEsZxUiY6LUU58Hc3xKf9VIAX0gI= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Provide a simple helper function to check whether given flags do contain one or multiple other flags. This is used by a subsequent patch implementing the Cmalloc `Allocator` to check for __GFP_ZERO. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin 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 aabdf80e4f7b..caa0b9dfac87 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 Wed Sep 11 22:52:58 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801195 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 BE241EE57DC for ; Wed, 11 Sep 2024 22:57:01 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 4B9636B00AF; Wed, 11 Sep 2024 18:57:01 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 43F6F6B00B1; Wed, 11 Sep 2024 18:57:01 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 2B8EA6B00B2; Wed, 11 Sep 2024 18:57:01 -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 05F906B00AF for ; Wed, 11 Sep 2024 18:57:01 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id A6FBF12199E for ; Wed, 11 Sep 2024 22:57:00 +0000 (UTC) X-FDA: 82553969400.02.F931F74 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf20.hostedemail.com (Postfix) with ESMTP id 101351C0006 for ; Wed, 11 Sep 2024 22:56:58 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f5op+dn3; dmarc=pass (policy=quarantine) 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=1726095303; 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=eXa2x4OjZn8IGqsRl6+iX1ZrqUX4h654eZ8ToLXnf+k=; b=AESXVFDb5g/jq8kRhwWUr9hSufnP9dNi46GjeZXYShU2lgu+bAi6ZdfaDeVLNvaVIj8Ujp k37eUHSD/lgY11aAHo+ZcK4y3higUxd6utEKP4D5s5Uj79JlVBDgJ6lgOWtPenYX7dEsXy bAXjhi+Jzyb/6WF4FW1Jt1980fOg/F4= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095303; a=rsa-sha256; cv=none; b=vUSkGTEgErXsrnHgkIfIBgflXrMQqQbdSiNmw9WEglprt6EivudjeZmpUCzk8qw4FODg0E 7zrkmNg6TbGKsNXlOSokqTIZ0fqjsPaLialvWm9TY7OJrMCcOhlH+C0Hw8iQkPhN7tgMwY S2Avphirh+OzjDgRs82/hv8Zs4i+6xw= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=f5op+dn3; dmarc=pass (policy=quarantine) 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 Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id B64365C0561; Wed, 11 Sep 2024 22:56:54 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1FDB0C4CEC5; Wed, 11 Sep 2024 22:56:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095418; bh=7DpUes9xKzKOnHl0l07t6QG5s3+EyWmOhpQ1qTWwvVs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=f5op+dn3i4tC7w4m44y0/BVWrjnqhdMaDeiTdj7gMMWFcEsqpLZ3Pa6TPZPRaP4cY qmEmmQ1ePSh9njO9xpDSMFbyvIRJb6q9b45i/+HuA8Dxa2F5WviMheL0MPyuHnMyw9 wSuONwROY37HCYTJp4C/cYpRCBRt6Y1D7TDsQLB1vDIVbNW+Q4JHkSTOkjGudVFAbO VfM43r7k/JwMyD9a1raOjQYvKomK26B9yfqeWASlzFccAZzHCgf4Zqk/d10KSXznVY +RusIWr7OsxCpxHn85aWDpBqtMlcY9xvAgj5hl7N9WFo+q3/O6HKBiju9fCvKnxJQK GahYDWnm/rHiA== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 22/26] rust: alloc: implement `Cmalloc` in module allocator_test Date: Thu, 12 Sep 2024 00:52:58 +0200 Message-ID: <20240911225449.152928-23-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 101351C0006 X-Stat-Signature: e7deajznypcqxmtzegb8e7iqapcn7rn5 X-Rspam-User: X-HE-Tag: 1726095418-18646 X-HE-Meta: U2FsdGVkX19B2Ft+Ji14IEommHu+mvyj51GGpeKXBe0GfQzoPlWFrAvWZVWdL4Sm4XCebWb/GFHcdyfO9kSmstN7I3xwL26k13zPFqtzGpVYlRqCOs5xs1C1kOjFBw3L7WkXnwU1Umg3/56YC2erMFwEkGDJuXAvVMOXbZo5vVGITrHT99jMp+blYSbaWFN+WRV8RXz1LqRdiaEDrwgyVdNtiI+wozy9Rohd3wUCelVDQ2Zf1Lxi7rck0aXlSsR3VpOyJAtNg9vgVplD2oXN08H4+8j3wz+27iylnRl9TIZueobVhVtr13ezRr9gLgQdI+tAEbI51yLI6Q3RmhQMdICX7OV8wL++tYeUBLIBNwW0GiUMxyzCgeI6JyQ4rCMQVBsx/4+poqeBC/YMnPCjWR9jfpsKat2hcTrivX/RdMziS5bhyIh6jnKGdf+bcZTuSTGXQ58QeUand/NHniNxH15n8yZI7SVnyyiIbPAPu9cQtwXO0USNvPeoBA5mLNrRCbRFMoZVUFtR6DEqBEmWPTOml275Np+Khw16P6+h3pxr+OxKlCtvlcMb7fp+3NfgXtcjGFoX/42JN/Xfc9MdXHdLqJOmMMIoNMqcSmh4KchNKpA7X8+SppGqCRqLMORbnlOIKagBsFN8/mS7W3C/RBngjbLkTtaLpbLZA+hj2qzQ7Ije8hanFXDr8Ol4J0bjqNkN8TzvL0eHH4Q2E7jGWO5gFOOh3Q8OlR9KVTpKrqYJOLVVPYEPs+8hIQAMHo8/2VwUKAkBeD8Y90ZPw847CyrGYkbmgBQlz3dTJ4INpPUTxDEZXEVbhNLK7fZG+zSlbPMBZtP8MfwkqXU7WP1OubSfZPgsuhQ59uoTkP2lgueFySKk4c5t9c8ILwzu1Fq6Z2A9q8F2LAjBXJFD9gymkQf5qMb0/0DeJWGMIebFljwIGMopEPDJSlaZWyuDmGFRRI59jckhDRe5GUKpz4A mn8lxDA0 Kqal/OEq1UVLg8DvY908f/r9p/vlaMfkULuqzk9pGR1DjdENbZESfdgYzoLsnBfH8GvY4pToPfsiGtvVahSnyUlMCa7uOJHCcca8nrfiD/RchK8ZFYa1feJO9dFl80HkTsjq2MtH6Cy+0dadjrPGtPC3kpXdbJmhPvf+OkQilCHFlrMmo1/r/QG2zifdNYWPeymFTEUbbt49bWfoxVYFunQPQam8kQbmgRgYHRklDvKlerhNeAXNFTdjxD8TKxpxz1TtqR5UlfP7w9NBcZcdSZv7y3Bh3r46xiSYeFoElyOGC4MENZlHSsJqjmN77AX+acbKP8Jme6NiPYlhRNLTc3v9rh4/mvo+JMuWx X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users of those types (e.g. `CString`) use kernel allocators for instantiation. In order to allow userspace test cases to make use of such types as well, implement the `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as allocator backend. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator_test.rs | 193 +++++++++++++++++++++++++++- 1 file changed, 186 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 1b2642c547ec..b5b30513c398 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -1,21 +1,200 @@ // SPDX-License-Identifier: GPL-2.0 +//! So far the kernel's `Box` and `Vec` types can't be used by userspace test cases, since all users +//! of those types (e.g. `CString`) use kernel allocators for instantiation. +//! +//! In order to allow userspace test cases to make use of such types as well, implement the +//! `Cmalloc` allocator within the allocator_test module and type alias all kernel allocators to +//! `Cmalloc`. The `Cmalloc` allocator uses libc's realloc() function as allocator backend. + #![allow(missing_docs)] -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use core::alloc::Layout; +use core::cmp; +use core::mem; +use core::ptr; use core::ptr::NonNull; -pub struct Kmalloc; +/// The userspace allocator based on libc. +pub struct Cmalloc; + +pub type Kmalloc = Cmalloc; pub type Vmalloc = Kmalloc; pub type KVmalloc = Kmalloc; -unsafe impl Allocator for Kmalloc { +extern "C" { + #[link_name = "aligned_alloc"] + fn libc_aligned_alloc(align: usize, size: usize) -> *mut core::ffi::c_void; + + #[link_name = "free"] + fn libc_free(ptr: *mut core::ffi::c_void); +} + +struct CmallocData { + // The actual size as requested through `Cmalloc::alloc` or `Cmalloc::realloc`. + size: usize, + // The offset from the pointer returned to the caller of `Cmalloc::alloc` or `Cmalloc::realloc` + // to the actual base address of the allocation. + offset: usize, +} + +impl Cmalloc { + /// Adjust the size and alignment such that we can additionally store `CmallocData` right + /// before the actual data described by `layout`. + /// + /// Example: + /// + /// - For `CmallocData` assume an alignment of 8 and a size of 16. + /// - For `layout` assume and alignment of 16 and a size of 64. + /// + ///```text + /// 0 16 32 96 + /// |----------------|----------------|------------------------------------------------| + /// empty CmallocData data + ///``` + /// + /// For this example the returned `Layout` has an alignment of 32 and a size of 96. + fn layout_adjust(layout: Layout) -> Result { + let layout = layout.pad_to_align(); + + // Ensure that `CmallocData` fits into half the alignment. Additionally, this guarantees + // that advancing a pointer aligned to `align` by `align / 2` we still satisfy or exceed + // the alignment requested through `layout`. + let align = cmp::max( + layout.align(), + mem::size_of::().next_power_of_two(), + ) * 2; + + // Add the additional space required for `CmallocData`. + let size = layout.size() + mem::size_of::(); + + Ok(Layout::from_size_align(size, align) + .map_err(|_| AllocError)? + .pad_to_align()) + } + + fn alloc_store_data(layout: Layout) -> Result, AllocError> { + let requested_size = layout.size(); + + let layout = Self::layout_adjust(layout)?; + let min_align = layout.align() / 2; + + // SAFETY: Returns either NULL or a pointer to a memory allocation that satisfies or + // exceeds the given size and alignment requirements. + let raw_ptr = unsafe { libc_aligned_alloc(layout.align(), layout.size()) } as *mut u8; + + let priv_ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; + + // SAFETY: + // - By adding `min_align` the pointer remains within the allocated object and `min_align` + // can not exceed `isize`. + // + // GUARANTEE: + // - The adjustments from `Self::layout_adjust` ensure that after this operation the + // original size and alignment requirements are still satisfied or exceeded. + let ptr = unsafe { priv_ptr.as_ptr().add(min_align) }; + + // SAFETY: `min_align` is greater than or equal to the size of `CmallocData`, hence we + // don't exceed the allocation boundaries. + let data_ptr: *mut CmallocData = unsafe { ptr.sub(mem::size_of::()) }.cast(); + + let data = CmallocData { + size: requested_size, + offset: min_align, + }; + + // SAFETY: `data_ptr` is properly aligned and within the allocation boundaries reserved for + // `CmallocData`. + unsafe { data_ptr.write(data) }; + + NonNull::new(ptr).ok_or(AllocError) + } + + /// # Safety + /// + /// - `ptr` must have been previously allocated with `Self::alloc_store_data`. + unsafe fn data(ptr: NonNull) -> CmallocData { + // SAFETY: `Self::alloc_store_data` stores the `CmallocData` right before the address + // returned to callers of `Self::alloc_store_data`. + let data_ptr: *mut CmallocData = + unsafe { ptr.as_ptr().sub(mem::size_of::()) }.cast(); + + // `CmallocData` has been previously stored at this offset with `Self::alloc_store_data`. + // + // SAFETY: + // - `data_ptr` points to a properly aligned and initialized value of `CmallocData`. + unsafe { core::ptr::read(data_ptr) } + } + + /// # Safety + /// + /// This function must not be called more than once for the same allocation. + /// + /// - `ptr` must have been previously allocated with `Self::alloc_store_data`. + unsafe fn free_read_data(ptr: NonNull) { + // SAFETY: `ptr` has been created by `Self::alloc_store_data`. + let data = unsafe { Self::data(ptr) }; + + // SAFETY: `ptr` has been created by `Self::alloc_store_data`. + let priv_ptr = unsafe { ptr.as_ptr().sub(data.offset) }; + + // SAFETY: `priv_ptr` has previously been allocatored with this `Allocator`. + unsafe { libc_free(priv_ptr.cast()) }; + } +} + +unsafe impl Allocator for Cmalloc { + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + if layout.size() == 0 { + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)); + } + + let ptr = Self::alloc_store_data(layout)?; + + if flags.contains(__GFP_ZERO) { + // SAFETY: `Self::alloc_store_data` guarantees that `ptr` points to memory of at least + // `layout.size()` bytes. + unsafe { ptr.as_ptr().write_bytes(0, layout.size()) }; + } + + Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) + } + unsafe fn realloc( - _ptr: Option>, - _layout: Layout, - _flags: Flags, + ptr: Option>, + layout: Layout, + flags: Flags, ) -> Result, AllocError> { - panic!(); + let Some(src) = ptr else { + return Self::alloc(layout, flags); + }; + + if layout.size() == 0 { + // SAFETY: `src` has been created by `Self::alloc_store_data`. + unsafe { Self::free_read_data(src) }; + + return Ok(NonNull::slice_from_raw_parts(NonNull::dangling(), 0)); + } + + let dst = Self::alloc(layout, flags)?; + + // SAFETY: `src` has been created by `Self::alloc_store_data`. + let data = unsafe { Self::data(src) }; + + // SAFETY: `src` has previously been allocated with this `Allocator`; `dst` has just been + // newly allocated. Copy up to the smaller of both sizes. + unsafe { + ptr::copy_nonoverlapping( + src.as_ptr(), + dst.as_ptr().cast(), + cmp::min(layout.size(), data.size), + ) + }; + + // SAFETY: `src` has been created by `Self::alloc_store_data`. + unsafe { Self::free_read_data(src) }; + + Ok(dst) } } From patchwork Wed Sep 11 22:52:59 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801196 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 8DC58EE57DC for ; Wed, 11 Sep 2024 22:57:07 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 183A36B00B1; Wed, 11 Sep 2024 18:57:07 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 133BC6B00B3; Wed, 11 Sep 2024 18:57:07 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id ECD0C6B00B4; Wed, 11 Sep 2024 18:57:06 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id C7BE76B00B1 for ; Wed, 11 Sep 2024 18:57:06 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 76338141094 for ; Wed, 11 Sep 2024 22:57:06 +0000 (UTC) X-FDA: 82553969652.10.1296D85 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf17.hostedemail.com (Postfix) with ESMTP id C0B1540017 for ; Wed, 11 Sep 2024 22:57:04 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=F2tMltIA; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095321; 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=xeZMQRweATNzsUU2VsVY3UXM5T0TGPEUM4pc7l5tHz4=; b=ipuYJXSBbx7VjCg+KZiDLa1H8RK6orRZFbJGH96QZJyfnALmIMxtqhdSC/+MvWOWdoW35h ZOrde+UMcc5Qsh4bh+t0SHXfFze1soR9dZ5JWreO4soopVW6LdL095PeLt64Aa5/vtJkNn ZVnIBIi1295LNGoIe6Yq6NCaemlW3/s= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095321; a=rsa-sha256; cv=none; b=53a7vGxaIRAH6ZbLrjd0qELXDMzTeY9t7Ay3qGOUrESBWkY66H3Dv527LPpuMLcoHF+EYd CGbeJovtSWmT0iOsBs9iqNYt9Vf0X4w1j4JmptbIyMHPG8b/EW03o3t1G1JKuHeIQgLqFs uvPO3i9hjef03cfCSzU4ujvaLeX7uuc= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=F2tMltIA; spf=pass (imf17.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 468F55C0655; Wed, 11 Sep 2024 22:57:00 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6DA91C4CEC5; Wed, 11 Sep 2024 22:56:58 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095423; bh=fJujYBGRQtYZqIjs4LKUGmLmSm16nkPMSrJSclIruqE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=F2tMltIAnv/i/tJGJe7bNbkIVpUV0WYSuNcZNfxRBs0WykhZrbPUzjYzdq1yY34uH 1Tx1f0x7bXrf25FFCClhtCtxPjxtJodKtTeMP74jggPIzmW/Z/1VJE6bDVMXBtUCvg XkIo9Xxs8cYlTzpQVFzlR6GruyGgXDdHHxUw8xMdtQ8zupFvp5V7el7Qx/kcfhcV6F S8uHLX7f2feRP+Gm60bPlSTQHq8hx+Uef+zFzcViVZkn5GWlUJqbW3040EiuFZo9sg rXwez/Mly+0HlkBG7ZYvORIQfbENvQGSBM11EbHHo2c4mMzroKLodWB7u1U76CPay2 nU3m0kqSg8I5w== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 23/26] rust: str: test: replace `alloc::format` Date: Thu, 12 Sep 2024 00:52:59 +0200 Message-ID: <20240911225449.152928-24-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: C0B1540017 X-Stat-Signature: xo7mfrhwgrf8wfxkzjkuqeoa1tzcw57k X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1726095424-389439 X-HE-Meta: U2FsdGVkX1+pa7GiWlF/w9ES5KTHVoo4wdMOpP+Sx73lH3GIelF7H0SviWEJA9WVKxZxrsbH0q/HaEWKfwk+6GdzhmAnucTM9d+hUnUxKQHs/9bWL0eZdFu3/3qU52C0kfTxwIXEIFBiDVtnY9PpLDMktlbxWS47qSzKlsCk0msvKxy5kdWsUJjlJ2mAkbptPbpLEPJL1GpkMeKKGdg+Tk2LbNtrZtz/MICEkuZr15oBZlrbJ7k99pjkHvppqoAJWwzbuaUPC8AmJwE2hLe281nt0mPpFqj+OkIDPWLfUkelfT62Th9+0JgzHRGe87LFtGjiqqh3Exfw/G3c6dwy6bGsbt3Qm1I9+Vb5hQntHvqUg3dJ8+SM5QXez4n1wM11L16bDxspnUbf/hvzCUY3zb7Yo/om+EEGCETyFHiDi3f9vtRzbu6HTn2/pgaIB+zF1ttULlOBOuPH3/Cviy2gRemWaTAxAXmF1U/VBV63O5Mk4rNjoLOFw41v+7HmMnikkRpajqqoaunh4LHBe0ZLQRWH4KQbXY3Nu28nunyi3ljQqk0j04tQ/N5L1Ql4J2GSjt+gWGaZqJ7ah3hjezi08ma/PbU1a4Wk1BHDeWaTjSLgpnHh4YZmJi9u9715/YP7Sr2BeMehuNbUCc3vKel8II9eWtSIQd6h/PA3l3Pn5BX1pY8woQ/tnDyXL9gJSQWE2mnS7oNHzXFVoV5zJBYPvdW3BbwcSVYtE4xPOozhCXXSbdmdY0GqeAar4OqR9HgmUUvvJLHcVKEvRhOFKUTmbFUdKQWFeCzopMA6/CU4AgXw97CLCOsRVsWWVzEXgG2ry9TVMGFfKAsM9K0ZAiTmbIuLGSQeHWS+cJllbqjmArLaYqPFEwx4HFYXvG4/g1s+fwHrfmNPKPI3eiWPMU0WY7nvqeVVPdMSGRDC580gYADwIASIkM8w7zbGpZfHQNgwlaTc5pcavt3UpBTEcn9 R8URy/ZA 0o9o2ErUmmLQNR0S3CrKUICQg2BpsZhmfk+HTLonGUMXdQhGlHjAbhdLE1asaFqp8AVCSOfzFjpt3hvrWsxqegb3QLn2SsOVlwIHGX5TsNi6BO5D55U3tgxZB8rKYvZketGcjNTjA1SLvf5U4/LrqoW6zafBApvB4k+pGMDSz1PKM8H7ZNwyJpq70ywkb4bgKOVOK4X2Bt1L4AXPvrSUidW6TNpXg7qPYYSOZXE2+qMmg/i+xrL6tvIsq3qk0Wax7jSE6pOZRTnuQgE/CCnLw9O+AEAaH5EmcLhHJNywmjF4piXTkBSoYph6MQ6YDlHwSGypQE/IlaGfrCcoKwLcfPRdwsA== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: The current implementation of tests in str.rs use `format!` to format strings for comparison, which, internally, creates a new `String`. In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement `format!` for `CString`. Note that for userspace tests, `Kmalloc`, which is backing `CString`'s memory, is just a type alias to `Cmalloc`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 209ad1bb1a49..726329530338 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,28 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; + + struct String(CString); + + impl String { + fn from_fmt(args: fmt::Arguments<'_>) -> Self { + String(CString::try_from_fmt(args).unwrap()) + } + } + + impl Deref for String { + type Target = str; + + fn deref(&self) -> &str { + self.0.to_str().unwrap() + } + } + + macro_rules! format { + ($($f:tt)*) => ({ + &*String::from_fmt(kernel::fmt!($($f)*)) + }) + } const ALL_ASCII_CHARS: &'static str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ From patchwork Wed Sep 11 22:53:00 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801197 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 48F0AEE57D7 for ; Wed, 11 Sep 2024 22:57:12 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id CA6906B00B3; Wed, 11 Sep 2024 18:57:11 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C56616B00B5; Wed, 11 Sep 2024 18:57:11 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id AD0876B00B6; Wed, 11 Sep 2024 18:57:11 -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 8C89D6B00B3 for ; Wed, 11 Sep 2024 18:57:11 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 4B3D11211BA for ; Wed, 11 Sep 2024 22:57:11 +0000 (UTC) X-FDA: 82553969862.10.545139F Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf11.hostedemail.com (Postfix) with ESMTP id B721240009 for ; Wed, 11 Sep 2024 22:57:09 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DeYNstig; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf11.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=1726095345; a=rsa-sha256; cv=none; b=B0HXGJpesUK7CpRjBAjdamGEn96bjqacq590iVjKxYfT6AU74dHly6m4ikYS7d24/3BPSq JW+iNFKqCaQPqTu8qGdvrJ0/Dq4o1btGZOUBx61ayIILHryclLEG+Mce+384zAdt+OUrvi tQnvGzt5sN/0En4XijPbKfMbyRUatNI= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DeYNstig; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf11.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=1726095345; 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=+sVHxx19dty4UwinjkDtOSpwBgpRexnlA4X3g5iuVEA=; b=pYal72EhT9pk03D40EQEtbgtVpAA0YRlaBe90lNozAss0mjh6NGeqW5jANSb0ZLNm5Wz44 OgrlSHYQDTYxPXvEGqULmAnak+8nbwieC2LDaf4Sz6E/DbDxVlGzSaw2ZjgirduaKzF/uf cY9xyK0Tcmvi7gyJZs6PZ+jP+q1ZzG0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 69D5D5C0620; Wed, 11 Sep 2024 22:57:05 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BB78BC4CED1; Wed, 11 Sep 2024 22:57:03 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095428; bh=CaTZ4LeQw3BXMae2HQHHYLspjHXmuSZPBFyX74iAlrI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DeYNstigf7BHHg9d++A50T0ZQ9zMFq1waReAFW0v/ZrnJ+90tBwoD7PgbeF4thuof i3XNPIjRBtijEIA0nxiwycvxCAugZs86jOqN5t4jRtqK45uk1x1PkYuBSAEQohW7cw yVwCoOX1R2K7Iq435/pWkB1kT/wD12FV3Izg7eXiJj1rvy/enbnx8E+1YUlFUtt0xM EIEP9Oa9Pn4YFtFrSgX6cYyzz9Z5MD8Un7y3ZU6BJFW/LHNOOezUSQle2eKhPka9sA lgKCc9KYkGHqije8Fd5etGJJqlTEBy27G0XMcb1v9IGLRvgIA7uTazvfc5oDujnfWA EBJlCGcUZC3BQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 24/26] rust: alloc: update module comment of alloc.rs Date: Thu, 12 Sep 2024 00:53:00 +0200 Message-ID: <20240911225449.152928-25-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: B721240009 X-Stat-Signature: fothcxxokc4sdoyytuim5cutegogar74 X-Rspam-User: X-HE-Tag: 1726095429-356725 X-HE-Meta: U2FsdGVkX19S2u3vIIA3zVS+1UAHjuJdaA7FqIWsTSQXbtkBNlJOaBZKaHxH9qAgLYCJH0FxEfXkjNj62lVfLi3q8YxdagtKedI2aYG6KQuri1E6YQ6z0xg8WSqlUvl7QIRP0S2T5fmmRxT0CtmKY6oaF9dbnN+sd0ZLGO8HpfXu+Urx6dBydYye9jLjkFbdHtIElN7rCi7wsBcWcB+xch8k+YlQG5QnjCqe5RelnEw95iB8Ld31HhmU1TLbsCH49Uyn2W7VFY8Mzd8zIgJbUsndlANKq61AiIGAYm5pDNOR1XfUCIaP7lWjuKJN+m4tLb06Q4fubcxjoqBd10AzDucKGDoSrvTCkDgkRX2baloH04flJhlDqLUKVW1xorCVtS3jrYbMK+n9h9j/OEeoyjx/oZRXHg05u1uFqL6Qbcpk9EwSkzDe8GIpU5UD149vJyBNWwW9KAvV8bL4drpZAEbJJ9OWUIj//fpeXR5a+uCaoSHLaKLApvPsfdNEnUrsYvj5OizOiUf03uHCkCaH1A3D4JzMViRcfIz7ZbxBKuZvVEp7lxQcLWoOfKUS862/mV8+89T1i6vumzhPx01mx7S9duU7JpWrRQXmogQTP0yJtGEUBVFqs7z1FjuWVOVwlPN5QUxCNxfqbyly/73qkD+NlLv1euo+7IQFI9f7HMCd3xF860NHxCyLRCy7ZEMZlSrHW+YT/bztZHq1GS/Yg1R5Bj7jJ6T5Ebgew0eo9hroqArojJ0huwCjVzIh46qlkpbNjQgB4QNJcKiHI9Q1EonOWYX9Wbxr7RVpjfSSsArRcXmvwpY3tBXNKYzvMD4J+GPcHEiRDZPw8RCwPIZkbjKdmxyh7o+tBncubbeX+N2XB8FUBIyxpsVa4aIH8hpqYf3FskUl6Vjr2I9H31dKfHou2YIEXf+utxMCgmH2o3R5XzzXRBFAw1lm33jZiHmYR0LjToZYe3Q/XrJwTcc h5ifputh wFdl5oVvht8VwF+2YxOIQg1ASVhcDxSGQ+Y/QVDHGXHU6/yK1lFBd/sXit8H44Q7+XrGTZXPBB85QS4qyDBl6uxqdt8PElkPvR4LFqc8XPl6atOlhdqdSSIJRJT8odubmJgRL86vU9GKHRuraoGUqibK6AYI5TrXLE0iYNDvCFLrAXDiwGLbd+AGlcKlKYMY90qBXvYbJRtlsFu5IHuUygGsziVEU5CTK2n0QiKul3ShB/hwgZNDX+ByGg3lFME8hAgYTulno1m5QIhHUxxalqyx6xKa3KLmSPoXriHzH4poD+aaCVKctZtTmFmwsJ+fO8r58fB173yKsvQ1run7GpkSyO6oMJ8wsZDicAuwaU3Ha5r4= X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Before we remove Rust's alloc crate, rewrite the module comment in alloc.rs to avoid a rustdoc warning. Besides that, the module comment in alloc.rs isn't correct anymore, we're no longer extending Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index caa0b9dfac87..2170b53acd0c 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 Wed Sep 11 22:53:01 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801198 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 8F41FEE57DC for ; Wed, 11 Sep 2024 22:57:17 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 1D0936B00B5; Wed, 11 Sep 2024 18:57:17 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 180716B00B7; Wed, 11 Sep 2024 18:57:17 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id F3CAE6B00B8; Wed, 11 Sep 2024 18:57:16 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id CD45E6B00B5 for ; Wed, 11 Sep 2024 18:57:16 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 88F73A074A for ; Wed, 11 Sep 2024 22:57:16 +0000 (UTC) X-FDA: 82553970072.26.00C20EB Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf05.hostedemail.com (Postfix) with ESMTP id F318F10000B for ; Wed, 11 Sep 2024 22:57:14 +0000 (UTC) Authentication-Results: imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RJiNqnpV; spf=pass (imf05.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095382; 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=aQdB567+RZbTOOnJXtoXet5qMBE3ZsZJffNH4QPfEmo=; b=fcTGBsE+oQQXyNXEHxjBbwBiLAOv78uGeI2ecPosWcoQ6WZ8lhyo91ILuIoCGIWoOHbl47 MFiEQjEm7ISj0Xg3TmdiFQ2A/8umATN99nUhDx6LT4n+MO0X6hSyfTtD6IFXYC2U5cKvf8 7FDrMOpK3u1dC+VGNDaS/QAI2USdTMQ= ARC-Authentication-Results: i=1; imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RJiNqnpV; spf=pass (imf05.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095382; a=rsa-sha256; cv=none; b=iU/NAArT5dJmuPox5VQPpJFeowFW6J7qWxRsleBZHEAuJtjLuXLC8IMproOrX2KXyqp5n1 koildEVoIYtRgVnd7cAu1/UogTkZ8lgTZmhvvDIuVxjKXcvNqJap/PR0emai17Ecm/Dfzf Op7cmTcBIjIrRxcyUbsF3c1AAKxSnXU= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id B5A6AA40254; Wed, 11 Sep 2024 22:57:06 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 15EC9C4CEC0; Wed, 11 Sep 2024 22:57:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095433; bh=o6caLp0Bu4YVbIWrrELzNR9rfCWDUl8VF9Pzb1+OsjI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RJiNqnpVGf4zZcQHVQhvpOspMyZlXjOoqlNJFt4k8jHwZHt6rA/hbJ6Go4cS1F70R rMG7SoqHykwihqfvc61iv3atjBAk3Q7ln9TrwNwB62iMeLUtsqnIANHdzvGpPb1xrf KYI/wb4HrNGMNQrh11mTShj5B/2Ka5ojA4rr3kEa6lgqeibjsLSc67Q4veJXjRdeMN A9rxdTH1RXxs8wo5aD1uCJtGhJ6piqMT8XvSltpgy8GPJyvAfWmyq+wGRgSupc92qH Od9Wjzc2fqaN3mF70rSxQx0LOYQN4ATyAZbNbDu29+ToxTxvRqehsHrRhBEhbpmNha I1HHqup5V/65g== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 25/26] kbuild: rust: remove the `alloc` crate and `GlobalAlloc` Date: Thu, 12 Sep 2024 00:53:01 +0200 Message-ID: <20240911225449.152928-26-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: F318F10000B X-Stat-Signature: 5zbjignpky33adncfqm47ko9papa78o4 X-HE-Tag: 1726095434-539932 X-HE-Meta: U2FsdGVkX187EIbzOnn84O2soVy4FaXbVbsOi8nBHSsYRWsx5jOWIUZc691ttbAwF1EWLDK1BmIx2x7NXDtBjEYq3WuJlypB3nVqbwed9wVHZG16fLoWZNV63gfDH6caZXKVz2nSAe11WVDGbkP/Ju8eCdg8LzZPEePsXd7teEhIBIqaNv+43TEem9U5TMhtLOEtpB1ziL5wN8ruq9OqZwKA0iY/TsdSjMZZzdroVwMGIAD19ZsTVc4HuSBg7sQr+bEKBer1ngD0HXcgn4dHYWfAYrcip97GW/vDBelDWdwfd3IzwIeI7nJE7PBQLSs6cKu8Vf4jiQl91BRXmckvZvkdzOgj3zu4VPSE2u8oBGHizt+nU25jwOHSu1spv8vFbFKLqa2PGYG+NQ3fcYI494NKOSsthKW/XfIGUlhsBv9WCf6YEF6QwGM9sPfF2tW/k7d6X6FazmS2QKAo6nXTTYJx/y2KTriT5X5pDwlbNYam4Oab5tp6+7dp/pArSjESCgoTKAKDfQH66w/jJ9rnHZvuSxjNA7snKgOeZHzn1PkXnNUFfLpW21A9jpq+qd1bU/wjfAYHXEoGECgevWnDFT03fcSEyTQ7Ytr+kktsO/K4SMoTtEdu8wsKQ4RP/3rV7wJ2pDJ8qU3Tc5PBHFxCynRB0qguO4CwoQtA6rmRIMQqJ9w5qUuNjJhTG2xqvf26DKl4ekhlKOoZlO7+0GjydyHFaogWTXjeesRTz23G6jwb1B5MthRzGaWV03DO6wf/2QLPSQA/VsmCCUFOrLntQDdKkjmm9bw36ZLT6d+k82raJJiVaD4tlOnuI/aug9WZju20/NL7kXsLLwAN9/Ha+3PCSz+Y+EkGk+G9lDccR4geQJjhTu6ZtpstbtDwr10durbHIox+ybu1swn002yLZYeZ+3Ovfp4lA+XpRtzs+a/RG0qGIhQBqvJrwe+frehJcnq5iY9zXyz5+EyE6uJ /Rd7ny7c 3h6deQavupJm/D7nt5QpuFULMo1aOqt3IQfJ38gdTBMTDqWR/FK2UP6zPF9OJ2BckhKDIYoDlSFKEIy4DCPTb5XkLAtokp0Jd0BxQ6Qp+Eqbc8TYapwQytJDEjO/O2SE8ubfsfhEs3uaWY6FPbXPGohecWVibZQfRQm4l0K9oZ7MhAEY3+XGpQUeDfKVdcte0LnSMIjfpYlEAVAFBldBrOOCfoR5JBYuLfLuoYhAfTqCRatd1ja39kCSdsrixBU3W1wQ4nRJUeJq9emAmHUMsLj0vo68jG7dJbog5IsFyiArIjhz1VtqbTsfiXUSieWG8kCRF4VfQ9n+B9oUmRDDjtEMT2WblI1SYwnDW X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Now that we have our own `Allocator`, `Box` and `Vec` types we can remove Rust's `alloc` crate and the `new_uninit` unstable feature. Also remove `Kmalloc`'s `GlobalAlloc` implementation -- we can't remove this in a separate patch, since the `alloc` crate requires a `#[global_allocator]` to set, that implements `GlobalAlloc`. Signed-off-by: Danilo Krummrich --- rust/Makefile | 43 +++++---------------- rust/exports.c | 1 - rust/kernel/alloc/allocator.rs | 63 +------------------------------ scripts/Makefile.build | 7 +--- scripts/generate_rust_analyzer.py | 11 +----- 5 files changed, 15 insertions(+), 110 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 4eae318f36ff..a3ac60b48ae1 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -15,8 +15,8 @@ always-$(CONFIG_RUST) += libmacros.so no-clean-files += libmacros.so always-$(CONFIG_RUST) += bindings/bindings_generated.rs bindings/bindings_helpers_generated.rs -obj-$(CONFIG_RUST) += alloc.o bindings.o kernel.o -always-$(CONFIG_RUST) += exports_alloc_generated.h exports_helpers_generated.h \ +obj-$(CONFIG_RUST) += bindings.o kernel.o +always-$(CONFIG_RUST) += exports_helpers_generated.h \ exports_bindings_generated.h exports_kernel_generated.h always-$(CONFIG_RUST) += uapi/uapi_generated.rs @@ -53,11 +53,6 @@ endif core-cfgs = \ --cfg no_fp_fmt_parse -alloc-cfgs = \ - --cfg no_global_oom_handling \ - --cfg no_rc \ - --cfg no_sync - quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< cmd_rustdoc = \ OBJTREE=$(abspath $(objtree)) \ @@ -81,7 +76,7 @@ quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< # command-like flags to solve the issue. Meanwhile, we use the non-custom case # and then retouch the generated files. rustdoc: rustdoc-core rustdoc-macros rustdoc-compiler_builtins \ - rustdoc-alloc rustdoc-kernel + rustdoc-kernel $(Q)cp $(srctree)/Documentation/images/logo.svg $(rustdoc_output)/static.files/ $(Q)cp $(srctree)/Documentation/images/COPYING-logo $(rustdoc_output)/static.files/ $(Q)find $(rustdoc_output) -name '*.html' -type f -print0 | xargs -0 sed -Ei \ @@ -105,20 +100,11 @@ rustdoc-core: $(RUST_LIB_SRC)/core/src/lib.rs FORCE rustdoc-compiler_builtins: $(src)/compiler_builtins.rs rustdoc-core FORCE +$(call if_changed,rustdoc) -# We need to allow `rustdoc::broken_intra_doc_links` because some -# `no_global_oom_handling` functions refer to non-`no_global_oom_handling` -# functions. Ideally `rustdoc` would have a way to distinguish broken links -# due to things that are "configured out" vs. entirely non-existing ones. -rustdoc-alloc: private rustc_target_flags = $(alloc-cfgs) \ - -Arustdoc::broken_intra_doc_links -rustdoc-alloc: $(RUST_LIB_SRC)/alloc/src/lib.rs rustdoc-core rustdoc-compiler_builtins FORCE - +$(call if_changed,rustdoc) - -rustdoc-kernel: private rustc_target_flags = --extern alloc \ +rustdoc-kernel: private rustc_target_flags = \ --extern build_error --extern macros=$(objtree)/$(obj)/libmacros.so \ --extern bindings --extern uapi rustdoc-kernel: $(src)/kernel/lib.rs rustdoc-core rustdoc-macros \ - rustdoc-compiler_builtins rustdoc-alloc $(obj)/libmacros.so \ + rustdoc-compiler_builtins $(obj)/libmacros.so \ $(obj)/bindings.o FORCE +$(call if_changed,rustdoc) @@ -162,7 +148,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $< mkdir -p $(objtree)/$(obj)/test/doctests/kernel; \ OBJTREE=$(abspath $(objtree)) \ $(RUSTDOC) --test $(rust_flags) \ - -L$(objtree)/$(obj) --extern alloc --extern kernel \ + -L$(objtree)/$(obj) --extern kernel \ --extern build_error --extern macros \ --extern bindings --extern uapi \ --no-run --crate-name kernel -Zunstable-options \ @@ -198,7 +184,7 @@ rusttest-macros: $(src)/macros/lib.rs FORCE +$(call if_changed,rustc_test) +$(call if_changed,rustdoc_test) -rusttest-kernel: private rustc_target_flags = --extern alloc \ +rusttest-kernel: private rustc_target_flags = \ --extern build_error --extern macros --extern bindings --extern uapi rusttest-kernel: $(src)/kernel/lib.rs \ rusttestlib-build_error rusttestlib-macros rusttestlib-bindings \ @@ -311,9 +297,6 @@ quiet_cmd_exports = EXPORTS $@ $(obj)/exports_core_generated.h: $(obj)/core.o FORCE $(call if_changed,exports) -$(obj)/exports_alloc_generated.h: $(obj)/alloc.o FORCE - $(call if_changed,exports) - # Even though Rust kernel modules should never use the bindings directly, # symbols from the `bindings` crate and the C helpers need to be exported # because Rust generics and inlined functions may not get their code generated @@ -360,7 +343,7 @@ quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L rust-analyzer: $(Q)$(srctree)/scripts/generate_rust_analyzer.py \ - --cfgs='core=$(core-cfgs)' --cfgs='alloc=$(alloc-cfgs)' \ + --cfgs='core=$(core-cfgs)' \ $(realpath $(srctree)) $(realpath $(objtree)) \ $(rustc_sysroot) $(RUST_LIB_SRC) $(KBUILD_EXTMOD) > \ $(if $(KBUILD_EXTMOD),$(extmod_prefix),$(objtree))/rust-project.json @@ -398,12 +381,6 @@ $(obj)/compiler_builtins.o: private rustc_objcopy = -w -W '__*' $(obj)/compiler_builtins.o: $(src)/compiler_builtins.rs $(obj)/core.o FORCE +$(call if_changed_rule,rustc_library) -$(obj)/alloc.o: private skip_clippy = 1 -$(obj)/alloc.o: private skip_flags = -Wunreachable_pub -$(obj)/alloc.o: private rustc_target_flags = $(alloc-cfgs) -$(obj)/alloc.o: $(RUST_LIB_SRC)/alloc/src/lib.rs $(obj)/compiler_builtins.o FORCE - +$(call if_changed_rule,rustc_library) - $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE +$(call if_changed_rule,rustc_library) @@ -418,9 +395,9 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_rule,rustc_library) -$(obj)/kernel.o: private rustc_target_flags = --extern alloc \ +$(obj)/kernel.o: private rustc_target_flags = \ --extern build_error --extern macros --extern bindings --extern uapi -$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/alloc.o $(obj)/build_error.o \ +$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/build_error.o \ $(obj)/libmacros.so $(obj)/bindings.o $(obj)/uapi.o FORCE +$(call if_changed_rule,rustc_library) diff --git a/rust/exports.c b/rust/exports.c index e5695f3b45b7..82a037381798 100644 --- a/rust/exports.c +++ b/rust/exports.c @@ -16,7 +16,6 @@ #define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym) #include "exports_core_generated.h" -#include "exports_alloc_generated.h" #include "exports_helpers_generated.h" #include "exports_bindings_generated.h" #include "exports_kernel_generated.h" diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index a5d7e66a68db..0b586c0361f4 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,8 +8,8 @@ //! //! Reference: -use super::{flags::*, Flags}; -use core::alloc::{GlobalAlloc, Layout}; +use super::Flags; +use core::alloc::Layout; use core::ptr; use core::ptr::NonNull; @@ -54,23 +54,6 @@ fn aligned_size(new_layout: Layout) -> usize { layout.size() } -/// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment. -/// -/// # Safety -/// -/// - `ptr` can be either null or a pointer which has been allocated by this allocator. -/// - `new_layout` must have a non-zero size. -pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - let size = aligned_size(new_layout); - - // SAFETY: - // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the - // function safety requirement. - // - `size` is greater than 0 since it's from `layout.size()` (which cannot be zero according - // to the function safety requirement) - unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } -} - /// # Invariants /// /// One of the following `krealloc`, `vrealloc`, `kvrealloc`. @@ -148,41 +131,6 @@ unsafe fn realloc( } } -unsafe impl GlobalAlloc for Kmalloc { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL) } - } - - unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { - unsafe { - bindings::kfree(ptr as *const core::ffi::c_void); - } - } - - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - // SAFETY: - // - `new_size`, when rounded up to the nearest multiple of `layout.align()`, will not - // overflow `isize` by the function safety requirement. - // - `layout.align()` is a proper alignment (i.e. not zero and must be a power of two). - let layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; - - // SAFETY: - // - `ptr` is either null or a pointer allocated by this allocator by the function safety - // requirement. - // - the size of `layout` is not zero because `new_size` is not zero by the function safety - // requirement. - unsafe { krealloc_aligned(ptr, layout, GFP_KERNEL) } - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL | __GFP_ZERO) } - } -} - // SAFETY: `realloc` delegates to `ReallocFunc::call`, which guarantees that // - memory remains valid until it is explicitly freed, // - passing a pointer to a valid memory allocation is OK, @@ -228,10 +176,3 @@ unsafe fn realloc( unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, flags) } } } - -#[global_allocator] -static ALLOCATOR: Kmalloc = Kmalloc; - -// See . -#[no_mangle] -static __rust_no_alloc_shim_is_unstable: u8 = 0; diff --git a/scripts/Makefile.build b/scripts/Makefile.build index 72b1232b1f7d..529ec5972e55 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -262,18 +262,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- - -rust_allowed_features := new_uninit - # `--out-dir` is required to avoid temporaries being created by `rustc` in the # current working directory, which may be not accessible in the out-of-tree # modules case. rust_common_cmd = \ RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \ - -Zallow-features=$(rust_allowed_features) \ -Zcrate-attr=no_std \ - -Zcrate-attr='feature($(rust_allowed_features))' \ - -Zunstable-options --extern force:alloc --extern kernel \ + -Zunstable-options --extern kernel \ --crate-type rlib -L $(objtree)/rust/ \ --crate-name $(basename $(notdir $@)) \ --sysroot=/dev/null \ diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py index d2bc63cde8c6..09e1d166d8d2 100755 --- a/scripts/generate_rust_analyzer.py +++ b/scripts/generate_rust_analyzer.py @@ -64,13 +64,6 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): [], ) - append_crate( - "alloc", - sysroot_src / "alloc" / "src" / "lib.rs", - ["core", "compiler_builtins"], - cfg=crates_cfgs.get("alloc", []), - ) - append_crate( "macros", srctree / "rust" / "macros" / "lib.rs", @@ -96,7 +89,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): append_crate( "kernel", srctree / "rust" / "kernel" / "lib.rs", - ["core", "alloc", "macros", "build_error", "bindings"], + ["core", "macros", "build_error", "bindings"], cfg=cfg, ) crates[-1]["source"] = { @@ -133,7 +126,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): append_crate( name, path, - ["core", "alloc", "kernel"], + ["core", "kernel"], cfg=cfg, ) From patchwork Wed Sep 11 22:53:02 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13801199 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 E3167EE57DC for ; Wed, 11 Sep 2024 22:57:22 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 701C46B00B7; Wed, 11 Sep 2024 18:57:22 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6AFE46B00B9; Wed, 11 Sep 2024 18:57:22 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5519C6B00BA; Wed, 11 Sep 2024 18:57:22 -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 362CF6B00B7 for ; Wed, 11 Sep 2024 18:57:22 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id E70051A169A for ; Wed, 11 Sep 2024 22:57:21 +0000 (UTC) X-FDA: 82553970282.17.2B9DBC8 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf28.hostedemail.com (Postfix) with ESMTP id 56B7AC000C for ; Wed, 11 Sep 2024 22:57:20 +0000 (UTC) Authentication-Results: imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=NR2myOkh; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095387; a=rsa-sha256; cv=none; b=2NijF1lZjriVmYI/8lwuiJYHN2OQ6/ArwTRKQ3/Ovkjk6R+IC+tMm7Cnnp1Qo/zyLCLoiY 5rABQGyXEc8C5ZqUlp98Jzfd5unlMKkKpnyXNp98kcvC1PgGMwaT60i2kBrzbdVEvqEvMk aiK960PpxiLBAcEkpmLTtwyJGGoqh+U= ARC-Authentication-Results: i=1; imf28.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=NR2myOkh; spf=pass (imf28.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1726095387; 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=3Sc7wGZZveCUZiTgo2kC+IeFhi6uNzXFgCKa5ZSpNwg=; b=3Akzcl9w2FY5wmlsyWQB/ZMu84HLmjL3uhsqlsVKeeeIaYI40zJFa2FQy8Dn/XOulw5lbh 6ilrPLBOTiLtykjOj2JfnR/qdiTWuS+WSqRRu342HJVVTyPCYwNQTvJYCMrwUiQ3zcmp+I b6FBl6YrI3DhXFEnZ6drqdEFMyWqPWI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 14F255C07C5; Wed, 11 Sep 2024 22:57:16 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6657DC4CECD; Wed, 11 Sep 2024 22:57:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095439; bh=MA63j2l96SFmNAW2ZFKeN7OYc4kzJPq4eXgb27o0nko=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=NR2myOkh+9gGnmPS2kTc/yg2gApS991zzrQnL13Z3QDyUHo8klpn52EysPtMFhadg rBBDarK2Lo3HtvcLZmyafp6cQ/NooD0a5Mr+BbG4ZDKrda9xzsWWbV5qJ8D+Rkk51x qmYHJcJl8x8siUwA9t2m9zPFZ0mXVEugSCkgMa+VUXsHZr+5nybS6F6pStN0zjZCMi fdyOg34SRfXUluMcm88odzsoq/DqrnOJ6Am3VF8g1/mcHzcvDXOOKyQ8oUHdexq4RP /wfna5X5/a7/6l/Dl6GecSb3Si8FLLzmMJzs96MWVGhq1LPrixpNmgFfXvKYxJzSVX hRx64lF9uLVdQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v7 26/26] MAINTAINERS: add entry for the Rust `alloc` module Date: Thu, 12 Sep 2024 00:53:02 +0200 Message-ID: <20240911225449.152928-27-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 6unoh4eknk81xaxhno4hji4kunmwa44u X-Rspamd-Queue-Id: 56B7AC000C X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1726095440-614834 X-HE-Meta: U2FsdGVkX1/EPRMuu6FPvqrH2CGCn01B0yFMhD8hAcI5pJ/n80K5oZFNtlRIyULlfXt1l/a2V0KblBoWBXGe8T/CVo5446i8CgaJJ1HSAqT5dmrTz8uMueJnXi7q5XF+iEY8FLYxch5l7Fl8OPKbTqCpfcHi4cLmKfOATASi/vH53VYwS/BnnFCaNmvprAgtugkUe3YsX6fKShTK+mZ1r7uS/SReMXMFqduDsTwbYLjil2Jy0nHxX2dTewRNSyIln2ebOEC25vFl8pcAO/PUBXloqwkt7k0P38pdmGMP/sEVKiiEM4NhHjXnoh7omzbZhCsAca0rBhAp866iB2UN+76P48J1g28dWJiVxCOHyWdTHTo1lILWzYqn0LZDhbZ6dDo4k2o/mLYDDWeR6x+gX+V4qD2CzWU96uxCy/4a+8v6aUd+w03imJK1ocp1iX3sxSgTIwRHmqDpZOO0fJLdwXloT4zcChspFcgwFBzyutGV+YYxv7LX4zpG9h3jJXj093rWzI4gSN8D54ux5qGkgMnoXpMRxO1wKo+mTxmw3xZvZw2beUfHV7mOmT5RQBZCdHkCUMH1RzDU8QFk37K6HGs/CRwW/glYcFkXzG6jiY1vFBP2tjQlA9xc62MIOS6mahlGq47QT25SOTM+10Ul8Vap14Iqr5TANMyhfO3F6kX+/fdaHwS7LCMfZ6v74guvxeU1wYQbxg6r5U5jp+2cBfBcQyXvo3LRelu9EZrbC2vXB/uzqtDTzSqPj+B0HjEpPJtFmMRGA96E6KkE1b1Fl+Y+VJHtas0as9XbZJU7PhphjxT43BR7dQJ0NJBRqZjkTKHe8fRQI7LgDqDsCcwntv582/15Rb+88Hb631M+a9cQ2AkYTVyIYXqnwL4uUkc7zPNK23pAl+skEkNwOH54Lq0s8HjaX/gBMzghURz14t2NufzvzgbRJoi9KDApT+yD2XeHNKyHKM6tATLYs82 GcdhZiyu 382wwK4gosLvkT3I/zQEVz9VmjYgREG8CUspnX58L/S284pVzJnb2XRLVnQMLuSp1aAEvfP1/LJK9wbIRSm5eTj5yX5cEYdwlqw5DQxzfHtjKRyjhlsZf/D4uQybatDKMn2UNO68sGLBSIbcUpdh9vSJn3CGmAhZ5agUHunMrD+F1pPClQ3y8c0ExzenrtZvRJUEMw8DHp+ajSpjPbTmjZZ7eFbq88Qnd6Pr+GO7AzXU6G6TDxjPP9iEqSqpxSNrqfCJvqatADdJ8KE0AlTZ6yP4ULObA4G1ASrwa1bEyzKUAclEC/6WqkPDahrE9v8SahoN7pZwHiqHtnCDT2brYoBrxI2KmvTNIa22UkOumPduLocqw781f1qrZJFyZiexoFWma X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Add maintainers entry for the Rust `alloc` module. Currently, this includes the `Allocator` API itself, `Allocator` implementations, such as `Kmalloc` or `Vmalloc`, as well as the kernel's implementation of the primary memory allocation data structures, `Box` and `Vec`. Signed-off-by: Danilo Krummrich --- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 77b395476a80..f57e3b5bc410 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -19929,6 +19929,13 @@ F: scripts/*rust* F: tools/testing/selftests/rust/ K: \b(?i:rust)\b +RUST [ALLOC] +M: Danilo Krummrich +L: rust-for-linux@vger.kernel.org +S: Maintained +F: rust/kernel/alloc.rs +F: rust/kernel/alloc/ + RXRPC SOCKETS (AF_RXRPC) M: David Howells M: Marc Dionne