From mboxrd@z Thu Jan 1 00:00:00 1970 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 0341AC52D7B for ; Tue, 13 Aug 2024 12:34:28 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 619A06B0088; Tue, 13 Aug 2024 08:34:28 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5C9D86B0092; Tue, 13 Aug 2024 08:34:28 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 469FB6B0095; Tue, 13 Aug 2024 08:34:28 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0012.hostedemail.com [216.40.44.12]) by kanga.kvack.org (Postfix) with ESMTP id 2A3516B0088 for ; Tue, 13 Aug 2024 08:34:28 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id C1DC2120684 for ; Tue, 13 Aug 2024 12:34:27 +0000 (UTC) X-FDA: 82447165374.14.536C1AB Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf14.hostedemail.com (Postfix) with ESMTP id D02E810001C for ; Tue, 13 Aug 2024 12:34:24 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=JTGVZdeT; spf=pass (imf14.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=1723552453; 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-type:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=X0UT0l+oVCD/1w9Dry6fICefyyXi+D5l/7biGBmj9BM=; b=ZQ1dZL8QXs1sVMgTRnCMZV989Bpubr+UdWCc42+SICQM6tTpyTLVLLYxLVsvuX9oYxbqPO eNugBSplOymdwfkfZUO5PYaT5F6/SroRzczjBxTIcDfEw3Iftz4pKYp7aPsf1E4PTnFQ+O cgVo1nlj9YUEgY/zkIjCbq34OtmY4cU= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=JTGVZdeT; spf=pass (imf14.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=1723552453; a=rsa-sha256; cv=none; b=ENI9mIWtg2KLpQrhV/KwsZrZNfcLew0nCspX6Ql60YU4PaOeTswguVu9qHjFGIixOWTWQY /xHABBTUNmLpNgsSzE8T8/IZSm4UvHo3PJLfO+apIO5SscKfKMrsZT/eoDYsx02K43K4p7 eOklzL8D8sQyHf1vTMoiMEUIa0izp/s= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 786A1CE129A; Tue, 13 Aug 2024 12:34:20 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B3248C4AF09; Tue, 13 Aug 2024 12:34:14 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723552459; bh=bW0pd426CfLUr0gi+Md4bSFtw6NDJFfo3qyLIOLPANA=; h=Date:From:To:Cc:Subject:References:In-Reply-To:From; b=JTGVZdeT5cNJ+af6GmRV2AXhB2H9XutFlGPOCxHJytWGs+RH7Li8s2BHhpU6zUrQE PtMnCkSYVEONS9ZWQRbRqD4frk0zOMQtORoXiPhKLnlBGIAtexPUbGmr3Hb3iI1U+Q ri4HQB9cNi4BP/ROjk3C58RvOT+JJt0AiYdmOYQ/n7rPfSrs4XXXrvzq5aE2R9EHfG 2VyNNVoczd38f0aRzb98on10qn8IXzHJS+CzmL+lEV26V+4nMOZNI9wdKSQSZRLLlw kNMO2ZpKd07SOkUi7QSIaClnOxKBiFOBqW5Ubr6YX0ayH5rGfKcAYf+K5jt79km/8j lBa/GS6XDzlGw== Date: Tue, 13 Aug 2024 14:34:11 +0200 From: Danilo Krummrich To: Heghedus Razvan Cc: 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, 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 Subject: Re: [PATCH v5 22/26] rust: alloc: implement `Cmalloc` in module allocator_test Message-ID: References: <20240812182355.11641-1-dakr@kernel.org> <20240812182355.11641-23-dakr@kernel.org> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: X-Rspam-User: X-Stat-Signature: tsmjrfwkaxkquywzucduzgyoidpzabym X-Rspamd-Queue-Id: D02E810001C X-Rspamd-Server: rspam11 X-HE-Tag: 1723552464-703398 X-HE-Meta: U2FsdGVkX1//HaYpbNXTQKePfvsoe9YkQ0j/d51tTbJfab3hEjur7S7fG5ywXsWz+cDE6CUuvioJjbaZq3CaKjq2cwqFY3vQc5YTZIVyo6L1q1jdIzFNU2rQ43cvseyh05eKAS7uKBIkjZE1T4rz1lSqkBPRmyXkCotpBQfyRm1V9gnmIs+6VQdvTlskvTBwk3pw1l5fzT9D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BV/ovNQH2wvfqksoGqume8W8C33e2UqN9bHz3Xj94iRff9GF3RqZdp3AYoSD5TKV3cdhLqk8DK9wyO3grKbDdHfMtUma6WE6lCqoNyMp4pauOWA= 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: On Tue, Aug 13, 2024 at 07:07:46AM +0000, Heghedus Razvan wrote: > On Mon Aug 12, 2024 at 9:23 PM EEST, Danilo Krummrich wrote: > > 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), > > + ) > > + }; > > + > At this point should we free the src? Or is the original pointer expected to remain valid? Yes, we're indeed missing `Self::free_read_data(src)` here. > > > + Ok(dst) > > } > > } > > -- > > 2.45.2 > >