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/GFHcdyf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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) } }