From patchwork Thu Aug 1 00:02:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749343 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 D875DC3DA64 for ; Thu, 1 Aug 2024 00:07:20 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 63AD86B0096; Wed, 31 Jul 2024 20:07:20 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5C3956B0098; Wed, 31 Jul 2024 20:07:20 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 43E256B0099; Wed, 31 Jul 2024 20:07:20 -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 23EB26B0096 for ; Wed, 31 Jul 2024 20:07:20 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id E0946A07E7 for ; Thu, 1 Aug 2024 00:07:19 +0000 (UTC) X-FDA: 82401736998.16.DD45FFA Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf21.hostedemail.com (Postfix) with ESMTP id A529E1C000D for ; Thu, 1 Aug 2024 00:07:17 +0000 (UTC) Authentication-Results: imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="DG/yCAlC"; spf=pass (imf21.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1722470810; 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=mJELk9aAnwioKgHChjfu0TpdI3TImwGpczRJrfMaEfs=; b=cWq3z3iY2IMwOz1OKlhuey/3dRDyCTPuk6I4vPqdtVabMA4wpRDpR9d05/FtMQ1fJrlgjw FM0okH+YDtsm6d4YWEMW4T/DzHTEzV3qBfCDGUF/y7lw+RcDoni6j7N/hFUQxuzvH/DG03 /i8ljT9et54Oi8/ZLKhmZZpg3PuO2PY= ARC-Authentication-Results: i=1; imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="DG/yCAlC"; spf=pass (imf21.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470810; a=rsa-sha256; cv=none; b=kC+L4v/7rUqtrkMP5l64gPWnUEKnQIwTJLPbpI6uZtIWzs/859odfwo0/dcLgM89cGsvc0 Ht6FPg5jHJHHdQFcPwP9QDExGNQ1w9rHQ+5yJRp2rd84rgKv5m4CvsnosbHmvi9Tx5Le+9 WrrZHeXlDihtnvz3KCITra3mDmmOvww= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 08213CE186A; Thu, 1 Aug 2024 00:07:15 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 40F03C32786; Thu, 1 Aug 2024 00:07:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470834; bh=0w3mioTnyHncnDbTDnqArHEDkcmV3wgJvYOvZszLfu0=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DG/yCAlC0W0UoH0gBjbQKLyIz1lq+qfvgUQGa2czCTNVyuX9Ygbi1vodeHPhP5gNg 9ZlEHV/epF+rc/4PywoBB2iRQGZLsxY8brfKti3MtPxy6lBjTvGFKzJFMRcb/FDnK+ 6/VrTFUCm3NXzq45y3+ZVPMsuZN5w0Mlm+M2b8qVQuX7YZkLZOpl7b2AZ/zWD4tMjK FkgYCouDy/ahsejtOmAsvtkZDdrRc9HJxplYYvC1+3Kh2TT/SQr+S1nq0YClOI3cy0 kAIw02uw43vQHyLdqkbE6LPFC8HAfxcPZx1XCgioanIkZUzAIMeZDpsINPR/tJR591 Q3MsKF+c8hGfg== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, acurrid@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v3 04/25] rust: alloc: implement `Allocator` for `Kmalloc` Date: Thu, 1 Aug 2024 02:02:03 +0200 Message-ID: <20240801000641.1882-5-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: A529E1C000D X-Stat-Signature: qfxq5jr6cubkgj43m3pmg473okc66qwu X-HE-Tag: 1722470837-315727 X-HE-Meta: U2FsdGVkX18JZ0ZTWcNCsXGxjl7o6pkXfX3h6jTTioOo/rqCwM2zNHnCHlqwSghQgaJatOdwthty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W9uC2sT58XOcN3agMFdHrDcsXVJ7q1r2NCASNGjZLl2n2EuC2v8S2f+HWtN8TTEorUbrHuyO06EoPvxE0U57yFLvCi9KrVwn8WxbK8yN09n2hW5qnJBhWwaOD+Scn1/m1UNPbdsM0A== 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 | 66 ++++++++++++++++++++++++++++++++-- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index b79dd2c49277..8cabc888393b 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 10774c51ae26..397ae5bcc043 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -5,9 +5,18 @@ use super::{flags::*, Flags}; use core::alloc::{GlobalAlloc, Layout}; use core::ptr; +use core::ptr::NonNull; -struct Kmalloc; +use crate::alloc::{AllocError, Allocator}; +use crate::bindings; +/// The contiguous kernel allocator. +/// +/// The contiguous kernel allocator only ever allocates physically contiguous memory through +/// `bindings::krealloc`. +pub struct Kmalloc; + +/// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. let layout = new_layout.pad_to_align(); @@ -18,7 +27,7 @@ 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. +/// Calls `krealloc` with a proper size to alloc a new object. /// /// # Safety /// @@ -39,6 +48,59 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F } } +struct ReallocFunc( + // INVARIANT: One of the following `krealloc`, `vrealloc`, `kvrealloc`. + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, +); + +impl ReallocFunc { + fn krealloc() -> Self { + Self(bindings::krealloc) + } + + // SAFETY: `call` has the exact same safety requirements as `Allocator::realloc`. + unsafe fn call( + &self, + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let size = aligned_size(layout); + let ptr = match ptr { + Some(ptr) => ptr.as_ptr(), + None => ptr::null(), + }; + + // SAFETY: `ptr` is valid by the safety requirements of this function. + let raw_ptr = unsafe { + // If `size == 0` and `ptr != NULL` the memory behind the pointer is freed. + self.0(ptr.cast(), size, flags.0).cast() + }; + + let ptr = if size == 0 { + NonNull::dangling() + } else { + NonNull::new(raw_ptr).ok_or(AllocError)? + }; + + Ok(NonNull::slice_from_raw_parts(ptr, size)) + } +} + +unsafe impl Allocator for Kmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc = ReallocFunc::krealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.call(ptr, layout, flags) } + } +} + unsafe impl GlobalAlloc for Kmalloc { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety