From patchwork Tue Oct 1 14:59:36 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13818220 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 E5FF3CEACDC for ; Tue, 1 Oct 2024 15:00:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7424E680005; Tue, 1 Oct 2024 11:00:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6F221280068; Tue, 1 Oct 2024 11:00:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5BB43680005; Tue, 1 Oct 2024 11:00:27 -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 3D653280068 for ; Tue, 1 Oct 2024 11:00:27 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id AE60E121477 for ; Tue, 1 Oct 2024 15:00:26 +0000 (UTC) X-FDA: 82625344452.11.CB7D8D4 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf24.hostedemail.com (Postfix) with ESMTP id C01CC180026 for ; Tue, 1 Oct 2024 15:00:23 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hx6rOwgd; 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=1727794683; 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=CXBFRHwXUbS7Tr/infYoiNrJ0DQJtSF6TY2nk6jPC3s=; b=etokPClbVHlygPCr9aFxTYJs4qNs6UFOUc5EmQM+drw3BVV0NTA6bQd0DneyxcQQ2+/jGu Bf25bEhsSStvp2ys3Hm9jUZwvXhpb3RY4P0cQo/xmiSiMHs1AYsXFE47bO6cnMw5Rkc0l8 +mn/D1ZmgTpLIdVERzLBrtfOBGMP8BQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1727794683; a=rsa-sha256; cv=none; b=1HdMamUaEFxXw6aSL+lvD6EOqzpCmWHllt5CvqkZ24F3JuUxiXeCeSPrvOyo7uNX1tFN94 7d9m7OBXgE/p3vviCy0YbCixVBJq2WWd++53/hiV6ohiudsRTYYsCOiDbB2IG2BcFv5iiu UerLtavdwy0rwyzUzz9KLGcwJcJyYsU= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hx6rOwgd; 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 Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 20401A4381B; Tue, 1 Oct 2024 15:00:14 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 33311C4CED2; Tue, 1 Oct 2024 15:00:17 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1727794822; bh=LFLXrXtZbe/puBmhEZdj7dt2Ld/jyYgOKMUua1Snsrs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hx6rOwgdkDdyOk+OI9PzxJNX6LUO2zgzRz35qMibhc3q4YyFPr8Kmn34CMWbb63Ua AT42hkFApCUfTVKZt+yfhrDVTORR9wIhiAxhX1K6zz3dHMTWRLrzNSRdCuKAKiPx5s AqaUT/nGfK8qJP/eshnYf5wQwXaOkFM3GdTp0l0jMLw0FpgYFz+xtHV/7iiC+YVniN iM8ANXoUsH3OEaK12KT5Gvd2kXqTcPl3ETot+dhr0UEoRGafIJtgX33acLod/naref BwluFtf9g7NEsetCGFDUtNQjzcvYiWAeOSGUv/QkXZkpCFwNV24UZ4gZFnPY7BZzpH oCJH8aO/gXHng== 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 v8 01/29] rust: alloc: add `Allocator` trait Date: Tue, 1 Oct 2024 16:59:36 +0200 Message-ID: <20241001150008.183102-2-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241001150008.183102-1-dakr@kernel.org> References: <20241001150008.183102-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: C01CC180026 X-Stat-Signature: ky6ugrxd6jbq5nsxsg7mrkcs3osygx1y X-Rspam-User: X-HE-Tag: 1727794823-204109 X-HE-Meta: U2FsdGVkX1/kzwhRjlQqE/wHbBLmAp5YnZjaRwLwIcv3MR1wrJAL9fcgO3osgtiPEdu6FCZONjTUCE3Zr+2ythv5+HhGT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53rbAwxEZRW35kLA/vuMOeMCXLs8FRk21HMUMNepUEqtd9qm/pkZyWoZaWTMGz2otfr4t0kyO/q2u9hVEGtCiAJL6SDKerkpb2Byl3bWTj+T2eqkALpdPsEiY3vYdzhAJvReBIheT4ZoFUwWf0BUSe/0TQKt0EKZ8zV0njqNCesLz 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 Reviewed-by: Gary Guo Reviewed-by: Benno Lossin --- rust/kernel/alloc.rs | 101 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..4deeea3488be 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,103 @@ 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. +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, Layout::new::<()>(), 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`]; if `old_layout` is zero-sized `p` does not need to be a + /// pointer returned by this [`Allocator`]. + /// - `ptr` is allowed to be `None`; in this case a new memory allocation is created and + /// `old_layout` is ignored. + /// - `old_layout` must match the `Layout` the allocation has been created with. + /// + /// # 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, i.e. `ret_ptr[0..min(layout.size(), old_layout.size())] == + /// p[0..min(layout.size(), old_layout.size())]`. + /// - when the return value is `Err(AllocError)`, then `ptr` is still valid. + unsafe fn realloc( + ptr: Option>, + layout: Layout, + old_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`]; + /// if `old_layout` is zero-sized `p` does not need to be a pointer returned by this + /// [`Allocator`]. + /// - `layout` must match the `Layout` the allocation has been created with. + /// - The memory allocation at `ptr` must never again be read from or written to. + unsafe fn free(ptr: NonNull, layout: Layout) { + // 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::<()>(), layout, Flags(0)) }; + } +}