From patchwork Fri Aug 16 00:11:04 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13765303 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 A1CA9C52D7D for ; Fri, 16 Aug 2024 00:14:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 2FEB18D0026; Thu, 15 Aug 2024 20:14:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 286738D0002; Thu, 15 Aug 2024 20:14:25 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 128298D0026; Thu, 15 Aug 2024 20:14:25 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0015.hostedemail.com [216.40.44.15]) by kanga.kvack.org (Postfix) with ESMTP id E1C818D0002 for ; Thu, 15 Aug 2024 20:14:24 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 9BDAB41565 for ; Fri, 16 Aug 2024 00:14:24 +0000 (UTC) X-FDA: 82456186848.28.DCF9386 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf09.hostedemail.com (Postfix) with ESMTP id F1CF4140022 for ; Fri, 16 Aug 2024 00:14:22 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="co2Cxo/8"; spf=pass (imf09.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=1723767189; 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=0tTlidtmmOQAWjyw9vqvZw2qilcOf97wHHt0+kf6b1c=; b=PmZCMJTV11KKhJhtzhG/owe6N7JtAoKy3vUm43j9Ri9V13xUMBV9zIhnJcoex8d2bccleQ WwOHDS+ov7k8LJk5N8zAI3HRuMMtufwwbwzEXTU8T4M1tmMFmkIQzYQ/siw0zArRbS/lje bUpOlcSDPnUVYaCNhq9f2pg857IYAmM= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767189; a=rsa-sha256; cv=none; b=zp1q1OVfLHddF6WkM4Ahq6fiCIR7Yf4KYs/7sAgdNtGsYZ602iW1/ONow1b67ys3DR7joW EKyQSL0/ObmkyqvaQExGBQyH1POqRzrKD1xMz/2YHYXKj9EKddb+4Cz2J+wfxO4kBRUp9U IgbPHyF/W/D9q+9C/FUp6tSYWhVFuNQ= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="co2Cxo/8"; spf=pass (imf09.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 Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 3ECCD62040; Fri, 16 Aug 2024 00:14:22 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 181A4C4AF09; Fri, 16 Aug 2024 00:14:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767261; bh=bQS+R7rUpUCrHg7w7Wbs4uih1faovavqPA1dZK4lOE8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=co2Cxo/87VbXdBwuqojeKmzm23LO/RIK14f+FTu+LF+rprPRCXT1tDINHnYhyjnCt SMao0AWgVzzXC3OLvkzmIycax/C7a0Me8IzH4XSHoSVYrGzD+0Ly/fgqfy1UB/L4XP yDLZfq7gI55st1vASvGOaQqaHp2mfSwwB2KQU7C4Qu2+qz5DYsQA0054VeSdBfRSdF tOwcSDxZ1RJ9zwxXORqx3C/RBxVpHy9cObcopIwOK4aRSTV13Ggief/V6FpgiMOiFK w1JrC6/279Gd+5vkJED2Rq33iguFOL3+0v7aWmKz0376Sxz9W8WoE7eWYmB2KOY+TK 0Ieyst9xxUVeA== 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 22/26] rust: alloc: implement `Cmalloc` in module allocator_test Date: Fri, 16 Aug 2024 02:11:04 +0200 Message-ID: <20240816001216.26575-23-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-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: F1CF4140022 X-Stat-Signature: mace3giks8isi7rb1upn4uwbr1ex4c91 X-HE-Tag: 1723767262-528652 X-HE-Meta: U2FsdGVkX18/estnXA9O/V4qGzejed5GhaGg3FaHjAieGLIiMsodsLVuPD0Z+VVDFsZD2k4fhRyb1ZmolqTrKHQMqVWoDHDSr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prSw+c3bp90rdtMZbaUgeIJLRgecbsKkF7mMXIhSI1iexAFc4r6KRgiS3mwxorBRsD/JP4+NMw4jFC8/kNj+ICLMKQG5sGOOTZmNtC8r+78lRRKEa8XmUXc1uC5ULqBHPDQpve2FjaGfKX3cueNru9ZTBmfw9F2ZQgz3rVKSTs= 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 | 178 ++++++++++++++++++++++++++-- 1 file changed, 171 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 1b2642c547ec..7fff308d02dc 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -2,20 +2,184 @@ #![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; +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. + /// + /// 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: Advance the pointer by `min_align`. 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<'a>(ptr: NonNull) -> &'a 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(); + + // SAFETY: The `CmallocData` has been previously stored at this offset with + // `Self::alloc_store_data`. + unsafe { &*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 src: NonNull = if let Some(src) = ptr { + src.cast() + } 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) } }