From patchwork Mon Aug 12 18:22:47 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760917 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 9139BC3DA7F for ; Mon, 12 Aug 2024 18:24:17 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E3A916B0089; Mon, 12 Aug 2024 14:24:16 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id DE9866B008C; Mon, 12 Aug 2024 14:24:16 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CB0DB6B009F; Mon, 12 Aug 2024 14:24:16 -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 AEC596B0089 for ; Mon, 12 Aug 2024 14:24:16 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 59D57C0377 for ; Mon, 12 Aug 2024 18:24:16 +0000 (UTC) X-FDA: 82444418112.02.F8EC201 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id A07E540014 for ; Mon, 12 Aug 2024 18:24:14 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Y0S8qU3y; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.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=1723486976; 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=2FD9Vbn5RGxp6wUveMNEi+OKaBxsoUkU9q3bQNxEhik=; b=Hx7aZcxCgGTrQi72FRNF/4tW8AUYBBp5WqkpRbOgc7rkSoyggxvBCLq4PM/Ls48LSFDwUe 9JDb+TRP2q4e/fulsca5mNpI2fTNXsG6RUGz0T/mqZXgNVD5QQbFVqV52nMrFiD7kxCBGj QQJGxnlc9ZmJ2ITK1bQpVGJ1VJxdxAo= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723486976; a=rsa-sha256; cv=none; b=QZ5S3doI22TlwuIt5vT8rcpYuIdTK3HdDYFtIGGNfuu56Hqb9E5Y+bD6o+jDae4uuXNbTv aqLcYUsm6kOLPDOc5gt5pdbqgGJYFAkj1wqA4V9drPaM87twNYDN+AvgWrZ+DyuvyiVWEu wflXqYG+N9DwRALfmY+EBgldDtVLLBo= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Y0S8qU3y; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.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 AFB1B61369; Mon, 12 Aug 2024 18:24:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8F796C4AF0C; Mon, 12 Aug 2024 18:24:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487053; bh=M1Wwvc1PMQiy2tSYLyMdNK6lKzi7oyHYDv/dPN7vzzs=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Y0S8qU3yW9xyw0FV2WFxe5tJ6xfV6A4RAetYAlao35rcuYSGc3kxSqYYOSIyvSGlg K8gPFxuu8eGEvuDuHp3ZV3P0n7swgSZjhvDt9zUqOVkjrhDqRVAi1HStM8lFhN5MNr nNuR0gbj94xcaN4MVpSpjulAxr4U5pGB7IsCuEUSxTatJDviLEojsaGJv6I80fmkEM wkossGl3of7NM3pu7JsEEQ7ht8amVK9+dr2vIUWHKOBt8uGBn/HHv21Z4IbjnTqNGD +AEzlU/2/bQ5SghHXgTa+OqtHrdSQbt2bzs4J9GWPWPGrO5IvTd9rPEFopHNBoBKWX 5l+1AxcAqop7Q== 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 01/26] rust: alloc: add `Allocator` trait Date: Mon, 12 Aug 2024 20:22:47 +0200 Message-ID: <20240812182355.11641-2-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-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: A07E540014 X-Stat-Signature: 6dfuadcy7tjizh79zbqg1je7tqgy3r9y X-Rspam-User: X-HE-Tag: 1723487054-209528 X-HE-Meta: U2FsdGVkX19fafhnwdYtbbhS/TA5rTFeGPUQdvzHOf8wCXJQfsGcuqOyVcYMq2u/recZbrMdLRcOYnr0U7f24hWEPx4eeQS+ZklEi2ldhGKZZmIRNR8H0jIlsgL+XUX6PMpKMQxAsGj0iGqof+r3Yw+gq/HXcKMjoLKlEPr8aRs0ZpAowQEMmOCufLfUb+8c7d5GvIGXpRDzdt8jHkhwWBhMnLyzs3vv4GeGyfwPSVHK8C/Q5c6b/HX1unmtOyP3iocRRYnD3TKReOQcgj6C8jKmoI+APgfL8eSg6K8aoYH8XVsPgd3tpAim3L5gh+4sut7o7RaOLuliAqAYtBNiPofs74oWw5ZjBgC7z1ki0/OL476fd1K3KGNEuA343abJ2IU/agQDGQgaPNNkj0Rh+DMnPZyJm4sCNEsoLMYLklVcfo/mCB5BB1/poAJpyS+z3NVAVpqxlz4j8tmn/LHyFY+H8xDGJ/6O0LuwXPhPUN9HU6GmRXV7Nj2WvXpEU1jXZspy17sHOmIEw2nT+TGD20hBv7jD8oQLBbnCpQVdUJK62DDd+LrG01Fc+BvOa6XcKyHoIY4tVB+OS+4mu5P8cbMiGa3KDqfC3CPkwvYWHuOznfXX1VnRPJ7GwucIZpXnaE1ds6Ul5qqEC6Q2UPLtHSNNJyHSXA3xZfxFtvMP2phOEbYpZr1De0Ie/LIZE541+7ufKT+/JdatM1FwlsMbO1DV4EnogiZf8hcap7aJdZ86Yl/LXioB3pDtZlXMKic7qSfcG3NZF6VGEwO4Ud3BBGnMvEwrp3SUFI39CgKL8f/q+KRtVeAM0IDIQ/37e+tiIWGwCErowBQtCbf+TjQcKg9d5Tp4F9BUXuc9qzKssVHzS2SXRuJWx54G2HAXjGnqR0h8g9uXJpDw1BJ352Rb+Nd20bTk4cZYOMdkdcH6HO5oLb2fFmnOef6VlTCK0nIhZb0Hxke29o4MYGIK2qJ 02/B99+1 glF3TU9+0arboyZfSWViylVPwC1zOwwSk05QwqHM8PwOFHzsxCWzWp0yTPU/94qa/FRj6VEINfKDsZdBw1pKqDHfsHnINfzVOFbW+ykx6OlZ9dkoVvlr/vlPYNaylSxdQ5YkaUQD+D3wII9AOWhMydHM9KAh2G7GfTmX5m3CnSO0jwscQ+okOIsraCf9eWZ+P3/vNiNDuLVQmrq4IIqyHFLBawrcVfDqqe8X5G3A9VOpIPzjV2fP4c3jyvfM8op9lhaPRYBz+x0dRyVVAgtuzInTw9KfqnuSZvxfvbmhY/iKdvYmtrXJgWEqDMHbrd+IWTIsdqNOo9/t3hTo= 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: Add a kernel specific `Allocator` trait, that in contrast to the one in Rust's core library doesn't require unstable features and supports GFP flags. Subsequent patches add the following trait implementors: `Kmalloc`, `Vmalloc` and `KVmalloc`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 81 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 1966bd407017..194745498a75 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -11,6 +11,7 @@ /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; +use core::{alloc::Layout, ptr::NonNull}; /// Flags to be used when allocating memory. /// @@ -86,3 +87,83 @@ pub mod flags { /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); } + +/// The kernel's [`Allocator`] trait. +/// +/// An implementation of [`Allocator`] can allocate, re-allocate and free memory buffer described +/// via [`Layout`]. +/// +/// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on +/// an object instance. +/// +/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design +/// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind +/// of `self` parameter. +/// +/// # Safety +/// +/// Memory returned from an allocator must point to a valid memory buffer and remain valid until +/// it is explicitly freed. +/// +/// Any pointer to a memory buffer which is currently allocated must be valid to be passed to any +/// other [`Allocator`] function of the same type. +/// +/// If `realloc` is called with: +/// - a size of zero, the given memory allocation, if any, must be freed +/// - `None`, a new memory allocation must be created +pub unsafe trait Allocator { + /// Allocate memory based on `layout` and `flags`. + /// + /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout + /// constraints (i.e. minimum size and alignment as specified by `layout`). + /// + /// This function is equivalent to `realloc` when called with `None`. + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + // SAFETY: Passing `None` to `realloc` is valid by it's safety requirements and asks for a + // new memory allocation. + unsafe { Self::realloc(None, layout, flags) } + } + + /// Re-allocate an existing memory allocation to satisfy the requested `layout`. If the + /// requested size is zero, `realloc` behaves equivalent to `free`. + /// + /// If the requested size is larger than the size of the existing allocation, a successful call + /// to `realloc` guarantees that the new or grown buffer has at least `Layout::size` bytes, but + /// may also be larger. + /// + /// If the requested size is smaller than the size of the existing allocation, `realloc` may or + /// may not shrink the buffer; this is implementation specific to the allocator. + /// + /// On allocation failure, the existing buffer, if any, remains valid. + /// + /// The buffer is represented as `NonNull<[u8]>`. + /// + /// # Safety + /// + /// If `ptr = Some(p)`, then `p` must point to an existing and valid memory allocation created + /// by this allocator. The alignment encoded in `layout` must be smaller than or equal to the + /// alignment requested in the previous `alloc` or `realloc` call of the same allocation. + /// + /// Additionally, `ptr` is allowed to be `None`; in this case a new memory allocation is + /// created. + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError>; + + /// Free an existing memory allocation. + /// + /// # Safety + /// + /// `ptr` must point to an existing and valid memory allocation created by this `Allocator` and + /// must not be a dangling pointer. + /// + /// The memory allocation at `ptr` must never again be read from or written to. + unsafe fn free(ptr: NonNull) { + // SAFETY: The caller guarantees that `ptr` points at a valid allocation created by this + // allocator. We are passing a `Layout` with the smallest possible alignment, so it is + // smaller than or equal to the alignment previously used with this allocation. + let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), Flags(0)) }; + } +} From patchwork Mon Aug 12 18:22:48 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760919 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 EF3ABC3DA7F for ; Mon, 12 Aug 2024 18:24:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7F8726B00A5; Mon, 12 Aug 2024 14:24:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 7A8146B00A6; Mon, 12 Aug 2024 14:24:25 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 6232B6B00A7; Mon, 12 Aug 2024 14:24:25 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0017.hostedemail.com [216.40.44.17]) by kanga.kvack.org (Postfix) with ESMTP id 3FE0B6B00A5 for ; Mon, 12 Aug 2024 14:24:25 -0400 (EDT) Received: from smtpin05.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id EDC271A0351 for ; Mon, 12 Aug 2024 18:24:24 +0000 (UTC) X-FDA: 82444418448.05.40AAC68 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf08.hostedemail.com (Postfix) with ESMTP id AB990160008 for ; Mon, 12 Aug 2024 18:24:22 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=c0I8hd5A; spf=pass (imf08.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=1723487008; 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=xjsKxaqIZJM0tVNeKe9Muttd7ZI8h4gkDNAWBc8bk0w=; b=RLW58nPNktFZacTB1sHLXUdtY7IR5gzkVIvGfiSy6T5m3djaBJHptLGZFLSqKjHuLD70CA rHeITMsQOJLTBpArrxWGhUTBgWNLeYYgVrK6Yse9id8eIB0TAI+jkHtMjgxwtIJlTH0ysz /ib/VAKcQMoKyn38QY20NdtOQJ73kpU= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=c0I8hd5A; spf=pass (imf08.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=1723487008; a=rsa-sha256; cv=none; b=tKv8yG1koLIWoZ8vEecl7fhWg3oCVBRkBcCNoRWx1M1bfNmAhRB2A1Nr9oDlUv+gNhDCk+ M5awFBW2oaPa9gAnI28eo0TXh6pWvVogLXC3LU4AJAkfEMTP6uWuDPjt8VJ/tjsaRAaAlP hR63KbXPYbReqM6oTc46XDD9S35B55s= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id B80F9CE102E; Mon, 12 Aug 2024 18:24:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id F08F9C4AF0D; Mon, 12 Aug 2024 18:24:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487058; bh=p++mQr6O15JhVUHtMmsU1D7fc1KQnWeRmH3GDyn4naw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=c0I8hd5AqEtUJ1AqcltnJQJXgDifadIagb8OT4ht7RND3/LIpX13gvQjzt3gLQowI ftjf2eUBi+kRnz1lX7eL9vGAeiEQ8VSt/93xhlmq3bo51SkTTtLhVlA1JeSJlhL1vO kKy1fu1ZpAWRTSx0A6dHnPwjSFST7YO372xKlpVClxYIjCcUPHvkSj+fQ1ApyURzYL iEsA/zOqK25c8hP18hXK60sIIPLcYcpYrmTHnk0vQhpz7wJPKOG5cBX2AXOvB7Pt59 OuPvw6w4Pra2zExwy8Z5Xaqski4YFdaIJkkvFVea5Z2LMfKRfUtJYYqefeQFClV0Vt gsbOh1+Jy/6+Q== 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 02/26] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Mon, 12 Aug 2024 20:22:48 +0200 Message-ID: <20240812182355.11641-3-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: gigp4de3rr8yxtkhikh5mpbxhxu9pn5e X-Rspam-User: X-Rspamd-Queue-Id: AB990160008 X-Rspamd-Server: rspam02 X-HE-Tag: 1723487062-813833 X-HE-Meta: U2FsdGVkX18Cz24RM3jpWfX6eewh7LJ4Ihp5/BqKBKXiG8HlROGYlWOPub8GZYHVxN9VJlkSMkP9Asjm0TP1N4kqLs2H65fLQdcfOS2fi0cd9FKyhiCtmsyPcreRk5IfOATfoj8Ne/fRWFDtzDTIRReVekS4gF8dvasOFxIfuaF1fdlNmpqRf9sixxG/O31trgpzNp8YHIKRLo0PNp5gVqu9SBF5/T0deSYYwXezSuppcsDKLsyyfe9uOHxxuISWvxr7mPPkikVpvDE4lE1/Bm4RkL6bHaMdB7uBe5L2dioHyucfrEznCFcvXUNNSFo6vf0PJ951R7JhnQAAXJHu/qKiK10svcx6SsaOjxzbkRS6shFk0K7/5+3Pij4XkB6MhCppp6NV7gLnurKV1O+atWL4X/vhfadsy6KT9i0b5XDSaLZTRoNWWb3XkUQFbntgk0W+x/ryyM1vq1A3XqY0Bzm4DPiqUR+DsLAMDIE22+BrwZ7pgDpupctl0MBeU+M0lSkIxFNzswKYVPJwBiDcu0AJLo9IwXE7DLNRr3hwGzf3huNk5TU/Tfcnw9HZzzWcerSLd6bqv7T0XcmKsDkCSR3cC7t0XkrWP3unu0D7Wz3kV4/EVMwrMPWkDOzOfG+u0+X781JFJS/nEBvtevvyWqhjolREx1Ujx+aUrGT4XdoxWT8oiKL8a1ka6vJ0kmtHtZ5s6ViX1pjd0nwa31n63HAp1g+Kl3t/uVNupmMyOCYHu9jtMvsxB4h/6SMCe/xEk1vzzuUJT5X0pGKifcS1GM+IJnkkHBv7W7UoWF8SM14e3vkyrkyhoB9BAAC9YTPYWR6O71E3kyqL/3oOcxLDu6k4sMiAT3rGwBsS/nWWOvPG9s0JL3PrAGJlGtWaZa5KmE/gs8rqTMFmHCP0CmfoXyQFMs6e2ZnqzCGstHZ920AY4EqtSTC18t1pl/Cy5PWKFrhPrAyeX0gc+Ysudyr CohEN3Pp ckAN1IBFzBKHsibgt8moh+eC+kCWLLezv8mHbMm4K1KnZwTplItjQpkWGtw8GKtHwUE6eG7rbaPw23ZWFdU93pRr4Yf3T2inwdzed/FCx+jV64RZ7u7ep91wa2BSS9wclWmGUfcSZEs5d8YT9gtQBp0PFyAgpuYgQYsu9lPOEfqhuLu2hLwxBSFYFPEAoqdK/t2GLnngXfw1vfmnvgwuZ1Kyw9Bx/j0SXdHLZgQwHnlFxXNKSnRkbt0b+Zq+7OrQIE7hI7surnaOSOXzn/vc8rH16BxFMsGPGdzel5PLFUiJLZV6GolAxNH8W8/smznS/vj6tT3laIJkX0wTUYj1FMl2f20TXDAkREqhQ+u1milgVnhUHM5UzPq+MVQ== 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: Separate `aligned_size` from `krealloc_aligned`. Subsequent patches implement `Allocator` derivates, such as `Kmalloc`, that require `aligned_size` and replace the original `krealloc_aligned`. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..c83b6dff896d 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,6 +8,17 @@ struct KernelAllocator; +/// 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(); + + // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` + // which together with the slab guarantees means the `krealloc` will return a properly aligned + // object (see comments in `kmalloc()` for more information). + layout.size() +} + /// Calls `krealloc` with a proper size to alloc a new object aligned to `new_layout`'s alignment. /// /// # Safety @@ -15,13 +26,7 @@ /// - `ptr` can be either null or a pointer which has been allocated by this allocator. /// - `new_layout` must have a non-zero size. pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. - let layout = new_layout.pad_to_align(); - - // Note that `layout.size()` (after padding) is guaranteed to be a multiple of `layout.align()` - // which together with the slab guarantees means the `krealloc` will return a properly aligned - // object (see comments in `kmalloc()` for more information). - let size = layout.size(); + let size = aligned_size(new_layout); // SAFETY: // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the From patchwork Mon Aug 12 18:22:49 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760920 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 EC132C531DC for ; Mon, 12 Aug 2024 18:24:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 820226B00A6; Mon, 12 Aug 2024 14:24:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 7A8BD6B00A7; Mon, 12 Aug 2024 14:24:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 622FD6B00A8; Mon, 12 Aug 2024 14:24:27 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 37A756B00A6 for ; Mon, 12 Aug 2024 14:24:27 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id ECB45140332 for ; Mon, 12 Aug 2024 18:24:26 +0000 (UTC) X-FDA: 82444418532.25.C5C6862 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf22.hostedemail.com (Postfix) with ESMTP id 5DB97C0015 for ; Mon, 12 Aug 2024 18:24:25 +0000 (UTC) Authentication-Results: imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=jwDjo9Cz; spf=pass (imf22.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=1723487010; 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=tiEB2Pdo1LxqTZ5vaW5IVzuQ0SoXBJ6b7ud672N8eTg=; b=KMyh8NyQzJypaKVV6ZYp/tvtawk+4JDDbZ+XbJnxgkZXbqzjOqvuEPjULF5E3aeYXKpjby Yaj02sdXgFajcLVknqRCkW0G6fEFVlqBBPgjYIF3Ieoc2O1smsFMgXr6G2vEwVsRTDrB+H X2vjLLQoB2+g+/dQ1QXnTrhQNkmQQ8M= ARC-Authentication-Results: i=1; imf22.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=jwDjo9Cz; spf=pass (imf22.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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487010; a=rsa-sha256; cv=none; b=GnS5blNw3EPh4LD949M7fKW/hf80SXVK/OGUKopn32HGINOpeheCPVjIWDvZ7OwUy72RkD UJ+Gy54vbl3uGHL5Og/QFPoPSl6AE1H327A/TD5kXIMNT+VfNqyK2J7nNzKDYmKB/PQozF Z1B5WmkGqMs4BaqgQKam+1V/bWecnus= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id A15C861465; Mon, 12 Aug 2024 18:24:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 63A19C4AF0F; Mon, 12 Aug 2024 18:24:19 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487064; bh=8oAuOdisYUjDdGnujzu+qdpGOC9b4wPMkAAnWfvuI7o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=jwDjo9Cz4msrN2OFv+80NjQx4rMmA203HaSKUMopmbA9GF9wV37pGy0wmAtVUds1f KMhgSVyZ3/x3j2p/33Ix6HNljGcAKQlS+dFv8JEmhsHX80rI7/JAXQKKrfMmP2e5tH TTHy+3GPqdb2nFkTn4mLZKS0VspwdWH3/BdIKLZPMkqeR2xc4tgsPcMLywfYnui0fN mILcDkSB2mO9sY5G80rk+PeTOoAPDCQz3Vxlv2N1H6RhptAoytES93kq/BrFwUJRCa EnW1AdyGLUeQjxjWCaTInoiz4pVCEB5o2ZpTdlTiAMi03PmlgvurTvgjpWC+2J4RC7 a9LV7QnrU4Ngw== 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 03/26] rust: alloc: rename `KernelAllocator` to `Kmalloc` Date: Mon, 12 Aug 2024 20:22:49 +0200 Message-ID: <20240812182355.11641-4-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: shfb3g8fznmr418rkr85ip7cb1wzqabm X-Rspam-User: X-Rspamd-Queue-Id: 5DB97C0015 X-Rspamd-Server: rspam02 X-HE-Tag: 1723487065-374123 X-HE-Meta: U2FsdGVkX1/WXcF2N6Y5hacxULs0EMC36FRZCOyGre8D9JEKOLKeeUcBk9UneA+3NigwWDXobove9HN220wJyC+To1sl0ttyxd9wJYrjljjuBIpGGarvvQzLoUab0PO2uIrfQPrlXdQwkcqK1CrphaQAQp9AR4JO9ypQSO1vVTn9PUmfWBj9TnN1boF9l8hGLdCZCEd/JPfMPSGucjluz44g6R0+VO+5a9/Tgke5sF94BlLRZJ9ea8rM/NGGF/UDby701O5HqtkafubPHasGbEnuOP5Dd65uV8TD+9KQhQ7S8jd/y45j8QSISJ/OmTmZOy86NqQycOnUsuEB08UPOGD/NtmS4VhFkD/BlP+PU/j+kD5jGc7Wpcigoib9SHUX6ENTjvytLQbHmjQDoOqqGVmfja2piaiPhzRGpC60xeU+nkPlIj36rOum77VRE4gG5cz0GYJOB5WhG08OUmOrfWg3qqgMJwCwz5InDjYRU0TYJseXiikbOiceoBBvdTrRGr1RrbmzYg4Mjxh8tDKjB1r6qcDOD8NaIGN3rkSIUUcpbvOe/VKbXD4vlDrMwRj7/UId364Q+RwOlSHbqJFy4h7fZC0lpE/TOdhXXru+Wmm/e9kwdc89PF8SosajeVbLT8vSKUAA48PJdDZJpZA4cIgMtRauVSbLaVRNzyQoEKKAsgm1JzBwineVURcSJwkqa0TU6A8dD6dbWiZBu3ofnpwQoQa4CkOScsS+1JrRyvVw/PPJ1qEElC1ikjCIwVfs+VURNou1IS+c8kx7f4ZFneCqnpYKv+JXUME/2I5Xx1FpMQGpzBJi1lPCzntHYDwYTDd1FgFgJfjOEvRO+BJIG6IWtyj8KYZ9bRIQG9RKC2IW+yrsTwh4gyvjAZwNCsf8qhoZkvd9dnvlASENPyrynnaLDVa7UC2Jxkp7GhzCeBV0MBRCnDktcHW4vEiExkqRMiDE4Twns/9GsWSC0iu 61lJh+u9 MxdNLsC5MwBQxW36tOAIw4AaFuNV1zqIiBpMFGIorzn2/MXBxlW0V0IKcTb+4/PRhdbOQQUG0iHOCRhy6rWot8PhfVtLL9+f/ULiUFS3EfQKYTZUXB84HmBn4f39TxdF19FrLce5E1kFl62DrAsJOEqd97abCjX0DiuSmxgpnqkg0e8l7O6cgMVYVaxvn/fuZl2AMgBZLSWFbTAIDzqi6gOEDY1lgqW+GeNSZjYpwqqxNIEaRFmVNye9AvivWiN4Lz1uOuDKra7GKhmTkx6BXPXnGN6UbgGN5ILdvlb89CI8hWOh63zt2tqUexGsd1sdhvAZKL3PGzLMcDgWyl6KfEZo0aJ0zL4DFLKmNv0Mh/aDfLE5aaUlhcNz6X4dhDR7s9twxS9RW8YXLOB6wxciJ/anZrIleiu2IsJaX 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: Subsequent patches implement `Vmalloc` and `KVmalloc` allocators, hence align `KernelAllocator` to this naming scheme. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Reviewed-by: Gary Guo Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index c83b6dff896d..e32182f91167 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -6,7 +6,7 @@ use core::alloc::{GlobalAlloc, Layout}; use core::ptr; -struct KernelAllocator; +struct Kmalloc; /// Returns a proper size to alloc a new object aligned to `new_layout`'s alignment. fn aligned_size(new_layout: Layout) -> usize { @@ -36,7 +36,7 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } } -unsafe impl GlobalAlloc for KernelAllocator { +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 // requirement. @@ -72,7 +72,7 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } #[global_allocator] -static ALLOCATOR: KernelAllocator = KernelAllocator; +static ALLOCATOR: Kmalloc = Kmalloc; // See . #[no_mangle] From patchwork Mon Aug 12 18:22:50 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760921 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 85730C52D7C for ; Mon, 12 Aug 2024 18:24:33 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 1B7D06B00A9; Mon, 12 Aug 2024 14:24:33 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 1676E6B00AA; Mon, 12 Aug 2024 14:24:33 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 02E456B00AB; Mon, 12 Aug 2024 14:24:32 -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 D89266B00A9 for ; Mon, 12 Aug 2024 14:24:32 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 9992B40379 for ; Mon, 12 Aug 2024 18:24:32 +0000 (UTC) X-FDA: 82444418784.28.5893A32 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf19.hostedemail.com (Postfix) with ESMTP id DB8C91A0011 for ; Mon, 12 Aug 2024 18:24:30 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ax0ovfo+; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf19.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487014; a=rsa-sha256; cv=none; b=vs7IUZ92zoyr2qwbKnY91nBI+gQZsi64sCf/bMwhpKpzpDJ4TLHIl+e766NWKMp1Kmhj3N uLMSolWj8iJ90lXxJpxAAhVgLx2c8MiZJ5sL6wqi3QuGjURBnJ1PCFOKiI68btyKViRmgx XwF8qTzhOFltVC6J+xMGPwrpqC86dEQ= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ax0ovfo+; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf19.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=1723487014; 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=BmPCGgJl9uu6+jXwwzElyK3f+SpfOcwge/5P9pLn8xQ=; b=YC+PWNw44edcR1+3JFOReToNers4MwSDnXSwmGZBbn2TfSYvaY77Z7GCOK5jZzW5c3tIz+ TRHftU2tWJr24eY0dQeG/43eYSB33377Ec+eOxYramORcq6FKFaIT8eoOgt34OeSSPKeCa De/eRaCPdhUcMxFJf48leV44o9zHvXc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 1404B61467; Mon, 12 Aug 2024 18:24:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C61ADC4AF09; Mon, 12 Aug 2024 18:24:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487069; bh=gb9gRmfntU6sLvTnzwOy0nZzExJzcMuzdJXh+XZXxrI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ax0ovfo+JPuw2LDf+OJPpzMSsXQE9YksuOJXuCo+WmnrW8NlGUwys0w3f+ygfqrio 28tnbwcxAKYNJidKiK73kPcgYOc6OCZK1i6y2SxKcgsiDpu8N1EYsTOhK4wawo2hLx 7GCa3TWWOFDAZVPaF+qPrr9g3pcy8XO77lCAchTLje0bB8y2vjHl8+wlBQ7ev3qVsU 5+46tl5L6he6oy/hfmoF53lwjEIN5lkT7hJHA0CUNtw/edL+OwQ7p+0rhTSM9Io9Av v+Fr10KAWwevX78GGFCLCpub/wgqkPU0baB6gUAY0fL3TZH2iMpz0J+I3zivupq8N1 OdkMYTzQx2l7Q== 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 04/26] rust: alloc: implement `Allocator` for `Kmalloc` Date: Mon, 12 Aug 2024 20:22:50 +0200 Message-ID: <20240812182355.11641-5-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-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: DB8C91A0011 X-Stat-Signature: xpjj3r3wosekkbw5r7xabzzmiwt31b4k X-Rspam-User: X-HE-Tag: 1723487070-45705 X-HE-Meta: U2FsdGVkX19Qpc/lO+nM6dPRu6mQc4qRO/uXOOjFPg/46fnAd+FzGA5zI8bM4PH8Rma3KqjyGu6JtRu5BVl+Uay2CLoKHOUIGqeA6BIgnh4uErI0tqUxRA27Lqlt+P5s5czvIkd7NrWrI+tl72HMdTR7yuZv0x5DV+eH9v1q5xH3BWalBaAFcELpiOUsIh1LTXFTl5O6qUiR0u7vKICnGoUlO7ePFnIJ3FB5c8hoCOE44Esgn1ozFk3jb0e0JqbxZuUjsiGENmLEo/Rlm0/pXKpH1WEXexK/W9Xm8Idi9QICWnm6nQ0MWk5d7yi59JvgZKXiAQkbNffTUJnPjn+AAk5mBqD8C/LJfTDDSrqopsvSp7YddVuGYttPDty5Oo20UzmXyR3kQtoka8rxxd6KgAm0g7jwOsx17XGHjqmjudG9LvOyC6GIkFVy8fvUdNnEm6K3IgAePGBX4CzgWEiE8iktDQRj0dp5NibTdQ9UOQg6NdjnTKllg468FTHrsaMn32ANyMjPs33EouKpKmA6kYN2JM9p9cnOxIZctZZP4XjQXE+aRmHAu34RnUL5Y9ICq0y6pIMq+iT3tvZgkW5fnzmCxA7JjUr0plMmyO5tgJnHvuNlxiqsn4iX3fxHYkm4D1wlAcEXyH/QU92cJGZwvEONCK54OK50iAIe/BgRo9x4CmJ6TjPllx78hXBK454/UMVNR4Qk3+LIa1eqy8dXwlkmNiVIjvJBczCF31p9akZS12laDBxvnLpKOAQp7E59Rax/WuWnbvhPN4YEvRg8odb3g0V/KSRlVtB3SwBJpf0h6nFeR/rglABttnkJ5M6NE85cmI5O35jvla+KjCYoTLDZbnpZ9edDCQ4rOA1Qp/mdCnksPpoSj/DXLbIZE+cvPd3XYDBKiQg9b93Zng7OJvsbL7aQcbIUBL9leKGRVVLJoE7iPHI5yvF9YdKKCol8aY19OuRUT5U2NHuDhLc npOKhmqx phcUOCJ3dxxwwph0avnZ3PqdXBHtk9RKD8pTbBnAq1AwqHe8g2pc9+MjtVCtF8ay2kLAY6kcQClQpTzy2lCOK8p+gBS5NtYGzX4O/ptX9Pa7yxFbqQ89ibJyXt3kVtP22fR6CVTbLYvcAfo0QaMeKURapVh41XwpGQQnIR3l+D/zVnhygDNNQtOvRajw00WQAl7EDpVPctuNESnbmpzwv/yxBVUn5VvKpWNwqcAEx88vZu8dW1WMhQa72RMI68j4Q1coIZw6fIdmed9/+j3tM2tD655jxF6ZAPunLRnW2yOyZc8Au9FHjoC906Q== 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/helpers.c | 3 +- rust/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 63 +++++++++++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 4 deletions(-) diff --git a/rust/helpers.c b/rust/helpers.c index 92d3c03ae1bd..9f7275493365 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -193,8 +193,7 @@ void rust_helper_init_work_with_key(struct work_struct *work, work_func_t func, } EXPORT_SYMBOL_GPL(rust_helper_init_work_with_key); -void * __must_check __realloc_size(2) -rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) +void *rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) { return krealloc(objp, new_size, flags); } diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 194745498a75..b732720cfb95 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 e32182f91167..b46883d87715 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -5,8 +5,16 @@ 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 { @@ -36,6 +44,59 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } } +/// # Invariants +/// +/// One of the following `krealloc`, `vrealloc`, `kvrealloc`. +struct ReallocFunc( + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, +); + +impl ReallocFunc { + // INVARIANT: `krealloc` satisfies the type invariants. + const KREALLOC: Self = Self(bindings::krealloc); + + /// # Safety + /// + /// This method has the 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 either NULL or 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> { + // SAFETY: `ReallocFunc::call` has the same safety requirements as `Allocator::realloc`. + unsafe { ReallocFunc::KREALLOC.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 From patchwork Mon Aug 12 18:22:51 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760922 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 C595EC52D7C for ; Mon, 12 Aug 2024 18:24:38 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5ADA06B00AB; Mon, 12 Aug 2024 14:24:38 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 55DD26B00AC; Mon, 12 Aug 2024 14:24:38 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3FE946B00AD; Mon, 12 Aug 2024 14:24:38 -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 238656B00AB for ; Mon, 12 Aug 2024 14:24:38 -0400 (EDT) Received: from smtpin13.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id D66E9140327 for ; Mon, 12 Aug 2024 18:24:37 +0000 (UTC) X-FDA: 82444418994.13.47E57ED Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf01.hostedemail.com (Postfix) with ESMTP id 4103740022 for ; Mon, 12 Aug 2024 18:24:36 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=m5lNQLNQ; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487024; a=rsa-sha256; cv=none; b=KcRQrCOKgPiVtlwLzBR2NHoomxZmmv72w/NjzRksLWLf+kZJGbxu9RGczRulUO7AvYTAwf cmDdHAIC60Jffeulao+lQx/mGoxRKFTvu9jxDhWYxavBhmRdQEbdiCbHi+xtkaSsZAzKtJ Rd7bgVygdqaPPO9O94BMF5gMs8XHr2I= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=m5lNQLNQ; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf01.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=1723487024; 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=H4dMpm/FiIvf86JDYd7aqkcxKnslTyBQ7n0iwYbXGS4=; b=snNVoItm5MU+psEgcwXfZFEWcQL4tTkvoVLTW7zA+9juGfqWY3llExCPBUNHuwGxteHdg7 qNYs+z3QcJo5TOFl4Co6rrP8crEq+AT2bmXhzkz0sKyQcbWTq9yPEuWTEaJ5u3RkhIkr76 bNCgaERpuC61D5t8Y82PTnfBdLAt/UM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 73378611FD; Mon, 12 Aug 2024 18:24:35 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 370A7C4AF12; Mon, 12 Aug 2024 18:24:30 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487075; bh=qBBwndXchuTUBdgsnYPoDfZNxNBpxLvVcMvZVRMmc6s=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=m5lNQLNQYt0Ppd0yuQfm7lGeTmotnrWGIWreHjtdouOP5zlDu/8/lEW1TJFBFN/hs 62DOmFEz4VvqDZ+mYVc/8des9VGhvZBbhKuMl9lUNT76ZKWEHKiG+QfD7Zb0j6ea/e aIa3mtkwEY/YoNKIxouC4NSrLYhRpyXdj2kZHOotMcS4y/TKI7JRKiEuUcmX5+0j8J 8ANlNtS+jIWN1IOkNw5Ajw4S3wij2VvAWr8CVuGFfiA3ueyEFcNhiiLgAHdeF4jhJW CH3DBtylU1WYpSPJL2kmykV28Pue4pqbsXKFAoXIK0AjVfw6pC2Dk4KaVLd3FhTPlm Ynb7j8zyApx7A== 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 05/26] rust: alloc: add module `allocator_test` Date: Mon, 12 Aug 2024 20:22:51 +0200 Message-ID: <20240812182355.11641-6-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-Rspamd-Queue-Id: 4103740022 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: oxniihqrodjbjnc99sitdjkp4k16isgr X-HE-Tag: 1723487076-637922 X-HE-Meta: U2FsdGVkX19FmcAiniYP9bF2aRO1wHG2TGfhHWF9x9DV6zcYT1C+9cQk3VEOzM/DSzxX7WUCJDNvwm6LX9lfKxOZRbgmcGY2aHuLtiwDL2I52sp3YrZ/cjZQcPlVrZCWYcmW5z7M3wZqE+XvlvbCODsBY6WsbIw0mRT39VhQsNJg50C88TzSDDYNzdT9mYtB1uweJPwF+HxbNJNL/YPG+x9iC2+R7X95jYluYOv0ZndVuUUGzMsXrAC8vfophEvINIRgSQMk3JLTc1w5e4twUk6RPDRCRmhUoAYtEMAhGl+/KMkn2azaCYR1+1mGXAU/GOviNT1nY5cHZA+2TgdylgFkS2xby0GF8hCausFSW3Rsqo6zfzKqultM0oXuIoLQNC2n36I4TPuqig6dhnSi+v9+9NP2SUlWJJrVnplqjXMFir0euCCA0paKbaOU9RiIeZ5YzqeypiJspoEHFQglzLfIqD6ZnZ6dSkZ6ELjjGILMR1ESI0RsY4/HzKdZkMemsAJK2DqeJ1ASN8sRVNzoHJefbWzdyok0DuJlwBr2vQeCtHvnKh5bJ3MYRR5b/SqIDJN/f9N+NIbLl4TUk0bQT7+l4qNEadAB+WqR4SeStHo22qoOQ2PH/i4IuC7hlV1b/ftzEYW6dotcaeRo4XmS9hb1MENTV5q31BlTpJDUWpkfhgBpOB1En1C9pRLBRTsRxP4dm0qdT3+gwXWefwvJn7+ZdRYvxrai2A2gs8G7KhLWsir8TRa64WDcs97kwNjv17IPZcvdou6URJsiE7ocRTTd0Axwibw++/rFUoYTKlZNKaq/JzYa4Oru4ukgYkkcOhfe6rvK1WMrmUHlOuid4i/hP1VH/UEvYWYtrD0z72d45PpeE88Q6Fbw7Gy6hZXxM44+Mn46XU2tsMtcnr8oTrgvxsWq7z14TW8qRYYEkVQPREzmjwKuEs4oqHx1ALvnFYVRBShhO2IlNcmyDi2 8yMAGiOs YbtKxtCPX7mT+YGTo1KHIIf8QI4rhMuiCK6Cpj+umunIyttWE+40nZIXljZVW8e70uUrltCObV/PvkCB+ADntpTGwqF0Ds1DT5wrvg2PiQ8cEtktjeLmlYXgfMzQb4lorn05ZAtuCiHiKaljyXTjRxz/6xLLEGRsS+KfmNW3q87TAvw3ms6f2nic7QhX7QTrh2tY3/tMXg1vX2QG6vV7Q2gCPp0ibZnyi1xrsGmIyx1IUr92YBEFHJ61VkAUmYymh6f+HjNUfpMrvSkeCmF/rd6Zi1hasF+efZP2erNdVAKLUgw1qDrnm3ElGflS2Qqa/b/wXgzdzQWtG9v1OaXH3KrTShJyfCU5H9NWW4yJxuPsOAfV3ZKa8P8X5zTsNtCYSRaeI 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: `Allocator`s, such as `Kmalloc`, will be used by e.g. `Box` and `Vec` in subsequent patches, and hence this dependency propagates throughout the whole kernel. Add the `allocator_test` module that provides an empty implementation for all `Allocator`s in the kernel, such that we don't break the `rusttest` make target in subsequent patches. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich Reviewed-by: Benno Lossin --- rust/kernel/alloc.rs | 9 +++++++-- rust/kernel/alloc/allocator_test.rs | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/allocator_test.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index b732720cfb95..f0c80ab78602 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -2,12 +2,17 @@ //! Extensions to the [`alloc`] crate. -#[cfg(not(test))] -#[cfg(not(testlib))] +#[cfg(not(any(test, testlib)))] pub mod allocator; pub mod box_ext; pub mod vec_ext; +#[cfg(any(test, testlib))] +pub mod allocator_test; + +#[cfg(any(test, testlib))] +pub use self::allocator_test as allocator; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs new file mode 100644 index 000000000000..4785efc474a7 --- /dev/null +++ b/rust/kernel/alloc/allocator_test.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0 + +#![allow(missing_docs)] + +use super::{AllocError, Allocator, Flags}; +use core::alloc::Layout; +use core::ptr::NonNull; + +pub struct Kmalloc; + +unsafe impl Allocator for Kmalloc { + unsafe fn realloc( + _ptr: Option>, + _layout: Layout, + _flags: Flags, + ) -> Result, AllocError> { + panic!(); + } +} From patchwork Mon Aug 12 18:22:52 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760923 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 4804BC52D7C for ; Mon, 12 Aug 2024 18:24:44 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id CDC6D6B0095; Mon, 12 Aug 2024 14:24:43 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id C8A336B00AD; Mon, 12 Aug 2024 14:24:43 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B042D6B00AE; Mon, 12 Aug 2024 14:24:43 -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 907BB6B0095 for ; Mon, 12 Aug 2024 14:24:43 -0400 (EDT) Received: from smtpin10.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 57A991C1BD1 for ; Mon, 12 Aug 2024 18:24:43 +0000 (UTC) X-FDA: 82444419246.10.C945D44 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf26.hostedemail.com (Postfix) with ESMTP id A770A140012 for ; Mon, 12 Aug 2024 18:24:41 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=NFvp3rUV; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf26.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487025; a=rsa-sha256; cv=none; b=z8qZQKDpT/puKSvw5LsuealndvD6akvy9mIoDkIM0zOdcsNNMWh8yqm9szDK22qzDqtkMr f0dPX87DC5sPxh4RBOW0a/H703fXd9iYcJbdTh2pk3+phlA2/joAx2Q1UxWuheyMM5JP6l W1rUkfNEJFjPLf7vaci2dEM3obsJZ24= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=NFvp3rUV; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf26.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=1723487025; 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=+PZFzOtqSsDrw+fHKr6d50Q2ufzJqro0ehZaXJdYeWo=; b=lW6XKoXwvm8jQ6KCxC+mnhOupNByhm6BifQh0B+gVbI0D9SZVjcCSLHrKcUtPJ/48StzQE ZlxH2ce+ONUu/kRyFimIctQ/1gRRDT6LTxmC2xJ0976Ndg+czyXae3Bs6JjzP2YwusZYw8 1I/s+ygIJkI2FyzWITKPkBsSQy9jOWo= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id D3E296146C; Mon, 12 Aug 2024 18:24:40 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 975EFC4AF0F; Mon, 12 Aug 2024 18:24:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487080; bh=h5pfzEktHmh1N0L77l+cZ8kzDdEbRgd13sQHut0w7XY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=NFvp3rUVlsJ+UIxsUGlMKE8VTsD2Aq8HQxJ6wXype4vyAHL2JtkK3mOcnqC2DvnGf RmFkZ/Axmc1yYu1S60+J355btuuhvCl8k6va48DkEb1AE+kv7+2ACKRPMVx/RA1Grm 8ju+i4zFpn3C6CpUsSopqqg9VC2Kra0gRKGL1W4dTZsSFnQcsgfnAGX3XZd6bP7Y1Q XOhWkTqlAKYoyI90KBpS3koeohXNoO4UW7OLvdIrC0VU1eFvFuJRTaJnyUP/w1XMaZ +Zcszs4mggLiSYZhQUaYYRApDVKuKQNFVkwynM6kBwM8NIb1v+WthEPX/Jcg0D/T4v rZ4s5Ccnx/0jw== 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 06/26] rust: alloc: implement `Vmalloc` allocator Date: Mon, 12 Aug 2024 20:22:52 +0200 Message-ID: <20240812182355.11641-7-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-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: A770A140012 X-Stat-Signature: 667cef14tjz4sj6gemgdnezps1zg9p15 X-Rspam-User: X-HE-Tag: 1723487081-453765 X-HE-Meta: U2FsdGVkX19h+hHs+scpWw9PlVX2rFhu3iIwHPgiIWpkdbxdHy9D+TajVnKb7XOKJPs4+CchPWpLvv89lDOV8sANW5gQ5fzwtwy6TCPSWcWhNBPlUQfQGa0BPSxzyKJzNkkHfzmHkPBP9LrKMhMN5HDG5UbRpflMcCKM44UtCENMuvL/Le2RNxY+fvBju5sMXzoNe8IZ6rCoj6Vp7evRaAScO4mPPqV6PvA8Y986txfZx/0GAMgRHKsRDwJg9y3QX7m4dTQYnPXLuVDsxBOSKo7wzxeLlKc4MrAE7LkOHggHKyj95zvm6pFbNi4PZEbarX6gnzUfPmpF//Nx65NxI8DwJ4too4Ehg7sgreC3ysw0A7FF3uj5xCthZWCKT6K1fFhxQ1COYGgtg3czO4jfJNOrmmAwNdjWZBZ39AqAAFOwF1qN645PScxGv6DTsElsvEss/DIpdeTTDAjl2UbhuVhf+lWa1RwvqVUHWvv4OtCPX4W/Hrh6apXDF8ZADtHwkysc+U8vcI5tJJNgE2L044wPymwuT43Dg3rdQ0nyUAy7ok+RWeqCNU33FKg9uZKHNTKiMUyPrH7xipzoOuID9fwvUzHeD/C9qlKysBszmLQpCPZ/aw+S4d3supiP0of84yKLKAMrahWLQZg2sHjNg6zUK8nT5S4uBV7Ns6Ij/492xtKCQHv8EdlOmEkPLwAOziZrkj98SI4C6KXJfH3XkLWn/Ehr207/AhViDjxV2+ygcCyMubxUR5Vd1cqM5yDAIxmVtU0g2tPBx6Yqe3/7exubROJq1oYalqliDo5KB4+QqSB1BzAD5s6od+RYNUcxUPRXxTwbSXwpiFHRW6nw+UsoI/7jUP/ihzRBrHJdI8QnAFxWK7U9HNC/4KEI1QfzQbIIV2b0l1o0rAm9MhEp0KZPmxkn7TBB6kBPyFzFT1Orwj9sPvbFf6kyiCHhgFKwvTnXn1v3dWRiKTjMU5q 9iG0gM+9 5f3RjaIva/q9z5g3uRT+QdPFc193LYZy/6N/JoJRg3Nlf9+5oHvbt2gZTIgGIe+CY/9A4WuRIGgzvGwVbQv91rGgNSbUoZpCKdzIlgPg/ABdnU/ddS/OJmgryKEg2GyA0tLHeW6CgL88Pac1DgFrqhY3EsLbRpVujPTwdmYfmGxo+g+oMGnpLE/HD5KhBmMd6mnwnr2b1ZycfWeYzBHPP/sB0mvYf5QwwYMbFhMbZX52siB/BeGwXxBp0Y3Aqo3Gt1hrqfBg2CladyBeY79THmlThAh2XG33bjjy566kH7scIejCvoNJ/68LT6wNHfam1VsBd4PO31CALEe4= 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 `Vmalloc`, the kernel's virtually contiguous allocator, typically used for larger objects, (much) larger than page size. All memory allocations made with `Vmalloc` end up in `vrealloc()`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/helpers.c | 7 +++++++ rust/kernel/alloc/allocator.rs | 28 ++++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 36 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 9f7275493365..7406943f887d 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include @@ -199,6 +200,12 @@ void *rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); +void *rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) +{ + return vrealloc(p, size, flags); +} +EXPORT_SYMBOL_GPL(rust_helper_vrealloc); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index b46883d87715..fdda22c6983f 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -9,6 +9,7 @@ use crate::alloc::{AllocError, Allocator}; use crate::bindings; +use crate::pr_warn; /// The contiguous kernel allocator. /// @@ -16,6 +17,12 @@ /// `bindings::krealloc`. pub struct Kmalloc; +/// The virtually contiguous kernel allocator. +/// +/// The vmalloc allocator allocates pages from the page level allocator and maps them into the +/// contiguous kernel virtual space. +pub struct Vmalloc; + /// 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. @@ -55,6 +62,9 @@ impl ReallocFunc { // INVARIANT: `krealloc` satisfies the type invariants. const KREALLOC: Self = Self(bindings::krealloc); + // INVARIANT: `vrealloc` satisfies the type invariants. + const VREALLOC: Self = Self(bindings::vrealloc); + /// # Safety /// /// This method has the same safety requirements as `Allocator::realloc`. @@ -132,6 +142,24 @@ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { } } +unsafe impl Allocator for Vmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("Vmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::VREALLOC.call(ptr, layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc = Kmalloc; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index 4785efc474a7..e7bf2982f68f 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -7,6 +7,7 @@ use core::ptr::NonNull; pub struct Kmalloc; +pub type Vmalloc = Kmalloc; unsafe impl Allocator for Kmalloc { unsafe fn realloc( From patchwork Mon Aug 12 18:22:53 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760924 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 27A2EC52D7C for ; Mon, 12 Aug 2024 18:24:53 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BA2086B00AD; Mon, 12 Aug 2024 14:24:52 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id B789A6B00AE; Mon, 12 Aug 2024 14:24:52 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id A40A16B00AF; Mon, 12 Aug 2024 14:24:52 -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 86FE06B00AD for ; Mon, 12 Aug 2024 14:24:52 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 4D11880339 for ; Mon, 12 Aug 2024 18:24:52 +0000 (UTC) X-FDA: 82444419624.20.0758A6B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf09.hostedemail.com (Postfix) with ESMTP id 005F6140017 for ; Mon, 12 Aug 2024 18:24:49 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=R2PRrRzm; spf=pass (imf09.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=1723487055; a=rsa-sha256; cv=none; b=F1MoUyY5flQcOxwfaL/1amrjlko3DHAZEE3D8NGmYe6vKGlWKb60nUY1Q1CG8txtKV/1K+ mN2scEeO8x1Xb8oPVZJdyIQ7yvG4KlwbpGXzIH9MJYKOpXfBoUFDwxlDua+eO27OsuG6bR 3AKNwdVFbXw4pRCNJIegj6eGJxVufRo= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=R2PRrRzm; spf=pass (imf09.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=1723487055; 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=wm78gxg5JM+3D7Rf9YN1GVNjw0uLawwkICw7qG6K2GU=; b=HCgumA0ReFAGDSIF97lL4z3phGPvBbTITBjYiV4bttzT4qZpDL9OTvRtQnK7WC1jrgpQbg vxiFKchshrdpdkDPVo96r8+xvbByrKhaKVVlk0plBMIF9IKHRYGIPeYAwnubmOUP2WP3rx QbOf1e503OBj6SSdefw/SPXgRAfj2es= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id DD181CE1037; Mon, 12 Aug 2024 18:24:46 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 02FB5C4AF0C; Mon, 12 Aug 2024 18:24:40 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487085; bh=ITHOVb+qmodDUzbraOhMnm/IPfqxkdSYWt9L0/6UUHg=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=R2PRrRzm+sxi6h0mbRIbj3sVO7A7/Rs9qf3CP6nSz1dh8f0SNA64zrjrpVVLruHlQ 3BFVUU3jvJcUVpqzGx4jNLWpDl+hSQupHUBTsfko5zSpxspOjFOgtOUUF6QLp4Eu2R P2Jwf3jgK2PvwPhtagm2rdrcySOoF9SrhGJL6HMf4A9loJ4iyl2lfIaFtfpx7L7asW tBaeenOsbRAjdWleNZtLtRAzjqOFlzIb6Hq34YSFJ6Ol265wgDMcjQOv+/pj/DQ+nK RVxXOrl8/btgq+is4+yhBy3Pohr5grqiaqeVr6zRrI98GAQel/Rdo/n6yQDvwAgyEi vs0Zb3VCnxxqQ== 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 07/26] rust: alloc: implement `KVmalloc` allocator Date: Mon, 12 Aug 2024 20:22:53 +0200 Message-ID: <20240812182355.11641-8-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: dtzfgtz339ngmfgows1hk13xrrndbwtg X-Rspamd-Queue-Id: 005F6140017 X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723487089-397678 X-HE-Meta: U2FsdGVkX18Aw5DyVx8NKSsEBIw8eUy2SCR6fZ/+h/yYU4U4LLKxahd16Rn0pG/E1c3iWd5Pu7nujv6eMUhOtXsgSELSXVEDEaV1A9A0w0Wg51qdv8W8GCC1K+KXJkxlZlPjaSAedhuHoQaphk5sSCwJnFxtY9BB28eAcAOy3NqbmKOMvKK82CPUH/n1nKBxpKHqEJ04VMETP6q06p4KFRvmhgKbwQZF5u8bvjN+0gHRhTqk8zliAxoY+vTHOpjQdizOQr/fhrHZ8x4nh74hRyW1GgEtNgqZEZnL/10+DBePXHRCCwtn5FlPDUNXHpB5hNDsH+39fMc7b+a+57nI07F0H92FJph/YAtMmFaw9yjS9TFgWYtPItf1OkndpTEdlEHGvK6HogpswILfhp6o7lv70DFiPMyOKtLWZ2JYh4T3qA35ayKphnxuAEU8sjNWb8Fd4xWqyaDwy01+ERcbfWqugGWPeGnohLSCGZib0EAXyj2y0w0qxGUDgFjp50xDn5oELDJY4dJGFJA6FBkptyavTSJ/zUrvslN3jjISWTaC9w6WEE/Ai5avFiLDyw1v2UbX3BRG4+ipKnANnAPkkr5HnJcA/cLO4CPZcEUQG4IC4Br2VS3HQ5pLB8mcm4X7bbidwdD3rpImBAdPC5T3gWRcJFZ6gyMcvv+iYpEjpB+cn3VxSiFpOY9CwjE9W2dBhphlQL1VSFdV9DCcgs0DveNBwvy4L8xzqu60zSSKo1RRvj2HEZS+qlTWRBi/GBejFGyJIRyHTGtX6GNgrtSiXUiWBaweYO1GS6u8GbV6E1TLpLga3Xwf/vJqz8zMSwE3oGrqESfUkfScP553hUuxSmfJuwkg9hhUQu2p36SuSgjxhYp92dBoM0L9Xk1KZHxEi2fpudyQl8D23Cs4L+cafYAL23tDXiVzjMNALa/ywyAzNQm/V7CJreY/udexSgO7D0eTB97XKqHJEVJvpRD MU5UL7U2 EUKNH7thRGK3eZP2Kdirh0XGiIp1BFACVwg4SN9aD8d/moWCkEpdJO6TR6DUMkriUvODRr/H+FHY62ZsnDHSW6zo+mqYlRjFCecLZI8GgvqNF3yDMTsNEKyJ9/XRIYJ5nuhY6oVFvqt6Pzh3uQHQb3VUF3Znq3XVDwdzB40Rnsz5djO6OiHSTZA/WOYgWwlwKebvPrQcQsxh5w5hmtUmHiJ2tPIu2jYw4TjkbdCCrhNc+sMzZNS4SBf1GA2OWHaEw1Uq0mMd8CjJOW4krkOqEG64uzpJiokFLIYA6qRnelM+PL2q/R9kJjhk7kyN2aeTAGPnu7/w5uVe+hF0= 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 `KVmalloc`, an `Allocator` that tries to allocate memory wth `kmalloc` first and, on failure, falls back to `vmalloc`. All memory allocations made with `KVmalloc` end up in `kvrealloc_noprof()`; all frees in `kvfree()`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/helpers.c | 6 ++++++ rust/kernel/alloc/allocator.rs | 27 +++++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 34 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 7406943f887d..3285a85765ff 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -206,6 +206,12 @@ void *rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_vrealloc); +void *rust_helper_kvrealloc(const void *p, size_t size, gfp_t flags) +{ + return kvrealloc(p, size, flags); +} +EXPORT_SYMBOL_GPL(rust_helper_kvrealloc); + /* * `bindgen` binds the C `size_t` type as the Rust `usize` type, so we can * use it in contexts where Rust expects a `usize` like slice (array) indices. diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index fdda22c6983f..243d8c49a57b 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -23,6 +23,12 @@ /// contiguous kernel virtual space. pub struct Vmalloc; +/// The kvmalloc kernel allocator. +/// +/// Attempt to allocate physically contiguous memory, but upon failure, fall back to non-contiguous +/// (vmalloc) allocation. +pub struct KVmalloc; + /// 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. @@ -65,6 +71,9 @@ impl ReallocFunc { // INVARIANT: `vrealloc` satisfies the type invariants. const VREALLOC: Self = Self(bindings::vrealloc); + // INVARIANT: `kvrealloc` satisfies the type invariants. + const KVREALLOC: Self = Self(bindings::kvrealloc); + /// # Safety /// /// This method has the same safety requirements as `Allocator::realloc`. @@ -160,6 +169,24 @@ unsafe fn realloc( } } +unsafe impl Allocator for KVmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + // TODO: Support alignments larger than PAGE_SIZE. + if layout.align() > bindings::PAGE_SIZE { + pr_warn!("KVmalloc does not support alignments larger than PAGE_SIZE yet.\n"); + return Err(AllocError); + } + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, flags) } + } +} + #[global_allocator] static ALLOCATOR: Kmalloc = Kmalloc; diff --git a/rust/kernel/alloc/allocator_test.rs b/rust/kernel/alloc/allocator_test.rs index e7bf2982f68f..1b2642c547ec 100644 --- a/rust/kernel/alloc/allocator_test.rs +++ b/rust/kernel/alloc/allocator_test.rs @@ -8,6 +8,7 @@ pub struct Kmalloc; pub type Vmalloc = Kmalloc; +pub type KVmalloc = Kmalloc; unsafe impl Allocator for Kmalloc { unsafe fn realloc( From patchwork Mon Aug 12 18:22:54 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760925 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 5F329C3DA7F for ; Mon, 12 Aug 2024 18:24:55 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E3A4B6B00AF; Mon, 12 Aug 2024 14:24:54 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D76176B00B0; Mon, 12 Aug 2024 14:24:54 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C3CA06B00B1; Mon, 12 Aug 2024 14:24:54 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0013.hostedemail.com [216.40.44.13]) by kanga.kvack.org (Postfix) with ESMTP id A58546B00AF for ; Mon, 12 Aug 2024 14:24:54 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id 29435A0328 for ; Mon, 12 Aug 2024 18:24:54 +0000 (UTC) X-FDA: 82444419708.01.1D75F9F Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf02.hostedemail.com (Postfix) with ESMTP id 6F59E80027 for ; Mon, 12 Aug 2024 18:24:52 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="reVFN/xm"; spf=pass (imf02.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=1723487037; 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=pKF9l0pC2M5VhiBLUwxSWLkapZ8tnFexGOOoWBSoz2c=; b=I5xo4ZLH/9jmlq6gjNhU+NgkPFo+IG8bO50vf6FCtkGG79e1FyVYD5LJ8buW2C5nJzbyiM +iwkUNTFtizhatuerrA+5HgHnbDvUNPfv204U7Wwv7Vpz5A/OBcvRDc235Eoa3mrUqRNla XyXLtd2me04ZFBlZvUdJrDNcYv78WZw= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="reVFN/xm"; spf=pass (imf02.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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487037; a=rsa-sha256; cv=none; b=Wgbk2jhK/FQi2ej+9iVLQe9rFKMlZLrpjm1ukz/YF6yWFfEFtOtYH3i5gwaJPoCwXiRdJW rT03yHq0jfV9PNY3ulm5kAEbY33l/I9hkoNDAHR33/pF87VEVx0tWaFX4VTuAgZJ3chwFq wzy67o62Iqpt4l60hAeAsIRRBq1uYJc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id A273B61369; Mon, 12 Aug 2024 18:24:51 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6456EC4AF0F; Mon, 12 Aug 2024 18:24:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487091; bh=agb767SEFvgiUIEEXO9aVEplEpFhszjniHeGVU9yvoo=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=reVFN/xm1E8Zs+oww/Sm//2DAa2Rw+MuElDOYO76uoQ2MsmfiIDVMGPd3+hhKDUl+ ZKQ3On9ODtNcI1ec9Gz1esyaAfQgqu+caq+k+7BGJnkg4smIDMVmgLUMUzNBXsYHr2 wRMNNMkdq4gIyw8dCsSrjMSGSDiHLJ58KmnljgsSHRfbnClljfdgmafKb9Hlv/KcPn ZX+XPgkq446EUBGjR/c6fi3nsvTH/p3kI5Qu4gFCrqbAjky1zQB6UceDRGvu4d7xzO BkgNAqSFBF8Zc1vzaEIFNgbgYYyxRX8ki24XnarQxBT9QqrJaxvJuGcoSD2KFGaOAQ eOnr0J9FrL41w== 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 08/26] rust: alloc: add __GFP_NOWARN to `Flags` Date: Mon, 12 Aug 2024 20:22:54 +0200 Message-ID: <20240812182355.11641-9-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: etxtprra3p4ku9jtnefe3rjthj511cew X-Rspam-User: X-Rspamd-Queue-Id: 6F59E80027 X-Rspamd-Server: rspam02 X-HE-Tag: 1723487092-439570 X-HE-Meta: U2FsdGVkX19e04UtmlqM883RGXVihodqDxjNiqIYOo/ZHqe8TFZUDciM39qrMj0ccqedSL1xK9kM3rTKtraM3tLkJ/F9Q1cnJsgJidbZjA8pmz0p55VmbPlKYB0w9MZIO3SvrcbdVqtT4nIhwZoy3bhGIM5hj1l9vlfHWV3TZY4JhDNbuElTS1b6K/2tvAMW9cFTVVDETdTX4MwW5leszsPffTdmayIoSfi98YL90457MGZEDkzm32kngEQG4ob4yeRiM0yAkQKIRo3DMBQG4waFLzyJAgEiyqoZPn+vQHxJfPS6/s1e712kZkS7we7fH9mu6futBcao9t9MMIYMCO85ZQnXuSM1DzJW/qakKC2HilhinbJ1x9h8oPdNzoOQXxhI5taqkoXi/nnfrVOV47tVV82z9ZtYph1dZ6LMgyEek6SizyyvNtq3fZPSr2CRNiL6BjAN+vncxFh2TkDtTel9KfzEEFSO38I8UlHLf2Qy3JJ82yl9D9vv2JeR3u9pk67zHToYxvmg5VshYfduudj4phr/ilLRKCRFaQurl1reL5TIjGFR9wLQRLTUmTxHgE9rl7iAsjqOIfdYfiYih4EVFFHC53VyHlEwXv4gzL4pux740/lWd+sm6YHA9XAnKoF9ELWlW/mUWZm5zERxdDk4sIHjzz6bw6F4lJZBbC5cXN3wvqVF6mdZyNDmNV5Xifru0+UVVGdziwEhlhjN5ICw5EtDwcSgayB4BUsDgtQK6WGdadkinMZrhwYXeuROD9BBD0jRa1LQrewbfCSMe+MZfIL/HkK+JiiriyIZKN7GIxyx3b7IxSC1Hu6dO7lX7vFO5TGR191JBNfTwBJp5em31NNvr+H27DrNnuGITcXv/ciF6vKO8owLF21SrVHgboyMvhd9579eITcl3JoVWGF8yFNsQC1WLjkIPSV/Dvc5W7cot1Pmer3HTWAep+nA66IDguxqMLhi3pcmKbC XKnMe0so ag4og51Wp5c/Get3iI9h8tVWPjdNFy68eFL3XfEYaOBYHZg/pgaoGMB9bwwplEuf9rqtrLB3IKUXi1KWWEerY45NAZWW+rviVDyVMkikrnGfH4gDVrCSkWTg0Ejdhx+EcqKd9RjGS1o/4+0biBPAxt9jRwYL19Gwh0qO1KVfPHJQYxEsbGjHJisX89mL/6wxM3TmvIXE/wgf6LhtYFbPkZmP8Ug/Q48LcLG2Kmnm2wzXKKqqFUSInaRtsHanb6CN9L0QoZKHiX6+6EQ325M0KqVQucDuUgb5lNNj7r92EIREEp62d3RxrY9JQ8VR2D5nZCXhBN2+/aLGAqBbcsghUW2es43QsfQJRQxMDX8RLb2nwS6Q= 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: Some test cases in subsequent patches provoke allocation failures. Add `__GFP_NOWARN` to enable test cases to silence unpleasant warnings. Signed-off-by: Danilo Krummrich Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin --- rust/bindings/bindings_helper.h | 1 + rust/kernel/alloc.rs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index b940a5777330..7f781256fda9 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -31,4 +31,5 @@ const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT = GFP_KERNEL_ACCOUNT; const gfp_t RUST_CONST_HELPER_GFP_NOWAIT = GFP_NOWAIT; const gfp_t RUST_CONST_HELPER___GFP_ZERO = __GFP_ZERO; const gfp_t RUST_CONST_HELPER___GFP_HIGHMEM = ___GFP_HIGHMEM; +const gfp_t RUST_CONST_HELPER___GFP_NOWARN = ___GFP_NOWARN; const blk_features_t RUST_CONST_HELPER_BLK_FEAT_ROTATIONAL = BLK_FEAT_ROTATIONAL; diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index f0c80ab78602..295107777a12 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -91,6 +91,11 @@ pub mod flags { /// use any filesystem callback. It is very likely to fail to allocate memory, even for very /// small allocations. pub const GFP_NOWAIT: Flags = Flags(bindings::GFP_NOWAIT); + + /// Suppresses allocation failure reports. + /// + /// This is normally or'd with other flags. + pub const __GFP_NOWARN: Flags = Flags(bindings::__GFP_NOWARN); } /// The kernel's [`Allocator`] trait. From patchwork Mon Aug 12 18:22:55 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760926 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 60B48C52D7C for ; Mon, 12 Aug 2024 18:25:04 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id ED6EF6B00B2; Mon, 12 Aug 2024 14:25:03 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E88966B00B3; Mon, 12 Aug 2024 14:25:03 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D00546B00B4; Mon, 12 Aug 2024 14:25:03 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id AC0BB6B00B2 for ; Mon, 12 Aug 2024 14:25:03 -0400 (EDT) Received: from smtpin09.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 699C01A02F7 for ; Mon, 12 Aug 2024 18:25:03 +0000 (UTC) X-FDA: 82444420086.09.5C39C1D Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf25.hostedemail.com (Postfix) with ESMTP id 127C4A0003 for ; Mon, 12 Aug 2024 18:25:00 +0000 (UTC) Authentication-Results: imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="NiNDPl/B"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf25.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1723487023; 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=3YntwT6pESkeLW5KcINR9byq+g9n0A2vBT25pTkeBZk=; b=A01M2vvbxtIhwbr9PN/ZI05Pw2ry77nHmV/jByNvmsdHiTx7sgIPebE+xUQ1JAYDLA2Wj9 kJCFoA73YJK9rnLsKz2C91eFjUwQ0dm3n2aKTT8hYc+2PlsUgWcwBoDdl1UaDg0YcY9BT5 D/PIZ9rQwDzHh3YcMQxwRwojAlZ9c/4= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487023; a=rsa-sha256; cv=none; b=QOxY6u2Q8Cs6nbAxbu+ZHnXX9PzEp9DiL5ngdIu9X8QTUYZ5dswIy8FIuRMd89kr6bM7pL E9ythSOwsmG6d7/D41N3Ln4ygs39IHcpaFBKn3pAx9jFEuF3w3WIdOKidQkmRg7EB/v3AC BhLxpiXc1eB3JGDtzT1oatzCruLO04w= ARC-Authentication-Results: i=1; imf25.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="NiNDPl/B"; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf25.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id CC806CE102B; Mon, 12 Aug 2024 18:24:57 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C5BC5C4AF0C; Mon, 12 Aug 2024 18:24:51 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487096; bh=h2D2etA1eZNDRwBqJ9/ejeC1ErIkz2eqBdYlpphzKNY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=NiNDPl/BH7gnS+WaQDWmkoUYMZGIY11LwdqswyAFjBtp7nWvam6Qad7zM3WvALbLw Z9Q0Dy+5BO7YvTLFc5wX25MSJV0vrpfVTN1d1GcNc249YnQcaLQDlZpjm/6+hyosgp i/VLiHir3nj/f337rNNFEbuWeURVLXTKIDrv26iubos8SlG+am3grIqvw2rioGrOwd 6fmW1vh1dj+KRTGlkGlWV1er8GTI2zt52QeYvAOORZUopb21d4Hg7Wkw+rUMrnOje8 5m/QjV5qeBJ9Y7fFGHbKGrosFBHWwiRwenV5ckmAI9W9zSz9/FBccNnnbsf4CSgveT WLkX1y9hJRNrw== 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 09/26] rust: alloc: implement kernel `Box` Date: Mon, 12 Aug 2024 20:22:55 +0200 Message-ID: <20240812182355.11641-10-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-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 127C4A0003 X-Stat-Signature: tdpg7xhd6yf4ub7zgymcu1qma95w81ty X-Rspam-User: X-HE-Tag: 1723487100-391028 X-HE-Meta: U2FsdGVkX19kig73ELXM0xye9+pxcobAl8+CrsJUQvC47vvK8ykdkx7rSOmcdKNVZlZXLFDcha/11dZOHxYivqlnABwLSmt3LPhAWIT/MWCXH2YiyBE7wejvuF75cQrYGyoPiWzS9OvL7PXZkdALEp7RPQRsCXfmYmQgqVOGqSr27NGCwdJHI6+XGEkIWpSrpwbq1Wxdaxye4tFaptU5oErGzJgeEkRY4MUFi8beBq0aAdfWkFqqM2ojQ2FyyifxJiu0SBHTLVjNRgLdqdabFXkNWnr38W67QB/Zgjm71INw8arXtp8JxREg6ZSyIwBEtC9BcRZumiM+Hi4ceBOHrMSzjYq6ygI+Lh7dPraSDpzGuRfXEXS+wa/HK8/RWr7+XlERd2AW8CNgmw1D2I44mmYHhM+CFpjbLtj7Vjslq8Si3phZ85hIzbWGamK2bixr7dBGRYeFkaS2kvuaFOkpEqDQjw1b5nwYGBs2BZkxgP80L2svS5FoSFXX2I+j4cAUHP8fC3nWfpJmZumakG8BQAjOqLWqbZJa0jstaR4oxtVseHDHVAb533VewC9Vb4EDTVAMJMOxrVc6BKZqjgnr6zqx0+fnapQbBFMqViiQOi3utufu/Ggz/7TCfF+rf3d7h9Vmwtvf1MlQHM2QIsStzDG6S5NGoAUd8r8NBZ2CrRCdaalkL3I2KgNXHM/RHVUmz99ftH7RzNB7Tl10KO5ivKkF+lLftdvnkvxfOD9yPdiI3hAhbouYQI22uBiGtBqzlnAvPnHHROMoG36e0oHM6zpblruF4VKZIuTpdgpivHDaycBjvzxqAijzwg6y2DxI2L+tDtSBrJ49CCkTBRKKRdGvFDBUSi7N20Z92cp6a6uNHP+hWVazlNf0qcWuTeujpFsD2ZKu3Fuc8ETV85kw8slZ0vLhF6xhsfgTXaDsMfX53aTdUIxzc/B2XcE2u82IXd2myaCDpLcjNbPjNus SJf0QEEb l+cNtrEjC9qiIFE25vfp5Q6UdHnV6Ta4Ig+mG6tMgnLFvgXiLFP5E1NWUQawBMl0niuMOxPOj1CX9zILV1/+y3ZCwpwjtR0b9MmOF8ZONSs/QnoK0AtI6+hWI5+ix5mBzpuRIqNuv5uZPwh7yL4f3CVwwYbfiFh0Dwx9n0toX2Sj3yi3YpIEdh/m0uCBe8EyyB1+kfD2gHUsW+o65WRMhhIEruWdU7xNGRlWYYzdnByMnQKVo7TK1aQISVfpid9kJLd9ePvlk4SqT1gtAnyeW5/Lq3ov0Ei3U7llmweYfeemV+pdUmT0jZp4RGg== 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: `Box` provides the simplest way to allocate memory for a generic type with one of the kernel's allocators, e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`. In contrast to Rust's `Box` type, the kernel `Box` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 423 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 430 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 295107777a12..ed46b69204d0 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -5,6 +5,7 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; pub mod box_ext; +pub mod kbox; pub mod vec_ext; #[cfg(any(test, testlib))] @@ -13,6 +14,11 @@ #[cfg(any(test, testlib))] pub use self::allocator_test as allocator; +pub use self::kbox::Box; +pub use self::kbox::KBox; +pub use self::kbox::KVBox; +pub use self::kbox::VBox; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs new file mode 100644 index 000000000000..67bdfc0712d2 --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,423 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Box`]. + +use super::{AllocError, Allocator, Flags}; +use core::fmt; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; +use core::mem::MaybeUninit; +use core::ops::{Deref, DerefMut}; +use core::pin::Pin; +use core::ptr::NonNull; +use core::result::Result; + +use crate::init::{InPlaceInit, Init, PinInit}; +use crate::types::ForeignOwnable; + +/// The kernel's [`Box`] type - a heap allocation for a single value of type `T`. +/// +/// This is the kernel's version of the Rust stdlib's `Box`. There are a couple of differences, +/// for example no `noalias` attribute is emitted and partially moving out of a `Box` is not +/// supported. +/// +/// `Box` works with any of the kernel's allocators, e.g. [`super::allocator::Kmalloc`], +/// [`super::allocator::Vmalloc`] or [`super::allocator::KVmalloc`]. There are aliases for `Box` +/// with these allocators ([`KBox`], [`VBox`], [`KVBox`]). +/// +/// When dropping a [`Box`], the value is also dropped and the heap memory is automatically freed. +/// +/// # Examples +/// +/// ``` +/// let b = KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// +/// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KBox::::new_uninit(GFP_KERNEL | __GFP_NOWARN).is_err()); +/// ``` +/// +/// ``` +/// # use kernel::bindings; +/// +/// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1; +/// struct Huge([u8; SIZE]); +/// +/// assert!(KVBox::::new_uninit(GFP_KERNEL).is_ok()); +/// ``` +/// +/// # Invariants +/// +/// The [`Box`]' pointer always properly aligned and either points to memory allocated with `A` or, +/// for zero-sized types, is a dangling pointer. +pub struct Box(NonNull, PhantomData); + +/// Type alias for `Box` with a `Kmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let b = KBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KBox = Box; + +/// Type alias for `Box` with a `Vmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let b = VBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type VBox = Box; + +/// Type alias for `Box` with a `KVmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let b = KVBox::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVBox = Box; + +// SAFETY: `Box` is `Send` if `T` is `Send` because the data referenced by `self.0` is unaliased. +unsafe impl Send for Box +where + T: Send + ?Sized, + A: Allocator, +{ +} + +// SAFETY: `Box` is `Sync` if `T` is `Sync` because the data referenced by `self.0` is unaliased. +unsafe impl Sync for Box +where + T: Send + ?Sized, + A: Allocator, +{ +} + +impl Box +where + T: ?Sized, + A: Allocator, +{ + /// Creates a new `Box` from a raw pointer. + /// + /// # Safety + /// + /// `raw` must point to valid memory, previously be allocated with `A`, and provide at least + /// the size of type `T`. For ZSTs `raw` must be a dangling pointer. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function. + // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer. + Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData::) + } + + /// Consumes the `Box` and returns a raw pointer. + /// + /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive + /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the + /// allocation, if any. + /// + /// # Examples + /// + /// ``` + /// let x = KBox::new(24, GFP_KERNEL)?; + /// let ptr = KBox::into_raw(x); + /// let x = unsafe { KBox::from_raw(ptr) }; + /// + /// assert_eq!(*x, 24); + /// + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + pub fn into_raw(b: Self) -> *mut T { + let b = ManuallyDrop::new(b); + + b.0.as_ptr() + } + + /// Consumes and leaks the `Box` and returns a mutable reference. + /// + /// See [Box::into_raw] for more details. + #[inline] + pub fn leak<'a>(b: Self) -> &'a mut T + where + T: 'a, + { + // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer + // which points to an initialized instance of `T`. + unsafe { &mut *Box::into_raw(b) } + } + + /// Converts a `Box` into a `Pin>`. If `T` does not implement [`Unpin`], then + /// `*b` will be pinned in memory and can't be moved. + /// + /// This moves `b` into `Pin` without moving `*b` or allocating and copying any memory. + #[inline] + pub fn into_pin(b: Self) -> Pin { + // SAFETY: The value wrapped inside a `Pin>` cannot be moved or replaced as long + // as `T` does not implement `Unpin`. + unsafe { Pin::new_unchecked(b) } + } +} + +impl Box, A> +where + A: Allocator, +{ + /// Converts a `Box, A>` to a `Box`. + /// + /// # Safety + /// + /// Callers must ensure that the value inside of `b` is in an initialized state. It is + /// undefined behavior to call this function while the value inside of `b` is not yet fully + /// initialized. + pub unsafe fn assume_init(b: Self) -> Box { + let raw = Self::into_raw(b); + + // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements + // of this function, the value inside the `Box` is in an initialized state. Hence, it is + // safe to reconstruct the `Box` as `Box`. + unsafe { Box::from_raw(raw as *mut T) } + } + + /// Writes the value and converts to `Box`. + pub fn write(mut b: Self, value: T) -> Box { + (*b).write(value); + // SAFETY: We've just initialized `boxed`'s value. + unsafe { Self::assume_init(b) } + } +} + +impl Box +where + A: Allocator, +{ + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Creates a new `Box` and initializes its contents with `x`. + /// + /// New memory is allocated with `a`. The allocation may fail, in which case an error is + /// returned. For ZSTs no memory is allocated. + pub fn new(x: T, flags: Flags) -> Result { + let b = Self::new_uninit(flags)?; + Ok(Box::write(b, x)) + } + + /// Creates a new `Box` with uninitialized contents. + /// + /// New memory is allocated with `a`. The allocation may fail, in which case an error is + /// returned. For ZSTs no memory is allocated. + /// + /// # Examples + /// + /// ``` + /// let b = KBox::::new_uninit(GFP_KERNEL)?; + /// let b = KBox::write(b, 24); + /// + /// assert_eq!(*b, 24_u64); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn new_uninit(flags: Flags) -> Result, A>, AllocError> { + let ptr = if Self::is_zst() { + NonNull::dangling() + } else { + let layout = core::alloc::Layout::new::>(); + let ptr = A::alloc(layout, flags)?; + + ptr.cast() + }; + + Ok(Box(ptr, PhantomData::)) + } + + /// Constructs a new `Pin>`. If `T` does not implement [`Unpin`], then `x` will be + /// pinned in memory and can't be moved. + #[inline] + pub fn pin(x: T, flags: Flags) -> Result>, AllocError> + where + A: 'static, + { + Ok(Self::new(x, flags)?.into()) + } +} + +impl From> for Pin> +where + T: ?Sized, + A: Allocator, +{ + /// Converts a `Box` into a `Pin>`. If `T` does not implement [`Unpin`], then + /// `*b` will be pinned in memory and can't be moved. + /// + /// See [`Box::into_pin`] for more details. + fn from(b: Box) -> Self { + Box::into_pin(b) + } +} + +impl InPlaceInit for Box +where + A: Allocator + 'static, +{ + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + let mut this = Box::<_, A>::new_uninit(flags)?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid and will not be moved, because we pin it later. + unsafe { init.__pinned_init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(this) }.into()) + } + + #[inline] + fn try_init(init: impl Init, flags: Flags) -> Result + where + E: From, + { + let mut this = Box::<_, A>::new_uninit(flags)?; + let slot = this.as_mut_ptr(); + // SAFETY: When init errors/panics, slot will get deallocated but not dropped, + // slot is valid. + unsafe { init.__init(slot)? }; + // SAFETY: All fields have been initialized. + Ok(unsafe { Box::assume_init(this) }) + } +} + +impl ForeignOwnable for Box +where + A: Allocator, +{ + type Borrowed<'a> = &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + Box::into_raw(self) as _ + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + unsafe { &*ptr.cast() } + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Box::from_raw(ptr as _) } + } +} + +impl ForeignOwnable for Pin> +where + A: Allocator, +{ + type Borrowed<'a> = Pin<&'a T>; + + fn into_foreign(self) -> *const core::ffi::c_void { + // SAFETY: We are still treating the box as pinned. + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ + } + + unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> Pin<&'a T> { + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + let r = unsafe { &*ptr.cast() }; + + // SAFETY: This pointer originates from a `Pin>`. + unsafe { Pin::new_unchecked(r) } + } + + unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } + } +} + +impl Deref for Box +where + T: ?Sized, + A: Allocator, +{ + type Target = T; + + fn deref(&self) -> &T { + // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized + // instance of `T`. + unsafe { self.0.as_ref() } + } +} + +impl DerefMut for Box +where + T: ?Sized, + A: Allocator, +{ + fn deref_mut(&mut self) -> &mut T { + // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized + // instance of `T`. + unsafe { self.0.as_mut() } + } +} + +impl fmt::Debug for Box +where + T: ?Sized + fmt::Debug, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Drop for Box +where + T: ?Sized, + A: Allocator, +{ + fn drop(&mut self) { + let size = core::mem::size_of_val::(self); + + // SAFETY: We need to drop `self.0` in place, before we free the backing memory. + unsafe { core::ptr::drop_in_place(self.0.as_ptr()) }; + + if size != 0 { + // SAFETY: `ptr` was previously allocated with `A`. + unsafe { A::free(self.0.cast()) }; + } + } +} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index b37a0b3180fb..39f9331a48e2 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt}; +pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; #[doc(no_inline)] pub use alloc::{boxed::Box, vec::Vec}; From patchwork Mon Aug 12 18:22:56 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760927 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 A7C39C52D7C for ; Mon, 12 Aug 2024 18:25:09 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 365A86B00B4; Mon, 12 Aug 2024 14:25:09 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 315416B00B5; Mon, 12 Aug 2024 14:25:09 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1692C6B00B6; Mon, 12 Aug 2024 14:25:09 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0017.hostedemail.com [216.40.44.17]) by kanga.kvack.org (Postfix) with ESMTP id E5E0E6B00B4 for ; Mon, 12 Aug 2024 14:25:08 -0400 (EDT) Received: from smtpin07.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id A6F371402E8 for ; Mon, 12 Aug 2024 18:25:08 +0000 (UTC) X-FDA: 82444420296.07.B6B253D Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf23.hostedemail.com (Postfix) with ESMTP id 65150140007 for ; Mon, 12 Aug 2024 18:25:05 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=EO3VgrTo; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487095; a=rsa-sha256; cv=none; b=FISwKtxLNStIzIQIzDyPU6I2c9S9plfN5MmQd1xh7t7xScOd3GnY6fV614Nm4ym7t0ehsu 4cu2IEtERGtqNLFfCEYvcASzXZdj1FvBIg7Fm4oP1depIy6EEw+Kb7JM6gfR7m8+RAjFzh R/6h2XEYRqv0UIFS2KrwftS2qyUeJYI= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=EO3VgrTo; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf23.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1723487095; 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=cPC0gSO8WyCPsCKXq6KkhSXFEZRtsefHSrDukdt/I9k=; b=6ylTdvpQ1M6fa6Qas1pqukNLKEvDjGavjSyl2wqMpqMSh1GsGEZUJpLne6s8AxqjklB+Qq c5Dc0KkGx0PVNDA35X1O2FMgN6Caij3tFcnpbfQpbNJhYEj1ihLzQBZl5GgMkMB2L2JrIS suexi/aH/2S6MA5AvIth+VUG/DK8KG4= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 4DA7ACE0FE7; Mon, 12 Aug 2024 18:25:03 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 60905C32782; Mon, 12 Aug 2024 18:24:57 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487102; bh=aL2zVuDOiic5J7pGULj5cj3jRLb//Q08+HJ/i/n5Y/8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=EO3VgrTo4+t616bab23cFHTtcNc4zrDlT23wwidhHJ6AIXhXSP1Pe4ZuOe+WnvX6Y w44Zmclgc9RL7E+KUdKJFDpEEL1wSHJgRQH0QlJOnbYFguq0vbJH8pbIewv481xrPp o1F2yd9D9bo4DOPIIAx0/Vm5t5YtIcgkytXm04TeP4A6q6zEc/7jpC3C/nCEu/u5cI USXq63KTqx2FljVTn5w54tSbn4YB6k+gHc+Y5eaKvptMgZfiQ4P+ZShi5INlmIoMuv eiexBhlmvO8uo/YAYKetZniNkeThRc6n9COyI2MNyX8Thc8wGVLQD7wdGFwsz2kx9B jrHaW7Fy9Q+kA== 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 10/26] rust: treewide: switch to our kernel `Box` type Date: Mon, 12 Aug 2024 20:22:56 +0200 Message-ID: <20240812182355.11641-11-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-Rspam-User: X-Rspamd-Queue-Id: 65150140007 X-Rspamd-Server: rspam01 X-Stat-Signature: 7doqgxobixpa6juh51db1zedtfcas39a X-HE-Tag: 1723487105-265134 X-HE-Meta: U2FsdGVkX1+IHEpSGpLtuAb3jOgjD3j/eiFYKc93i9gGk72KWLrUDUwxe5rNWw4lMR0mXclrAiKp+Q8NJEccR1Pka0j5AF2ObPbNf3ZM1x+9g/rZf6LdVqV/UH4JWIc3ptSCSdLTStGxMkPHnzDnI/jIw9CBVjNjgf5Sy26JEqIb7E5UBWAA/o1W178jnAIlPKyLfHFlS3T+ETJ/YBfP2HdQk8TuA0CZUpAZFvsHdC6H2pFqhO5XBG97LIWj0mUUXEWd+riGp1/nq+WOxGXKipTizpYzu1FR20iyGEpVocYz2jXMlUSlZ1D3y89z+2vn2VB+MadhjGbw1FLN5izRvabWYDtafDHkUtl5zGQ7m18th6S1s0tsDgOLFTQridTqhpYkXfRkQQi8Wo+S/119fD4yuEKfaF5C8PrOsfJXlcjEdDqzqaalQ1a/a0ZCl7B+G9FH2LARMgCVju4Uxi6eRPiUV0sw0KD0GmCfTUyv4jiWAvBfs12lqqb3eXukMBjg0S4KAlv3VEVtgi1711Y9DizKHEXktjHBk6++RyPVSpY2UrDbPbUs8A6tM4odHpByijkQpU5XsxF7SK0Fcc2tl22CC8rZyDfHJLS8zw7k0jgQRXSv6O4vEh2iGKs3KkGkU0G8nzRrcd78yJGlviu8BiJCpyFkLkjGbHzaFNPVsSL5wu2qjure473xG2LLXRbFwFgCkeAMocQWDwFao8YD9PW2KOCFHylMBGvXUGnkND1JmlHMqDJZo0o/SNa3jZgDeZ/TDmz0c5N+BiEtIBew+q3p4dv/i17jFUzKl+pJt2Le+Aum/Y+BiHqvA1hCxgN9ldA3MCWuXSOHHokdtVz+zpXUzjjefPJ44xv9VnEyNbSw2Xx6yDToGZpip20AeQXYpk63VMCssoA7HaQmzmUJSynKoPm87w4dD3ERWPanKo/pE16Wuo4Jb9MXx+J3aFUJ+HtrOpcipcq588zIMm/ /Rk7IHeB i5jvxIOiSOlNY1Y7QQLG46oyZYauUUf+2RdSWNLEisnavkGOpwjynocygOxtjj5Ek9ZgaARHgHatRHWnAe/mMhhu6Tprptrbk6eZ6Ifu0WXbo3ZEckIjQ6m0Cq4r9fJaffaLV2B+BGF04+9mQauz/gHMXZgXX0wE5gYwXg/4G2335v+8anubnptqGecQYhMDVo8pMGCM0OCpQmcgtwdu/VK/DI4uHFYQWA0qGnQV6eXrxesprCr3/TQ3Tjcj+oFC6tVg5uz60FSzyhWdzVqsoMV71Bn92iKAvY/3G3UwbXE4hcU795sv2hfKzdcQIDQFJbJajqqn0iad9wE7G2G6li0gxtMVr5/MZHd2rcng5oIb+OMxFLe+ap+/28ogK64SNliCYubRprQSUpED71GL9Ls0WFaOQvV6DkO6u 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: Now that we got the kernel `Box` type in place, convert all existing `Box` users to make use of it. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- drivers/block/rnull.rs | 4 +-- rust/kernel/init.rs | 51 ++++++++++++++++--------------- rust/kernel/init/__internal.rs | 2 +- rust/kernel/sync/arc.rs | 17 +++++------ rust/kernel/sync/condvar.rs | 4 +-- rust/kernel/sync/lock/mutex.rs | 2 +- rust/kernel/sync/lock/spinlock.rs | 2 +- rust/kernel/workqueue.rs | 20 ++++++------ rust/macros/lib.rs | 6 ++-- 9 files changed, 54 insertions(+), 54 deletions(-) diff --git a/drivers/block/rnull.rs b/drivers/block/rnull.rs index b0227cf9ddd3..5de7223beb4d 100644 --- a/drivers/block/rnull.rs +++ b/drivers/block/rnull.rs @@ -32,7 +32,7 @@ } struct NullBlkModule { - _disk: Pin>>>, + _disk: Pin>>>, } impl kernel::Module for NullBlkModule { @@ -47,7 +47,7 @@ fn init(_module: &'static ThisModule) -> Result { .rotational(false) .build(format_args!("rnullb{}", 0), tagset)?; - let disk = Box::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?; + let disk = KBox::pin_init(new_mutex!(disk, "nullb:disk"), flags::GFP_KERNEL)?; Ok(Self { _disk: disk }) } diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 495c09ebe3a3..d3639243f8c7 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -13,7 +13,7 @@ //! To initialize a `struct` with an in-place constructor you will need two things: //! - an in-place constructor, //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc`], -//! [`UniqueArc`], [`Box`] or any other smart pointer that implements [`InPlaceInit`]). +//! [`UniqueArc`], [`KBox`] or any other smart pointer that implements [`InPlaceInit`]). //! //! To get an in-place constructor there are generally three options: //! - directly creating an in-place constructor using the [`pin_init!`] macro, @@ -68,7 +68,7 @@ //! # a <- new_mutex!(42, "Foo::a"), //! # b: 24, //! # }); -//! let foo: Result>> = Box::pin_init(foo, GFP_KERNEL); +//! let foo: Result>> = KBox::pin_init(foo, GFP_KERNEL); //! ``` //! //! For more information see the [`pin_init!`] macro. @@ -93,14 +93,14 @@ //! struct DriverData { //! #[pin] //! status: Mutex, -//! buffer: Box<[u8; 1_000_000]>, +//! buffer: KBox<[u8; 1_000_000]>, //! } //! //! impl DriverData { //! fn new() -> impl PinInit { //! try_pin_init!(Self { //! status <- new_mutex!(0, "DriverData::status"), -//! buffer: Box::init(kernel::init::zeroed(), GFP_KERNEL)?, +//! buffer: KBox::init(kernel::init::zeroed(), GFP_KERNEL)?, //! }) //! } //! } @@ -211,7 +211,7 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, @@ -297,7 +297,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -306,7 +306,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Result, AllocError> = pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -323,7 +323,7 @@ macro_rules! stack_pin_init { /// struct Foo { /// #[pin] /// a: Mutex, -/// b: Box, +/// b: KBox, /// } /// /// struct Bar { @@ -332,7 +332,7 @@ macro_rules! stack_pin_init { /// /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo { /// a <- new_mutex!(42), -/// b: Box::new(Bar { +/// b: KBox::new(Bar { /// x: 64, /// }, GFP_KERNEL)?, /// })); @@ -391,7 +391,7 @@ macro_rules! stack_try_pin_init { /// }, /// }); /// # initializer } -/// # Box::pin_init(demo(), GFP_KERNEL).unwrap(); +/// # KBox::pin_init(demo(), GFP_KERNEL).unwrap(); /// ``` /// /// Arbitrary Rust expressions can be used to set the value of a variable. @@ -461,7 +461,7 @@ macro_rules! stack_try_pin_init { /// # }) /// # } /// # } -/// let foo = Box::pin_init(Foo::new(), GFP_KERNEL); +/// let foo = KBox::pin_init(Foo::new(), GFP_KERNEL); /// ``` /// /// They can also easily embed it into their own `struct`s: @@ -593,7 +593,7 @@ macro_rules! pin_init { /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// ptr: *mut u8, /// } @@ -601,7 +601,7 @@ macro_rules! pin_init { /// impl BigBuf { /// fn new() -> impl PinInit { /// try_pin_init!(Self { -/// big: Box::init(init::zeroed(), GFP_KERNEL)?, +/// big: KBox::init(init::zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// ptr: core::ptr::null_mut(), /// }? Error) @@ -693,16 +693,16 @@ macro_rules! init { /// # Examples /// /// ```rust -/// use kernel::{init::{PinInit, zeroed}, error::Error}; +/// use kernel::{alloc::KBox, init::{PinInit, zeroed}, error::Error}; /// struct BigBuf { -/// big: Box<[u8; 1024 * 1024 * 1024]>, +/// big: KBox<[u8; 1024 * 1024 * 1024]>, /// small: [u8; 1024 * 1024], /// } /// /// impl BigBuf { /// fn new() -> impl Init { /// try_init!(Self { -/// big: Box::init(zeroed(), GFP_KERNEL)?, +/// big: KBox::init(zeroed(), GFP_KERNEL)?, /// small: [0; 1024 * 1024], /// }? Error) /// } @@ -745,8 +745,8 @@ macro_rules! try_init { /// A pin-initializer for the type `T`. /// /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use the -/// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use +/// the [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc`] on this. /// /// Also see the [module description](self). /// @@ -825,7 +825,7 @@ fn pin_chain(self, f: F) -> ChainPinInit } /// An initializer returned by [`PinInit::pin_chain`]. -pub struct ChainPinInit(I, F, __internal::Invariant<(E, Box)>); +pub struct ChainPinInit(I, F, __internal::Invariant<(E, KBox)>); // SAFETY: The `__pinned_init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -851,8 +851,8 @@ unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { /// An initializer for `T`. /// /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can -/// be [`Box`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use the -/// [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on this. Because +/// be [`KBox`], [`Arc`], [`UniqueArc`] or even the stack (see [`stack_pin_init!`]). Use +/// the [`InPlaceInit::init`] function of a smart pointer like [`Arc`] on this. Because /// [`PinInit`] is a super trait, you can use every function that takes it as well. /// /// Also see the [module description](self). @@ -924,7 +924,7 @@ fn chain(self, f: F) -> ChainInit } /// An initializer returned by [`Init::chain`]. -pub struct ChainInit(I, F, __internal::Invariant<(E, Box)>); +pub struct ChainInit(I, F, __internal::Invariant<(E, KBox)>); // SAFETY: The `__init` function is implemented such that it // - returns `Ok(())` on successful initialization, @@ -1008,8 +1008,9 @@ pub fn uninit() -> impl Init, E> { /// # Examples /// /// ```rust -/// use kernel::{error::Error, init::init_array_from_fn}; -/// let array: Box<[usize; 1_000]> = Box::init::(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(); +/// use kernel::{alloc::KBox, error::Error, init::init_array_from_fn}; +/// let array: KBox<[usize; 1_000]> = +/// KBox::init::(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(); /// assert_eq!(array.len(), 1_000); /// ``` pub fn init_array_from_fn( @@ -1316,7 +1317,7 @@ macro_rules! impl_zeroable { // // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant. {} Option>, - {} Option>, + {} Option>, // SAFETY: `null` pointer is valid. // diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.rs index db3372619ecd..dfb2204918c7 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -102,7 +102,7 @@ fn make_closure(self, f: F) -> F } } -pub struct AllData(PhantomData) -> Box>); +pub struct AllData(PhantomData) -> KBox>); impl Clone for AllData { fn clone(&self) -> Self { diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 3673496c2363..b5c84995d7d2 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -16,13 +16,12 @@ //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags}, + alloc::{AllocError, Flags, KBox}, error::{self, Error}, init::{self, InPlaceInit, Init, PinInit}, try_init, types::{ForeignOwnable, Opaque}, }; -use alloc::boxed::Box; use core::{ alloc::Layout, fmt, @@ -203,11 +202,11 @@ pub fn new(contents: T, flags: Flags) -> Result { data: contents, }; - let inner = as BoxExt<_>>::new(value, flags)?; + let inner = KBox::new(value, flags)?; // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new // `Arc` object. - Ok(unsafe { Self::from_inner(Box::leak(inner).into()) }) + Ok(unsafe { Self::from_inner(KBox::leak(inner).into()) }) } /// Use the given initializer to in-place initialize a `T`. @@ -422,8 +421,8 @@ fn drop(&mut self) { if is_zero { // The count reached zero, we must free the memory. // - // SAFETY: The pointer was initialised from the result of `Box::leak`. - unsafe { drop(Box::from_raw(self.ptr.as_ptr())) }; + // SAFETY: The pointer was initialised from the result of `KBox::leak`. + unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) }; } } } @@ -668,7 +667,7 @@ pub fn new(value: T, flags: Flags) -> Result { /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. pub fn new_uninit(flags: Flags) -> Result>, AllocError> { // INVARIANT: The refcount is initialised to a non-zero value. - let inner = Box::try_init::( + let inner = KBox::try_init::( try_init!(ArcInner { // SAFETY: There are no safety requirements for this FFI call. refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), @@ -678,8 +677,8 @@ pub fn new_uninit(flags: Flags) -> Result>, AllocError> )?; Ok(UniqueArc { // INVARIANT: The newly-created object has a refcount of 1. - // SAFETY: The pointer from the `Box` is valid. - inner: unsafe { Arc::from_inner(Box::leak(inner).into()) }, + // SAFETY: The pointer from the `KBox` is valid. + inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) }, }) } } diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs index 2b306afbe56d..2081932bb4b9 100644 --- a/rust/kernel/sync/condvar.rs +++ b/rust/kernel/sync/condvar.rs @@ -70,8 +70,8 @@ macro_rules! new_condvar { /// } /// /// /// Allocates a new boxed `Example`. -/// fn new_example() -> Result>> { -/// Box::pin_init(pin_init!(Example { +/// fn new_example() -> Result>> { +/// KBox::pin_init(pin_init!(Example { /// value <- new_mutex!(0), /// value_changed <- new_condvar!(), /// }), GFP_KERNEL) diff --git a/rust/kernel/sync/lock/mutex.rs b/rust/kernel/sync/lock/mutex.rs index 30632070ee67..f8f6d530db7d 100644 --- a/rust/kernel/sync/lock/mutex.rs +++ b/rust/kernel/sync/lock/mutex.rs @@ -58,7 +58,7 @@ macro_rules! new_mutex { /// } /// /// // Allocate a boxed `Example`. -/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spinlock.rs index ea5c5bc1ce12..a9096a4dc42a 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -56,7 +56,7 @@ macro_rules! new_spinlock { /// } /// /// // Allocate a boxed `Example`. -/// let e = Box::pin_init(Example::new(), GFP_KERNEL)?; +/// let e = KBox::pin_init(Example::new(), GFP_KERNEL)?; /// assert_eq!(e.c, 10); /// assert_eq!(e.d.lock().a, 20); /// assert_eq!(e.d.lock().b, 30); diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 553a5cba2adc..94318472507f 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -216,7 +216,7 @@ pub fn try_spawn( func: Some(func), }); - self.enqueue(Box::pin_init(init, flags).map_err(|_| AllocError)?); + self.enqueue(KBox::pin_init(init, flags).map_err(|_| AllocError)?); Ok(()) } } @@ -239,9 +239,9 @@ fn project(self: Pin<&mut Self>) -> &mut Option { } impl WorkItem for ClosureWork { - type Pointer = Pin>; + type Pointer = Pin>; - fn run(mut this: Pin>) { + fn run(mut this: Pin>) { if let Some(func) = this.as_mut().project().take() { (func)() } @@ -297,7 +297,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput /// Defines the method that should be called directly when a work item is executed. /// -/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be +/// This trait is implemented by `Pin>` and [`Arc`], and is mainly intended to be /// implemented for smart pointer types. For your own structs, you would implement [`WorkItem`] /// instead. The [`run`] method on this trait will usually just perform the appropriate /// `container_of` translation and then call into the [`run`][WorkItem::run] method from the @@ -329,7 +329,7 @@ pub unsafe trait WorkItemPointer: RawWorkItem { /// This trait is used when the `work_struct` field is defined using the [`Work`] helper. pub trait WorkItem { /// The pointer type that this struct is wrapped in. This will typically be `Arc` or - /// `Pin>`. + /// `Pin>`. type Pointer: WorkItemPointer; /// The method that should be called when this work item is executed. @@ -565,7 +565,7 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput } } -unsafe impl WorkItemPointer for Pin> +unsafe impl WorkItemPointer for Pin> where T: WorkItem, T: HasWork, @@ -576,7 +576,7 @@ unsafe impl WorkItemPointer for Pin> // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`. let ptr = unsafe { T::work_container_of(ptr) }; // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership. - let boxed = unsafe { Box::from_raw(ptr) }; + let boxed = unsafe { KBox::from_raw(ptr) }; // SAFETY: The box was already pinned when it was enqueued. let pinned = unsafe { Pin::new_unchecked(boxed) }; @@ -584,7 +584,7 @@ unsafe impl WorkItemPointer for Pin> } } -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -598,9 +598,9 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput // SAFETY: We're not going to move `self` or any of its fields, so its okay to temporarily // remove the `Pin` wrapper. let boxed = unsafe { Pin::into_inner_unchecked(self) }; - let ptr = Box::into_raw(boxed); + let ptr = KBox::into_raw(boxed); - // SAFETY: Pointers into a `Box` point at a valid value. + // SAFETY: Pointers into a `KBox` point at a valid value. let work_ptr = unsafe { T::raw_get_work(ptr) }; // SAFETY: `raw_get_work` returns a pointer to a valid value. let work_ptr = unsafe { Work::raw_get(work_ptr) }; diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 159e75292970..c327fe0617c8 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -239,7 +239,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` /// @@ -248,7 +248,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// @@ -278,7 +278,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { /// struct DriverData { /// #[pin] /// queue: Mutex>, -/// buf: Box<[u8; 1024 * 1024]>, +/// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } /// From patchwork Mon Aug 12 18:22:57 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760928 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 73088C3DA7F for ; Mon, 12 Aug 2024 18:25:11 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 058E26B00B5; Mon, 12 Aug 2024 14:25:11 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id F26ED6B00B6; Mon, 12 Aug 2024 14:25:10 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D78EB6B00B7; Mon, 12 Aug 2024 14:25:10 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id B45EB6B00B5 for ; Mon, 12 Aug 2024 14:25:10 -0400 (EDT) Received: from smtpin29.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 6CD43C037D for ; Mon, 12 Aug 2024 18:25:10 +0000 (UTC) X-FDA: 82444420380.29.2971DAE Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf08.hostedemail.com (Postfix) with ESMTP id BEF3D160027 for ; Mon, 12 Aug 2024 18:25:08 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=gzQfQXuq; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf08.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=1723487031; 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=A0XX3SA37rHgF8mkEL+tIIpSBjq51+p25HIIgGdIIAM=; b=bx2i8qjx4ZD/gUjtJjr6sIlzvRaWtPRHgc8nXN92zCx1DFvYhuKp8rz171evcR0n914jqh oLDGYvBjOr1uOY3POnlK46nkFnsWKqiqXjhbsHiEbBwnHIpGltBTHA+voe2ripn25So6mk S5uGPA2Iw0fZqevn0F2rTiw1PTnIL4o= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487031; a=rsa-sha256; cv=none; b=CE11qhjIQWTqSMDpqTm8qQ23V1Rdhdy1AzY5lV2qRZStxin+xQX3c/2v8MsyY2SFZhE+BJ MsuJBrxY8GkvKye2P7ALfOcWZLdrGpHOicT97R7ZVMmT+sf1MPKSCbc14dHSO3NSg6jkDP jz5mQGQLH4IR/JYkqxWDjbeUOHt2sUM= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=gzQfQXuq; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf08.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 E4B1C61369; Mon, 12 Aug 2024 18:25:07 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C1AE9C4AF0C; Mon, 12 Aug 2024 18:25:02 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487107; bh=vJmxOB7AGqLlyQmlorOYiNjZzw+KKAXmcrFSlXxsvFE=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=gzQfQXuq96ggnJND706Rt7zVvArRkbVlxihfPz2TakWWKbNovhjxdEGVcquoZwmFg YsMVtZIUTpE7D8VdukUyTJwr899ZiJagclA2fZKv8TBXdUEi9jasTkt01z0AOPwEVL LdX3kdN6KvSSBhlLgnD7eGk544BOMeyE7mLhd5w5kCPuyt77cJZPIStrslTgYV54oa cX0c2+ij3qFs8quP7TlNABPeFe19JFHrm1+bJJ/DMuWlGWnjeDRpyiVhWhHGrp8mbT VOPiQDdY6vdbJOF56Fl/t9OSc2cKyZkHcrOfFb/cQ8Asc/ssNxPM06LvBB/vC1Y3Do gJUacAnLc725w== 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 11/26] rust: alloc: remove `BoxExt` extension Date: Mon, 12 Aug 2024 20:22:57 +0200 Message-ID: <20240812182355.11641-12-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-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: BEF3D160027 X-Stat-Signature: hyesyx7yuf5royfxkjrroixbggyy8smm X-Rspam-User: X-HE-Tag: 1723487108-342623 X-HE-Meta: U2FsdGVkX19DqZxMKNFvsNAKHtDkX7x7Dyuf5PvbZCuiva9ORdwWSFk/6jyUuAY5QWLVVlfy2aYK/Kw+dCw7DOkGzytVt2OXS5lxGzwFQ8C8/Drs9AV3SWOjBd2zOr18qWhSBcY3t34wjsyaRPidRuDWT88P8hgnN8k/U1Rv+Ocz5B0QzqPz/EvWFQ8NvCTCCTSwItMBAoaZfN1jcwM1svNy6xeN7nxdkxbxA342cFFXEBhA3EnNAZ5nrRtjtm3N2HlfepE5GvfwLOBS5PlguUNgoQ9egCDMIpHPxC33/1T1EXg31fP20tGgJMvNTRghHxdaBtkzE4D/6fS27G513SmVj6IXFmJblEEdA0XnGXXVX97jhn9kgsAt67WY9rBkmmTjN/scqfZO0MC5rOborG2AgznsJPGwPACKvTxa4Oheptmt0JYz2pSk7sgi9koeQFZoTiheY+bSkF4jKZdO31wH+evCCw3o9taneH+6P3ToOOOAcsUE5tuS8pCVGCmkHAaQlX9ctxSNOEUO99ALEb46Z5IuV8tl3I4xcZfI4eWs567GAfENUx3bcc5NTYqcK8mcTgTUY5No1pxqbs0ljHYuz78Kjy5b164xmsnnSF7aiA9DE0lErQvD1JL4zfRJMzTeeaEshbpd5PC3f/lkvNf3U6P235w/Rk7GrW9MDQS4+0u4urF51BKjbnqzixEXnv/6BYH5GmL/0DYEp6aj7uYcPb2OHPaq7+q0XPQPJA1B5yRs+/xmmtQ/M/jdZQX34Auq69JfhJV8yoovcy2i3eXRG43TlcFwWpidzc3K7UUFH8MMYee8HyLD4zCplMhnQB7OL1Fb/DGjsFNQPpkxR51RxB3K0PXvl+Nc6AvhTdG5i9vjyPrm1z7z5Ea6qpP9FGu/a5YIQeHnnMel55RrPSNDjQEmoNr+//FmwQhIB+oB47JEYICq/WUvRB0/sRfskFbxg+IQzfmr7wz8kiU C3dP8WwS wr8RBxvWV9KyJtmXm/wPwdUhQ/+5CPdKRoC5KsHbkTQmByOMSWNqEA+IY7QPHgSgD31y6NjPEs6Nw3S9bUEB5R+nNHRjpfGIyzmziqji3kM/qpHUoaOvTSWmrlJHA0auNk8vBxUbvLuQVLD66BRdH98ssjrkOqD3LZGP05mmFmvlC1pwzyhMp8Id9a7AQuIM9XF8fe1on1WrbrZynuoPycc/72nlYaT+7i1K6mII+Yb5FX1pE/uC/FFV4KfA1tUGAbSMEuCOWw16eLcytQmiKxpJSAnzOGHbCf0tZLmok0en0z5jfnNKhxm6j100KrUhwyMDsIub17jyYJ+Q= 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: Now that all existing `Box` users were moved to the kernel `Box` type, remove the `BoxExt` extension and all other related extensions. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/box_ext.rs | 56 ------------------------------------ rust/kernel/init.rs | 34 +--------------------- rust/kernel/lib.rs | 1 - rust/kernel/prelude.rs | 4 +-- rust/kernel/types.rs | 23 --------------- 6 files changed, 3 insertions(+), 116 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index ed46b69204d0..47cab5bd803e 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -4,7 +4,6 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; -pub mod box_ext; pub mod kbox; pub mod vec_ext; diff --git a/rust/kernel/alloc/box_ext.rs b/rust/kernel/alloc/box_ext.rs deleted file mode 100644 index 829cb1c1cf9e..000000000000 --- a/rust/kernel/alloc/box_ext.rs +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Box`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::boxed::Box; -use core::mem::MaybeUninit; - -/// Extensions to [`Box`]. -pub trait BoxExt: Sized { - /// Allocates a new box. - /// - /// The allocation may fail, in which case an error is returned. - fn new(x: T, flags: Flags) -> Result; - - /// Allocates a new uninitialised box. - /// - /// The allocation may fail, in which case an error is returned. - fn new_uninit(flags: Flags) -> Result>, AllocError>; -} - -impl BoxExt for Box { - fn new(x: T, flags: Flags) -> Result { - let b = >::new_uninit(flags)?; - Ok(Box::write(b, x)) - } - - #[cfg(any(test, testlib))] - fn new_uninit(_flags: Flags) -> Result>, AllocError> { - Ok(Box::new_uninit()) - } - - #[cfg(not(any(test, testlib)))] - fn new_uninit(flags: Flags) -> Result>, AllocError> { - let ptr = if core::mem::size_of::>() == 0 { - core::ptr::NonNull::<_>::dangling().as_ptr() - } else { - let layout = core::alloc::Layout::new::>(); - - // SAFETY: Memory is being allocated (first arg is null). The only other source of - // safety issues is sleeping on atomic context, which is addressed by klint. Lastly, - // the type is not a SZT (checked above). - let ptr = - unsafe { super::allocator::krealloc_aligned(core::ptr::null_mut(), layout, flags) }; - if ptr.is_null() { - return Err(AllocError); - } - - ptr.cast::>() - }; - - // SAFETY: For non-zero-sized types, we allocate above using the global allocator. For - // zero-sized types, we use `NonNull::dangling`. - Ok(unsafe { Box::from_raw(ptr) }) - } -} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index d3639243f8c7..eb55787eddee 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -211,12 +211,11 @@ //! [`pin_init!`]: crate::pin_init! use crate::{ - alloc::{box_ext::BoxExt, AllocError, Flags, KBox}, + alloc::{AllocError, Flags, KBox}, error::{self, Error}, sync::UniqueArc, types::{Opaque, ScopeGuard}, }; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, convert::Infallible, @@ -589,7 +588,6 @@ macro_rules! pin_init { /// # Examples /// /// ```rust -/// # #![feature(new_uninit)] /// use kernel::{init::{self, PinInit}, error::Error}; /// #[pin_data] /// struct BigBuf { @@ -1149,36 +1147,6 @@ fn init(init: impl Init, flags: Flags) -> error::Result } } -impl InPlaceInit for Box { - #[inline] - fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> - where - E: From, - { - let mut this = as BoxExt<_>>::new_uninit(flags)?; - let slot = this.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid and will not be moved, because we pin it later. - unsafe { init.__pinned_init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { this.assume_init() }.into()) - } - - #[inline] - fn try_init(init: impl Init, flags: Flags) -> Result - where - E: From, - { - let mut this = as BoxExt<_>>::new_uninit(flags)?; - let slot = this.as_mut_ptr(); - // SAFETY: When init errors/panics, slot will get deallocated but not dropped, - // slot is valid. - unsafe { init.__init(slot)? }; - // SAFETY: All fields have been initialized. - Ok(unsafe { this.assume_init() }) - } -} - impl InPlaceInit for UniqueArc { #[inline] fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 274bdc1b0a82..042f05c45214 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -14,7 +14,6 @@ #![no_std] #![feature(coerce_unsized)] #![feature(dispatch_from_dyn)] -#![feature(new_uninit)] #![feature(receiver_trait)] #![feature(unsize)] diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 39f9331a48e2..a8018ef2e691 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,10 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{box_ext::BoxExt, flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; #[doc(no_inline)] -pub use alloc::{boxed::Box, vec::Vec}; +pub use alloc::vec::Vec; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index bd189d646adb..f48704db33c1 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -3,7 +3,6 @@ //! Kernel types. use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, @@ -67,28 +66,6 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option { } } -impl ForeignOwnable for Box { - type Borrowed<'a> = &'a T; - - fn into_foreign(self) -> *const core::ffi::c_void { - Box::into_raw(self) as _ - } - - unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { - // SAFETY: The safety requirements for this function ensure that the object is still alive, - // so it is safe to dereference the raw pointer. - // The safety requirements of `from_foreign` also ensure that the object remains alive for - // the lifetime of the returned value. - unsafe { &*ptr.cast() } - } - - unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { - // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous - // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr as _) } - } -} - impl ForeignOwnable for () { type Borrowed<'a> = (); From patchwork Mon Aug 12 18:22: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: 13760929 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 CA776C3DA7F for ; Mon, 12 Aug 2024 18:25:16 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5D5E66B00B8; Mon, 12 Aug 2024 14:25:16 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5867F6B00B9; Mon, 12 Aug 2024 14:25:16 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 427656B00BA; Mon, 12 Aug 2024 14:25:16 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0017.hostedemail.com [216.40.44.17]) by kanga.kvack.org (Postfix) with ESMTP id 2299B6B00B8 for ; Mon, 12 Aug 2024 14:25:16 -0400 (EDT) Received: from smtpin18.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id C6233160324 for ; Mon, 12 Aug 2024 18:25:15 +0000 (UTC) X-FDA: 82444420590.18.A8FE690 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf24.hostedemail.com (Postfix) with ESMTP id 28770180021 for ; Mon, 12 Aug 2024 18:25:13 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=tv5GuWoQ; spf=pass (imf24.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=1723487079; 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=VlnLEaIxQWg4kfUlEJYGycSUsX+NAMgK+4UAKvGqx2Y=; b=lO9T68FbQUtd5i9UM0duj1qrdDz03J8UhYR7xYb/vV5rhsVOp6HKaCw5pDOd5UV7vNR1Z7 PNwnP9PxcYRCh6i5bGB1DGtSzzj30Bu+r6YQ2uO4ciIyHyaCTXP4lmIQ2lOCKEDwsUJczy bzBVgDr7kBv9D+14GgnC4GUOw0V/FHc= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=tv5GuWoQ; spf=pass (imf24.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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487079; a=rsa-sha256; cv=none; b=jExsTMy8z78cxtmiShgkegLhtnw0pDuEqzTUvgZvLzXAi7dw/TeXhEoFWNTPX7wVEHZ5VN A9DwvO2EFVQf4halGVZjYcQScOOIcgUDLBLEGfdzVHhIzSUkScn3l4vw7i4Jzn9Tia4SRN 1CkNdXAW5hUSkIaM8twJaoLO3fmP61o= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 5F98161465; Mon, 12 Aug 2024 18:25:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 32487C4AF0C; Mon, 12 Aug 2024 18:25:08 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487113; bh=T1FuSmy3wKKtte/FIc8FwS4B4+fz3kPLj/bCRcKqMJQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=tv5GuWoQlwKbMwwjnKoMTrb4grtNMZEHotZjBmBsuaqEFBKhwQNv9xRogc3nnqQRs UFvpo+qQd+H4kCiuXK/SFpJtltvWgWCrflqvvBmrHvwYPjQ5YbEESlchJbh5dm++Ra oUNwdkg/bK+xdupv706WHrQJ6X3GGbjgYMpoziDIO++aRAmCgDc2CLPZTscx0oP1Ik gPZ1Fs+Jkeof0ff6yyBebVf2aBekQ6Huvdx47F1yRvBr5FsMp2snsObG9loYWAnZw6 dNu8ugaSnnz4153ZUOesYJJ0F0WzRxPBqY4q/l+YODCVZJjjwG2mXaCAbomuWVgj+E MPJ+ew6WAqoxw== 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 12/26] rust: alloc: add `Box` to prelude Date: Mon, 12 Aug 2024 20:22:58 +0200 Message-ID: <20240812182355.11641-13-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-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 28770180021 X-Stat-Signature: jdfoysa64nsde4ru598oq6asc9knh5kk X-HE-Tag: 1723487113-736870 X-HE-Meta: U2FsdGVkX18VaKR9BHbC970Jrv/Zq7U2tNukGJXCOW7bUyWswP83ziPXwXXgdMKyLx59y2BROotGhyX2ysptL0bOWDJmmZWavk1XC6+DuEHNrc2/ukSEY1MOhR82v/WId1Bef2BGbkE2RLOL74f7b8OysMEM2IqTkWv29yHJL4SYEVqXI3DGhB1CnYdq8pm5GFm6xBkjVBxzQwB8JeR1N/h1C+U0w+Nd+Do6hWNJYmhL23Nug0gcJNzbGKdT0H9vxWvhmvw5Jx/lo0/ZqKUYvXR1jkRO7sz/BSxD4oz4Fny0jI2Xzt/9CdvUdkDnKm9EO0C4DWSU8KYN3K16+xpTPbv8unBSf+btL4BSClEhK5oQ1le9LfrHF5LlBm5rgmcA+BwRDvHR/1r0mH+UyFaC/z1sKKTbF51YOuDF4jPWr7kutdGqZiVy5eRguQ9fPIwxMm3JBlMx6Dn4gflWQ2ZHjSRjg5nZkXkcUUPTkyBFPlbZRwGf38xMrIZvupBYLXoybmEQmJOWV65no/FCo78Yrh8FfE3sRSXFmDFzQkrs/Aes8MaArFt3aIL6Qv5+nau9TzdZgRMGGG2kCoGJu6JLfCY2pKmu6YUBQ2CEQB/tub2dDZICkdQ0pL1llfVZLung0L8Pf1E67OGgeGZnPApFhL7t1CWOrYecfBjfvxvswYhUdLVpawGCO1JKs3LHH/p3UBrONGgfV3liqoUPOpqUUjgNvX3gbdfLFxfLjyzTe+0S+NhHmZlb7x9kspA2lyqWT2yGrIjO8J/e8mwsgY5KNZD91l6yr3VKt67WS4a/jDyxNRkC3/+1hQCtcvfksASNYWSnCFKtv5bDJrcjhRihC0V6J/0OpFHcWLwiXKIzFiMkqqMez5p39g5T8ZyLjISj15PSympx34bkXuTwS2J0IW/TWr6p8XYr2ELzDwLGh0VgRVXItmQ+dl7SJZU5DiYUbBQhN51GIMf0DgAZhHG +csVq5qP Gjyl+AIPwuvrtfZLMBLqE7EqKxJIEHIG5xye99Kogn9HcKxhRp6mAVRNZkl9AX3NXzTcrrZu5p49XNr2kZUUpX5sENbIdzKynkM9FB9O+98amR6g+hJFSc6uedHCy617BK9diiBj4KQ9Rjt4uO/Vf1FYHH3G7L7bqEjX2tND7vtrqv6Y2rIMK6X5k/N+TOKnZZw4sZbPRv0GPBTgsanVOfdbK9Aur30UKHTfgHd2yXhG3U8tgX2lxfopPw3A54TXB2FIDJ0JBeQHTMLu9TSkXm4I2XBBkoDTljCMUuEr/EkJMz3PF1AegjeCYszs9iRPE9e6HIOFGlUG8mZI= 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: Now that we removed `BoxExt` and the corresponding includes in prelude.rs, add the new kernel `Box` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index a8018ef2e691..6bf77577eae7 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, vec_ext::VecExt, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox}; #[doc(no_inline)] pub use alloc::vec::Vec; From patchwork Mon Aug 12 18:22:59 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760930 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 0305EC3DA7F for ; Mon, 12 Aug 2024 18:25:26 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 896D26B00BB; Mon, 12 Aug 2024 14:25:25 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 81DF86B00BC; Mon, 12 Aug 2024 14:25:25 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 698EC6B00BD; Mon, 12 Aug 2024 14:25:25 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0016.hostedemail.com [216.40.44.16]) by kanga.kvack.org (Postfix) with ESMTP id 4135A6B00BB for ; Mon, 12 Aug 2024 14:25:25 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 03946A5BCB for ; Mon, 12 Aug 2024 18:25:24 +0000 (UTC) X-FDA: 82444421010.02.BC3E2AA Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf12.hostedemail.com (Postfix) with ESMTP id A3CB640012 for ; Mon, 12 Aug 2024 18:25:22 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=teMUFWqf; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf12.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487071; a=rsa-sha256; cv=none; b=DbJugjFIL5rMLX9emYAvSmsR1q/feL3njd3OpPx+lTSo+Tn8c9cqLNcwQ89lzW4J0Fv4XP NfkO2BujQdlM6pjs7i7u4AfLIjjrovFD7TDgByCrrD3foqoJA8jP9ftcbHNvWmoahhnT7u qPRfnUZxOczxyKXWHikDBJGHbrx7I8Y= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=teMUFWqf; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf12.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1723487071; 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=H3/GfOzROeShGJeRj7pU/IE87UX0JY3XpawjsIZGZ/E=; b=xEQETTtxeDjabvJEwoVH8PPysd9+pYq4sD5CfPoS9t/d+5YbxqQfmCqcFFjHnpyRkfCCW0 hkcr8htmh8TcATC/Tsc5F5qB6pl+FytTqE7K7GMJKMD5h/Vrjaqf0dq/0ZwDJi2RIQiYZs Fo7qT9ji8cg6kLcuJFXPfcqe5eQjXzg= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 78CAECE102D; Mon, 12 Aug 2024 18:25:19 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A09C6C32782; Mon, 12 Aug 2024 18:25:13 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487118; bh=8cg9wKbQuvsA1DHr/ARpLKQtv/43NG0iFT8VBNeBpMA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=teMUFWqfczNMBEEN4u6dBQ/n2BH0v+ID6U/4BUYy20oyGRAU7iFhNAfSg2ASmZfWm 8iiG2F5NhedAI7dlk63WWX88GVuR4QY27fimyvQOJQ91WK5Y1zqldK8ROMd62XqUgp 0heNuompL715Gmlqh0qLKEbC0NfZHw/CoXb3f1lBa0QSsw3eKHfkQOAepV8EFsfqQV Pu/2BcDChpH1Be+kOJahWRbWLn19snB0mf+Rxi7cZ569HWBdnsqMuAz/6K3FJFgm09 VfGW45orELU3WGYgfH79RIbWK3VQ4xVx4TDHFc8CqwQXjcqdJotIQtYKlpx9E9tPei ntnYViPxkQxBA== 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 13/26] rust: alloc: implement kernel `Vec` type Date: Mon, 12 Aug 2024 20:22:59 +0200 Message-ID: <20240812182355.11641-14-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-Rspamd-Queue-Id: A3CB640012 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: i6n6ty653fm1cb5rajpugxye81etqd1w X-HE-Tag: 1723487122-903604 X-HE-Meta: U2FsdGVkX1+92Ro5DYkQCu6ae7fV4vyKSaFk4UjgMJ4XXRpvrSiP2F9Bb0iKGs0foUDC7mDYRth+91S2s8y1JVRkLstJXMaW990xJnULwxHTMhq7jjZubr+nqM9+qvZ+oJl3o0wgULD8CKHYi+dZhGMA4ScHIPXZszX5wCZq6rAlUVS5PhaO7k/qLylLa2hePWe3oEvuPWSPdYT1pyuOv/IMeYWVp/S6fzTlO0rfYfC5XKfMUQbtnDxaNVYra/LEHe2H6MbPb/Zti5mtjEDMAny1+SYjp/m3eD9oNAUxOJxO9O1L6xvpIC66zorJsIbwcAQtOlroVCr6lVV3rfjM6PbEKSz7lSGPiaaSV0x0O7VZnyZh2y3cIm2+RO0XGWTJHJ63BO2zpPCzcCM/C+L1OMYhQ6A33NFGiZFo5hQutNxulegR3sD5mNfNufB3TYI8EZm0xY6lIX5Vv984SOI5rfLjZzRmAM2TS1N9N5fAbA2cYcU1oiOtyndeRXpQfE/ABiTnsNVsUvZm42VWFqrEsMcO80fsbFgcMS29kLVkUwApHYLsY6RblLNKnHHmp+gO5lCcqvAa91FTICCgkaiIHMz8fvU8TE54E4IKwRoudWBY5glDXH/5VsMSZzu778s6Tvr0r+3q/TwJIsbfslsm35rwwSv8PHNhldJ8EilJ+YbPYBE61IhJj95cPXzLK5KXV2/BmcZAUkJSUHESGCKHNrbD1XmVFSNMytL8A8YFX1E+OfvN7KXOgO+MtltsQSbwuqoFsWGEZ1oCCSXk3v1rzMn3t0F6HjIXJJqoE+lyIY7WI+HdLVm8ut0Xhwa6zNzuY/ilmJpqRsw08Ui+XGVdVB2cqldIIeTkghFtnchGl46cgGa3Yr3YX6ns8F4P1aIDQ5sjHxJYAbrLGbrJDaXY5cbmHW2QnM7TqCMP4vSQDXoTgd74TcLmxQ2uaNVo8jQqCq6mqSisePE9pVObo4+ ZRV3VMwC 6dIl25gFN3q7o0gX8Q8rPqwp/V8UIheOKVKUTaTmqoFJ4+hz08mNea6EMw5cVbKraZ/jjW9gbt4W6e1NkIrz4/+jgWPPxn+QAU8LjO51YnRXHiPbIMit244BDo8yaprghE9CXwamq9w7OuETaTjxbrnnsNNcdhiUKcPBx3i7qcaS8EX/jGS65msUiw0K0DVcGOtSF0RXOZxC7j7y66oKCDJB4BtPfbZ9vNduE5vKrSKcAezDG2xWrap9kJswWYx5o8gMr3d5EOImIgPH2Ide6biktUGMLOEgwBFo8Z5f50646zvf2wAGLIba58w== 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: `Vec` provides a contiguous growable array type (such as `Vec`) with contents allocated with the kernel's allocators (e.g. `Kmalloc`, `Vmalloc` or `KVmalloc`). In contrast to Rust's `Vec` type, the kernel `Vec` type considers the kernel's GFP flags for all appropriate functions, always reports allocation failures through `Result<_, AllocError>` and remains independent from unstable features. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 6 + rust/kernel/alloc/kbox.rs | 16 +- rust/kernel/alloc/kvec.rs | 613 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 4 files changed, 635 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 47cab5bd803e..4d7190594076 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -5,6 +5,7 @@ #[cfg(not(any(test, testlib)))] pub mod allocator; pub mod kbox; +pub mod kvec; pub mod vec_ext; #[cfg(any(test, testlib))] @@ -18,6 +19,11 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; +pub use self::kvec::KVVec; +pub use self::kvec::KVec; +pub use self::kvec::VVec; +pub use self::kvec::Vec; + /// Indicates an allocation error. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct AllocError; diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs index 67bdfc0712d2..d67f97550224 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -2,7 +2,7 @@ //! Implementation of [`Box`]. -use super::{AllocError, Allocator, Flags}; +use super::{AllocError, Allocator, Flags, Vec}; use core::fmt; use core::marker::PhantomData; use core::mem::ManuallyDrop; @@ -183,6 +183,20 @@ pub fn into_pin(b: Self) -> Pin { } } +impl Box<[T; N], A> +where + A: Allocator, +{ + /// Convert a `Box<[T, N], A>` to a `Vec`. + pub fn into_vec(b: Self) -> Vec { + let len = b.len(); + unsafe { + let ptr = Self::into_raw(b); + Vec::from_raw_parts(ptr as _, len, len) + } + } +} + impl Box, A> where A: Allocator, diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs new file mode 100644 index 000000000000..351c4f1702db --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,613 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{AllocError, Allocator, Flags}; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + ptr::NonNull, + slice, + slice::SliceIndex, +}; + +/// Create a [`Vec`] containing the arguments. +/// +/// # Examples +/// +/// ``` +/// let mut v = kernel::kvec![]; +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(v, [1]); +/// +/// let mut v = kernel::kvec![1; 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 1, 1, 4]); +/// +/// let mut v = kernel::kvec![1, 2, 3]?; +/// v.push(4, GFP_KERNEL)?; +/// assert_eq!(v, [1, 2, 3, 4]); +/// +/// # Ok::<(), Error>(()) +/// ``` +#[macro_export] +macro_rules! kvec { + () => ( + { + $crate::alloc::KVec::new() + } + ); + ($elem:expr; $n:expr) => ( + { + $crate::alloc::KVec::from_elem($elem, $n, GFP_KERNEL) + } + ); + ($($x:expr),+ $(,)?) => ( + { + match $crate::alloc::KBox::new([$($x),+], GFP_KERNEL) { + Ok(b) => Ok($crate::alloc::KBox::into_vec(b)), + Err(e) => Err(e), + } + } + ); +} + +/// The kernel's [`Vec`] type. +/// +/// A contiguous growable array type with contents allocated with the kernel's allocators (e.g. +/// `Kmalloc`, `Vmalloc` or `KVmalloc`), written `Vec`. +/// +/// For non-zero-sized values, a [`Vec`] will use the given allocator `A` for its allocation. For +/// the most common allocators the type aliases `KVec`, `VVec` and `KVVec` exist. +/// +/// For zero-sized types the [`Vec`]'s pointer must be `dangling_mut::`; no memory is allocated. +/// +/// Generally, [`Vec`] consists of a pointer that represents the vector's backing buffer, the +/// capacity of the vector (the number of elements that currently fit into the vector), it's length +/// (the number of elements that are currently stored in the vector) and the `Allocator` type used +/// to allocate (and free) the backing buffer. +/// +/// A [`Vec`] can be deconstructed into and (re-)constructed from it's previously named raw parts +/// and manually modified. +/// +/// [`Vec`]'s backing buffer gets, if required, automatically increased (re-allocated) when elements +/// are added to the vector. +/// +/// # Invariants +/// +/// The [`Vec`] backing buffer's pointer is always properly aligned and either points to memory +/// allocated with `A` or, for zero-sized types, is a dangling pointer. +/// +/// The length of the vector always represents the exact number of elements stored in the vector. +/// +/// The capacity of the vector always represents the absolute number of elements that can be stored +/// within the vector without re-allocation. However, it is legal for the backing buffer to be +/// larger than `size_of` times the capacity. +/// +/// The `Allocator` type `A` of the vector is the exact same `Allocator` type the backing buffer was +/// allocated with (and must be freed with). +pub struct Vec { + ptr: NonNull, + /// Represents the actual buffer size as `cap` times `size_of::` bytes. + /// + /// Note: This isn't quite the same as `Self::capacity`, which in contrast returns the number of + /// elements we can still store without reallocating. + /// + /// # Invariants + /// + /// `cap` must be in the `0..=isize::MAX` range. + cap: usize, + len: usize, + _p: PhantomData, +} + +/// Type alias for `Vec` with a `Kmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVec = Vec; + +/// Type alias for `Vec` with a `Vmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = VVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type VVec = Vec; + +/// Type alias for `Vec` with a `KVmalloc` allocator. +/// +/// # Examples +/// +/// ``` +/// let mut v = KVVec::new(); +/// v.push(1, GFP_KERNEL)?; +/// assert_eq!(&v, &[1]); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub type KVVec = Vec; + +// SAFETY: `Vec` is `Send` if `T` is `Send` because the data referenced by `self.ptr` is unaliased. +unsafe impl Send for Vec +where + T: Send, + A: Allocator, +{ +} + +// SAFETY: `Vec` is `Sync` if `T` is `Sync` because the data referenced by `self.ptr` is unaliased. +unsafe impl Sync for Vec +where + T: Send, + A: Allocator, +{ +} + +impl Vec +where + A: Allocator, +{ + #[inline] + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Returns the number of elements that can be stored within the vector without allocating + /// additional memory. + pub fn capacity(&self) -> usize { + if Self::is_zst() { + usize::MAX + } else { + self.cap + } + } + + /// Returns the number of elements stored within the vector. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forcefully sets `self.len` to `new_len`. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity`]. + /// - If `new_len` is greater than `self.len`, all elements within the interval + /// [`self.len`,`new_len`] must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + self.len = new_len; + } + + /// Returns a slice of the entire vector. + /// + /// Equivalent to `&s[..]`. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Returns a mutable slice of the entire vector. + /// + /// Equivalent to `&mut s[..]`. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + /// Returns a mutable raw pointer to the vector's backing buffer, or, if `T` is a ZST, a + /// dangling raw pointer. + #[inline] + pub fn as_mut_ptr(&self) -> *mut T { + self.ptr.as_ptr() + } + + /// Returns a raw pointer to the vector's backing buffer, or, if `T` is a ZST, a dangling raw + /// pointer. + #[inline] + pub fn as_ptr(&self) -> *const T { + self.as_mut_ptr() + } + + /// Returns `true` if the vector contains no elements, `false` otherwise. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// assert!(v.is_empty()); + /// + /// v.push(1, GFP_KERNEL); + /// assert!(!v.is_empty()); + /// ``` + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Creates a new, empty Vec. + /// + /// This method does not allocate by itself. + #[inline] + pub const fn new() -> Self { + Self { + ptr: NonNull::dangling(), + cap: 0, + len: 0, + _p: PhantomData::, + } + } + + /// Returns a slice of `MaybeUninit` for the remaining spare capacity of the vector. + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // SAFETY: The memory between `self.len` and `self.capacity` is guaranteed to be allocated + // and valid, but uninitialized. + unsafe { + slice::from_raw_parts_mut( + self.as_mut_ptr().add(self.len) as *mut MaybeUninit, + self.capacity() - self.len, + ) + } + } + + /// Appends an element to the back of the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// assert_eq!(&v, &[1]); + /// + /// v.push(2, GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 2]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { + Vec::reserve(self, 1, flags)?; + let s = self.spare_capacity_mut(); + s[0].write(v); + + // SAFETY: We just initialised the first spare entry, so it is safe to increase the length + // by 1. We also know that the new length is <= capacity because of the previous call to + // `reserve` above. + unsafe { self.set_len(self.len() + 1) }; + Ok(()) + } + + /// Creates a new [`Vec`] instance with at least the given capacity. + /// + /// # Examples + /// + /// ``` + /// let v = KVec::::with_capacity(20, GFP_KERNEL)?; + /// + /// assert!(v.capacity() >= 20); + /// # Ok::<(), Error>(()) + /// ``` + pub fn with_capacity(capacity: usize, flags: Flags) -> Result { + let mut v = Vec::new(); + + Self::reserve(&mut v, capacity, flags)?; + + Ok(v) + } + + /// Pushes clones of the elements of slice into the [`Vec`] instance. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// + /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 20, 30, 40]); + /// + /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?; + /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]); + /// # Ok::<(), Error>(()) + /// ``` + pub fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> + where + T: Clone, + { + self.reserve(other.len(), flags)?; + for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) { + slot.write(item.clone()); + } + + // SAFETY: We just initialised the `other.len()` spare entries, so it is safe to increase + // the length by the same amount. We also know that the new length is <= capacity because + // of the previous call to `reserve` above. + unsafe { self.set_len(self.len() + other.len()) }; + Ok(()) + } + + /// Creates a Vec from a pointer, a length and a capacity using the allocator `A`. + /// + /// # Safety + /// + /// If `T` is a ZST: + /// + /// - `ptr` must be a dangling pointer. + /// - `capacity` must be zero. + /// - `length` must be smaller than or equal to `usize::MAX`. + /// + /// Otherwise: + /// + /// - `ptr` must have been allocated with the allocator `A`. + /// - `ptr` must satisfy or exceed the alignment requirements of `T`. + /// - `ptr` must point to memory with a size of at least `size_of::` times the `capacity` + /// bytes. + /// - The allocated size in bytes must not be larger than `isize::MAX`. + /// - `length` must be less than or equal to `capacity`. + /// - The first `length` elements must be initialized values of type `T`. + /// + /// It is also valid to create an empty `Vec` passing a dangling pointer for `ptr` and zero for + /// `cap` and `len`. + /// + /// # Examples + /// + /// ``` + /// let mut v = kernel::kvec![1, 2, 3]?; + /// v.reserve(1, GFP_KERNEL)?; + /// + /// let (mut ptr, mut len, cap) = v.into_raw_parts(); + /// + /// // SAFETY: We've just reserved memory for another element. + /// unsafe { ptr.add(len).write(4) }; + /// len += 1; + /// + /// // SAFETY: We only wrote an additional element at the end of the `KVec`'s buffer and + /// // correspondingly increased the length of the `KVec` by one. Otherwise, we construct it + /// // from the exact same raw parts. + /// let v = unsafe { KVec::from_raw_parts(ptr, len, cap) }; + /// + /// assert_eq!(v, [1, 2, 3, 4]); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { + let cap = if Self::is_zst() { 0 } else { capacity }; + + Self { + // SAFETY: By the safety requirements, `ptr` is either dangling or pointing to a valid + // memory allocation, allocated with `A`. + ptr: unsafe { NonNull::new_unchecked(ptr) }, + cap, + len: length, + _p: PhantomData::, + } + } + + /// Consumes the `Vec` and returns its raw components `pointer`, `length` and `capacity`. + /// + /// This will not run the destructor of the contained elements and for non-ZSTs the allocation + /// will stay alive indefinitely. Use [`Vec::from_raw_parts`] to recover the [`Vec`], drop the + /// elements and free the allocation, if any. + pub fn into_raw_parts(self) -> (*mut T, usize, usize) { + let me = ManuallyDrop::new(self); + let len = me.len(); + let capacity = me.capacity(); + let ptr = me.as_mut_ptr(); + (ptr, len, capacity) + } + + /// Ensures that the capacity exceeds the length by at least `additional` + /// elements. + /// + /// # Examples + /// + /// ``` + /// let mut v = KVec::new(); + /// v.push(1, GFP_KERNEL)?; + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let cap = v.capacity(); + /// assert!(cap >= 10); + /// + /// v.reserve(10, GFP_KERNEL)?; + /// let new_cap = v.capacity(); + /// assert_eq!(new_cap, cap); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> { + let len = self.len(); + let cap = self.capacity(); + + if cap - len >= additional { + return Ok(()); + } + + if Self::is_zst() { + // The capacity is already `usize::MAX` for SZTs, we can't go higher. + return Err(AllocError); + } + + // We know `cap` is <= `isize::MAX` because of it's type invariant. So the multiplication by + // two won't overflow. + let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?); + let layout = core::alloc::Layout::array::(new_cap).map_err(|_| AllocError)?; + + // We need to make sure that `ptr` is either NULL or comes from a previous call to + // `realloc_flags`. A `Vec`'s `ptr` value is not guaranteed to be NULL and might be + // dangling after being created with `Vec::new`. Instead, we can rely on `Vec`'s + // capacity to be zero if no memory has been allocated yet. + let ptr = if cap == 0 { + None + } else { + Some(self.ptr.cast()) + }; + + // SAFETY: `ptr` is valid because it's either `None` or comes from a previous call to + // `A::realloc`. We also verified that the type is not a ZST. + let ptr = unsafe { A::realloc(ptr, layout, flags)? }; + + self.ptr = ptr.cast(); + + // INVARIANT: `Layout::array` fails if the resulting byte size is greater than `isize::MAX`. + self.cap = new_cap; + + Ok(()) + } +} + +impl Vec { + /// Extend the vector by `n` clones of value. + pub fn extend_with(&mut self, n: usize, value: T, flags: Flags) -> Result<(), AllocError> { + self.reserve(n, flags)?; + + let spare = self.spare_capacity_mut(); + + for item in spare.iter_mut().take(n - 1) { + item.write(value.clone()); + } + + // We can write the last element directly without cloning needlessly. + spare[n - 1].write(value); + + // SAFETY: `self.reserve` not bailing out with an error guarantees that we're not + // exceeding the capacity of this `Vec`. + unsafe { self.set_len(self.len() + n) }; + + Ok(()) + } + + /// Create a new `Vec and extend it by `n` clones of `value`. + pub fn from_elem(value: T, n: usize, flags: Flags) -> Result { + let mut v = Self::with_capacity(n, flags)?; + + v.extend_with(n, value, flags)?; + + Ok(v) + } +} + +impl Drop for Vec +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: We need to drop the vector's elements in place, before we free the backing + // memory. + unsafe { + core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( + self.as_mut_ptr(), + self.len, + )) + }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.ptr` was previously allocated with `A`. + unsafe { A::free(self.ptr.cast()) }; + } + } +} + +impl Default for KVec { + #[inline] + fn default() -> Self { + Self::new() + } +} + +impl fmt::Debug for Vec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Deref for Vec +where + A: Allocator, +{ + type Target = [T]; + + #[inline] + fn deref(&self) -> &[T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } + } +} + +impl DerefMut for Vec +where + A: Allocator, +{ + #[inline] + fn deref_mut(&mut self) -> &mut [T] { + // SAFETY: The memory behind `self.as_ptr()` is guaranteed to contain `self.len` + // initialized elements of type `T`. + unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } + } +} + +impl Eq for Vec where A: Allocator {} + +impl, A> Index for Vec +where + A: Allocator, +{ + type Output = I::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + Index::index(&**self, index) + } +} + +impl, A> IndexMut for Vec +where + A: Allocator, +{ + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + IndexMut::index_mut(&mut **self, index) + } +} + +macro_rules! __impl_slice_eq { + ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?) => { + impl PartialEq<$rhs> for $lhs + where + T: PartialEq, + $($ty: $bound)? + { + #[inline] + fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } + } + } +} + +__impl_slice_eq! { [A1: Allocator, A2: Allocator] Vec, Vec } +__impl_slice_eq! { [A: Allocator] Vec, &[U] } +__impl_slice_eq! { [A: Allocator] Vec, &mut [U] } +__impl_slice_eq! { [A: Allocator] &[T], Vec } +__impl_slice_eq! { [A: Allocator] &mut [T], Vec } +__impl_slice_eq! { [A: Allocator] Vec, [U] } +__impl_slice_eq! { [A: Allocator] [T], Vec } +__impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } +__impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 6bf77577eae7..bb80a43d20fb 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, VBox}; +pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; #[doc(no_inline)] pub use alloc::vec::Vec; From patchwork Mon Aug 12 18:23:00 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760931 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 CFF53C531DC for ; Mon, 12 Aug 2024 18:25:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 5D99C6B00BC; Mon, 12 Aug 2024 14:25:27 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5877D6B00BD; Mon, 12 Aug 2024 14:25:27 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3B3E46B00BE; Mon, 12 Aug 2024 14:25:27 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 1823D6B00BC for ; Mon, 12 Aug 2024 14:25:27 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id CC5A91C1DD5 for ; Mon, 12 Aug 2024 18:25:26 +0000 (UTC) X-FDA: 82444421052.26.5CFDE9D Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf14.hostedemail.com (Postfix) with ESMTP id 23259100013 for ; Mon, 12 Aug 2024 18:25:24 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DzWbtvOL; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487073; a=rsa-sha256; cv=none; b=ZCD2RtQJEM1Uko6e+GsMryBDkco8bEpOf1dMbyVdcoiZZ9DFJ0wbtLFldcj2kNjebf19UN IYNTL0UConadl6z/QOF3cQTqfEfeR9y6nE8ojPBf4vTig8lCQszDi+Y0Mek/PmiI6U46TC Ko8o1E7xWp/CJUI0ZhcF6faL4BquHxs= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=DzWbtvOL; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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=1723487073; 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=+02v6UkCEvj5+l130gfbqMJrAukl19W3hDWLIwY16l0=; b=AVZ4tJgQPqkitt1m+B5BVxa5+ZeO0SKdZ0PS+5VQMMnRHrSlYastGw0KJPpMy6yU9wo/0J xKA342U7FTZeKF6tz0vwubLQpwqEdtoiGIARd7HpjfQPzIi0J2xR9l6dCQOSk3BJyhKzHb ZJEOu//Necye9zhJ9J247vBrF/5a/w4= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 489E961179; Mon, 12 Aug 2024 18:25:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 0A7CDC4AF0D; Mon, 12 Aug 2024 18:25:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487124; bh=0DSeKEWLXJuqwaFBkmO+F7vBvNPyAyPpY0O8t3RwT4Y=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=DzWbtvOLiWrMOUXG/qelU1xQ8qo72M+ErF8g+N9WKMUpaKdzkCMw3Pcp+65+lpkdg nHiF7XNu6z9JZ7HHR/o8Vwh3Ksbdz8jmxdZCPUvGSNMrW1AYnlbSBk4UQcg1zrWj5W jzqXjT9F51KHwg0Q7rYyPT02u0/Bkz1egaE5BYR8x7klRCsoyEwqcO3LUoLOEI4SYK KPnLvbJmMYz9zUV/mgmU287ki/YZ4UTEkuslHHNnKpO6E/eui1r52+B0Z1OVddG5e1 BCr2KdFXi2WiN4UW7x2CBq700z3FF5Nhj6dprjns6t66FeWibt+ir93XSqxqRKfZJy 2fSASsmLBWMNQ== 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 14/26] rust: alloc: implement `IntoIterator` for `Vec` Date: Mon, 12 Aug 2024 20:23:00 +0200 Message-ID: <20240812182355.11641-15-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-Rspamd-Queue-Id: 23259100013 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: mqr8nuf9sg18i3dn61wdsk3k9cj7ikmp X-HE-Tag: 1723487124-219172 X-HE-Meta: U2FsdGVkX18UtCkPVnyC5Wcp25/rAc/vzCEidDnBqGNUALBK9hQpFZvhxAzmS0OiLcFwfYdIN3vHFkn9SwUcr7IVikNsiD7ujcdDVZnlbNw5ZTTqWhhUpWZa0h/U2Os6wnPcYdtQsiJ9Yw/JWA0T8UMydmzh6Lh5a306fFN9aVvhh60zB9xa3dfCW+YLxhB8+hgtC8rFmh+xLsDX2G855Q/GmaMqOOWGQHFXJBSnrtYtQwALUgQOqpN4uynWYBPxj0jDgDzu068PHwhUlbQiryFrIf/LdM34DBm6G0eBJHXXc24wC3GQaHR7rQM8BlHWxMrEH8IZfcbnKaKFn4LvSfwCxSOkkC1WPaW8EGA4bTdmmXOPFIz5hhqocJHsmUue4FcPjLvMbKD5V4e3BcgBDyPC/3TOI8exQRGUaKOOLlGGi88wwLiA5fOuWfLwrgFz8vTu9C4W2EOVYiHzMV+zHsZz0SPO3yGYVppr1gU7ARcXH+hnHMEaTx4TNPyFB+CXgTha9VcoX6jON+GHtlbvnhI7K/z3FJNJW97mtWd8/Jvt7lbRBnf+KA3n+lpWsZ+dwq5/JE/YpH6DCYJSayaQ3z2UxE9bayJkrak6t7D3D1mDcOYkoFPVlIXMSsFxdPamNXyVANDNl053mVwipzkFqnWgOEs60o7VCgkoFh9q3zluPSBXSapsfdZuwI2xm5/HgvPgGsrACKERWF9sr6mL/jS0XY6hHOVaqHSFJmSaHVENdsR53zWkdzYXojmAASr2rE3J2x3zuXhMt6FSXwOBdQtv9Vquz+dGHT1mLpyEgNWp7KTO61ku7DK69myRaPgd2n1/a9Gy1tEPoVagUtmSMsiuOF3cBWBQY6zZTC7ejIZGzPBJTjs3SxGEhrJSL/Kgu39yBsTgLTR1fVjEJr4HcJ4BxGhh5Sy65YyotplqCCljg9elRPrNuL7WJLWiVgrGjZZhFSODK6ypf6NR3Gb ApyKp+VB 77lq69g65HGjelJ4q/fPsD5yISdxniSzk4MYPdZ/x81h2ApK64FMiXUCbjuA/spq2RFsesHEe+BlJ+TOFjoEisjJ4CxYoZWZEShofZT4en6TGJ7C8FQZt0mMhFbXDqOLfcETbfWY219GugvMAiqD0rumvuc/Ns6W1yPLcRJ4IbS+x3iTjt2Hkvw2fE0piH13mU3oeOcmmFwW5eFg4HUtcahdC+DXHB1xVgHPzAbxdhd81KMMugiSirLEeGyURyNeoNNNzi90K774gvn/gPkOlXCrZI/wUpZcwbTVeh81yRN1mG/CNpOnHq3OtFk1CM8ViwLgFlw8lxFUxLigIJgkdmbRUiInMb8Avzap+ 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 `IntoIterator` for `Vec`, `Vec`'s `IntoIter` type, as well as `Iterator` for `IntoIter`. `Vec::into_iter` disassembles the `Vec` into its raw parts; additionally, `IntoIter` keeps track of a separate pointer, which is incremented correspondingsly as the iterator advances, while the length, or the count of elements, is decremented. This also means that `IntoIter` takes the ownership of the backing buffer and is responsible to drop the remaining elements and free the backing buffer, if it's dropped. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 184 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 185 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 4d7190594076..4035644b5dca 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -19,6 +19,7 @@ pub use self::kbox::KVBox; pub use self::kbox::VBox; +pub use self::kvec::IntoIter; pub use self::kvec::KVVec; pub use self::kvec::KVec; pub use self::kvec::VVec; diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 351c4f1702db..cc8f3c555d1e 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -11,6 +11,7 @@ ops::DerefMut, ops::Index, ops::IndexMut, + ptr, ptr::NonNull, slice, slice::SliceIndex, @@ -611,3 +612,186 @@ fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] } __impl_slice_eq! { [A: Allocator] [T], Vec } __impl_slice_eq! { [A: Allocator, const N: usize] Vec, [U; N] } __impl_slice_eq! { [A: Allocator, const N: usize] Vec, &[U; N] } + +impl<'a, T, A> IntoIterator for &'a Vec +where + A: Allocator, +{ + type Item = &'a T; + type IntoIter = slice::Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec +where + A: Allocator, +{ + type Item = &'a mut T; + type IntoIter = slice::IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +/// An `Iterator` implementation for `Vec` that moves elements out of a vector. +/// +/// This structure is created by the `Vec::into_iter` method on [`Vec`] (provided by the +/// [`IntoIterator`] trait). +/// +/// # Examples +/// +/// ``` +/// let v = kernel::kvec![0, 1, 2]?; +/// let iter = v.into_iter(); +/// +/// # Ok::<(), Error>(()) +/// ``` +pub struct IntoIter { + ptr: *mut T, + buf: NonNull, + len: usize, + cap: usize, + _p: PhantomData, +} + +impl IntoIter +where + A: Allocator, +{ + fn as_raw_mut_slice(&mut self) -> *mut [T] { + ptr::slice_from_raw_parts_mut(self.ptr, self.len) + } +} + +impl Iterator for IntoIter +where + A: Allocator, +{ + type Item = T; + + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// assert_eq!(it.next(), Some(2)); + /// assert_eq!(it.next(), Some(3)); + /// assert_eq!(it.next(), None); + /// + /// # Ok::<(), Error>(()) + /// ``` + fn next(&mut self) -> Option { + if self.len == 0 { + return None; + } + + let ptr = self.ptr; + if !Vec::::is_zst() { + // SAFETY: We can't overflow; `end` is guaranteed to mark the end of the buffer. + unsafe { self.ptr = self.ptr.add(1) }; + } else { + // For ZST `ptr` has to stay where it is to remain aligned, so we just reduce `self.len` + // by 1. + } + self.len -= 1; + + // SAFETY: `ptr` is guaranteed to point at a valid element within the buffer. + Some(unsafe { ptr.read() }) + } + + /// # Examples + /// + /// ``` + /// let v: KVec = kernel::kvec![1, 2, 3]?; + /// let mut iter = v.into_iter(); + /// let size = iter.size_hint().0; + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 1); + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 2); + /// + /// iter.next(); + /// assert_eq!(iter.size_hint().0, size - 3); + /// + /// # Ok::<(), Error>(()) + /// ``` + fn size_hint(&self) -> (usize, Option) { + (self.len, Some(self.len)) + } +} + +impl Drop for IntoIter +where + A: Allocator, +{ + fn drop(&mut self) { + // SAFETY: Drop the remaining vector's elements in place, before we free the backing + // memory. + unsafe { ptr::drop_in_place(self.as_raw_mut_slice()) }; + + // If `cap == 0` we never allocated any memory in the first place. + if self.cap != 0 { + // SAFETY: `self.buf` was previously allocated with `A`. + unsafe { A::free(self.buf.cast()) }; + } + } +} + +impl IntoIterator for Vec +where + A: Allocator, +{ + type Item = T; + type IntoIter = IntoIter; + + /// Consumes the `Vec` and creates an `Iterator`, which moves each value out of the + /// vector (from start to end). + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2]?; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, Some(1)); + /// assert_eq!(v_iter.next(), Some(2)); + /// assert_eq!(v_iter.next(), None); + /// + /// # Ok::<(), Error>(()) + /// ``` + /// + /// ``` + /// let v = kernel::kvec![]; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, None); + /// + /// # Ok::<(), Error>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (ptr, len, cap) = self.into_raw_parts(); + + IntoIter { + ptr, + // SAFETY: `ptr` is either a dangling pointer or a pointer to a valid memory + // allocation, allocated with `A`. + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +} From patchwork Mon Aug 12 18:23:01 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760932 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 1E3E3C52D7C for ; Mon, 12 Aug 2024 18:25:33 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9ADD96B0083; Mon, 12 Aug 2024 14:25:32 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 956A66B00C0; Mon, 12 Aug 2024 14:25:32 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7D0446B00C1; Mon, 12 Aug 2024 14:25:32 -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 5E2226B0083 for ; Mon, 12 Aug 2024 14:25:32 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 239EBA5BC0 for ; Mon, 12 Aug 2024 18:25:32 +0000 (UTC) X-FDA: 82444421304.06.11687AE Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf24.hostedemail.com (Postfix) with ESMTP id 77F30180027 for ; Mon, 12 Aug 2024 18:25:30 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aUAfrY2L; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487079; a=rsa-sha256; cv=none; b=RdPGGamiqMRjmmBZyGI8bqQ0UVVFzn2EHAqxN1hHo7hpg5Y6WpeNHOksLNYVxdMuZ88DNi ZKFF1XD2Zk5MpDje8YweHBCXNUQRoVc+70kX3R6AMQxlTozQFJjMWyfXMm0jV+FGvXA6Ka kRUirjaqYqyGrJ8hQxWrGObIIXOPKY4= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aUAfrY2L; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.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=1723487079; 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=TjEjT5zmijLvv4lboYXherII1LZULW9T9sIInQkB9nU=; b=uWgosJnhSLRfzsub3hYzwpqESjjPYFox28KLQugJteSHU59UuQ9jp6y99UmBl2gwP85g0l ScDmJORaSii9flq+99A3rgKKChBh8ibDMasS85rkanXEewIJXBlhgsn8WpAknmFj9oCGaK cXnqi9Tcboh8PBVKBl45SG7i4vB1VoI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id AAB506145D; Mon, 12 Aug 2024 18:25:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6C829C4AF0F; Mon, 12 Aug 2024 18:25:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487129; bh=mGfLMacmI9WDRKwXe7Dbjq2onMgKyS4ooeQ6tXyvXVU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=aUAfrY2LujU/UqM2eFzPgifWU2KN+zf4RZN2dHFqJ+3IFJko9zyAO+izB4L54XRR2 LwvFMGpAflvg4EvIkKuiaJfGM1D7tphFfc1Shb/m/I4CmkcSpApOJVX2JXT5MoCdt8 juPxgQNxSF60Xomyz0tTsocIX23l55U2zkGayA9RwpTgrUGEIU8ZGlYzGYs606VbG5 SZdo+LCGAg6LbZl+8ti45727MdmV8ltrSNRmTZp28Inuodv+in4hWC26wjTF+ZffDn sZjNiVEon9nWrjyN4sqITxTgCUIrfDIeYX0hYqnHkx5HqnQBeMMuY1so0J4SRXZBSA baU3gqDD0ASyQ== 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 15/26] rust: alloc: implement `collect` for `IntoIter` Date: Mon, 12 Aug 2024 20:23:01 +0200 Message-ID: <20240812182355.11641-16-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-Rspamd-Queue-Id: 77F30180027 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: d5m8nf7dasrjdfwspmmcx4qdcjs5xk7u X-HE-Tag: 1723487130-407899 X-HE-Meta: U2FsdGVkX1+l7P4KqOfswEnSuUdElppLiscPx4gQPlYTR6o225gncruUHnIvFmWz42yNK6A3wbuSoR8UGhRQSZjmoEfmB+jZeIUzzmbGlLzXNf8GWEXpxTAHZoS2GdoReV3Nz36tSgNc3Gb60qdgyZVnDd6PF4NTdxbykD4rg9pi8OxDSayHjqcmmMVRsXHrMqka3ICVIsSTYQpVGk/fsAgd2AfJlRZPcDg06hARExvy9PIiow7Yv6ToQLPAtOa/LIMKR5AfUBGN0dpZ4AhgtsMLmO9wXy+j/CpbrhfEuZursAEFPicNV3YGEdeCCHi3R2O0Vmt2NMXPchMIcY3F/mvO6QMnnPbm6NBYj9Qf4sLuO2CSSJdHwZgVNlNqMR7bfRtW1qbl/cYNxGp4dHIP4Rb7eXJtF9ludiOeZRkNkeScO5FnTRGuZtDRhijRINvyTnAPJ+52CmlrpzLEh4/JPYLzMZ69MUYR17W/YPTDvB+H+IGyOpr8VN/qDC/BW0nvVBlJUOfeZgyyZMTnFWOx1lsWEMUV160B8JNovI62qOBBV//O4kGVx7UP5iy0+Kki9XlNH6ftGv1MWyPbl7V5mLlW6tg4Qudqe52sAsT4OmJRNOQs6t/k4Fyjhoo+EXoC6UYC3BGOYnH8YPPdag/64B/wUXMOYxWqLXCvkT/zEdKa8GHa5FSQRzTUZXHE2VjH9wa+LbrUHknV9C53NfXs6WTS40i+jrdQXpxZnO1U/KkDuK3neWc5G/KIFJCw+vbid2lzbJ1iGCS10FWx9VyfT3PL4fsQs99vDQQt2m8YywF4O0aVtOySNxozXmkcDKlxnB6WCW3g8RiWFFmsrBB2oIvsHD66WwhQaRIIGmq93iVDxt6ey1BbixkMvkntK/AIDNS7f18o0GiQL72LeWjyzVWBI4Y0FdCK7aWqUJSXocf1tvUYhvi6Dfo0glMR9A1yRmBunF8+rD5LIfZXLJM RaGptiJ1 Q6renuew3daXaHMNTXJWdlEL/p8k/cYWZM2nuCH7BdkgmgVC1nGMmDhwFCFdhOU5Ly8ZuZMVs0LhomgxSluRPgxjh4CnZNypWSpoxmS71jsq/SqK+ng2PDNZ/xjvKDwMNe20a7TD1ZGTm9cNQGZaWXymI/kHCTGWGzzJalnHTm3g8XJ/RF85GftKbClC+88MlxxSIoBzzAn0gHSLYAx/cAEUwhNrTMCxUg6wutBIo2atMyQ+MZ0HxU4o7Y/NBLVovIaxekaWoqy4R61EGgsKZ/A+sneSSOajZE60w3Jx4/U1AiviU0dW26a07rJRSA9Ug6cdGiRMb17GfvbrP7lzc2RMEpw== 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: Currently, we can't implement `FromIterator`. There are a couple of issues with this trait in the kernel, namely: - Rust's specialization feature is unstable. This prevents us to optimze for the special case where `I::IntoIter` equals `Vec`'s `IntoIter` type. - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` doesn't require this type to be `'static`. - `FromIterator::from_iter` does return `Self` instead of `Result`, hence we can't properly handle allocation failures. - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation flags. Instead, provide `IntoIter::collect`, such that we can at least convert `IntoIter` into a `Vec` again. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 78 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index cc8f3c555d1e..db58e764db4b 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -665,6 +665,84 @@ impl IntoIter fn as_raw_mut_slice(&mut self) -> *mut [T] { ptr::slice_from_raw_parts_mut(self.ptr, self.len) } + + fn into_raw_parts(self) -> (*mut T, NonNull, usize, usize) { + let me = ManuallyDrop::new(self); + let ptr = me.ptr; + let buf = me.buf; + let len = me.len; + let cap = me.cap; + (ptr, buf, len, cap) + } + + /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`. + /// + /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait + /// in the kernel, namely: + /// + /// - Rust's specialization feature is unstable. This prevents us to optimze for the special + /// case where `I::IntoIter` equals `Vec`'s `IntoIter` type. + /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` + /// doesn't require this type to be `'static`. + /// - `FromIterator::from_iter` does return `Self` instead of `Result`, hence + /// we can't properly handle allocation failures. + /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation + /// flags. + /// + /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a + /// `Vec` again. + /// + /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing + /// buffer. However, this backing buffer may be shrunk to the actual count of elements. + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// + /// let v = it.collect(GFP_KERNEL); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn collect(self, flags: Flags) -> Vec { + let (mut ptr, buf, len, mut cap) = self.into_raw_parts(); + let has_advanced = ptr != buf.as_ptr(); + + if has_advanced { + // SAFETY: Copy the contents we have advanced to at the beginning of the buffer. + // `ptr` is guaranteed to be between `buf` and `buf.add(cap)` and `ptr.add(len)` is + // guaranteed to be smaller than `buf.add(cap)`. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr = buf.as_ptr(); + } + + // This can never fail, `len` is guaranteed to be smaller than `cap`. + let layout = core::alloc::Layout::array::(len).unwrap(); + + // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be + // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves + // it as it is. + ptr = match unsafe { A::realloc(Some(buf.cast()), layout, flags) } { + // If we fail to shrink, which likely can't even happen, continue with the existing + // buffer. + Err(_) => ptr, + Ok(ptr) => { + cap = len; + ptr.as_ptr().cast() + } + }; + + // SAFETY: If the iterator has been advanced, the advanced elements have been copied to + // the beginning of the buffer and `len` has been adjusted accordingly. `ptr` is guaranteed + // to point to the start of the backing buffer. `cap` is either the original capacity or, + // after shrinking the buffer, equal to `len`. `alloc` is guaranteed to be unchanged since + // `into_iter` has been called on the original `Vec`. + unsafe { Vec::from_raw_parts(ptr, len, cap) } + } } impl Iterator for IntoIter From patchwork Mon Aug 12 18:23:02 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760933 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 3DF1DC531DC for ; Mon, 12 Aug 2024 18:25:42 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id D02666B0085; Mon, 12 Aug 2024 14:25:41 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id CB1FA6B00C3; Mon, 12 Aug 2024 14:25:41 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id B2D296B00C4; Mon, 12 Aug 2024 14:25:41 -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 8F8726B0085 for ; Mon, 12 Aug 2024 14:25:41 -0400 (EDT) Received: from smtpin15.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 563E7160322 for ; Mon, 12 Aug 2024 18:25:41 +0000 (UTC) X-FDA: 82444421682.15.F061DA4 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf27.hostedemail.com (Postfix) with ESMTP id 1292940008 for ; Mon, 12 Aug 2024 18:25:38 +0000 (UTC) Authentication-Results: imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mVtAY1mW; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=1723487061; 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=D1vt4R+2TeBNziQiXLugIjCQRzMoZ+UPSnzMQO3D3zk=; b=clNqZ3EtaWgbk7a/OUSM85ygdU8+3DjT+YZBrT9a5V8tgQbQUAfhPOdmZyURoRvbMAPDN+ z4dqNNGZE7aBN0gbEVjCdQVbKLa2RGUMBjGv3FHC/oY9/xLOjn2X8Mhxxv5r9NPWTNZfs5 kM4ZkuyppIHgSQuOlkyMaiFDqkyHdMQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487061; a=rsa-sha256; cv=none; b=WmZDIs9sqQa/RBjeiZQt1XavYutVYJonpwPQyJwYPfa3IOWzfJCsSFTi3p89G/5GGNWJRM YSaEbV/x4KBKXk+ZPJr1UoC7/ynq+6CbGCNQu9CHYL1aVVX/TG5wa40WdwTGGkc8EsBfJa vAoM8jxwVoRQiHkY7zdHdWXiYtzKUBI= ARC-Authentication-Results: i=1; imf27.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mVtAY1mW; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf27.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id AEBEECE1034; Mon, 12 Aug 2024 18:25:35 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D0069C4AF14; Mon, 12 Aug 2024 18:25:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487134; bh=OOOwgVRJfePu8PY+REcfTzHgRHI6ksicI60irRAmGTI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mVtAY1mWFugPVxOUM9PJ/yXnWtCliEGpVKwDTimyad7a1Rv8QsFzGDFxAhFDDBNh+ xr8VuK2bfnQktrv8PCU+FJNu7ZRdtKAIslM3iSCV8pAOwjAobwUuMiCnnJnv88ojm4 Cy2e3GPtNHaxKuMlMGR4ZDcgabHxC9cmlTXDWP1JBh1yewOZnsWpXLwkdbbZpYgngO Q2EIYuG6L4h/7t9ZsbcM9ILpreAZg9NxIjaeRRVQ7zAOLCOrxAeY3hk03CEhfc0FMp oha6Y0mhw4uK5fN2gwB23kpfyb3HiRMQBTjRwnq2VshAyLXpsI774JNrbQyQGw+9Jx g+z6UgAzMzfOA== 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 16/26] rust: treewide: switch to the kernel `Vec` type Date: Mon, 12 Aug 2024 20:23:02 +0200 Message-ID: <20240812182355.11641-17-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-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 1292940008 X-Stat-Signature: e91jcdb5ma5oiqh7sadqzhtbf8fxaxgo X-Rspam-User: X-HE-Tag: 1723487138-892663 X-HE-Meta: U2FsdGVkX1/6+Avf1R3Eh97W/aBvzluSZnYyCvXLJ2LU2RAHCYX6EgzK4esQvYXdFYVqDbYFZ/TuNFyqwaE0ZhBLHWJxEBPku/AfbzmO8Kbdpqyn8SD1dv1zjeGmZJO2zNO5/qkrKThABoIAhfF5L3lY4GOPX+HEGPHKAy6OusbSL9M34FKs740IxgCee7kVaqqxsjIDAj8pZYi/qEkNTLr92etvgRRYgZ2Pu3u42jYCiBvJrHuOtgQdQY1LK1FcdQRDVNSj1ncsO0cpHL6dqiE2/JSMFAwugzJVMaLfJMPRHqLlIDp0efBBjy/lu7+ZnrUNnFfXEu0Kf076YKCAadHor7J49TQ/DPOBCOkOKxf9JDrGu8fYwb13ta+3SrP1I17WzA/fMJqAy5wtQoX1y5X9/gsxw35WjJ6GNLz+FKFLMFRbiSJ2/32dD0IVUIJOcfVNkHco4isdwDbzWZ3daOnoPE6AxXRF2AeqA0OeZ1okWU+ZiJ5j8b86ovNXmHx8tGwmj6WDWfU7f62wziH9C6zKrNMk818Le48z1pK7Xl3sO3JykQlBP7tHKYL63BSB6wL9LONCfvQ5zlcbK5ycAaFpJ7sOw+cFy32LpqxI5oCJYNkoVkuJO3eWS+2y0B/KvMWMGEMxg6XofPgnZxqQtvfYfYHNpWY74+B5a+dLSpv5QLqWIJRnn0FzT80FNCrCCy9OQuCh8dj+AzwPyBfGktGflUNf+Ff72sb1Vftoh52DqBpimFchOEu1FE3jew/4ll4IQ7wlNTWjzy9knETndbpXoAIIOg/YbsZM16HkXtW9X6oFch6GjhDOKBlNceOfSu84Ox9+eC7u99HPWfW7lJvUGo0n9/jyrSgGMEM9Zyp6S7aTK6302GR4bIuvdhr5mtylhA13j2T9uSfymZlhphNIKkL48YrM/AYiFScxBUQ4N6aKpzQvT8tAIhHKPSnXjdBkwrBtVmCsJAdC5u3 oJ3yNFZm gPPXf6G4xz/FxR/izC9v8UgBiUV89NfhrRJB5/UeFZkNnstw0MsjpidLWtuEMck1nq4YTotnyC7Xtg2b4PeaMMp0vJzEgQFNWWLW867LPLCzOeQwlLd1+i6i8xR+jt/RrL8B3g5riTaBi12xQfEvmYW7SAfauXhkbxo5p0hNerR/yAcCSeTj32o+eCbpW6GcnX/yi6xs3Dk8s1rQh26mKUn/cX+ybtsDireeb6GLMJzFIBXIP468g6/PdZzALW8VYmRRwD0VCbptCj7uy5WUGikU5zKnuh7nslm7kp3QkgdFQZsOQHxuip15fX/vx8uY7KS5MeRH1HXKU6fU= 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: Now that we got the kernel `Vec` in place, convert all existing `Vec` users to make use of it. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- rust/kernel/uaccess.rs | 17 +++++++---------- rust/macros/lib.rs | 6 +++--- samples/rust/rust_minimal.rs | 4 ++-- 6 files changed, 19 insertions(+), 24 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..209ad1bb1a49 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -2,8 +2,7 @@ //! String representations. -use crate::alloc::{flags::*, vec_ext::VecExt, AllocError}; -use alloc::vec::Vec; +use crate::alloc::{flags::*, AllocError, KVec}; use core::fmt::{self, Write}; use core::ops::{self, Deref, DerefMut, Index}; @@ -790,7 +789,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result { /// assert_eq!(s.is_ok(), false); /// ``` pub struct CString { - buf: Vec, + buf: KVec, } impl CString { @@ -803,7 +802,7 @@ pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result { let size = f.bytes_written(); // Allocate a vector with the required number of bytes, and write to it. - let mut buf = as VecExt<_>>::with_capacity(size, GFP_KERNEL)?; + let mut buf = KVec::with_capacity(size, GFP_KERNEL)?; // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes. let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; f.write_fmt(args)?; @@ -850,10 +849,9 @@ impl<'a> TryFrom<&'a CStr> for CString { type Error = AllocError; fn try_from(cstr: &'a CStr) -> Result { - let mut buf = Vec::new(); + let mut buf = KVec::new(); - as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KERNEL) - .map_err(|_| AllocError)?; + buf.extend_from_slice(cstr.as_bytes_with_nul(), GFP_KERNEL)?; // INVARIANT: The `CStr` and `CString` types have the same invariants for // the string data, and we copied it over without changes. diff --git a/rust/kernel/sync/locked_by.rs b/rust/kernel/sync/locked_by.rs index babc731bd5f6..b94517231fcc 100644 --- a/rust/kernel/sync/locked_by.rs +++ b/rust/kernel/sync/locked_by.rs @@ -43,7 +43,7 @@ /// struct InnerDirectory { /// /// The sum of the bytes used by all files. /// bytes_used: u64, -/// _files: Vec, +/// _files: KVec, /// } /// /// struct Directory { diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index f48704db33c1..3c66f2fbd737 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -132,7 +132,7 @@ unsafe fn from_foreign(_: *const core::ffi::c_void) -> Self {} /// # use kernel::types::ScopeGuard; /// fn example3(arg: bool) -> Result { /// let mut vec = -/// ScopeGuard::new_with_data(Vec::new(), |v| pr_info!("vec had {} elements\n", v.len())); +/// ScopeGuard::new_with_data(KVec::new(), |v| pr_info!("vec had {} elements\n", v.len())); /// /// vec.push(10u8, GFP_KERNEL)?; /// if arg { diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index e9347cff99ab..bc011061de45 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -11,7 +11,6 @@ prelude::*, types::{AsBytes, FromBytes}, }; -use alloc::vec::Vec; use core::ffi::{c_ulong, c_void}; use core::mem::{size_of, MaybeUninit}; @@ -46,7 +45,6 @@ /// every byte in the region. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::Result; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -54,7 +52,7 @@ /// fn bytes_add_one(uptr: UserPtr, len: usize) -> Result<()> { /// let (read, mut write) = UserSlice::new(uptr, len).reader_writer(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// for b in &mut buf { @@ -69,7 +67,6 @@ /// Example illustrating a TOCTOU (time-of-check to time-of-use) bug. /// /// ```no_run -/// use alloc::vec::Vec; /// use core::ffi::c_void; /// use kernel::error::{code::EINVAL, Result}; /// use kernel::uaccess::{UserPtr, UserSlice}; @@ -78,21 +75,21 @@ /// fn is_valid(uptr: UserPtr, len: usize) -> Result { /// let read = UserSlice::new(uptr, len).reader(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// todo!() /// } /// /// /// Returns the bytes behind this user pointer if they are valid. -/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { +/// fn get_bytes_if_valid(uptr: UserPtr, len: usize) -> Result> { /// if !is_valid(uptr, len)? { /// return Err(EINVAL); /// } /// /// let read = UserSlice::new(uptr, len).reader(); /// -/// let mut buf = Vec::new(); +/// let mut buf = KVec::new(); /// read.read_all(&mut buf, GFP_KERNEL)?; /// /// // THIS IS A BUG! The bytes could have changed since we checked them. @@ -130,7 +127,7 @@ pub fn new(ptr: UserPtr, length: usize) -> Self { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(self, buf: &mut KVec, flags: Flags) -> Result { self.reader().read_all(buf, flags) } @@ -291,9 +288,9 @@ pub fn read(&mut self) -> Result { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(mut self, buf: &mut Vec, flags: Flags) -> Result { + pub fn read_all(mut self, buf: &mut KVec, flags: Flags) -> Result { let len = self.length; - VecExt::::reserve(buf, len, flags)?; + buf.reserve(len, flags)?; // The call to `try_reserve` was successful, so the spare capacity is at least `len` bytes // long. diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index c327fe0617c8..a733168d40f9 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -238,7 +238,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// } /// ``` @@ -247,7 +247,7 @@ pub fn concat_idents(ts: TokenStream) -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } @@ -277,7 +277,7 @@ pub fn pin_data(inner: TokenStream, item: TokenStream) -> TokenStream { /// #[pin_data(PinnedDrop)] /// struct DriverData { /// #[pin] -/// queue: Mutex>, +/// queue: Mutex>, /// buf: KBox<[u8; 1024 * 1024]>, /// raw_info: *mut Info, /// } diff --git a/samples/rust/rust_minimal.rs b/samples/rust/rust_minimal.rs index 2a9eaab62d1c..4aaf117bf8e3 100644 --- a/samples/rust/rust_minimal.rs +++ b/samples/rust/rust_minimal.rs @@ -13,7 +13,7 @@ } struct RustMinimal { - numbers: Vec, + numbers: KVec, } impl kernel::Module for RustMinimal { @@ -21,7 +21,7 @@ fn init(_module: &'static ThisModule) -> Result { pr_info!("Rust minimal sample (init)\n"); pr_info!("Am I built-in? {}\n", !cfg!(MODULE)); - let mut numbers = Vec::new(); + let mut numbers = KVec::new(); numbers.push(72, GFP_KERNEL)?; numbers.push(108, GFP_KERNEL)?; numbers.push(200, GFP_KERNEL)?; From patchwork Mon Aug 12 18:23: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: 13760934 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 5FA9CC52D7C for ; Mon, 12 Aug 2024 18:25:47 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id DEDDB6B00A4; Mon, 12 Aug 2024 14:25:46 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D9CAB6B00C4; Mon, 12 Aug 2024 14:25:46 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C16756B00C5; Mon, 12 Aug 2024 14:25:46 -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 A18936B00A4 for ; Mon, 12 Aug 2024 14:25:46 -0400 (EDT) Received: from smtpin20.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 58D90140332 for ; Mon, 12 Aug 2024 18:25:46 +0000 (UTC) X-FDA: 82444421892.20.358BD2D Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf19.hostedemail.com (Postfix) with ESMTP id 131121A001D for ; Mon, 12 Aug 2024 18:25:43 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=sJY0rk4M; spf=pass (imf19.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=1723487109; a=rsa-sha256; cv=none; b=g/sLlicj2AHhrQfumj9omB9j2AschysNRiGapj6zSvOXuvWr11SrTa3h7+XSud9cqPKHg9 V3CJpJLIbWZt3iAKkRM966SDXMwYHpVzsHdkhjUc3udU3vsKZSWvK3LAKW+9cDIySYaxiU ThrnHKC+pp1ydtPJsM2AobeTN5cz6hA= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=sJY0rk4M; spf=pass (imf19.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=1723487109; 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=l/aK8SVNP4/by+IYOAh1dy1PdbqgPcDXyxNLX0L0/Ss=; b=awR7MGfUe7zCQype7TEN03A1O22UFK7kNyyAvMNQ9NMVdmbbRjnLkIRo9Atu22xDOdnkWm xxG9gcuny8iJNXxzdyv60tnMhDRKS8MxsEwY9cXRnYgK4pRhqiFoG00kVoK3yElP5MXLaz ku1VN+q2T3EGAwgA8bkeF0ej3qD/jfc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 02555CE0A6A; Mon, 12 Aug 2024 18:25:41 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3E33AC4AF0C; Mon, 12 Aug 2024 18:25:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487140; bh=m7HbTZHBJlRggfNUaOoLamnAddQQ70J0syR4UcM8PHQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=sJY0rk4M9CRwGFBQj6kA3sbwR/ZmLcxfe+tIJ4uV0rcOTwIIqbB7WbzkqHXgsu2Mm UROXeQoa0dDch3iwyW68ngAgaeNXpooPE7Nqm5RZceLi2EYWlv5HItx7etZ5EiPv5D vLE24RkZvPAPEH1zjsIz30yONsus8VI0Cb5th5wU/I2O2/ZLZhPi8wsvUPK3HOJpfX y8xMsFR4Apdry2bcw0so3b5sQahNPk4ItAQkzUV2a4auoi9oK4t98KDEBfjijJN75t Qha7iHPu9kFSUD9pxxFxIHNkgNlC/hEx9cMJTQm6vTyEp3PBOIzKvT73rUI6Us6maq Ly2irV4fbwLcw== 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 17/26] rust: alloc: remove `VecExt` extension Date: Mon, 12 Aug 2024 20:23:03 +0200 Message-ID: <20240812182355.11641-18-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: 8r5bw1i9zy1ythgzciy9yzpau6nedfck X-Rspamd-Queue-Id: 131121A001D X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723487143-807995 X-HE-Meta: U2FsdGVkX19BqBr7434S4jo46EuY16dnxQs/XTRUX37q5UeD+Jy+54GErHnmRPw8O65qgEh6BIBfq5EvDGPneSr3ncQRgNIPZSNeLN9kZDyPsLVh3bT3pWP9O13I8nUItrPiFz8/vEXX20h06Jdk2ZGGP4ZzWIi8LdvwL/WaIeJD3e/tx+t8Wr6SjPXrwlg8iqPMM30t0+BI4/dt+krXrd9x++K5+MSkxJHlZ5ec5H/2laf4GL5QpMtEVnGvig/LDsK5V71aWICBxdDoNcU4SsmMmh3iQwhbotCJoJ/7zH1gAwqTHfl8HD0ZsU94bA2wuXchWnsoJI+3z1izpy/p6C+wrhSkF7//HI1SpiY2lU2xFP5tvmCpk+dCkaIqNETUaMe8cZgVsUYmmGYDMsgrFWATdvtTrdYqoaSUMBI4NrhzHhePLT82JNqROCDmEYgVyWjQ5UzN17fu8yowEz7qLIzJrzNZ+D/cwAd/FMAkPXnKD6WdLIg1ELhCI16fh/0nBKFU2wVynTQFYsIHam+1YEzYmXBuWkhf+4zVJflp70zM9KOh2CVBTspPSEXo+f9WzaAb9EA9ftxpK9klFrCV3+fO84E4bTvFnM2dVR13rHV+5arQmItv8eLRnL8/7H4InzYv410JCz5hFuxxX9Vh0hbrsIrnbPvyj4OPJHbPGN3pN/9PuM2dbrQFxyhsYXnARF42Rka1iMhSHWrQeCtE/QVgdGLKin9IRrLi+tYutUFoa/xddUpdDDVEwhUsibJBOr5oQ1rcuQRUPCc1fNwYXyvbN8Nk+AFik30MVHi+uO3yeZfzzPy29Ek6F/t3WgyXW3AYe6ywiJv+13tPoRGM8Iv1MomjI1k3fVHK0DHf9d8bKp1mT4qwrpQeftxZ6gN/3kcpIyJThfO5gpGs3W2X0CbsJsBXimiZewHbeknNIQDs6MCCsh2qoO3+Jd/ymZbfddS83ICvlbFj8NSbqT5 8ozOyygX abPM9vzSKXYuNbk7KkRzb34rkUoVTTNocxppzvUlGqkzhbcqMGVZNOcRpr+7MBMQU+/dWC/KUvErjYxoorcKfwV/kXhLOGL2Q7YA6NlWm6gAJqdXkS6kHrKYCytV1ujoJ2BGTTQCiexGqUKlkFzNGrhPfChbvNESARzytdsGVAum1tpUDD92tQ+ndk+EsCGrvxrCGMNcYqYvnGfZAq8OauBSAmrEqGkHK7dDGLVI1pjjNorm8oxSJZ/7XEtsRfbC7KshDP81DTj6W7TErikjWCXDwy/m7RCtJg3ecfBWTLbGotJCG0Kn6+iUIQ6MDI9BsFFhK1SRIDZ/Yz5U= 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: Now that all existing `Vec` users were moved to the kernel `Vec` type, remove the `VecExt` extension. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 1 - rust/kernel/alloc/vec_ext.rs | 185 ----------------------------------- rust/kernel/prelude.rs | 5 +- 3 files changed, 1 insertion(+), 190 deletions(-) delete mode 100644 rust/kernel/alloc/vec_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 4035644b5dca..820ef6072e02 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -6,7 +6,6 @@ pub mod allocator; pub mod kbox; pub mod kvec; -pub mod vec_ext; #[cfg(any(test, testlib))] pub mod allocator_test; diff --git a/rust/kernel/alloc/vec_ext.rs b/rust/kernel/alloc/vec_ext.rs deleted file mode 100644 index 1297a4be32e8..000000000000 --- a/rust/kernel/alloc/vec_ext.rs +++ /dev/null @@ -1,185 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0 - -//! Extensions to [`Vec`] for fallible allocations. - -use super::{AllocError, Flags}; -use alloc::vec::Vec; - -/// Extensions to [`Vec`]. -pub trait VecExt: Sized { - /// Creates a new [`Vec`] instance with at least the given capacity. - /// - /// # Examples - /// - /// ``` - /// let v = Vec::::with_capacity(20, GFP_KERNEL)?; - /// - /// assert!(v.capacity() >= 20); - /// # Ok::<(), Error>(()) - /// ``` - fn with_capacity(capacity: usize, flags: Flags) -> Result; - - /// Appends an element to the back of the [`Vec`] instance. - /// - /// # Examples - /// - /// ``` - /// let mut v = Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// assert_eq!(&v, &[1]); - /// - /// v.push(2, GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 2]); - /// # Ok::<(), Error>(()) - /// ``` - fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError>; - - /// Pushes clones of the elements of slice into the [`Vec`] instance. - /// - /// # Examples - /// - /// ``` - /// let mut v = Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// - /// v.extend_from_slice(&[20, 30, 40], GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 20, 30, 40]); - /// - /// v.extend_from_slice(&[50, 60], GFP_KERNEL)?; - /// assert_eq!(&v, &[1, 20, 30, 40, 50, 60]); - /// # Ok::<(), Error>(()) - /// ``` - fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> - where - T: Clone; - - /// Ensures that the capacity exceeds the length by at least `additional` elements. - /// - /// # Examples - /// - /// ``` - /// let mut v = Vec::new(); - /// v.push(1, GFP_KERNEL)?; - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let cap = v.capacity(); - /// assert!(cap >= 10); - /// - /// v.reserve(10, GFP_KERNEL)?; - /// let new_cap = v.capacity(); - /// assert_eq!(new_cap, cap); - /// - /// # Ok::<(), Error>(()) - /// ``` - fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError>; -} - -impl VecExt for Vec { - fn with_capacity(capacity: usize, flags: Flags) -> Result { - let mut v = Vec::new(); - >::reserve(&mut v, capacity, flags)?; - Ok(v) - } - - fn push(&mut self, v: T, flags: Flags) -> Result<(), AllocError> { - >::reserve(self, 1, flags)?; - let s = self.spare_capacity_mut(); - s[0].write(v); - - // SAFETY: We just initialised the first spare entry, so it is safe to increase the length - // by 1. We also know that the new length is <= capacity because of the previous call to - // `reserve` above. - unsafe { self.set_len(self.len() + 1) }; - Ok(()) - } - - fn extend_from_slice(&mut self, other: &[T], flags: Flags) -> Result<(), AllocError> - where - T: Clone, - { - >::reserve(self, other.len(), flags)?; - for (slot, item) in core::iter::zip(self.spare_capacity_mut(), other) { - slot.write(item.clone()); - } - - // SAFETY: We just initialised the `other.len()` spare entries, so it is safe to increase - // the length by the same amount. We also know that the new length is <= capacity because - // of the previous call to `reserve` above. - unsafe { self.set_len(self.len() + other.len()) }; - Ok(()) - } - - #[cfg(any(test, testlib))] - fn reserve(&mut self, additional: usize, _flags: Flags) -> Result<(), AllocError> { - Vec::reserve(self, additional); - Ok(()) - } - - #[cfg(not(any(test, testlib)))] - fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocError> { - let len = self.len(); - let cap = self.capacity(); - - if cap - len >= additional { - return Ok(()); - } - - if core::mem::size_of::() == 0 { - // The capacity is already `usize::MAX` for SZTs, we can't go higher. - return Err(AllocError); - } - - // We know cap is <= `isize::MAX` because `Layout::array` fails if the resulting byte size - // is greater than `isize::MAX`. So the multiplication by two won't overflow. - let new_cap = core::cmp::max(cap * 2, len.checked_add(additional).ok_or(AllocError)?); - let layout = core::alloc::Layout::array::(new_cap).map_err(|_| AllocError)?; - - let (old_ptr, len, cap) = destructure(self); - - // We need to make sure that `ptr` is either NULL or comes from a previous call to - // `krealloc_aligned`. A `Vec`'s `ptr` value is not guaranteed to be NULL and might be - // dangling after being created with `Vec::new`. Instead, we can rely on `Vec`'s capacity - // to be zero if no memory has been allocated yet. - let ptr = if cap == 0 { - core::ptr::null_mut() - } else { - old_ptr - }; - - // SAFETY: `ptr` is valid because it's either NULL or comes from a previous call to - // `krealloc_aligned`. We also verified that the type is not a ZST. - let new_ptr = unsafe { super::allocator::krealloc_aligned(ptr.cast(), layout, flags) }; - if new_ptr.is_null() { - // SAFETY: We are just rebuilding the existing `Vec` with no changes. - unsafe { rebuild(self, old_ptr, len, cap) }; - Err(AllocError) - } else { - // SAFETY: `ptr` has been reallocated with the layout for `new_cap` elements. New cap - // is greater than `cap`, so it continues to be >= `len`. - unsafe { rebuild(self, new_ptr.cast::(), len, new_cap) }; - Ok(()) - } - } -} - -#[cfg(not(any(test, testlib)))] -fn destructure(v: &mut Vec) -> (*mut T, usize, usize) { - let mut tmp = Vec::new(); - core::mem::swap(&mut tmp, v); - let mut tmp = core::mem::ManuallyDrop::new(tmp); - let len = tmp.len(); - let cap = tmp.capacity(); - (tmp.as_mut_ptr(), len, cap) -} - -/// Rebuilds a `Vec` from a pointer, length, and capacity. -/// -/// # Safety -/// -/// The same as [`Vec::from_raw_parts`]. -#[cfg(not(any(test, testlib)))] -unsafe fn rebuild(v: &mut Vec, ptr: *mut T, len: usize, cap: usize) { - // SAFETY: The safety requirements from this function satisfy those of `from_raw_parts`. - let mut tmp = unsafe { Vec::from_raw_parts(ptr, len, cap) }; - core::mem::swap(&mut tmp, v); -} diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index bb80a43d20fb..fcc8656fdb51 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,10 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, vec_ext::VecExt, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; - -#[doc(no_inline)] -pub use alloc::vec::Vec; +pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; From patchwork Mon Aug 12 18:23: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: 13760935 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 E82F8C52D7C for ; Mon, 12 Aug 2024 18:25:51 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7F9636B00C5; Mon, 12 Aug 2024 14:25:51 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 781EA6B00C6; Mon, 12 Aug 2024 14:25:51 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 623216B00C7; Mon, 12 Aug 2024 14:25:51 -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 41E466B00C5 for ; Mon, 12 Aug 2024 14:25:51 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id DE7D4A0328 for ; Mon, 12 Aug 2024 18:25:50 +0000 (UTC) X-FDA: 82444422060.11.1838DF1 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf09.hostedemail.com (Postfix) with ESMTP id D67F2140029 for ; Mon, 12 Aug 2024 18:25:48 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Auu0ERRR; spf=pass (imf09.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=1723487080; 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=sT2eAl4+IxqSwmkPc/e/PoVlVcf+D4UkLX6oOA2Sql0=; b=tAlg8oSxCeYeh9KpXcoudzJ0NhNTxoILEYU/QOAuw6Z1SQPM/2Kw2ZAeAufhglxniBd+Rx zgwUtndoid2bhTp2equQP98B1y2i6llA41nH8aLV9Jmtse69CeOdM7vps9c0ENCalcRsKS 0HXaWM4eow1aqIjxqKwqSgcW2er6Xis= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487080; a=rsa-sha256; cv=none; b=fqF92+VXimkE6E07W0LYzISJfY6TStg1LYFGVCpaEdptoMXhsS7vvD9po6i2Hko0JkpBRZ z+LVnnbYtmNuYPxApQNH7D/6X1TFadymLCBbYUefbny6JVQ77L+QfZak5TKsZvq4x74LL+ ygC+A1kBgR5uO67SGNXjBwayyZJWf1k= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=Auu0ERRR; spf=pass (imf09.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 Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 65794CE1037; Mon, 12 Aug 2024 18:25:46 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id A1AB1C4AF14; Mon, 12 Aug 2024 18:25:40 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487145; bh=vy8jMGyAXJW8mhTpujuxbveXx/4kmHcgFJLvoNpXzVk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=Auu0ERRRl9iKXCUlp+SoDSPzRZnO6/enifkp7q/lRVDC359BYyHjhZIp3yRatrfYF S3ccNm4tHObneYmnWQKVsryy2upOOW8E8rI+fkP9NEOVwlxld6DMJnxx8AOeygcl7V +Q082Cm/kttOPG40J20BMGYsBqeouZsvblgAsois/QIOy/WXveFj3AhYFQAUHHobT3 r0SLJX91V7pQno0s86X7/UzrtBDTnvD9NZulQ9yqyVGlD2zoeGMT0kdTG8n6jaAgSd tUHgiQ3e1KWZAAPB7UbIyMgBTSCmkGb4iyYgxsFJDcR663RNTI3JqDxrNYQ4EznMO+ b5v0rZ4k+hpOg== 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 18/26] rust: alloc: add `Vec` to prelude Date: Mon, 12 Aug 2024 20:23:04 +0200 Message-ID: <20240812182355.11641-19-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-Rspamd-Queue-Id: D67F2140029 X-Stat-Signature: m5xm4fwrqqtu91z6sox79wq681kxi9ge X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1723487148-538208 X-HE-Meta: U2FsdGVkX1/Du5bKiK4TgCjlO+pbsjEOI5ol1dsMzbPy93yGjapFg/9aC/gRATT3Pbt7C5jPGPTLC+04pMrBk8asDJj4CRIDfbCy5fCjOjIZO3IhYiCuKM7pmLSJP136XIaJaaKNvTTYG7+QIlYrNuELCj0UlBo8k+S8uBDJtemsMOgqMEYre2OBwEkgep/pAfL7Z+vFbJRtNwqzEPPsuYLFo6PQ9EvCqYGRofDW9u6GB5doAHiWJt44TT+GOFDcmXZx9ldbKQN4mHi8DMp+uT4AzURseWPvP/rYm2amq7IJQiO+7xtaocHhRooEKDcfuQjo7lDIerT6T7i0jJ8idnVO9WJETPSWC/TnEZiPlsiW7CSg2YeURDeVzvu0it2vWVhS3S0yY7GHNh/YQSnDl9ZxRBh7eZS8fnUBlIlvTbWFugcIzRUQdADzWvuHYo2ivX6IVRbiP7S+Pw+KIENDSGZWuGK0Kef7wV+e6k8lFE1FlTCO4BW1+12DWBBKUqAiE5HoKMwZwkD5ixRnBzwQzzZP2cwx1JqT7/n3YjD8Sq3HYBxgkmdqu0qzhIwYZO/3u4zNBVgzJqnvf3D2gyx49CIsOemg/ed/6rNlnMlYCYIkEhSJiVto2qXLGRe9lb3CRyimlUPMQ/RnqnrgVNo+7oKFiY4GT35UsTe5Zo3fAu4i7N5r3ggHtw2yoBFYYoZXG09EnjPDMNu95zyL3YlWzvLZFFoL4xMHPhZQCdi2OXRPAn8kMWvKmZTpPd6+iHFocyyaYk32xooobeG/LkuAFdRaKucWWrwOCrfhAgs1yztJoiZHhjT9MMkoPNxBiR8pdF4RH93SzEUfZJvV4O0IyNEfBZoUoCN3A1uQnq3Oa504OPG5L1dQEAHfx/VSreU5RkbjlKS+kEr3hF8fzsLmMUN6IABWhfdFG3CrFUF5qOPu5ZfiGoZIOZwCwMJtdDruA78/NOO62KvVhOlj96E W4YyI6rY B8ji6r/Wn0slvIJ5aNcFYxQLYwFv27k4AhBaOUxdqjJNgDD9q1ejdMRucQFBl1l5c0HGpagomORuCnCTxG0J5LgvhI6iSXELizQZit9EQtsSWhpfbaOxIE6f5MNJCnAiVSO9XJ4b/EPSA/GXUsv3XuuAs2/ihWhv99psq7AqoLfLX3/Uea9UpTl75HBNA2V9XOOs5Yye5LNofo4uK3cBe3je6HaABeoIe2QmI2o/KqalhbcqUxEOu94HTs5GcNQCaw//jt+9Zmdmq0rPRqi3cVo9gway+puop0ZjZeMqSwpcQ3g+oiw5twQMHrKESne0r+hMuGySGAHZAgEA= 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: Now that we removed `VecExt` and the corresponding includes in prelude.rs, add the new kernel `Vec` type instead. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/prelude.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index fcc8656fdb51..b049ab96202e 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -14,7 +14,7 @@ #[doc(no_inline)] pub use core::pin::Pin; -pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec}; +pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec}; #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; From patchwork Mon Aug 12 18:23:05 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760936 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 5FCFAC52D7C for ; Mon, 12 Aug 2024 18:25:57 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E634C6B00C8; Mon, 12 Aug 2024 14:25:56 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E11B76B00C9; Mon, 12 Aug 2024 14:25:56 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CB3386B00CA; Mon, 12 Aug 2024 14:25:56 -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 AC4516B00C8 for ; Mon, 12 Aug 2024 14:25:56 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 5C94912032C for ; Mon, 12 Aug 2024 18:25:56 +0000 (UTC) X-FDA: 82444422312.16.ADCE3CE Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf07.hostedemail.com (Postfix) with ESMTP id 58A6F4001B for ; Mon, 12 Aug 2024 18:25:53 +0000 (UTC) Authentication-Results: imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RFANQs8K; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf07.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487098; a=rsa-sha256; cv=none; b=VIiSZ7rGWdGUIaf5CPBqz0YPE5jasInVwzqPtfs6g072A9xEfASmg6gl5aSTx6wRY8aD7o /QLmeCfZJeeBD+lt88D9Et6pGVBHvEISW8bIw0MgqztVRyBPrLUVP8rBP631gbtg9oDV/w SEWQv35CYyZ4T4MYdaFkJdwAB56Sxio= ARC-Authentication-Results: i=1; imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RFANQs8K; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf07.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 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=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=g1R9gIj4SQMr42HuGSUWbYPxxOPjOGUq6XkQelh+mrc=; b=NfSijM3u2/nvb5WS3YdrhsJO9KZ4GxVuiyz7LNvWyRneh0RA1hr37XCBqUicyMYf7JP73B FeOn0m4S7DLElBQuRamoWj9T/EoWLKY4rUfEyc7o14iC9OYE2USOrPflYTWKvFYrmlCn4D YQnBqFS39kb7HQWFvxuTqSB2ctsankw= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id D028FCE0FE7; Mon, 12 Aug 2024 18:25:51 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1086BC4AF0D; Mon, 12 Aug 2024 18:25:45 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487151; bh=0dpQ6RwX2xjp+lowuXDw7W+vANiY3byDZScI1bxbWmI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RFANQs8KnWUbqjWcgpReCK3akBNyTxN5G7+ALY8zDgxdFBUbg91hMAYGLm8Cyy46y 8hQ3vT0NqM6HMBHSF7PX/VMuaWGV6mqSQsdqCsquwk3VNxrZsONORzV7d1nPVvZhFR g2ojtllxh+Pkc9ypjJW9hBOU5J/CAVz2utpgqVYP5Ty+Itj77oCQRABIyPQHSL6bv3 cbZFxVx2do+sVzOMzZnlTpud1jdCOey3VwBjhOOZqaQYrwBUvp1JySoJIiPfkjS5Zp E+FgglRyvAii+4VL4l9l8d129f9gLgWwCHBKnPLqu9NtmuAn2KirH56B/V7DCIW5gY wP2q8rBP7VSEg== 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 19/26] rust: error: use `core::alloc::LayoutError` Date: Mon, 12 Aug 2024 20:23:05 +0200 Message-ID: <20240812182355.11641-20-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-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 58A6F4001B X-Stat-Signature: ircsq4ff7up9bincyjrxnbrddcor5iu3 X-Rspam-User: X-HE-Tag: 1723487153-479695 X-HE-Meta: U2FsdGVkX19RuNJQfKu7oeeudAIcqTa6/CRXRdj4NWycUslMO1wCSXG8O531tg+0HTfJOJ5AYxuXHDWJbuKxdaVVnpiFMAZXK8K8TEUd/EfrbF/44H0F/BpteALUrgv9cRV9X47aJ1c3/29xqScXiIFQsVKUJ/Xt+71kG64GfcQX6fFQDZBIDP6+VCnQOHrN3keE2z6JPrpLhRKPIXW+DJThvTA74nRZ0Xoixfki/Vyb9QeZRLOycsNQCxBCxy13Noq8xTEWody2UYcxKdSTk0LIQBhPkexZyBd+v6Riu1czPwGZY3OSWMBX0luAA8e3wa7iwgh+zVTCPJhCAD9GgFydzzRF+WZeig18prSECkA3WpZraP2SdvrDmMXyKb41HgU6vSusuASko42j40t8sY+V0JpdQBMvx59crStZE4Dp97gyz+r84SUKwy5lrjClc82a6aia7OgWJF0hIhEL2aTuLMfeZvAoKGegSTL2RGirzsBZntEQwBeNDMQRWISHwSJQU0BzdnbETZlkgeltiJAhJ3QrS3PCUVtFYRHgF1dWJpE4y1qyyhhiORXzy0CP1+NVu3uHTOrgZw2EOJdeSd05AzattGXoEe80arTeEeoPmbmR3xe35IHiXbMJ3NfIx1iiNLWLD+LaFsqG3uySHFNlZDwuURP0teavaDCX+VxkkDfLwiZaDPN9aeiJbmTj2WcltZ7trRv/B39lFYr2F612Pd89aSgjAoUiqZhXqjWpdAWZJnzSqaz5vSU5vAhk+UXPxd1wZfUYllQIbnIvWXCJYZeFlPWgdMz7jKE7ExlEgrF9EBZNvr7loTgDuK9YmQfHM30URL1MdHsjNm9ju9WlVdhgGNgYxjsue1DMnna52G5imuzDa+yIojG3TZp0Ue2qTRgAz0dhUazq9X/s+mLRK9lmhpimdGxMf5oCDyvJzNYV0QbCEBEEgp63xljW5Eh/+EGljEpqQwpczLR JYAaEhdg jhbop+MuTH+wSlsNw2E+eJNMdOOxIoojEu13tggmyPsSwinxklsl2XFl0yQqtk79l59U3HBuDcR8DF7WYenP1Nd3fV+pPvkNST0B+3n5AMRjcDVyDIYw6MsOqJkdb36MZGdRM9Z4/BLonuHBnqQpdLNJbwZ44njdVIW85VVbNUMl7DSUxoSFZTh+sK+JHxyUvQv2/qZ021rSfN6kByIglVr08HH0WHxba5Dr3EMk/8LJ8b/Nhoj3pTb1FSE0XfrhpVM2MfQx+zbleV6zHpYWaBM2yh0H+JL3AvK56pGdmaKgjPCCY6MSvAZwYV03MxndIsCCYrfEIF16r9ao= 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: Use `core::alloc::LayoutError` instead of `alloc::alloc::LayoutError` in preparation to get rid of Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 145f5c397009..2d012cc3881a 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -6,7 +6,7 @@ use crate::{alloc::AllocError, str::CStr}; -use alloc::alloc::LayoutError; +use core::alloc::LayoutError; use core::fmt; use core::num::TryFromIntError; From patchwork Mon Aug 12 18:23:06 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760937 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 F16D0C3DA7F for ; Mon, 12 Aug 2024 18:26:02 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 7D3366B00A1; Mon, 12 Aug 2024 14:26:02 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 75B9A6B00AE; Mon, 12 Aug 2024 14:26:02 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 5FB226B00CA; Mon, 12 Aug 2024 14:26:02 -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 372A06B00A1 for ; Mon, 12 Aug 2024 14:26:02 -0400 (EDT) Received: from smtpin02.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id EBB5F1C1DF0 for ; Mon, 12 Aug 2024 18:26:01 +0000 (UTC) X-FDA: 82444422522.02.7F1AE61 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf08.hostedemail.com (Postfix) with ESMTP id CFCDB160030 for ; Mon, 12 Aug 2024 18:25:59 +0000 (UTC) Authentication-Results: imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=p6j+mJpZ; spf=pass (imf08.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=1723487067; 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=4Rd5AInb2DngjvLHcLtOVGOOZeTvJsEDnW1UeOyjq70=; b=7S0oPOrQlBv3Dt1srXitcFHreGl2HN0nCcOD2mnl7EWaqlDI66l6pGXZaIr2f6n+KlHCCk T/if7+9+1fs2MIB9gB+khOEz9zcac4gWs9Yp4LTlwVY3fPmcVZNBWxF9t/psJgNc2aKnaA VUaztDHh++KCwc01MV0zS1OISuZD/EM= ARC-Authentication-Results: i=1; imf08.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=p6j+mJpZ; spf=pass (imf08.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=1723487067; a=rsa-sha256; cv=none; b=0GOWKEmg7cVLQ+jsmwfLfBO/LNlwo/s1GBF1Xz+PRlutoYMfuIfYInKBGJpDxjwZuYV/Wd MuvapPOc0djf1ENRc5tiT639skIfzL5oSHSGf28he773d/HlULi1Gza2GXxUhDvS2dbHMc w9MhXsBPtMQy+h18yvHYPGN14csxMvE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 3C02BCE1034; Mon, 12 Aug 2024 18:25:57 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7B5DDC4AF09; Mon, 12 Aug 2024 18:25:51 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487156; bh=2F6Eq8ZEErgwGsu4sxTQuCutTP6qKEaQ1vvV8Sy7t1I=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=p6j+mJpZtX+GQyemhh1YN3z+WuLKkO07HkID9hB60cEgOmMMs5DJr4cHKl1pgGPeR 2zIpFnJHzziufgeTVg+xA5uce22bQeLWbfLDPV5oiSEq+SNKklaaVdlEROb6c81rIQ Q8CDN418goWJaq0ttWBuLX4VyQ7c24iY7eQ9d+3oJ7Gp9lREGXADM9jAIKJ3qTMJq4 eV4yUFZsIj6KTKDzj/3ZaX3CItDMBhnlUIwrWi7BQ819hVr6+KgPLw13G5v6DLQ6K8 tTVj59KMhsXhTZd8JhgIDl+XQxhKQiN4I+WuM2Eg0yLzJBA4rY+drE+cbFM0avdu4N sSJ85j4Uw23OQ== 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 20/26] rust: error: check for config `test` in `Error::name` Date: Mon, 12 Aug 2024 20:23:06 +0200 Message-ID: <20240812182355.11641-21-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-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: CFCDB160030 X-Stat-Signature: gcaiz7paamudqtqf6f7hbyjbbsnfymfx X-Rspam-User: X-HE-Tag: 1723487159-512748 X-HE-Meta: U2FsdGVkX1/95h/azFzjFms83Sf+ffrX7z2hyxgZV/OhHki13xjLpB7C20LD8dHwPtfd49CWTb9Gf0Rq+V0AFSon6t4EDf5KKCX21cJ91P+vz13bK+TJBIt//iPqJ0nCR4rGb4ouOwRyUaLiJT4tGnAMU4+iNF39JZhLJr1h6zqcnIct5WNkR78Y2IFC/poD0QPE6pxWgFFVuylzb4MeRVae+ZZpHpBZV7yv68l/hejV/O1LDDsYFDUTMK9xRgA6j0eVgtXXXqynYm/wgYP3uiFvtjy88ZU0t7+yQ3QyZmaSdG14RuYomZU5fHj0BBs3OXIxGM7Xw0DZLLJS/jRvtYxpSj6FDSE6LgDIyTOQ2UlUr5SJJr4tKX37F1W0jYsccEpU9HvnvcdW4DjFU5iRdFkSfp2FGuipbKry/A9cGFX+YW8eX491Pb3PDamMaO4Mx9MCjAaGcgOHhz5xR2O5KVH7XR68lFNX4rkeLpnrtJ0Rla3zdxnzIlWAy6VdpKnZfk2wrSfaK+zC06Fa+ZfKM9IjoNtvYORQLjktQCjm6x1CHyZcleAwuw3fl3cwIuUfYc0OlZTjTq0TBrmePY84K6Vppzwc/AUkwOcOZc97RnS9OUTXkt5+IC5nsY8zBzJH+wuv6234hGpCKG5wHA9BwFTSQlDRJFlUDFS7W1oPXN+vpGmoyjmg/ZGmMtXLFFbrJy9ZCH0R5ZgfBD2A3u+265M9so1jNi4LHNrUBaqt/TbEuVP+Z3QvBwXlDFABuF4hggoUE3hxlUQ0G7vy8KUIQAJgWrSrf5TrSDMqBynfwVaA4FTwnDm69YeH2jLZODon77kbvgyMhHGNijpTSkV1ZTGVfctgpgolICBmuihJxlJ4nUyS9+30qkDj3GgdpZJihgQo13vF//1digy64R8F2gSViIgH9xtUo06HvDLtqePeFLjYVSMtFJk+ci71N7F5yYj20QHZ2v1npjS6P3V j8SFNvXs JePsITRoocYEplTvnVQ16DxtA6I27Ooj6TFlgg6ZSaKIKXkhobRRCpMmMAGhYWGpwdefKD7hIhVXRL94Ete0G1HyyKnaX6axpuLJkIWDQ5lKRAhHFriWHLcal4VGMcfkSdvvD0lWW2G+6X8c1Dz9bGLnSzLmY9rjwp0LF0N/zbW5fNjdUj58zc6j1HWqLnYNDqIzeIpsC35sP6Ss0/NrysYPDj/TDeJdyA5qh+BaGSIsJ5O4lo1uyJSjtthSXYqX0IeQjaYO2OnC0ikdy0jvnZrjc9B9MMGOuZhl+wKS7nD64GvXMdKW26yVt/rCNZWY/xRmlNLmyIYSagc8= 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: Additional to `testlib` also check for `test` in `Error::name`. This is required by a subsequent patch that (indirectly) uses `Error` in test cases. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/error.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 2d012cc3881a..7adf889b9526 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -140,7 +140,7 @@ pub(crate) fn to_ptr(self) -> *mut T { } /// Returns a string representing the error, if one exists. - #[cfg(not(testlib))] + #[cfg(not(any(test, testlib)))] pub fn name(&self) -> Option<&'static CStr> { // SAFETY: Just an FFI call, there are no extra safety requirements. let ptr = unsafe { bindings::errname(-self.0) }; @@ -157,7 +157,7 @@ pub fn name(&self) -> Option<&'static CStr> { /// When `testlib` is configured, this always returns `None` to avoid the dependency on a /// kernel function so that tests that use this (e.g., by calling [`Result::unwrap`]) can still /// run in userspace. - #[cfg(testlib)] + #[cfg(any(test, testlib))] pub fn name(&self) -> Option<&'static CStr> { None } From patchwork Mon Aug 12 18:23:07 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760938 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 61725C52D7C for ; Mon, 12 Aug 2024 18:26:08 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id F26186B0088; Mon, 12 Aug 2024 14:26:07 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id ED6B26B00A7; Mon, 12 Aug 2024 14:26:07 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D75DA6B00A8; Mon, 12 Aug 2024 14:26:07 -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 BA04A6B0088 for ; Mon, 12 Aug 2024 14:26:07 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 7740C160359 for ; Mon, 12 Aug 2024 18:26:07 +0000 (UTC) X-FDA: 82444422774.11.6C7BF1B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf18.hostedemail.com (Postfix) with ESMTP id 6FD891C0012 for ; Mon, 12 Aug 2024 18:26:05 +0000 (UTC) Authentication-Results: imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fE8d51Uy; spf=pass (imf18.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=1723487096; 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=dkPtj490zlFGnVlHtWZ3Siudb6D0KpgjZXn9rYj4+jw=; b=ZH6qa9iK+MnqF7qboUYCKb7D8me1S8oABTo1s0fMRTk/cXRhZwKy5McLc5hFgJ6dm2HEgC wMwr03ZARYnETDSPbHclVYs7MnPbMPDaXZZbSnitlis2k9hrh8uSaauFr3pB9HduEX2Ujq q+pq9GnQFAyKOQ5nn1dLzUkApIJY9Js= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487096; a=rsa-sha256; cv=none; b=VAqjMzfvOxvdLXOzGYEL3SFl3GySph9i5rzV4dkmmtuMiXcsf+LBGpXY/2Jn/4BVNI2YEp KDxzGzrtCFxuE+m40FWQu39PvCRKkbGHDeNtzqSFWUnq7wtZ8OITLjdZmvCJF1URImsC0E 8qQBY79sgmeKEf2ADGxIYHiRpQx6r5g= ARC-Authentication-Results: i=1; imf18.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=fE8d51Uy; spf=pass (imf18.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 Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 9A585CE0FE7; Mon, 12 Aug 2024 18:26:02 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DAB24C32782; Mon, 12 Aug 2024 18:25:56 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487161; bh=tl80HVK20EtCGNYhPnG7N36D8g8ociS1KN//HywX5k4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=fE8d51Uywi9gQkO5aVDXQS6bCB1Esv9I/pGSi59+t323AQL2pLKex1YwXjRRlx6d5 /eMp8maDX8Z24YUglnm+TSz8p7tRMIXY6wA+hBLiVjTzJB8Z8UI4V7rfMUIySu8X05 NbpWU0BEcdDgCiWUCEJnk3RlTEtUoBjFYUZ8WYduUgOgZvaMJuvH5NX8w8Gb1L7yJN UOC7iLtJy1PUyPNFyWha7v5bQqsNZqK1J4V/j69V+bjeeiTqX8Fh8BY5ogM0CUP9H0 XS038gpPB6uo1XOmJhNY4JDsPmsllDzyaQFHv2n1Vfa6YQEuYH9rcE9xx7NjVAw0lk iaDfSWN3spO5A== 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 21/26] rust: alloc: implement `contains` for `Flags` Date: Mon, 12 Aug 2024 20:23:07 +0200 Message-ID: <20240812182355.11641-22-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-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 6FD891C0012 X-Stat-Signature: joh6kc7r5rshk1a4e45dhjbps6ggjoxx X-HE-Tag: 1723487165-5875 X-HE-Meta: U2FsdGVkX18B0EmSnh3cB4qALDuzd7RlSoyV/+iqLo10BbJt1sRK/IAG+RnL7y2iBRkLn1aS7Mx1Ud0qEi+CQ5H+4ptK7Ye+uC/++O/6S2XXi+s84SUh2wuRGpCdjauIgh7OfQl++BGzBURmgwlBYIrM6INMvr3roCUhM0armgznmhgcU81FzVGgFxckcytFEZhk0wRaz969rFoAOjqFu8FnbJcI0AGpJn5/4y18/QXnBBxFLrRhUoNo6PlRaedQA1ADHwcLVMTjUxf4s5wvyt50LhnUM6ZcuQ/hkb65N3o73FLfXP5RFDV6UvNoMKKrcxuj0fiDsYRDZvX1IIial2B4LHeZpt2GwnzB8/RF6B8ngeUPLkHUtnUXbCzqXS4k9vqPj2ThlDU+obX61BGHP9MAjD716M9AwmIQ/lRDhVqgFFqS4v19LeM5QZCQtsXGH+ugDuC4P1DfQcvyCYqQtbd7Qv3UICXP0DMTq25QV0ZGCXMza4krO1h2nN7ZXxZ1RP+yoCEPF9VGoie0VazPqrtdn0s/bMxu2yNzjyYLxaaIU/Hvt0KmmskUHJG6egLPthede4M9allHQFtr+VB6bpfqzFRFPMceQyfYKue5kSipJ/tTzBkhPHF4mwKC7lzifcmWpXa85i2pxrYJPo2QPRrSdKNgednjbhmm3/UPIMXSGqISAuygW39yM9ef0N/ycpaDMe0nOxqIWcEhQjO2XVLfYcKi+jPh5fNLVeHxItY8aQwDZf6IrfkawBtC1Hbv7TRogH8G9P03GqK40hy8rfZens4fxDcfXcXqurKg902jRGyel3I8TGjggJc9d7J1YbUER2ZMG1uU/xMvem5r++ZfVvXI9k6+bukyIu1mRrkyn7El6n1TJJeNtentkD1HfzflKe8KR5F3012MGm48hZikBf6avAZGYDRcoCkszoEWv+N/bwRAGiTzZ5Eio7cFk7/pmqjE0e1kXB2dv8E XzOAtm5O KAmehG8vTOZ9Ar3c0uwrqb20HcTxvZp68ORU6mlMSDAROxW45t2OemiG3b6JTs+Xd4sHrtwxFUPVz1DByLmlRGs8Bofl3iP2SXmf/mJJU8T0Tb/hlUGzhO5Zi/xqbHRDn77SmYCCGOF8Qw/fQW03P/ENfWMbNbwssp/LvD7EBpIGIXVhreNXdW22RF/hxD+9BS3EcLGALk0E6d/7Cr5ERR4QYxxDEnzkNa+gUFhQxBPWzdSYiFhF7wsVX1J53gyiQZQDm2YOo3b60ws3sUncpeaK+S6A0uTFBFBpG7pdsE4JBxPz80klNvk5LevzzMsc62EvQrWR0lUq0am8= 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: Provide a simple helper function to check whether given flags do contain one or multiple other flags. This is used by a subsequent patch implementing the Cmalloc `Allocator` to check for __GFP_ZERO. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 820ef6072e02..be2bd0f1e74a 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -34,7 +34,7 @@ /// They can be combined with the operators `|`, `&`, and `!`. /// /// Values can be used from the [`flags`] module. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq)] pub struct Flags(u32); impl Flags { @@ -42,6 +42,11 @@ impl Flags { pub(crate) fn as_raw(self) -> u32 { self.0 } + + /// Check whether `flags` is contained in `self`. + pub fn contains(self, flags: Flags) -> bool { + (self & flags) == flags + } } impl core::ops::BitOr for Flags { 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+BHDB2siszS1LtDoAzrNKStcZXBNfKE89vfHUS3HZzStOfj3pc9CAafZTES+36+r1XrnIEq20JvM+9clmFoMaWe8PfuLpK42kMW8rOBdrkeZKRm3QDrbD4FYtv5vXtp93ixrKgLzCkkivg8DmJ6xNvQzUuxMUe14xkBunKy8qW8A9v+KX0qH/6nYk3xIq5zqqCGDGLBz5rR1fNkQ8IsTshodYi5Lgdx+gVx211L8aJYHYD/MO3gfrKe/4rDtGREiAS/5lUQwBVmlcoocMA/kdHZkuQYFyXu8AI/yS3eJMzg6CfVDARyNKQCKfEzw/JHNqn1dy5CZWsssuMyX7GxxRC++zJuUms83uthobj9gmKuwQrI13ft7qSqgC/FmCNqeSIYRFK7z2s0lyYnZFY6tw641axOof297rU0X2rWKGJs9qKyZSTwhZwl/hxwqT+W2iZZbv5EijLJMHpwRCO3AlbzDUZaK1XGI5WWcbiLGuhkxTsZ34ytdq0DfZyjPRqi+OHuOwG4nQO8kk/dFrLI28/RXXT6RPVbAcsL+E6J6k8DNxbhCf86WdkWA9wAwtogKB5ePnUfGjxBKFTWVuMC/CWOKSvGNTG6pWbGkSt/Y8lR/gBqYO13GxzjKT7dxMznfYY9kvux6yw8JycKUqSA9diriuixW2h4F4RhnFbx5OKe17C2a74FYFnaKLu5bGb5kLztCzRUkvkn+iqw2LJlvHJjVGhUNGiS+EuhBmhxdhuPPxgDtFF1N6PHkGFcQzh19hbVqhDZdxuBelxFb6dPMf+ZrNjfoeG9KBQEu0bPcdEpfdWNS+JkkhPJNH4X5y5TqrR7UgONL9kK0Nu/gPlkm1B2dmAS1pv/ByRJ06xFc9Hls+NzdoxJFvwM1mlNJPW47/3wz7tMoP5M6AyNpI2Xm3bER9Y0Lh4nM4WdIBl+H zu8Cn921 RSLTy35d7RrvBkbkbqu+3hxB8Hp4i6XOZiYA2UPIczPFgJEU/+XFP9ANahTuwk1m/Fom6kt7IVANSpSIiVkVf4jvjNQ51r96V8Tmihr6s/elH3yqdIL/DWI7mpMCH8ICt1VCXttuABmFb4//B47dGN7TibgmPAlCCMfFFWNDEwUaFQADvJp/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) } } From patchwork Mon Aug 12 18:23:09 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760940 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 52B1BC3DA7F for ; Mon, 12 Aug 2024 18:26:19 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id DFB9C6B00CC; Mon, 12 Aug 2024 14:26:18 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D9E476B00CD; Mon, 12 Aug 2024 14:26:18 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C3E8B6B00CE; Mon, 12 Aug 2024 14:26:18 -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 A6E7F6B00CC for ; Mon, 12 Aug 2024 14:26:18 -0400 (EDT) Received: from smtpin25.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 5D779C011E for ; Mon, 12 Aug 2024 18:26:18 +0000 (UTC) X-FDA: 82444423236.25.8834702 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf02.hostedemail.com (Postfix) with ESMTP id 5BD248001F for ; Mon, 12 Aug 2024 18:26:15 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=K7jG6z+3; spf=pass (imf02.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=1723487084; 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=53m9V8AoGWStcovhU1hAENmzANHwIczK/XyCtNmkf3I=; b=tC4McZMFAD0JRDoeQvsIRxKA3H1OM0qwoGRhkzhwSanja9FSTukTY/fpAkVFhmkdyXnUbV cCg15o9XleYy3cYdGdwz+CmMOLFg8XQ27r4zGmihjg3Pn0iDBlNORtHA7nnVjBu+wee39I cZg6YpxtoYHz2f9VImdiSXXf968U3P8= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=K7jG6z+3; spf=pass (imf02.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=1723487084; a=rsa-sha256; cv=none; b=g8DrKbuOkK/ctXddy72BAnEzB6fkzpEuG2ZV+vFmeHAlt7S03xPbUUrLI1GowGsXo4ebm5 dMxp1o+t7VeKG8ahdDr/tH/w7fXp0MSFAMFcbvKrdGh+tSxaYpqj+G1kLwgTta7RvT3mRf wThNmrtA4UiDOE3MydjHDkf6EwVCRuE= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 70055CE0A6A; Mon, 12 Aug 2024 18:26:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id AD867C4AF09; Mon, 12 Aug 2024 18:26:07 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487172; bh=SxIIf+SSSfq/ByqB+qb2+RtiJyH5BPK+PFBZGcm3qDM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=K7jG6z+3m6ZxFsGXWBawNolBPj9HDFiJ+jJbgWgSYU/Bo/BLz6Pp3ReAsC31yciEI RmHM57eHf3FgMPfF4E0cuk0P3mTZJe1gWJuKYbnyDPUaA04ll0yzwsvXSaCJ3BlBck WyO81o6zRTQMz831jpTuwtl4Jh9LVcLBhNeAGQfpu9rcJHNTSEEJNYF71Go5BM5bX6 S2y4NTJ1ealfzYlRIIGKlxwSAwRHoeKbSk1QtVAoFmRDWgr7GXsHjl643pPGylZTW3 RFedq47VIXKszDfEcxP1PJkcuDHYtpF7oC2Z4s6hqB/DvMsvDUMO8neVPx1WuCqKbp g1ggCMovo94Pw== 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 23/26] rust: str: test: replace `alloc::format` Date: Mon, 12 Aug 2024 20:23:09 +0200 Message-ID: <20240812182355.11641-24-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-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 5BD248001F X-Stat-Signature: m8h3uo6aqre6kwqur563eq14z7p8p46c X-Rspam-User: X-HE-Tag: 1723487175-594623 X-HE-Meta: U2FsdGVkX1+HD/G3z+F3hPjGx4NPqyoHd8Zo4jhBgiXncdoGEDkBk1qAIjojH+faukFjFu4/urWaUJm6PfgaDTWFKnN15R9NKyDdoe6DX5Zk5xIEluhbquJ3/ov+L5hu6sBbrTLmX79mWEfnphJkPcVWkylKReCA7iI8BcpoIYXLAj6hqK15U8l3b2/zi5TiuPDnWuJtz+hVcUo+EIhvxSIvCpKKhlk+gXTWDqhJSvM+x8TlvxvP1m3IMK7HCaoZ7CQ0lfpsmg44/nXA7iRWk75BIgB9lYWkmyp9JehRAV1P7FM+nzYPc/i+/ZMH624s/gzg8v1oOH99TopRX3jrrLcqPApdXlWrPdvpms4cJJEXCfSG4lLsLCUwsIpsNYkSqiv1R3mSzKynNrwmA7q1aGqe4kU6Gss3TaLq21V4j1WnIuI3WQZ1a+VuP8VXeUrTIU2PBExNwn674FMZ1XHWasHjZlky6OCx3AJlGgjzRT7N84CtvR9OL+LyyDCrZZvk4LT+0D7RbaV0RThQp1kHdIkdbPrIdQbdBYripCssDPk4jDsi7eZgdU66IM0XTKQnBmzMSgGgy1Cl2x20LmuGt1iJLTN2+1QGhM5S9/4+rW2caRHtHQuXRRXCu9xKeuIyxVV/Nt2dPmgyk0sClII5hvsxVUPsX+fjMtf6NHfQwe/bX+Zohjg30+xeVK8bcuZWdlWiGAmmRN3fVj145384DR1U/1UZ3fK1B3vbhnwfvrOOpH99H9s30KfRHFgmcnveTQyvFcPeY6AqSCaMlBugsbcqgM2mo1t+e6P9K6SOLHktkx6MoaahdROMy71OSU2vebQi9ZT90/V4VfiKL2voVzj28f+NbEQNP0ducupT00YiYzg0aKIxzF9q2XFJwrPWbHdI7jJ1LE80T/4vJHTXAv6DWo+KXpIidiARtaWJY2UzDTYELVLMFhonDCfwwtuM1BwTuhlJk8t9I81etF1 zjAcCvOj MmkZvvmBHhyd+M25328BUSyNQtBQiUulpbSPZhjGETcXz5/ZxtiwPFKKfrG16as6+7vzE4OM5SVU8+zya/Ybwsl/C/pQU5AtyU2xDWxcyqggtaqbhHdLflvuU/eSk1fDLHP2Z/iBLw0PfjNhIYOOXdOpXfgn1IZuazfBB/y6r0V4W5pqo/3bpeyg8xJFVXDvql4ngTvIoo8VWgGQEwUars0X4ZZQ75js5Pv9poxAzxZTcLm4x/LRWyzIuhN5Gu/zmnPb+QR8GITvlvWWfFJJn3xVVKsKPFpI/EeG+JhWFFOFGR7g19KTlgMPmuuqijWUdpbF4H1dokp98E18= 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: The current implementation of tests in str.rs use `format!` to format strings for comparison, which, internally, creates a new `String`. In order to prepare for getting rid of Rust's alloc crate, we have to cut this dependency. Instead, implement `format!` for `CString`. Note that for userspace tests, `Kmalloc`, which is backing `CString`'s memory, is just a type alias to `Cmalloc`. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 209ad1bb1a49..726329530338 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,28 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; + + struct String(CString); + + impl String { + fn from_fmt(args: fmt::Arguments<'_>) -> Self { + String(CString::try_from_fmt(args).unwrap()) + } + } + + impl Deref for String { + type Target = str; + + fn deref(&self) -> &str { + self.0.to_str().unwrap() + } + } + + macro_rules! format { + ($($f:tt)*) => ({ + &*String::from_fmt(kernel::fmt!($($f)*)) + }) + } const ALL_ASCII_CHARS: &'static str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ From patchwork Mon Aug 12 18:23:10 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760941 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 D6539C52D7C for ; Mon, 12 Aug 2024 18:26:21 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 69AE36B007B; Mon, 12 Aug 2024 14:26:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 5ADFB6B00AC; Mon, 12 Aug 2024 14:26:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 3DB056B00CE; Mon, 12 Aug 2024 14:26:21 -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 19EC86B007B for ; Mon, 12 Aug 2024 14:26:21 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id C44F5401FF for ; Mon, 12 Aug 2024 18:26:20 +0000 (UTC) X-FDA: 82444423320.06.52DA723 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf10.hostedemail.com (Postfix) with ESMTP id 21AF1C000E for ; Mon, 12 Aug 2024 18:26:18 +0000 (UTC) Authentication-Results: imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=j0ejD2cK; spf=pass (imf10.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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487144; a=rsa-sha256; cv=none; b=Xwrq80iLYIvwFBZzEtelX2Wi6KwZkZQX9Zl30LqySpBi1RqGzQ7SIZ09jtiXEgFU5SlhtS SLSu2ioRNHscRZqfzdYlFtNw8cclB6LnsPe6LdluXjhodAnxLecBSlnmGmjCWNzn5Z3/xw /7qrBV971NRaQGDA3wSaiJSxmNNI6G4= ARC-Authentication-Results: i=1; imf10.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=j0ejD2cK; spf=pass (imf10.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=1723487144; 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=hX2RxSun3JSZVkOm5hxWH4T9kP8IaSZYNFKLw9Yy0nM=; b=Dq0jyiEVn81F+TgvW5x1q4bTC2yw46ZbvX8A5juw7PO9kRnyrnIR2N83jxd/OjOlkEo7jt dbWkXh/cZZMozhLaGDpAB2r8iaJ2FVNEM9Psq7pcnCdCdNvE6X0e7SbzyKtydAhwq4ad0o 2YDOtgAXp8hJdNYFXV2JLKTskLKwjvA= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 59F2E611DC; Mon, 12 Aug 2024 18:26:18 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1BC2FC4AF0C; Mon, 12 Aug 2024 18:26:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487178; bh=blDL6gfz+IKgF0QGtqP0bU2aIjtbW4lMlGcoQxrbKCw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=j0ejD2cKN1Yda7MLbZ1sGcQbdEykpeupJ5GzPzGRGxYBhzuKhNwTbgYdHuXLkWvDK /RUO4uugW0iM0P/QTXZA2Iph+OGwWBO9VpBZ83LwxJo2DOVZ0IBnRNYEgUhKSQU91u yxvHaWSNEezuB/y14tKW15XS1MF/Ir6HnqsiRxpnlZxXYfUw6KDF491K8qq3ZI8Xil 9USenuaFeAd6QGmwCPocQ2MUj5Jklpflnt32sggrRqvJkEftwifrXb5ZLM9ZzncQJJ pnX0qMZiwpWdiOFwhZpC73tM7TKDkRnSm5IEiUHlSwSiz2+KeEiAADLfFw9leKcXL8 L8lVNrPJBzkzg== 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 24/26] rust: alloc: update module comment of alloc.rs Date: Mon, 12 Aug 2024 20:23:10 +0200 Message-ID: <20240812182355.11641-25-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: ifjum53tu5ibx7c3pa14twe618b8f1uu X-Rspamd-Queue-Id: 21AF1C000E X-Rspam-User: X-Rspamd-Server: rspam10 X-HE-Tag: 1723487178-932367 X-HE-Meta: U2FsdGVkX18E47e8gsVGHP+AbZN1fCtvwgSLFAf/nBfGGks74Sah9VxD3Jodw+6mGY/aHOGzHZyFj/Y0fqcZIz8TvBiAg1Ngs1sBwCREX4TLWgE2WAN+12S7c78iNRtRbrpEe0eLmwatCe2PDL1NYTGsUlN4Ly/X6ExvvNNNcPipB748i+Jbq/83Q8ZwM7YK39KqRkz9jGMNn4zPXF42YFhDulcVtXWRQQzdkpMgbxwj9TAtHQFpEb+cSqXS7f5xYgYM1/of+Gc3tLtM+azVNiukcgOwGa4KuT7VKwnV/mC9/AiaIYnahvooQbFSbK7EHYw3B9FlWl+Cdu4W+GGcIAdxB25vnTMUgLtc8TNHgL1kVP74gQMxY5B9+iIv1bu2KIVfMH5P2z3lxTQ4tTxBYUem00/RORCvPdyie0aSOsYt963UujM74P0ns2MarsxlsWDJuwieV6s1XhlHCgD9qdqOb0V0lt5VZoiKZ737qn7fLXtTbCt2uj9yp55LUmICHvVGqyVQLseQexGj2zoUnFfnb/mbGj6QQBWDh9rnvUOCKBJUX7MiIOEkFxzwy26qdsWCdQ222rHs1QBArdo2Xy+8TZtK8W3AKeGmHEA7M0n6zC1Z2yqZoJJbvsrd+rjYzxydSoqdA8FOqMDvexEvRUBPz8WRgD5fQoBjdB7YcTerYTbzLGsxaa6sxVitJi5gws9M1TfAA9WvSe/PDYLI3hQY4wp55CuXZFRe3K6BnTZT36BE24yahx+jv2L91T1w1cbogzTfFOd220XxekRLWrC6UMXYXhtniLmuXLjBsFjfoK6T/HDTPQkSHxrMEnz+4/aB3VkM9CAB5rRwhLfL6OKXO44b1V/pWx79e6PXLxLIdnb3olTmtRGBTTPIBfKT8JK39xFuBfvUjOiFsUVdfRWksQlaJ7sYN73mUB79dzmk3kD+yQkuhPXeXX2ea7nkLrFvioBRhaHYGy74rTD +oyE18Wa Xse9McM3MkJ6BvVll7vED0pCQrefph7zakEFmqaRudMzsq7mu8xWco1npl1vGyO+/Y+iZeAux0ukYoVszW1N/1LRHSJDX7hxj0yStYNEFzXemKXINo0Vr0ST5M7aKPYnjdHlnXP//zmIjjFHxqGo3s66mPXwHkU7EoF+rDe1nj2AW5N8OHdsh1zekTataoEFMi6OPi4FWb459kadHB9T9mpFZxBEHxkn9RnANsJuY24t9If/nF3q1XYdpSH53YcX8/bmsjGpGJeu/rdZcPIJPdYHgGKfAohovVP4y2JK5Z988w1G3kWcgb56/yw9gQYqzlSeB7ABJXwSy+IwGv9jVRtsk1cNL0MhN1LxNA7Chs36D5a8= 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: Before we remove Rust's alloc crate, rewrite the module comment in alloc.rs to avoid a rustdoc warning. Besides that, the module comment in alloc.rs isn't correct anymore, we're no longer extending Rust's alloc crate. Reviewed-by: Alice Ryhl Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index be2bd0f1e74a..b2a41359a18d 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 -//! Extensions to the [`alloc`] crate. +//! Implementation of the kernel's memory allocation infrastructure. #[cfg(not(any(test, testlib)))] pub mod allocator; From patchwork Mon Aug 12 18:23:11 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760942 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 5AA60C52D7C for ; Mon, 12 Aug 2024 18:26:27 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id E15A86B00D0; Mon, 12 Aug 2024 14:26:26 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id D9DEB6B00D1; Mon, 12 Aug 2024 14:26:26 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id BA2C26B00D2; Mon, 12 Aug 2024 14:26:26 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0010.hostedemail.com [216.40.44.10]) by kanga.kvack.org (Postfix) with ESMTP id 8FD106B00D0 for ; Mon, 12 Aug 2024 14:26:26 -0400 (EDT) Received: from smtpin14.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay04.hostedemail.com (Postfix) with ESMTP id 45E9C1A0322 for ; Mon, 12 Aug 2024 18:26:26 +0000 (UTC) X-FDA: 82444423572.14.354BAA6 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf06.hostedemail.com (Postfix) with ESMTP id 922D0180007 for ; Mon, 12 Aug 2024 18:26:24 +0000 (UTC) Authentication-Results: imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hxAVZOB3; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf06.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487133; a=rsa-sha256; cv=none; b=2p1MsLflzIOQX3KL8vAbS0qMApXRoaQbqGLit9lpmmW4/kpUGTbBwptSmx7XHrx6kDBkQX t2Sx4BxuqO+kGIJq919T/2bvGbxt+QzP7oMCFERqkcYhIi2PQ1dn7M+77b7m2GlhUlB3YP Up1oyjrsCOZTwhjYtQvQtMCxxLRYJVs= ARC-Authentication-Results: i=1; imf06.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hxAVZOB3; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf06.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=1723487133; 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=jp22YIlinlo/QUmhflSXjpfv5W6CO2anwFGcy4Z3qA4=; b=JWUq8VOAlp+pu68ot0KBRkE9t2Tt5TtsIMfjE8CtXFhnHGRLj0QfxtjJ0IHi/E4mp2yx76 oiuztDVkEhUJo7lGX0VpGzYtYyv4FFBlV02hF584CmwtGFHydKAYZLByFW7QgWjehnf5i+ 6aSe6QEMd6Rm2909AfkUiuiUZrE04Ns= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id B6D2761179; Mon, 12 Aug 2024 18:26:23 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7B5D7C4AF09; Mon, 12 Aug 2024 18:26:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487183; bh=hgqCEKFBsyL+bevkPQnvZdQLN9AhKh3OlQraSfmVBSQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hxAVZOB30txHaSBwNvrnh50bmOB3ceSc6NeV11kFNLhvnvTZNZ/+gexWW6jxTqkng t2HhVZUfSlX3zuf804kywEinA7H8t8cox81+rl7TROlFFadluDpoNUk6qPzeAT4eBq vgnMDcUwcLwLLuKRXP+bqZ1biIU+T6tw/CWUtF+42Vx5dUiD/3GgLsjHGv7Mr6asIe kdMUodxwGB+MgZHejZv1lCoyVWNehPT4R6uiFoJ78NFApdLK5xUZJ59ciaR7okUzcV IVHOg/E/WLZEhlkI+UWVGxtVdD1jZjAM0Ija4GxLZ8rFaMn4G56zIxOTs26e1YFqYg ZmIHskGQifxOA== 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 25/26] kbuild: rust: remove the `alloc` crate and `GlobalAlloc` Date: Mon, 12 Aug 2024 20:23:11 +0200 Message-ID: <20240812182355.11641-26-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-Rspamd-Queue-Id: 922D0180007 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: y6bja8mdp8qfc8i7k5yffjcogrxxmuey X-HE-Tag: 1723487184-949958 X-HE-Meta: U2FsdGVkX1+mcYSuaquCnv3f5inoVOqzYLjXbMu7km8Ome1tYUDW3kBjDYjffI+jniLZZcxUkmrlYMKPI8cRN7ve1OyvPt7eV2l8yMh5W+2qk3IXsBmRxwMNAanHjQ6hI2KmENfieI/eO6ICytD6gE26XJr7j+XFhb4R/yCzPvZsu00tKAWtMvUE4MIYyj8DbmfgqPNP4l+FREbbrUPZOzdFNcsl6p078GXscDYfQrSrKJPec2+KOOaXiPn1TM1a0ni9S+ej7sn/8ZkkFCHEMkOAwdF+nHOC2NtKo/MKDCHpO8PyNaQV0WRxQkDtQwpcSOaobnaH0v7LEi1zF7GZGDrwEomrJUJNIZ337lwqJ8KAel1IL9lfZ8ZfhzOf19GDfNdd3ESEdSUQNixHZVBvwfWO1bKKzyvH7tDoxdAPDwWhNDxBWGPnNtFbAO9Xy3uTV+LmUs4t673J9Tg4xjO5b8iBKiy9dBVtMIHE/tljednwg3zLLfy6oFC4eWbs8/5oUVa3DmlOhf+mQmUi5A1ZNOFGFRbIfrgp59uqJkCkvINK8gQ4g5GeHQcmkmAp2aIH7kfK1MAA60mrWtaU0Pk9AzYJFiJJ8lsKcGrSp0eyFLehtMb/3i0XCd1ypuD4Vc0+lAajUSF9mIfYPoom1EytGw5bNfqHZieWxF0tSglF01m3iUKDhGX3xYyTNetEgwpj76fapK0Wdr3W5cjQua7UjPXKYOCZFIjfZu/SqYp49RX9S3KP8Uz8Snb3K+B0yFDp1FH4BtKvS6vgxy6mCmFCZR4WK2W9Xm5NxiR/hdQxTtxouSxtKmhhQoaQ54NNGWlnS8z8ODXXBvYr6cF7dvR/H1epC/svgdjbqMuoccwK37x3Ji7FId+18ChfLty2B3CMzHP4unX9cfWsvVtXWm+uvS2BcNVgplncHb/zgQVwdmZMInWr9i0865zKDWH5RPDm8rF6CLmsmOM2MTc/3Uh 9Qcd3k3N IngTywQaobjxbXsKZGXKJJPosHYXC99FC/wjxGvuMuY8LDH4s3KmGn7n+ZKH7w007Oad7w/tbziVr3ZhfH2tuSJeD3KeT5Q7sKkNrXHYAca7UwVdRU/e6lAom+PqGEdvgR3NxYEED8rspxhPM7HTjWCwOE5i/R11uQfbHZwTEq1B1mjCzrMUzj4lKnuD13VaY8DdLAxgWEseL+tS42bSiMug2hq7qEu6ZTKbT0gWu9IeiZ+b8s/oY6LV5ALH55KDVf4JnOTR0ep3sThoHHV32XRw8AMBdZKwEd3oqVoyOjUUDGv5yV0AKR80/8nW4VkGLPol01YSAyE4F5R5CxdxxptT+FQ== 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: Now that we have our own `Allocator`, `Box` and `Vec` types we can remove Rust's `alloc` crate and the `new_uninit` unstable feature. Also remove `Kmalloc`'s `GlobalAlloc` implementation -- we can't remove this in a separate patch, since the `alloc` crate requires a `#[global_allocator]` to set, that implements `GlobalAlloc`. Signed-off-by: Danilo Krummrich --- rust/Makefile | 44 ++++++----------------- rust/exports.c | 1 - rust/kernel/alloc/allocator.rs | 59 ++----------------------------- scripts/Makefile.build | 7 +--- scripts/generate_rust_analyzer.py | 11 ++---- 5 files changed, 15 insertions(+), 107 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index 1f10f92737f2..8900c3d06573 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -15,9 +15,8 @@ always-$(CONFIG_RUST) += libmacros.so no-clean-files += libmacros.so always-$(CONFIG_RUST) += bindings/bindings_generated.rs bindings/bindings_helpers_generated.rs -obj-$(CONFIG_RUST) += alloc.o bindings.o kernel.o -always-$(CONFIG_RUST) += exports_alloc_generated.h exports_bindings_generated.h \ - exports_kernel_generated.h +obj-$(CONFIG_RUST) += bindings.o kernel.o +always-$(CONFIG_RUST) += exports_bindings_generated.h exports_kernel_generated.h always-$(CONFIG_RUST) += uapi/uapi_generated.rs obj-$(CONFIG_RUST) += uapi.o @@ -53,11 +52,6 @@ endif core-cfgs = \ --cfg no_fp_fmt_parse -alloc-cfgs = \ - --cfg no_global_oom_handling \ - --cfg no_rc \ - --cfg no_sync - quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< cmd_rustdoc = \ OBJTREE=$(abspath $(objtree)) \ @@ -80,7 +74,7 @@ quiet_cmd_rustdoc = RUSTDOC $(if $(rustdoc_host),H, ) $< # command-like flags to solve the issue. Meanwhile, we use the non-custom case # and then retouch the generated files. rustdoc: rustdoc-core rustdoc-macros rustdoc-compiler_builtins \ - rustdoc-alloc rustdoc-kernel + rustdoc-kernel $(Q)cp $(srctree)/Documentation/images/logo.svg $(rustdoc_output)/static.files/ $(Q)cp $(srctree)/Documentation/images/COPYING-logo $(rustdoc_output)/static.files/ $(Q)find $(rustdoc_output) -name '*.html' -type f -print0 | xargs -0 sed -Ei \ @@ -104,20 +98,11 @@ rustdoc-core: $(RUST_LIB_SRC)/core/src/lib.rs FORCE rustdoc-compiler_builtins: $(src)/compiler_builtins.rs rustdoc-core FORCE +$(call if_changed,rustdoc) -# We need to allow `rustdoc::broken_intra_doc_links` because some -# `no_global_oom_handling` functions refer to non-`no_global_oom_handling` -# functions. Ideally `rustdoc` would have a way to distinguish broken links -# due to things that are "configured out" vs. entirely non-existing ones. -rustdoc-alloc: private rustc_target_flags = $(alloc-cfgs) \ - -Arustdoc::broken_intra_doc_links -rustdoc-alloc: $(RUST_LIB_SRC)/alloc/src/lib.rs rustdoc-core rustdoc-compiler_builtins FORCE - +$(call if_changed,rustdoc) - -rustdoc-kernel: private rustc_target_flags = --extern alloc \ +rustdoc-kernel: private rustc_target_flags = \ --extern build_error --extern macros=$(objtree)/$(obj)/libmacros.so \ --extern bindings --extern uapi rustdoc-kernel: $(src)/kernel/lib.rs rustdoc-core rustdoc-macros \ - rustdoc-compiler_builtins rustdoc-alloc $(obj)/libmacros.so \ + rustdoc-compiler_builtins $(obj)/libmacros.so \ $(obj)/bindings.o FORCE +$(call if_changed,rustdoc) @@ -161,7 +146,7 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $< mkdir -p $(objtree)/$(obj)/test/doctests/kernel; \ OBJTREE=$(abspath $(objtree)) \ $(RUSTDOC) --test $(rust_flags) \ - -L$(objtree)/$(obj) --extern alloc --extern kernel \ + -L$(objtree)/$(obj) --extern kernel \ --extern build_error --extern macros \ --extern bindings --extern uapi \ --no-run --crate-name kernel -Zunstable-options \ @@ -197,7 +182,7 @@ rusttest-macros: $(src)/macros/lib.rs FORCE +$(call if_changed,rustc_test) +$(call if_changed,rustdoc_test) -rusttest-kernel: private rustc_target_flags = --extern alloc \ +rusttest-kernel: private rustc_target_flags = \ --extern build_error --extern macros --extern bindings --extern uapi rusttest-kernel: $(src)/kernel/lib.rs \ rusttestlib-build_error rusttestlib-macros rusttestlib-bindings \ @@ -310,9 +295,6 @@ quiet_cmd_exports = EXPORTS $@ $(obj)/exports_core_generated.h: $(obj)/core.o FORCE $(call if_changed,exports) -$(obj)/exports_alloc_generated.h: $(obj)/alloc.o FORCE - $(call if_changed,exports) - $(obj)/exports_bindings_generated.h: $(obj)/bindings.o FORCE $(call if_changed,exports) @@ -348,7 +330,7 @@ quiet_cmd_rustc_library = $(if $(skip_clippy),RUSTC,$(RUSTC_OR_CLIPPY_QUIET)) L rust-analyzer: $(Q)$(srctree)/scripts/generate_rust_analyzer.py \ - --cfgs='core=$(core-cfgs)' --cfgs='alloc=$(alloc-cfgs)' \ + --cfgs='core=$(core-cfgs)' \ $(realpath $(srctree)) $(realpath $(objtree)) \ $(RUST_LIB_SRC) $(KBUILD_EXTMOD) > \ $(if $(KBUILD_EXTMOD),$(extmod_prefix),$(objtree))/rust-project.json @@ -380,12 +362,6 @@ $(obj)/compiler_builtins.o: private rustc_objcopy = -w -W '__*' $(obj)/compiler_builtins.o: $(src)/compiler_builtins.rs $(obj)/core.o FORCE +$(call if_changed_dep,rustc_library) -$(obj)/alloc.o: private skip_clippy = 1 -$(obj)/alloc.o: private skip_flags = -Wunreachable_pub -$(obj)/alloc.o: private rustc_target_flags = $(alloc-cfgs) -$(obj)/alloc.o: $(RUST_LIB_SRC)/alloc/src/lib.rs $(obj)/compiler_builtins.o FORCE - +$(call if_changed_dep,rustc_library) - $(obj)/build_error.o: $(src)/build_error.rs $(obj)/compiler_builtins.o FORCE +$(call if_changed_dep,rustc_library) @@ -400,9 +376,9 @@ $(obj)/uapi.o: $(src)/uapi/lib.rs \ $(obj)/uapi/uapi_generated.rs FORCE +$(call if_changed_dep,rustc_library) -$(obj)/kernel.o: private rustc_target_flags = --extern alloc \ +$(obj)/kernel.o: private rustc_target_flags = \ --extern build_error --extern macros --extern bindings --extern uapi -$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/alloc.o $(obj)/build_error.o \ +$(obj)/kernel.o: $(src)/kernel/lib.rs $(obj)/build_error.o \ $(obj)/libmacros.so $(obj)/bindings.o $(obj)/uapi.o FORCE +$(call if_changed_dep,rustc_library) diff --git a/rust/exports.c b/rust/exports.c index 3803c21d1403..1b870e8e83ea 100644 --- a/rust/exports.c +++ b/rust/exports.c @@ -16,7 +16,6 @@ #define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym) #include "exports_core_generated.h" -#include "exports_alloc_generated.h" #include "exports_bindings_generated.h" #include "exports_kernel_generated.h" diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 243d8c49a57b..b1580534947d 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -2,8 +2,8 @@ //! Allocator support. -use super::{flags::*, Flags}; -use core::alloc::{GlobalAlloc, Layout}; +use super::Flags; +use core::alloc::Layout; use core::ptr; use core::ptr::NonNull; @@ -40,23 +40,6 @@ 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. -/// -/// # Safety -/// -/// - `ptr` can be either null or a pointer which has been allocated by this allocator. -/// - `new_layout` must have a non-zero size. -pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: Flags) -> *mut u8 { - let size = aligned_size(new_layout); - - // SAFETY: - // - `ptr` is either null or a pointer returned from a previous `k{re}alloc()` by the - // function safety requirement. - // - `size` is greater than 0 since it's from `layout.size()` (which cannot be zero according - // to the function safety requirement) - unsafe { bindings::krealloc(ptr as *const core::ffi::c_void, size, flags.0) as *mut u8 } -} - /// # Invariants /// /// One of the following `krealloc`, `vrealloc`, `kvrealloc`. @@ -116,41 +99,6 @@ unsafe fn realloc( } } -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 - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL) } - } - - unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { - unsafe { - bindings::kfree(ptr as *const core::ffi::c_void); - } - } - - unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - // SAFETY: - // - `new_size`, when rounded up to the nearest multiple of `layout.align()`, will not - // overflow `isize` by the function safety requirement. - // - `layout.align()` is a proper alignment (i.e. not zero and must be a power of two). - let layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; - - // SAFETY: - // - `ptr` is either null or a pointer allocated by this allocator by the function safety - // requirement. - // - the size of `layout` is not zero because `new_size` is not zero by the function safety - // requirement. - unsafe { krealloc_aligned(ptr, layout, GFP_KERNEL) } - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - // SAFETY: `ptr::null_mut()` is null and `layout` has a non-zero size by the function safety - // requirement. - unsafe { krealloc_aligned(ptr::null_mut(), layout, GFP_KERNEL | __GFP_ZERO) } - } -} - unsafe impl Allocator for Vmalloc { unsafe fn realloc( ptr: Option>, @@ -187,9 +135,6 @@ unsafe fn realloc( } } -#[global_allocator] -static ALLOCATOR: Kmalloc = Kmalloc; - // See . #[no_mangle] static __rust_no_alloc_shim_is_unstable: u8 = 0; diff --git a/scripts/Makefile.build b/scripts/Makefile.build index efacca63c897..7e7b6b3d5bb9 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -262,18 +262,13 @@ $(obj)/%.lst: $(obj)/%.c FORCE # Compile Rust sources (.rs) # --------------------------------------------------------------------------- - -rust_allowed_features := new_uninit - # `--out-dir` is required to avoid temporaries being created by `rustc` in the # current working directory, which may be not accessible in the out-of-tree # modules case. rust_common_cmd = \ RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \ - -Zallow-features=$(rust_allowed_features) \ -Zcrate-attr=no_std \ - -Zcrate-attr='feature($(rust_allowed_features))' \ - -Zunstable-options --extern force:alloc --extern kernel \ + -Zunstable-options --extern kernel \ --crate-type rlib -L $(objtree)/rust/ \ --crate-name $(basename $(notdir $@)) \ --sysroot=/dev/null \ diff --git a/scripts/generate_rust_analyzer.py b/scripts/generate_rust_analyzer.py index f270c7b0cf34..3421a9ea3604 100755 --- a/scripts/generate_rust_analyzer.py +++ b/scripts/generate_rust_analyzer.py @@ -64,13 +64,6 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): [], ) - append_crate( - "alloc", - sysroot_src / "alloc" / "src" / "lib.rs", - ["core", "compiler_builtins"], - cfg=crates_cfgs.get("alloc", []), - ) - append_crate( "macros", srctree / "rust" / "macros" / "lib.rs", @@ -96,7 +89,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): append_crate( "kernel", srctree / "rust" / "kernel" / "lib.rs", - ["core", "alloc", "macros", "build_error", "bindings"], + ["core", "macros", "build_error", "bindings"], cfg=cfg, ) crates[-1]["source"] = { @@ -133,7 +126,7 @@ def generate_crates(srctree, objtree, sysroot_src, external_src, cfgs): append_crate( name, path, - ["core", "alloc", "kernel"], + ["core", "kernel"], cfg=cfg, ) From patchwork Mon Aug 12 18:23:12 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760943 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 B298BC3DA7F for ; Mon, 12 Aug 2024 18:26:32 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 47A036B00D1; Mon, 12 Aug 2024 14:26:32 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 401B36B00D2; Mon, 12 Aug 2024 14:26:32 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 206216B00D3; Mon, 12 Aug 2024 14:26:32 -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 F0C086B00D1 for ; Mon, 12 Aug 2024 14:26:31 -0400 (EDT) Received: from smtpin08.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id A1C9BA5B7A for ; Mon, 12 Aug 2024 18:26:31 +0000 (UTC) X-FDA: 82444423782.08.F8EF9A2 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf24.hostedemail.com (Postfix) with ESMTP id EADF4180011 for ; Mon, 12 Aug 2024 18:26:29 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=IrewnQXR; spf=pass (imf24.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=1723487178; 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=uDHi2ETLSKtKzcpzDPCYSwIN408EjcuQzuehCCcM8ws=; b=skP0JJ1DGn9w2MJuzZsUK83OIY+YC0Bh8ikPkK9lEL++mxy1C4Og2fGvXi8uHBgoR5VzGD 7njKFMs2NUTYR95SknYOQq2vTlyhd7S5eO00abAFmgG7MfxUcaMHl0gMViP/SBwaoMs3xZ ALc6yF+vE62lBzUemhSV/bOY7vqUijY= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=IrewnQXR; spf=pass (imf24.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-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487178; a=rsa-sha256; cv=none; b=ihIfV4WIFFIMaO2enQrlwrnBSxf52ClKKE4UgseSTEAfSVVne46+7ktV3KRw3EZf+ToyA8 Leoh7VXDiqJ1FXh2gY5ZKGhvxfTUly2CyqaAGlOOvO2kNjkwfHgImSI228B0P6pepd5tnk AlOiruZftaKo4XK53P5JFtXRYQZFBLk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 2B02D6145D; Mon, 12 Aug 2024 18:26:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id D9884C4AF15; Mon, 12 Aug 2024 18:26:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487188; bh=pq9p+3MKfusrm9d+dkS4M59Yq++w7zxN0VRikqPFNQM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=IrewnQXRBh0PBYuwXSIQzmoElmSkGlvcMIqqYkJoje+DqQVUvmpLyAjNKgHZj2XyC bLeNJWuUkdDY83SrJNoBjfbUX/5YEjdHOr2qvbI08G7Y8m/JJ9C9PWI7gEj7NEdg56 QMfJavksWPUfcD+0yrlxQqeXCHHsLY//EgheijRgeFWVjkW8fiAINf04QtccJXnICd zX4WVPUZ6XkHAB9nTETApAZM7kDsvWEMYZW0Ds5g9QfWDJtXvff/bLThXq6pF6eTdN eHpJ9utvJFX4N4z0b7ivpkyafVprJqj/0uvR1l/Hd/U+aH/x++mqll/JMs5mbzrMTI ImMXMjHnkjaeQ== 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 26/26] MAINTAINERS: add entry for the Rust `alloc` module Date: Mon, 12 Aug 2024 20:23:12 +0200 Message-ID: <20240812182355.11641-27-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-Rspam-User: X-Stat-Signature: x46b8o8jqpn7ip96q86orbmfwbsbe3ud X-Rspamd-Queue-Id: EADF4180011 X-Rspamd-Server: rspam11 X-HE-Tag: 1723487189-558544 X-HE-Meta: U2FsdGVkX195aGHWHMpUrttFcCxbQ6Z2wEUyXfEKTg1l67ztk2n9pacCORcjhyFvX7ZIAcwyk/4yZriWZWXp2JtpElKqSleHaRoJgPI99O5kNDfiB5t/gS1y1nLaVLZ/wHsmYOtfh2ctnhajGdTkg/Rpn5UwodYPWeVu/ez7hulRozns1wc6AtlRv918V5Hz7Yn79HxyZD0Lx9lPZ7UZW4qQJ7mN0vS2jEhGR6p3i8vivi8VN9cBMKsGBK5ZAD/NituaVoH3Mm09tn5QmUSjOk2UEvhUOqTP3YuudUUHG7KciBaOXuMAVH6CF4Uz68/Ns2vFhnWXEj+PuswYDhkbq47bFwD6XFP4Iy+XqBF8k2AWa0ZUhB0cDLJ6uWk03Eh+Aszn3bTWlef3AobabfkzZQbk86Ko1Ux7Rzyqfz+xWJ9ZOhoVmF9eoL/jqBisUXNHJlqTUvGYebrWctXJVMObHf6zC3ReXhQO2NjI8KafZcngMASSUckuZLgXWKDXZEnX9OK5DM3aPJJfNOtyIrF+plYdgqVLuMNhinRvxNNuaLT96SvUV2dptpNlgjeqOZ9AJwIH5J0wYZV3CsCslSZ4v650yw2z0vOoOkk3sWWL/0U/Gyd7jROr2IpYfvGVw1aD6EbFudzfr+chp8ieghjddWwyGQqBwnU7BpeV+k7S3UPlUjAWhf+SuXyApXbpIq9cmFXq+JFdAoybtwuI0OLE1Hoe6iB0Q+n+Xl6OaocYYpZsf+TDZSPXiQRB7zMVTh0n4GaqRQluplrnU+7TTPfh2VyG/t+ASz8tDl5esxx9dLsj0D0A+7P1RvY0ajw2PpeUh1Cm/x9TEzDzh7z/21nF2U16iXi567PAdPzF6ThtCubNcp1Td9XvJzbLUvgqV2OCsnJ9zyRKYoDnlU9izAvELzQGgP9eTLrpOSmTHfWHVtHW0JHjSRHImWmmrgxjWHe9kclzJ7odky9rOczTtoQ Q8Xs5KaM NuepttMP8uNb/OcAxkkm2yR6ravGtVGRy4isJXsJh/h12b7JdAmdYoBux1f+NQyGSQtQM77oG5gvR1MqkulJBxMk9kVSylUlLJD+adASUYzFR7PjftH5/SXGHXZ1QTexRWQmWVoFozdUZ1+t2kT/SHym9w5S8ek6pE3X4lCjiQtx2Z4Zwa+4WloL8faMQPpmLyeUav+N9CX67jcVBKRC73ZmbSu30FQyoLzDBqsjjfuSJM+UhPIk4HxWd2N0YOimArW+w0jJQ99FKD/QsYCZCao21Zc9jq7ccd5YagAC6zk2xO+51NIEq5h9I0Vg1fgZRsqwuAXsDea2EK0MTRG/B53WBHZV12YKBkTSKw70sPyJ7ZPY4strLY+bXjGG42mK3lDnnrK0CuAMh/NQ= 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: Add maintainers entry for the Rust `alloc` module. Currently, this includes the `Allocator` API itself, `Allocator` implementations, such as `Kmalloc` or `Vmalloc`, as well as the kernel's implementation of the primary memory allocation data structures, `Box` and `Vec`. Signed-off-by: Danilo Krummrich --- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/MAINTAINERS b/MAINTAINERS index 42decde38320..560516b3aaf4 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -19925,6 +19925,13 @@ F: scripts/*rust* F: tools/testing/selftests/rust/ K: \b(?i:rust)\b +RUST [ALLOC] +M: Danilo Krummrich +L: rust-for-linux@vger.kernel.org +S: Maintained +F: rust/kernel/alloc.rs +F: rust/kernel/alloc/ + RXRPC SOCKETS (AF_RXRPC) M: David Howells M: Marc Dionne