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/ODrrzTLGQtahVaEJocbtDa50E2Smm8XLY5VcnAljyaNLGnuNyNFqimue9jDCcCqce4iC4oJ9yJb6Mlbm9GboMp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mhC6rYHAfoP9uxgHxvuyC6HCe2lExDggBWawTD+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)) }; + } +}