From patchwork Fri Aug 16 00:10: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: 13765282 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 190FCC52D7F for ; Fri, 16 Aug 2024 00:12:35 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E6E176B027B; Thu, 15 Aug 2024 20:12:33 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E1DB46B027C; Thu, 15 Aug 2024 20:12:33 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CBD0C6B027D; Thu, 15 Aug 2024 20:12:33 -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 B08CF6B027B for ; Thu, 15 Aug 2024 20:12:33 -0400 (EDT) Received: from smtpin30.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 66A34419B9 for ; Fri, 16 Aug 2024 00:12:33 +0000 (UTC) X-FDA: 82456182186.30.2FD1E3E Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf17.hostedemail.com (Postfix) with ESMTP id BA77040003 for ; Fri, 16 Aug 2024 00:12:31 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ZHAELe33; 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=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767114; a=rsa-sha256; cv=none; b=mw79gSV7+sxySe2Fz1/fiQpg9DXO/W3k05VgxSH7SKvFq0PZ3kFDAIoy5ELlVrU5ozzNtz 2NvdCDHH+s/PNV7pkNReIg4OO/33JvnCapFqwmbonraMP4wRvnCaENw04S9M1p0CUu7/+Z 7EH1oKIRZNqMF8EOlqg6ftc2idK5fWU= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ZHAELe33; 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=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723767114; 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=izPWcm+31T2WE8RFh7WL04RuSNp+LqqNmQu4RAuN+t0=; b=NnrlQ2kWFSL0AXwxbjGljnA7c3t840E8lVmoaGPqLiriBgTxZsb4B50jF6mjgKr/w9/Ta7 kTf3kQd0WRII7XE+XC+aBTMgGZypCFaoMSAZR8F2vAC8g6wCDjcgrpOcH/8ONdxx36Gyk5 abuoZXX2ZeCRZsqUhcadQsO0EKJL3Kk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 9674262061; Fri, 16 Aug 2024 00:12:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6DA4AC4AF09; Fri, 16 Aug 2024 00:12:25 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767150; bh=q5RlNxfkOyLhc4BgL6waKEiGm6mWXft+//KdK2R27M4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ZHAELe33Ua3jRDxbSxhvloXmYD45gcH+zzoE+3wSpdYojUyPsqnnjpsXyLQkCnZmw qGXEbtqFSDD21/hS1rLaCDCOuJw15Z6EmLmJYatnBupG26mWIPTi+IUQ9XGCHwsZhp x74Y0Ztdeq95QwupMO+oJ5J1C39IeowFODY0W3se/2naWCjnnkwbtTWNpzH7etTewP ihJTjiLb/YVxcXbbMegBv55uvc2wJ1RuxeA5ssNQbkZogN25k3YRe9xluyiSfM0rSg jHhNCqJUc6HDriX5Ie9m21BpHGt2u1C1lC6lAQGGsiI5e2ZGRIHoiHVRAiDJ/12mC1 L+RaFrjKBhfgw== 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 v6 01/26] rust: alloc: add `Allocator` trait Date: Fri, 16 Aug 2024 02:10:43 +0200 Message-ID: <20240816001216.26575-2-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: jfcshw9nftighit5rt9x9yrr4rg3hb3b X-Rspamd-Queue-Id: BA77040003 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723767151-419121 X-HE-Meta: U2FsdGVkX19or+FDZfc8UPXWamtn87YuChi2Tjc/PmkpBKDNh9m3hbgKPiBATf2Glrv5HkxvSGJzWyAKUNUIvCf6wjBBI/gD+VI4HEvC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QVumHhuwkLEpTTKbb/Vap1WGW9qjjdvQLZ3PO/2wT+e+gOvY5cZgsEW0Lbv+YVbMTZDaje+Es/I7gKCizrwCQZzW1j3UlsKA4B6EXniYwOs9XePQwvAbzQRcLBT7+xbOE/yKSW4jDWEtFneDeiQ51fRlIhHF8iDbLy2Q= 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 | 102 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..9932f21b0539 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,104 @@ pub mod flags { /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); } + +/// The kernel's [`Allocator`] trait. +/// +/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffer described +/// via [`Layout`]. +/// +/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on +/// an object instance. +/// +/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design +/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind +/// of `self` parameter. +/// +/// # Safety +/// +/// 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, 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)) }; + } +}