From patchwork Mon Aug 12 18:23:08 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760939 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 09301C3DA7F for ; Mon, 12 Aug 2024 18:26:11 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 89AE06B00A8; Mon, 12 Aug 2024 14:26:10 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 84B076B00CA; Mon, 12 Aug 2024 14:26:10 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6C0F36B00CB; Mon, 12 Aug 2024 14:26:10 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 480676B00A8 for ; Mon, 12 Aug 2024 14:26:10 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 013071C1AC4 for ; Mon, 12 Aug 2024 18:26:09 +0000 (UTC) X-FDA: 82444422900.06.6E05865 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id 5481F4000E for ; Mon, 12 Aug 2024 18:26:08 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=t3GTSs4f; spf=pass (imf01.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=1723487098; 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=DFAzb6DJqs6ZxjZtU3Q4WqQbuzj8tvl1Xymcqb8CjwU=; b=7lSiD5tBv4Lk7fBeZN9Z6GMC4G+kIOizPfWRHWR5zCFoo4aRn5NRorpZcC0PMMyq79YR0B GX1/TsjOlg1QcC13yFaPN1VpEQk685+jntanuU9IbpfleGPBTm34ZmPABWlLmseJ3tAf8i QuYno2iUmoVtogDsQ85Ro/L4ybJRSy8= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487098; a=rsa-sha256; cv=none; b=8V3Z/b4rWEV+HlDtsUchRGFjimNfQwXi7xBMLA4pDpWxB4xOspMVwE1f4VuZ512N3JxI+s tHBG3vf+MYuUWGun9RHq9HqAkqZdBHiHcTvihfj2p8nu5NIOA9Bvn7OGbORKn97m8ipi2v hick6JVq9LPTj2TiwihebKD7PLcCutE= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=t3GTSs4f; spf=pass (imf01.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 88528611DC; Mon, 12 Aug 2024 18:26:07 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4597DC4AF09; Mon, 12 Aug 2024 18:26:02 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487167; bh=LmCPyxbPqQaXkN27gPwAem4xdq5E92W3egezxGjW9eU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=t3GTSs4fGkfZXM4GLdYx9cwZTTgUpoGrI0FQ223qj2qmxXFuUgIMzF4mwsPA9A3yy BKqXYJAHNzPxxGAjf7IjZg4vgB+VEqDp3cwR26u8qhpueJz5nMUkX4oD5+lJnEUjlo Trc5yTqDP1rBNSwPP63aaqdyBmLmnuG+/DrA2WGrn25kZ6YYpOLVwaHaCA01tpcGLd 3tZ2/FjPyFZPZLiVItLdCy4hktujV38iB7QGnGR7ZmEjK6oqIlsYfe40y4V6BNrkfR X7F2nplRpLsGngdaeXX6A6GfmvQD7B4Ijwd4cvNhZi2oqIfdv9xtqgfh5JUIb4zMBh 4CA5NswVVefPA== 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 v5 22/26] rust: alloc: implement `Cmalloc` in module allocator_test Date: Mon, 12 Aug 2024 20:23:08 +0200 Message-ID: <20240812182355.11641-23-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240812182355.11641-1-dakr@kernel.org> References: <20240812182355.11641-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: m6dfdnbxh6ket46abcyhxfx1ckzeoxoo X-Rspamd-Queue-Id: 5481F4000E X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1723487168-631181 X-HE-Meta: U2FsdGVkX1+Sr/Gblbp4lWexF0PEH1X404T9tDC4F3s+BHDB2siszS1LtDoAzrNKStcZXBNfKE89vfHUS3HZzStOfj3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/uFTWxFx2Tsu/OtwNRzdWAt/HqyPfBHUL9arfW5eh+WHPtYh2x7lLGjdKFmBmZ//m36GoWHtCO4VfsbEwCEGP2VmQJQJBehCn5vDso1bgsidYEjy0ObVxVy3AbqfyHfBgYBiw+a1Wy2qR5hzj/xJ0BEPfurPgcxomC0L4AtF4G9dtKpKmmujSjUOoIVi4= 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 --- I know, having an `old_size` parameter would indeed help implementing `Cmalloc`. However, I really don't want test infrastructure to influence the design of kernel internal APIs. It's on the test infrastructure to find a way to deal with it, even if it's more complicated. --- rust/kernel/alloc/allocator_test.rs | 175 ++++++++++++++++++++++++++-- 1 file changed, 168 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 1b2642c547ec..7a20e64431ea 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -2,20 +2,181 @@ #![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), + ) + }; + + Ok(dst) } }