From patchwork Tue Jul 23 18:09: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: 13740246 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 B53E7C3DA63 for ; Tue, 23 Jul 2024 18:11:07 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 26D066B0088; Tue, 23 Jul 2024 14:11:07 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 21D336B0089; Tue, 23 Jul 2024 14:11:07 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0BD646B008A; Tue, 23 Jul 2024 14:11:07 -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 E174A6B0088 for ; Tue, 23 Jul 2024 14:11:06 -0400 (EDT) Received: from smtpin22.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 5D0DCA1FEE for ; Tue, 23 Jul 2024 18:11:06 +0000 (UTC) X-FDA: 82371808932.22.E7551A1 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf14.hostedemail.com (Postfix) with ESMTP id 10F60100003 for ; Tue, 23 Jul 2024 18:11:03 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cjrbMJLC; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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=1721758226; a=rsa-sha256; cv=none; b=lT0RiSjjnV7vLr6zcrSNTTmHohnU2u2KPQUQQJYzeXtmTESonCE41xgNBurrwrYlW0/jC/ J1/z7IzK6duS/j50+kWPNJfdlDUqyGOBT0D5a055hsNhwOOOt6KR5RntQaWPGmQUGe6h4C 1V+DC+xZGz13WFT99zVU3AsGZtKwMIQ= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cjrbMJLC; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf14.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=1721758226; 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=65iHjkAVjiXJB5+rLgDwSvPQzMM/0XWdgNqjcUC4Xz8=; b=U+4Ow2aNRwOhOBQmvIXDNhRtdx1MYjwKOLfaI2Q1pzPC82x9UvukCSMDQrufPEwY5zYkXY sviIJ9t/V1RcSduYc4A+Z4un85IDapwW09ZiMnVWYSN4QwgLimuV9xXWTNe4g/s0Pxeaan 0lEKcqc6Yy4EClnK80Ex2S60+DiaVsc= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id A4E8ACE0E80; Tue, 23 Jul 2024 18:10:59 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id AAFE7C4AF0E; Tue, 23 Jul 2024 18:10:53 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758258; bh=U0O51DFRkgND42OAvkxZ2VxyksXXw+gcqA7TuTA2fv8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cjrbMJLCrzNPfee1nrhopoa1trofVE4tsz7J1F3oNIona4S90KwXUIalrPc8F6Au1 46nGN4ic64WLD5fDUuucmc/HhC1cOY4syzUfFChpzeE4AM7ckrJeojfV8VwRDpRv0Z +/qyz4B/fZZirH7/DC0AhSHsYbcha0LPevAR7/vXcfTV358pu6PsnbaGR0olFKOvTH bz09bgRNONd+ULZe8XXTjlHDJjO4TgZCW7tmStTGIIUI/XbdiTIpIzsQ75GyEj9uLP 4WDgR1Dyd00ajlYfCKX0wINAWgV0usrCz2mK8CrH4RwG5Oo2heQxPXsUnejR22ymwV C5JRoF7PkYGxg== 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, acurrid@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 v2 01/23] rust: alloc: add `Allocator` trait Date: Tue, 23 Jul 2024 20:09:50 +0200 Message-ID: <20240723181024.21168-2-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 10F60100003 X-Stat-Signature: btbut9zzwcspyn6p3s9eghhbinbfeknx X-Rspam-User: X-HE-Tag: 1721758263-728992 X-HE-Meta: U2FsdGVkX18nPnrvdpGeiU3dlv93cMo/+BrpCrAxdWN/WWN95xfVqHsSGgKNBtdkEIQZVfMPzsa1qYxZnaIjKLrx1cqb6dh+JMnPmAoKfyUGDHPq5rnXg12j2xRgW+xW2RgMcpX+WYNJs1P3NHg6SJPQXtA+ugbsqKgUScVjBPA8mJu+dvKBbOZthb1FYJd5yS86S284oZe3U4ocQoZwGg4YoaiLi0PfBPg1HYU1lDX7QmRvZJUkEkqyDS/W5MELxZkztKnkdsXxqX5yZ4rlCiZzTtk7Vpg3EMg7zVBTlzPFUbLbBDKAHB975mAGjXs948U0XQSr1y+Gqv+ODUYBsMywHHr0twRuBw3lZ1Hwdd13UwPWaDPl6JOT9OBrCPfn5rAxBG5NNu+mvDeRot1bEzDd7iDwsDrnsMpupgsCWWtWb7R65Qay3i+gFyW+QHd0I6PlmNjZxKyqFjNRO5NlJcp2WqPPhczcjLrjut3s95jsW3xJWBHZOx0z93ydIdZwZ9SEwPQNxXy8hWC8GlTLWwrLAxNqCsXX3c2yNeyNIwxBEau7En4HgnuT3O5U+0vMSpaPnDgnRJevXfl6Gzf7mPRkuaXOeZc6WjUt1U6g/Ws/LkaHWe1XF4KAzEUQRA3NeRCsPap7PRsotDobvtFxFNPM5Mnp0xvxHxAG38wDUYFDgcSEzUI//ybJI+uD7RAl6gagPR/EUlHydfWsF7SbGPHJAgm7yozMxmo8PU3A6QIq+8o4fk7l0nmmS37Ug10iD2hGXxT7Vsv8XqgTLJwTfU2OZGbq57LlRCUGMtgQsQxIvcciaqJ62mmSSyFAwcjxx/OXRGN9zfXEOnPX7y3M6+9OZqXc8X32a12Eyp4g4+sKNDRWBZ6ev1nJcondlb9AILSfoDz5X679Ut3ZzY0FsfNLlAHxzRprsEm+xBUc8mBOcPa+Vh+lVFlK5LjlnBKLTwr6LLhL//uhnQTl6sx vOL3djKW woj/ucQCAgV7VEGyZiAnXm0yp0g0Lp9JaubwCZZhME61G5y2TyW9d0o0+HZEV7fn8iGzfo0iUmLdH4prA5qHhFuOkWYcQTTqWqVdkBgLrb21UZGpYA1ccTVcQhb0vjcL7ZzKXCZONwdoYw6ruT6w9+TzkkhwX8R3iH5lEAwrxyROlGdJDRikKb59l1mRkxI8iM24IxhYhYs02hytpw1hBGO7YIRf8oZvNOdIwfcKb2wxEkivtvUxsP+vZ2p6uuwVnyMEcx611ULwLjxax/zlSM4vBzNY462UMJPHSTGlLa/DBxXiuHU4uMZSBTg== 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`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 73 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 531b5e471cb1..11d12264c194 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. /// @@ -71,3 +72,75 @@ 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. +/// +/// # 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. The same applies for a NULL pointer. +/// +/// If `realloc` is called with: +/// - a size of zero, the given memory allocation, if any, must be freed +/// - a NULL pointer, 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 a NULL pointer. + fn alloc(layout: Layout, flags: Flags) -> Result, AllocError> { + // SAFETY: Passing a NULL pointer 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 + /// + /// `ptr` must point to an existing and valid memory allocation created by this allocator + /// instance. + /// + /// Additionally, `ptr` is allowed to be a NULL pointer; 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` + /// instance. + unsafe fn free(ptr: NonNull) { + // SAFETY: `ptr` is guaranteed to be previously allocated with this `Allocator` or NULL. + // Calling `realloc` with a buffer size of zero, frees the buffer `ptr` points to. + let _ = unsafe { Self::realloc(Some(ptr), Layout::new::<()>(), Flags(0)) }; + } +} From patchwork Tue Jul 23 18:09: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: 13740247 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 81CAAC3DA63 for ; Tue, 23 Jul 2024 18:11:11 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 1A9C06B008A; Tue, 23 Jul 2024 14:11:11 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 159916B008C; Tue, 23 Jul 2024 14:11:11 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id F3E3B6B0092; Tue, 23 Jul 2024 14:11:10 -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 D1FC16B008A for ; Tue, 23 Jul 2024 14:11:10 -0400 (EDT) Received: from smtpin04.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 8CB2880354 for ; Tue, 23 Jul 2024 18:11:10 +0000 (UTC) X-FDA: 82371809100.04.3F6622B Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf20.hostedemail.com (Postfix) with ESMTP id 3B1501C0017 for ; Tue, 23 Jul 2024 18:11:07 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=G6jovfZm; spf=pass (imf20.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=1721758221; 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=Q+939kC/O+kSEIr8mFyDMfc8xtGxKWUWzEi/7lcM42c=; b=wNWWqTSTZcMbUocThk2JZtFgX233CwLElho31T35NZ+2W1YObi/HvbS+/Uj/0ANHjDug6p CIBsDCdqQeIMCjA327uRlPzCQrfUKZ0orDGJ/q4kcwi2SxijMFmYZWVxOtsPDqICiM2+9A nBH8TqCWe9wr3BSwTgfZQV8UBDRoOKo= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758221; a=rsa-sha256; cv=none; b=KlJQmxTfvBPUm4ZcQXhZZiJHzgyxl0Tsqfzog0ZCNlnfQ4dJJyyiP6EGIcja9zdPvELyaR E9CLxL72ZSSveVMJ2SNa45ASbiWgn4zR4EPgeYbgxF8UUoJSbjlvWFa7de20j0ZMOqvLA+ YCvUdhMaFX0Aeskfq27BltmXnbZy/YY= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=G6jovfZm; spf=pass (imf20.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 477EFCE0E88; Tue, 23 Jul 2024 18:11:05 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 59F59C4AF0B; Tue, 23 Jul 2024 18:10:59 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758264; bh=EF5TVGHtjh4ZWyprrgf/Kmvg5Hex1RNnX1bjJzrWn+g=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=G6jovfZmXmWU2u+CRVnM/WkrcdUz8kYHbBGAcB9lI6dbRqsuZp2V0ciRIaazVMLjy h8xvO988V8AjJvelD6vG/yuVh9BMRh1mA9kRWBQd8FqeHurCI46aZHyjv41Ycz3PSM 1eqKfbB6b7PdalMqqALZsnr3nuT4kIz29Dz0lX3jN3RW9frxXIICZgEQVNjKxiBo27 8Zhd9Y37MKGAHnXc9NI1sKCoTiQArx70KB19Q0NqLtw+SQUHP8xeCjV+vqfqXXBVIk 5Wq+ITwkanPAzm9XMDqxtswIgIak5p4Uq8ZiXnN8NEkaHYJ6SxCsrfVvpnybX7ZV9Y L1NIl3l8yVmEw== 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, acurrid@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 v2 02/23] rust: alloc: separate `aligned_size` from `krealloc_aligned` Date: Tue, 23 Jul 2024 20:09:51 +0200 Message-ID: <20240723181024.21168-3-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 1r4rcsry1t3yy73jgtfq1zapdfpq8sfj X-Rspamd-Queue-Id: 3B1501C0017 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1721758267-232356 X-HE-Meta: U2FsdGVkX194QIkZhD5p8b33bih+vTGhQ33FGcclHr2d42/rI3RJi6kQMwQ69xRIvmRVOjbiblPZXt/E9XyNtKHjHua3Am/EmeHY/KLk+HHQeLdvoK+x9k3nVCUwTkVVpyxWYraJaKCjCyHgNsLADTUBYRNqwpQCNNAwzPNuKptwZf51TV4/vSRT/ytoHAwgp5lyJ+FFdbmo9h7EVlGAOsf7kU9cmhwQQXlclb2RL2Y8bndB/P0Y0oldWQxcjH25+nruxrmJkcubcW/0c3Ns5taB142jLmEK6IipfRhfuJ8NTk/mBATCcNtUgH8vEcInw0tZx+uyiIgxyeXKgHbtNnu/6ypBP+RKWq9KqEQswJWlQe61fOWGPBWU/FE4+e4DTQN93S0hOgPAhbUaNpcEjh7N2gkEiiXse/AUC0zKUmht6Pjox5a9EhG1LnNbYGLUxlja4Awy5Q8DlS0VgfY7/K11O6kw2mvwLob5PSyaiH6ZdAdcU3BRge/WV6i9irzlBXpuNfsmxO5Vgk6ZjwUGT9RbdQTpRgLfkmgu4vg0wHNJbe5uJ8PisZvYiuLLJObXHjE4FV974rtIhmKhGhLd4p4H9d/lZtj27N7WfpeB3NMk+Bcej0yRpThY8eXLqP2i909wrwzCKt1iOiXZ6TjBnrU4KC4h16NPw2c6/+6GZZEOrq1ZXSHtMEhKLDvI0LRdh2E4NDBDKUgV5rxA6uPKfxM+wGjdNCAayKt9V/aBtgC8jnoUWaQC4u/9ukQWN8M5HpLqOPNQ4BfAWzyo8CQ2CCUZ+nr7rMgKrZgCiDEZU9cxWSAjACiHP2HtgXzi7PRFD1tHIJfI/QPOl1lk4Of+UJ0tftWs8uUoQjMYezcg7K1f6xU8sR+YxkGauBPmPugqQsC2hBPwGC8ZpVelTBhPbAnm+m3tKlTCjXG5AffLXlyttx8Rm18iR6H0XsNzFE9cL58hi/GxtOtY2Na20aj leb7BlhP BJeQNs4ixF913PZu0srSTOS6sZl2Jaiy4TRNW0rZ/Hxe1C79jMj0gmwPFR2ywh/4+ptrmNLTPzpISb5ONv0ojhxsNxjNC8mvkt73LmfMjLS89FkdayixAS31xem/sePu+h/9hgxF+hDAQmvnU+UKNnyFLbmGRk6jtMsiu0ums5Z7Uh21+23tJBg44e3y9g65CWZK0GjPLC+ll2mnoH7hj8GrL2mJrLOd/FcHcO3/J7v5LKa8rH2LsjWsSUvdQRjcmHKm6TpOnsq7WLaEObx68p5Si7zMy1duJgVfXftcLbvaxK30KTGwN/pX6j+AAlwRCZ/M6F0C8rjPHq0M5CZXFDFpPHnaf5wUgV/kh3IuVpldEOiw= 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`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index e6ea601f38c6..6e133780a4a1 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -8,27 +8,35 @@ struct KernelAllocator; -/// 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 { +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). - let size = layout.size(); + 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 { // 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 } + unsafe { + bindings::krealloc( + ptr as *const core::ffi::c_void, + aligned_size(new_layout), + flags.0, + ) as *mut u8 + } } unsafe impl GlobalAlloc for KernelAllocator { From patchwork Tue Jul 23 18:09: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: 13740248 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 67E6AC3DA63 for ; Tue, 23 Jul 2024 18:11:22 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id EEFF06B0092; Tue, 23 Jul 2024 14:11:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E7A6A6B0093; Tue, 23 Jul 2024 14:11:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id D199F6B0095; Tue, 23 Jul 2024 14:11:21 -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 AEB636B0092 for ; Tue, 23 Jul 2024 14:11:21 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 670211C05DE for ; Tue, 23 Jul 2024 18:11:21 +0000 (UTC) X-FDA: 82371809562.28.A4B0906 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf04.hostedemail.com (Postfix) with ESMTP id 25D0140005 for ; Tue, 23 Jul 2024 18:11:18 +0000 (UTC) Authentication-Results: imf04.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RDOuFQ8+; spf=pass (imf04.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=1721758257; 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=XJQFnSigBs64AK6qJbsb/6K4YewhmH5hGvCy+TIFET0=; b=MG0s94y+eKRClIK4ZcSwMjyFB6vapVCePQEVEs1YJ6H0ZJED1KKq0ZITwqJqKsu1rYyXq5 RN2/g367rZJGw7yF5ueX0P0eyXCw3Mi6QkiY5o54++SKReWoaxqVELpnz/bVtraWgfQsmb tidHuIpOzEWMgZFH7AI+ZJezxU9hd8Y= ARC-Authentication-Results: i=1; imf04.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=RDOuFQ8+; spf=pass (imf04.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=1721758257; a=rsa-sha256; cv=none; b=D6OIViFFdixhUYt006lbxxcVY9cW1DWutV0v6LIjJFJCHcF7Ngczxjd8SDu4cMF5zrhWry GHyV7RW/pz0esPtFVzsoOymtcu47GQMlXE+p8NZO9k4YT0xhFp9Xkz+5X0p8CqwIKMCo3s MJelniJLVAp95qUawHNxkXQ5XKRwG68= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 85368CE0E8B; Tue, 23 Jul 2024 18:11:16 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8F4CEC4AF13; Tue, 23 Jul 2024 18:11:10 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758275; bh=LIUBeLsNsDjs5xTYqpQj2wzu9Kf9qHfPrPDSatbqKYw=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RDOuFQ8+8bKHj3kQ5nWdYX5MCjfcmldiMQGhEIFnZxm/KBri2pLNVpBER8FMKqVci ZT92rVWWPBz+aDCzyZdSSlXazYnHOxRhSrZAF5QtXKwt6Yx/roa7uuwiT5e3gl2AS4 ntdGyFz4xLeHT1Odjc3gkiTPeQmqzUy5JSfBib2nOqbOmIBArs/cI3wHr+/Tcngfhh VY34vof/Bv2HOLTCI3+ufH6FwSU5SErRmZtq+aKhDsI7/BuNAW3/1MYF+7slArtDav LDp3Q+xY6tp5G2K70K4w2N47olFreJnlgve7+Lg6ah1OJeGemb78FuuGuCsBvXn0d4 T4QqZnGPBIRQg== 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, acurrid@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 v2 04/23] rust: alloc: implement `Allocator` for `Kmalloc` Date: Tue, 23 Jul 2024 20:09:53 +0200 Message-ID: <20240723181024.21168-5-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam01 X-Rspamd-Queue-Id: 25D0140005 X-Stat-Signature: s5ec9wzyoofp9bf79s9ps53hurr3jre6 X-HE-Tag: 1721758278-34996 X-HE-Meta: U2FsdGVkX18hCJqpaqyelU83/98tLVJcHmZpBOsGQwgfnoAgVwMtk/ORl1iSP5T0rg/PTM90aXZkuROizPbPGeUUN5pOUuc7qwlvrE31Ffo5vQM99fu45web+swo8AHtJBDdLaK8MbbIkP5P9VozyFOuksTVJlHLGrTDz0vQc2BWta+TbXrqGbOGC52ScN7lsMfvr0e165Uruudfz32/W7BzglPm0tSgfc76PECbaVpOfQBj1cUqggiaCmZwL9peDXiKCd0mlddL6lY43PCEirURxwn29d6aYs2ZiM44Ay9LmP2l6Z+UAvH0xoShQheo68F6WlF4z66LmM+KgOzLyjYRm8LKgMWzJF7FkDgBfTy5tPRIgN4CXMhQ7nS0+eEEk5kjXP4sK2Kp1bFQ4MijIYd96YdTfq6K9nIfJiqjgFc27A3byo/E59xxNQMcEsbtZmj97ax2D1ilZU9KStckDY3iXnZJ5K32FYYyFYk6iuk4VCTJJD3R8+aL7jms36H0PkZ5lkQd0RP3+qNBYBE2jsNFqSX8asWvSHhvF9hc0+Tuq0cXQXqKcuJV/EabpD4w077MxjEQUrN3sAzJivRT6SFfmXXZPPvNh14ZKxjQCBLlOhUW8zCzAHgWxd/jU29xdIKS64hfISe1EkFZ1HxIEk0E5EH7uu4gQJ2Nw9AKyyXNtZ7OndQQKaJVP0Bu2/1nRuQv391KLddJVmr1XKxeAm1bKUcSmBajiACGOLpuwQjsjmWGFgggxc5q/KtoCMJiwIn2LgAgiUrVftzzgXcidvCUhXJODJFirtABp2or7qHuVDRYZKulGd+Gmfl+GlfanOahoR+tcuvnX7H3nJ8O+hhAnT3ibGi9dN+tgjRG/NlkUS1MYv2EvvfAKEmEHnJ86RgBG9emYy/k79UpSwXMCBbhRJWhOvRwj6nV0+oBJT221cjcVChwoeilGe0Szw6q7dXBeknqorSks4hk7rY vWBG1qhq aIa5I7l3/P2j7CeL5R6qnc6ur6twuMUbBhzKhDHOM/qNkUSdTkMeg5nKuU+k7arZji8WA9UjsK9afMdRS3sri5BKl50XcLRdakMQ7YLF9KLKs5eapoIGCorB40VGqixDOB8mExZmJHWfXkhmwOXg/qB6DF7geaDWPJ4BRA35lAjLynyZ2fQqFIqr+L7WFHNrhcjeKrYNUAuWP5JOJtGmWNvEPEr9BvR1Xt269Te37jfCDkySoy3xR95KxDkNaMSZgc/Pr1hltcYgLb+1xFxG03INnW6sIFnJMnqYhVXg8mqj6+IayZbQGNV7iNQ== 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/kernel/alloc.rs | 2 +- rust/kernel/alloc/allocator.rs | 66 ++++++++++++++++++++++++++++++++-- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 11d12264c194..bf739ce65387 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 10774c51ae26..397ae5bcc043 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -5,9 +5,18 @@ 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 { // Customized layouts from `Layout::from_size_align()` can have size < align, so pad first. let layout = new_layout.pad_to_align(); @@ -18,7 +27,7 @@ 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. +/// Calls `krealloc` with a proper size to alloc a new object. /// /// # Safety /// @@ -39,6 +48,59 @@ pub(crate) unsafe fn krealloc_aligned(ptr: *mut u8, new_layout: Layout, flags: F } } +struct ReallocFunc( + // INVARIANT: One of the following `krealloc`, `vrealloc`, `kvrealloc`. + unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, +); + +impl ReallocFunc { + fn krealloc() -> Self { + Self(bindings::krealloc) + } + + // SAFETY: `call` has the exact 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 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> { + let realloc = ReallocFunc::krealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.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 Tue Jul 23 18:09: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: 13740249 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 6078BC3DA7E for ; Tue, 23 Jul 2024 18:11:25 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id EA4496B0095; Tue, 23 Jul 2024 14:11:24 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E04536B0096; Tue, 23 Jul 2024 14:11:24 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id C80276B0098; Tue, 23 Jul 2024 14:11:24 -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 A6A646B0095 for ; Tue, 23 Jul 2024 14:11:24 -0400 (EDT) Received: from smtpin27.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 41EC51402C9 for ; Tue, 23 Jul 2024 18:11:24 +0000 (UTC) X-FDA: 82371809688.27.C5A46DF Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf11.hostedemail.com (Postfix) with ESMTP id 9D5F94000D for ; Tue, 23 Jul 2024 18:11:22 +0000 (UTC) Authentication-Results: imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KMGsYeNW; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf11.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=1721758244; a=rsa-sha256; cv=none; b=21sHuW36RDmGkDSuuIvYcR/666dBgZF3/VAooN80OLk5DfuXuZM/O3xtr2fbIwVyz/ObQz IQ2krRpFiw/4Hw+NqUfJG8y6oHEMruHg8IgZfUlZ1XMsHJ9SIpjgOuzvQcgnSIwgTH0oQS aj/oPCQXJd0DUr6zEfRGKxrltjbi1OQ= ARC-Authentication-Results: i=1; imf11.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=KMGsYeNW; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf11.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=1721758244; 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=eAoPkOZLW05v6G+jAaln6NWstcFkluicyLaP4RGhw2k=; b=K+VXcNxEALddGhnNrkrvIlRUrDl538y8Bz6JhywcdE0klWhfW/1zJqJcn7ISERGg8d3f/c PQzArq0hQKfOQ5smFYVWwl8+YSi9VTJV6W/f5NBzWldS04Xr/agN4OfsuHl+1iLpvj1T/x 3SAblE95P0QlIAgp1HVJ6n212A8IwPQ= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id B3DBC60E15; Tue, 23 Jul 2024 18:11:21 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 3A874C4AF0F; Tue, 23 Jul 2024 18:11:16 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758281; bh=/CAVj622i+EjUqJe9C6/xiYM7R6rhnj9Rb056J9W4L4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=KMGsYeNW8i1peerLA/ZxLTXTQB9autbiVJPYjR+Z7R/ZSaXPgKMAOX82xJwY94ndK j6uF99PhRxWMBTW3xVh6hAyjUH8iSWR3Cqu5/pc6UVffMXJNCJyumJIBn131wOrlSe 8IFbhkCh1ORfxDTu/EGVqEmc0BgLW48bdJCypLh3aA4tHsvMaozfT/A9AYXOqgXpXJ 0cCRVVFRxfthxcjIODCObO9cZyV1r1/dBPiDqkIOB8F2MzBQ+PF3MQcjZCmS0SNVoV 1lYsPT8UEgprnAIv+APz1a2AhuCoGmxgUNwnbYiYShoWixYfSwlOobf+7ER2pcFhn8 DMVAdjIiCdnHA== 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, acurrid@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 v2 05/23] rust: alloc: add module `allocator_test` Date: Tue, 23 Jul 2024 20:09:54 +0200 Message-ID: <20240723181024.21168-6-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 9D5F94000D X-Stat-Signature: dma1pzswhrm35xwj4k8am5srk91nmjd8 X-Rspam-User: X-HE-Tag: 1721758282-291898 X-HE-Meta: U2FsdGVkX19u35HPgdu9snNKzrwKPxHmQyBi9WD7+hdBYtU20zGBmi4Qjn6x04E5l88IjoX6GgI+LNY7Dyf7J/NOWI4VQJAyJS4+Anl40aow9gmiWalBZNCUQPhrwHv4gII1yGtpslaAZJhvvt1gz+qeLad2ipt9N04D03HivSHi4kButfMw+f96XEk2Eoj6jh++im8RlUMMQOKRDJf2bfr/hsNhx1xkp2rzntplaoQh1YG7MBGDyRaIw0aIwDMf5J+wOQC4fi0+VvcD0Ih/URdezqWZ75le0Kqxd7BaKgNhcLfT8elVf3QFiVFlXXUuqLJuncpJWID7i19P5q9oKTh+UlwWGQ1iqM77HnKIEhyQuy1J4QWe6fR/3124Dn3BxUCKB8TfdNBB+TDTB0zJTZRfVl7ZvdvAJX2z87Wjpjnox0sva/cWz6UyG/YMjxXSroFHero0ky2gceD/EbBlGHHLangehkwKyPc7z2b41gJY+dEVaYmHpaWuim/aPTSYj14QZcZD8onMmGJa2lGj0i1BbHABa8Y0QIHOfwf65gbg4zcZa2meopZ0HBD97IKSKMixoS5ujBlIfVt4+/B0Mf3hCPzzckUcKofoPk+U77tiT+ykH9I/1Wl8fIkxtwHaeZvZ1CvnjjNoCbtiVRnwWCGrv4opVfWlKBo1s2my3Q0ROfKvDcppJIl+yXUMohGhBEi3Kv/SIe2QwD6G4CGQ1P0SmCOWIXTITWca1PeV7xgXpq0OIbOaRKjaUfG2OOA5OCQWU3KeJdDzTXY9VPKECl7kkQueNw7/pG+0Go3fdjEuXwRQT2n8GVlHIyjSnByXYKJq8+iJay4Rio70y0I2cl1Jx/Rv/xoaTK9tg+cVjcfWDhdY3/exS+YBunDoW1pEzBLmf7LOrE9yUdhW8IqnoptjaLU4zf/2Jm4T58S6akFD4W/IZjurFm46RkSaT0V2qC2HPv1drI5IitYHCkl L7xHzkDQ 4cYyuDk19QiSuGJBdkEB17Dg0h9KNqaPKYZASGOMDwooaXCq8zB5z6aJOFGPQSWILcLqNeYcJPvC2EycdaPhh8zm4j2yzOKdlO2G9xGqlx81Q15EgDmB/3ekHwvjlJravsywdWlVVCX4nEAVTu4R7vHYw2FuH6qp4h2IsrMIGv0yN5bt2VRBm29f6Y2oAw4M4JVSBkK9Xb917+ywztezUOdJsPizWgtBFLgSRDNbgm9oeMWPqSOoKbwVBNAtkMRQLI7h/thc1WTiXN+0eNebvC+758yEhWG20eHTaWYBQTbaN+7vM4Ho46LwPs0H3MiWfaPyih9FILteMtDq7TLMeOZu8+wFxkbbb9OBwgWUOSjZCn08= 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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc.rs | 9 +++++++-- rust/kernel/alloc/allocator_test.rs | 21 +++++++++++++++++++++ 2 files changed, 28 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 bf739ce65387..90ebe79e86cb 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..3a0abe65491d --- /dev/null +++ b/rust/kernel/alloc/allocator_test.rs @@ -0,0 +1,21 @@ +// 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( + &self, + _old_ptr: *mut u8, + _old_size: usize, + _layout: Layout, + _flags: Flags, + ) -> Result, AllocError> { + panic!(); + } +} From patchwork Tue Jul 23 18:09: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: 13740250 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 75853C3DA63 for ; Tue, 23 Jul 2024 18:11:34 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 071D46B0098; Tue, 23 Jul 2024 14:11:34 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 021736B0099; Tue, 23 Jul 2024 14:11:33 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E04C26B009A; Tue, 23 Jul 2024 14:11:33 -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 C1A736B0098 for ; Tue, 23 Jul 2024 14:11:33 -0400 (EDT) Received: from smtpin11.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 44F7DA1F9A for ; Tue, 23 Jul 2024 18:11:33 +0000 (UTC) X-FDA: 82371810066.11.1D0DDE2 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf01.hostedemail.com (Postfix) with ESMTP id D6D1740007 for ; Tue, 23 Jul 2024 18:11:30 +0000 (UTC) Authentication-Results: imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=baOAej1A; spf=pass (imf01.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=1721758255; 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=a1Z170eel8JgQ9M7Yxbm+eSyWn0zSiRoP53h7G2mg/Q=; b=LMGz7onK3R3rPArWHYVYpAwu1WpmK+al+xT1kzHllK4NjKDclxetrpujGbUjyQh+SgIM9O 1kT01DXUGgkwkcO/l/8RjhtQiamaes1QnbcUvYsAw4ULWljqBbJ4ewQe7guxS08XbdTimM TYSvauaxjC1vEz5Kwk0T0jH5z3IR1Eo= ARC-Authentication-Results: i=1; imf01.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=baOAej1A; spf=pass (imf01.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=1721758255; a=rsa-sha256; cv=none; b=ElG4P8ijvjw6SZLawIHJmHrdEISElg/aQT0Gfr5YF2RNCHys9JYwinlgiEIO8KuQPCUcCC SKJ7rRzq9sU3oyDL3PqbWF9KvOtoAA3oPL6FbvY+sWccXCb0zraX3qlSOSKckID/59Wo9o MIVCRJahwBlXBh53hk6rPhoANdr9D4c= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id DA21ACE0EAC; Tue, 23 Jul 2024 18:11:27 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id DBEB5C4AF11; Tue, 23 Jul 2024 18:11:21 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758287; bh=YaemE3GyNUw6k5SxqCko0qV/GMMCyuitkbWwSJz9u6E=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=baOAej1Au7/hHblUtzSZcJOHCZz7qZr12SRUNNlEDYgjYE8epT7uQ6Ol6uKD0vVle 7KTQvroSucEVwHrGu82BmmATVO34yILswc2nfJqeTGChptNBIA2IaOeaev9rzZjGsg 5meeIrkW+uA5ZeBIitR9pR/a4Y8ngqdWbvCYEcf4QU18vwY3kKTPbK8bMyNMke3u0Z 4h8SOfuWi3fpJrF8AO46vqQI0DbAHLPLmlZdTIpdjq4+hDc6KtS4WMcxrWRSzvknT3 S8FSd0onOAXFkJCFP9n4LqJ67ES+ojOTTatk9WwKYHOAzbWDV9DJzwkMfmXPBErcuD b2mfW9M/rKnEQ== 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, acurrid@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 v2 06/23] rust: alloc: implement `Vmalloc` allocator Date: Tue, 23 Jul 2024 20:09:55 +0200 Message-ID: <20240723181024.21168-7-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: bjbkprd58apz7px754zcwg6mfxthka97 X-Rspam-User: X-Rspamd-Queue-Id: D6D1740007 X-Rspamd-Server: rspam02 X-HE-Tag: 1721758290-646410 X-HE-Meta: U2FsdGVkX19Az8ssZrqOtq4HGVsQtqHzVvqXNxUfWchS0679dc2kAEPIImtf3LD8aIwUntPXNbF1xXLuA+VHgyLOcUEJZuVOCfKeZhwo/nW82e5DNyPEKEaHFAkIWChn0gFup/01hIeLJnj4fsAH79n8mLQ3GtzHoeug44dA8AOJdNuSR0BCWMjoQfHi+HYdIfC7BByBH3Jz9025SbO7jrdb4JCeXWoHWKwbKngw79dOR/XFzAd8e/SsBp6Nvtu7nWwD+gwZdmHZYzo0UL331sLjf/oE23LtAhDfj5PQamxJ1C2hFJdtYQZlDN1gJsvngSVECsHJgZ7pD57XeWb8Hw5b8P4WF/jSvTcZ8/SW0Bwx3u3yqA+LWUajSbgv0hSRTHTS+u+Szm9vjk4/xTz1D0ZPLGY+Br+gIpOdmjjJHKiGre8VxXD30XMlI9/LbYRWPbjFZ2dsambo57hKQvQYkFLBtDXyo3H2jLobWaUS24mKw/DO/0GZroPT8zhL3kX/t8tM9WFH2dIOsMEAZbfz1uWvbHDwx3AcbKOTUGbc8QmOlCdMFV6u+ub2U2DV4LAx0V9JZOcYPuirLIgrdGiwyviEUs9ShBAcW3ixW01C2g5N3Sl+SkBQBR/6wR4UdwVRdpwM96zxIwd6h5ojaRpJom5KIDP6vCscPSQABOgSny4/W6Zsg9JxJ8Zgi/97SxEI9cdmV1mnqOP59VH10CwXy0l73rbkVEPhwxqb4K3VGmB70EiFdfQQ4iSCf9fQS9o2sNh8Kfbt+iXxHBSGFuOh3+StB6RlUsK3nWWDJyl/7GDnK0EtgjkQamK5UKdHwxarrrQCHlsk7t35RoItkMHc7tvDIu/NK7PW5s4T4sTp6EOSy1bDA+qotug6jMVIzZyGagYDpCNWEQWNSBJptCwCdhUY/pR1FMrN/IPfTYIEMzQr/48d8yzImYuUZbBdf2XP92i1mogiL+yaOYETq0b cWRndfQc 7GosnffdtPfnYAp4OtgsAh03e/DCrhTxgcCrz8SaTT9AIxqGxsCL9nXxY0KSu+qkZaFS/O6XWL31md0nukH+B3qxNkJxnL6ZJy+3gBnk9jmbsRXnCWdhQ1H1DWyeGk79SH8iJk798d1Y8R6RZ+x/jIyFcJBYW9y1m5tW1XMRpJ5R04COrCaAuMRcafeNhau7a4M1kAUkLdNQN0ETeiJaLSN2BB4HRhnEQ5KufLoB18NSc88GYskJTuDoX+Ip5Ji2ZbXOJHDOlkUzSOnoZ8vWi+t2vqJDjIleuGkbsuEwq84Cm426eZwn1vz2BlA== 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()`. Signed-off-by: Danilo Krummrich --- rust/helpers.c | 8 ++++++++ rust/kernel/alloc/allocator.rs | 24 ++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 33 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 3df5217fb2ff..5ca7e4872ee8 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -165,6 +166,13 @@ rust_helper_krealloc(const void *objp, size_t new_size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_krealloc); +void * __must_check __realloc_size(2) +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 397ae5bcc043..e9a3d0694f41 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -16,6 +16,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. @@ -58,6 +64,10 @@ fn krealloc() -> Self { Self(bindings::krealloc) } + fn vrealloc() -> Self { + Self(bindings::vrealloc) + } + // SAFETY: `call` has the exact same safety requirements as `Allocator::realloc`. unsafe fn call( &self, @@ -136,6 +146,20 @@ 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> { + let realloc = ReallocFunc::vrealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.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 3a0abe65491d..b2d7db492ba6 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 Tue Jul 23 18:09: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: 13740251 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 7D771C3DA63 for ; Tue, 23 Jul 2024 18:11:39 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 10E556B009A; Tue, 23 Jul 2024 14:11:39 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0BDEE6B009B; Tue, 23 Jul 2024 14:11:39 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E7B276B009C; Tue, 23 Jul 2024 14:11: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 C7F2B6B009A for ; Tue, 23 Jul 2024 14:11:38 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id 7D30B14032D for ; Tue, 23 Jul 2024 18:11:38 +0000 (UTC) X-FDA: 82371810276.26.6569BA3 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf30.hostedemail.com (Postfix) with ESMTP id 3707F80034 for ; Tue, 23 Jul 2024 18:11:35 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=P0fy4oHg; spf=pass (imf30.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=1721758273; 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=TDB1iNccaH+8aHo8IMoKY9aDpMHOdcr7EYA8sLrNcLI=; b=U2FTZMFoMJt3t40ACJRxttoNUXH8EL8Cpm3YNeGi8wwQOapWH3M/UfDm45PAg4CgbufPkZ cdO6B5x/1ygJZdFHSOEf1+CEc2vGLg9RgehMMpIocJYEdvMlc/PQtCyRJG8t0eJWJSOt/l 4Kjv5vsdDnQSSp9thA2aQ6NOSI7M6fU= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=P0fy4oHg; spf=pass (imf30.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=1721758273; a=rsa-sha256; cv=none; b=O0YDZa+0+K5r2y8HdMNMl2DJV29Dwl442x0cgEifigsFRxinvwMDQc15ddUy7LWorZYTxH wQaQovucXtI1wX+6pjFOly9cN+mU0s4ffoWWdR32XP6QBOJGjI6/2uRzLypByCgcEyVM7E okDLgCrq7JnS5S8qojYFOVkOVyEBuPs= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 6D36ECE0E93; Tue, 23 Jul 2024 18:11:33 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 7E755C4AF09; Tue, 23 Jul 2024 18:11:27 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758292; bh=VoSgcZBnVOwLP7rZy/xS0BTIj35SmIvHWDRctFLWgt8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=P0fy4oHgiIxm8fq1X97zoBznf3/NVarogrH+h0ecVwl2+FDYFNOUrCCy0ZNOG3Jm0 adQ50MkRsjoHOEd+Oc5uFHJbeibMZYhLLVzoVHjQD25QlzgVmqhoZkDozm+er2h1Pf 7q8u9sl1Bkhpo/f2FPlzT0E6H1kdmmhQQN9/yEevF+Z6pu97nY9WgN4drWO/N8wkRH Owu/UB9CgoG4HYoAfjgEMhUAl8uEkBtoBGlPL9NZwcBJ1gZsAqASGeeFsNxkoyk/KV 8cR5UTpSHU1s+WRfjTz6fAp3R5Pf/bE8F7tvuYMOu6vKAFuoLWE83As6FHoGyF8fus oo9UN0/r3MqtA== 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, acurrid@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 v2 07/23] rust: alloc: implement `KVmalloc` allocator Date: Tue, 23 Jul 2024 20:09:56 +0200 Message-ID: <20240723181024.21168-8-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 3707F80034 X-Stat-Signature: o3455fwt6aiczt3cwrc8u77xzo1fr93k X-HE-Tag: 1721758295-750930 X-HE-Meta: U2FsdGVkX1+1ZxoE+I1+P7xWRi/0Sx922xluUHHUnU22ghcKE9JOkTIJaFDuuK2eQPMorzteGb1io1UYmX5nrtDHxxs0BSvuRrFJa2Jq1FOCXZNUOMKeW+vsZS42IB7qe5z2R3XTtWAR5OggvUckiDpkic8jBozUo04iaxe3x20TFu056b/o3VJ1+3o/bGenrK2eRDHTUPcmBUD7e+wLxMX9DKiq8P/nIMDmkVTW87WVUQy9DK3xPU6RhUewlr8elo+u5PNf/zcXi75gOGs3P8zmF13rXUNzGt2wSgSkXoE72ToFT7Y4FJa0vovoG0Tqk1VlRkczG5oGdDEAN86u1WSyM6n+N0KXKEuRV+nbm1ZB1WVuO3lH16Ut5cmT3DGLTP6hlkySe2Dif7W6r5REzXegWWaYpoL9H/OiG+mYsWr0rWz6dmxtjGTeltmo+ZoQDd/qht+GoLgW1RbmJBp1elZEnxO+Uo2wGFmsZPbf/oAISjAoga6fYNg/ceL7n3igNaSqHAm5N0K/Rf34BkydmTqWSj3urhjrKzKU2iwEEG6oaBCD5GzTWYXZTjSz53SQ+6tgMDYWID+lq8hobdYMPqezVF9rogjMCAguwmDfO5tENGyuHYW4rW+8Hb3pauC1Zr/W0aRQW0+sFv7YfX6S//vGyslrhLF4qdqCpZVWr3SwGotWcOeHcwwP3W/04XeMskA411SFx2MoiyvId/4ScVCcRK363jw8QM5rT9z9BY2JLvzdIFT38aDNbTRNmdvz2c0Ua8TYtPH5LZzRrYSnJVseGYHpNEfOGqcGnVYV9CDn7zVYWNyzBo4a7l1pYQu1nmxnOd5e7XrvErAYU8NP1onslwBpdz7/uD7dbj8Z/m7yRTSsEuA1uewhzd2UwU4IiEKklF8X+mHEW13iLAsToCcMoBGOHsvZnteTUXiJS2k9MSliccztmEDTICJnV4R/YpL9M8MDYqglIl4eVDO gOexVr3e btaPbctqbjg08AHVoW3gm5gEj+6IM7uEp0TUGRj4JUmB5unnKjo2/7+R5Xj8DAId6Xg3U6ZMDL7UIBTbrEccjz4s1esaTQK3IGrw2p61Gd/ejT+x0+bp3DQWhqcxFCkAHIV5hBTBHLTxtFruV9c64GX/X99O2TiBQEy221DekZuIZc+DnYcKF3aNbnQHV/B4ZFsxJYydLQSMsHa48AFTFPGJgq2KRItn+v4C9YCEmituo583nMLBs1ZE9DBaGT3Ff3dwcQMGLeGFwQV+emGsuBXSXt9Qpq68u66QLsfDwH3bFbcG2Bg0tG+yYxQ== 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()`. Signed-off-by: Danilo Krummrich --- rust/helpers.c | 7 +++++++ rust/kernel/alloc/allocator.rs | 24 ++++++++++++++++++++++++ rust/kernel/alloc/allocator_test.rs | 1 + 3 files changed, 32 insertions(+) diff --git a/rust/helpers.c b/rust/helpers.c index 5ca7e4872ee8..19a5e4a0c7ee 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -173,6 +173,13 @@ rust_helper_vrealloc(const void *p, size_t size, gfp_t flags) } EXPORT_SYMBOL_GPL(rust_helper_vrealloc); +void * __must_check __realloc_size(2) +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 e9a3d0694f41..1e53f149db96 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -22,6 +22,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. @@ -68,6 +74,10 @@ fn vrealloc() -> Self { Self(bindings::vrealloc) } + fn kvrealloc() -> Self { + Self(bindings::kvrealloc) + } + // SAFETY: `call` has the exact same safety requirements as `Allocator::realloc`. unsafe fn call( &self, @@ -160,6 +170,20 @@ unsafe fn realloc( } } +unsafe impl Allocator for KVmalloc { + unsafe fn realloc( + ptr: Option>, + layout: Layout, + flags: Flags, + ) -> Result, AllocError> { + let realloc = ReallocFunc::kvrealloc(); + + // SAFETY: If not `None`, `ptr` is guaranteed to point to valid memory, which was previously + // allocated with this `Allocator`. + unsafe { realloc.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 b2d7db492ba6..f0e96016b196 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 Tue Jul 23 18:09: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: 13740252 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 B3D9DC3DA63 for ; Tue, 23 Jul 2024 18:11:45 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3A6366B009C; Tue, 23 Jul 2024 14:11:45 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 37D376B009D; Tue, 23 Jul 2024 14:11:45 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 21D766B009E; Tue, 23 Jul 2024 14:11:45 -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 03B2F6B009C for ; Tue, 23 Jul 2024 14:11:44 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay02.hostedemail.com (Postfix) with ESMTP id 9E81E12033C for ; Tue, 23 Jul 2024 18:11:44 +0000 (UTC) X-FDA: 82371810528.06.146627C Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf12.hostedemail.com (Postfix) with ESMTP id 581BD40010 for ; Tue, 23 Jul 2024 18:11:41 +0000 (UTC) Authentication-Results: imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=jzRMYXdL; spf=pass (imf12.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=1721758255; 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=degiQLL6SW/nvK42Iyzxff+yJMKE2WSy3me3PkqPOec=; b=a10qzPqty0AGA9RW+09cRp7fdV9hqgD4Y+ZTWDm4l920YaM8hc5igrKAEnl5pAeskhQdLa 6gRrQwh7OZ9GUCjfdrRBRj8o5cLjkzwAQR05YJmEwtnK9wFzZkA4jQqflspuWATGrtZ8MW xYup3IU8xvA1ncnFq0fo5ZZVSfQQ7Yg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758255; a=rsa-sha256; cv=none; b=mISMqr0Z46R2diPYed+qf5kJgEqrrjRyLOZCkVKLoZvmdF4mRf5OfdBO65tG9wUMXWKlKC DzUVGY9p9brVEZIpz3hmvYFqNT5IlrwZjJQlYo873iFdhbq6OF/uHeH8cuxcH7I1+amF2c 7G8q2UjkFJMUAdEkx6B1nUb4Qh7f/b0= ARC-Authentication-Results: i=1; imf12.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=jzRMYXdL; spf=pass (imf12.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 385F8CE0E9C; Tue, 23 Jul 2024 18:11:39 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 22C00C4AF0A; Tue, 23 Jul 2024 18:11:32 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758298; bh=EADnfi1fGvsx4VhAV2Fq3TLA5MaiZGvO/PM1XNctkMk=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=jzRMYXdLknWKU0suCrVLj8MEFGuTCk7/uXsRG/mzuUaad6aFwdImo0hpVVrtIv7kH 0Rv1AXFLqi29AxP5TBXGlkF16TDnKbx4X3Cv8xPp6L3L5gcMSys9a9enKH5QrtEEMf GJWj+dRnU8pYOsxpsuvVbiLkTaJi+K3Av/YRPwhEiiXcDNbenfTiCEhgLVg/NRN6j3 vne/BLvKZRqxoVtlZ5qZ+4hIl7cVphYA1vSQMzC9xXLrnOFcCIMPXShVFDDPiSm+ZF 5ga/F3VxiqKohPR51k3FZes5jjxBRQtQqLSQ61rf6jJindASfC6V14JtEaD0+fBpHf cwIojKBj2UxmA== 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, acurrid@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 v2 08/23] rust: types: implement `Unique` Date: Tue, 23 Jul 2024 20:09:57 +0200 Message-ID: <20240723181024.21168-9-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: qj8pjjo4g65orb6dq5zjmmnp8xygeimb X-Rspamd-Queue-Id: 581BD40010 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1721758301-925137 X-HE-Meta: U2FsdGVkX1/UhBkacKd1HZrRHeTM9cLfmJInAWrwY68GnTj8b6oQS8WqU4TPwcEperw5QIMeOwi2WjZoJF5snmqpaxIwoQUHf1tCdLJ4NboQYvIBWQEBj0BFyDNRsSs4gI4I4/HYfLbjTleU85Ks1ZrZNTdQEZSSC3RKzOrg/cJ9kXsDWlLmPlDPCWWWK605fqtK2lxE5b5X4ImkHkYOJo067w9XcWXOFgbebruwJPadHuBJhj+RbfD11Y8tN/L7j3gkSlUQPuyxR0LF9mESvKx6BYky7+6a4ZXCSgvyr45oXqu+h3bUBHRd9LL46+fwQTFeH6oXN4m3/PJDoyOmNmFWmBS8tV4yWWZYzpLEfk3hulTMVElEpMXGqQ7ShGxopXZhtpNw8endBIfPmOHjvJeTouPWBqgk0hOuta+pAE6tw3TTwxKrA8CEFAebwbE5Xi4e05sWEt3vHOO8EhXXWHHrL9vxMv4aKQ2FE465dUNdCTWzpDFqHC+3L5iGbZ8H/AHPZ3/ZuWzwUr6AT9TsNw6EJf8icQZGjnOAOIHAZOWzF+g4ioiLZadYEDlwsPqDSQ0E74I5qsTs2xcEKJZHjoPEtlASy/L4bzqZdkx8gGHMKZyEIPJVwpFeciOmaZJg9HSFkj8pexHtkhtA8EX5VBU97S91pvoR38mvTAMm3xOzOu1ZpLar3cdFC6pBZk1Qh0mjgbTAD1CnQAjpIZPFLyPIClZsLnl0un11TPkNdyC0wTc+649kj2DAytu/P+yV9wZjQM/XEKUiHp1Sof5QE0eItyNIxRNMlZ8+0H7qZ987ZLrMOnXLAmRock3kfeKwoc57ZvXRU5Cjjv3i6ysbn0/I2ElXM+i6uh6ulYAtu4tStaDg6zyGFYds+R6t+LFk4y1QGufryDz9w96T5PiO2+MNnXoSuqZX/uzzD4RWyr66IlpuUJ4SKNbAwy26XUiuecTAug1SkKerE97E9na PZYZ1TgH r2N4RvT7/jxsadm5qzAVQ2QWQhYmJr9DoRYX/MfJYWSia98eUsfWqlEoZWpzP9HLp44ur7YucO1vy/9CW/kR20dMxHzUNJBfnw475F+Uz3omVvm2HTEpbKCWRd0v7wM3pOiLd/l6iMpNpidOfa3r1vKfnvQzY4uUJnfzyKvaTI4tGC6CrLPHwjXEkrfvQxIyh5ClLrmp72iBvKblb2nobpqcmRSIO3kisAHRrdUl9cit516f0O5BYjBuQ3Za4Qx7worVoO7tkDLxDweRoqniqUJ3pt4xk+vOy9fWo+qLSHoqQKxtd/ilp0g0RLxWrBdHqOXkxn5J9qFk3lP8= X-Bogosity: Ham, tests=bogofilter, spamicity=0.037709, 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 the `Unique` type as a prerequisite for `Box` and `Vec` introduced in subsequent patches. `Unique` serves as wrapper around a `NonNull`, but indicates that the possessor of this wrapper owns the referent. This type already exists in Rust's core library, but, unfortunately, is exposed as unstable API and hence shouldn't be used in the kernel. This implementation of `Unique` is almost identical, but mostly stripped down to the functionality we need for `Box` and `Vec`. Additionally, all unstable features are removed and / or replaced by stable ones. Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 183 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 2e7c9008621f..9cd20fe41c20 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -409,3 +409,186 @@ pub enum Either { /// Constructs an instance of [`Either`] containing a value of type `R`. Right(R), } + +/// A wrapper around a raw non-null `*mut T` that indicates that the possessor +/// of this wrapper owns the referent. Useful for building abstractions like +/// `Box`, `Vec`, `String`, and `HashMap`. +/// +/// Unlike `*mut T`, `Unique` behaves "as if" it were an instance of `T`. +/// It implements `Send`/`Sync` if `T` is `Send`/`Sync`. It also implies +/// the kind of strong aliasing guarantees an instance of `T` can expect: +/// the referent of the pointer should not be modified without a unique path to +/// its owning Unique. +/// +/// If you're uncertain of whether it's correct to use `Unique` for your purposes, +/// consider using `NonNull`, which has weaker semantics. +/// +/// Unlike `*mut T`, the pointer must always be non-null, even if the pointer +/// is never dereferenced. This is so that enums may use this forbidden value +/// as a discriminant -- `Option>` has the same size as `Unique`. +/// However the pointer may still dangle if it isn't dereferenced. +/// +/// Unlike `*mut T`, `Unique` is covariant over `T`. This should always be correct +/// for any type which upholds Unique's aliasing requirements. +#[repr(transparent)] +pub struct Unique { + pointer: NonNull, + // NOTE: this marker has no consequences for variance, but is necessary + // for dropck to understand that we logically own a `T`. + // + // For details, see: + // https://github.com/rust-lang/rfcs/blob/master/text/0769-sound-generic-drop.md#phantom-data + _marker: PhantomData, +} + +/// `Unique` pointers are `Send` if `T` is `Send` because the data they +/// reference is unaliased. Note that this aliasing invariant is +/// unenforced by the type system; the abstraction using the +/// `Unique` must enforce it. +unsafe impl Send for Unique {} + +/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they +/// reference is unaliased. Note that this aliasing invariant is +/// unenforced by the type system; the abstraction using the +/// `Unique` must enforce it. +unsafe impl Sync for Unique {} + +impl Unique { + /// Creates a new `Unique` that is dangling, but well-aligned. + /// + /// This is useful for initializing types which lazily allocate, like + /// `Vec::new` does. + /// + /// Note that the pointer value may potentially represent a valid pointer to + /// a `T`, which means this must not be used as a "not yet initialized" + /// sentinel value. Types that lazily allocate must track initialization by + /// some other means. + #[must_use] + #[inline] + pub const fn dangling() -> Self { + Unique { + pointer: NonNull::dangling(), + _marker: PhantomData, + } + } +} + +impl Unique { + /// Creates a new `Unique`. + /// + /// # Safety + /// + /// `ptr` must be non-null. + #[inline] + pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { + // SAFETY: the caller must guarantee that `ptr` is non-null. + unsafe { + Unique { + pointer: NonNull::new_unchecked(ptr), + _marker: PhantomData, + } + } + } + + /// Creates a new `Unique` if `ptr` is non-null. + #[allow(clippy::manual_map)] + #[inline] + pub fn new(ptr: *mut T) -> Option { + if let Some(pointer) = NonNull::new(ptr) { + Some(Unique { + pointer, + _marker: PhantomData, + }) + } else { + None + } + } + + /// Acquires the underlying `*mut` pointer. + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub const fn as_ptr(self) -> *mut T { + self.pointer.as_ptr() + } + + /// Dereferences the content. + /// + /// The resulting lifetime is bound to self so this behaves "as if" + /// it were actually an instance of T that is getting borrowed. If a longer + /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`. + /// + /// # Safety + /// + /// Safety requirements for this function are inherited from [NonNull::as_ref]. + /// + #[must_use] + #[inline] + pub const unsafe fn as_ref(&self) -> &T { + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a reference. + unsafe { self.pointer.as_ref() } + } + + /// Mutably dereferences the content. + /// + /// The resulting lifetime is bound to self so this behaves "as if" + /// it were actually an instance of T that is getting borrowed. If a longer + /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`. + /// + /// # Safety + /// + /// Safety requirements for this function are inherited from [NonNull::as_mut]. + #[must_use] + #[inline] + pub unsafe fn as_mut(&mut self) -> &mut T { + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a mutable reference. + unsafe { self.pointer.as_mut() } + } + + /// Casts to a pointer of another type. + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub fn cast(self) -> Unique { + Unique::from(self.pointer.cast()) + } + + /// Acquires the underlying `*mut` pointer. + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub const fn as_non_null(self) -> NonNull { + self.pointer + } +} + +impl Clone for Unique { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Unique {} + +impl From<&mut T> for Unique { + /// Converts a `&mut T` to a `Unique`. + /// + /// This conversion is infallible since references cannot be null. + #[inline] + fn from(reference: &mut T) -> Self { + Self::from(NonNull::from(reference)) + } +} + +impl From> for Unique { + /// Converts a `NonNull` to a `Unique`. + /// + /// This conversion is infallible since `NonNull` cannot be null. + #[inline] + fn from(pointer: NonNull) -> Self { + Unique { + pointer, + _marker: PhantomData, + } + } +} From patchwork Tue Jul 23 18:09:58 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13740253 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 8A308C3DA63 for ; Tue, 23 Jul 2024 18:11:51 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 15D766B009E; Tue, 23 Jul 2024 14:11:51 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0E5106B009F; Tue, 23 Jul 2024 14:11:51 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id EA0956B00A0; Tue, 23 Jul 2024 14:11:50 -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 C2AB36B009E for ; Tue, 23 Jul 2024 14:11:50 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay07.hostedemail.com (Postfix) with ESMTP id 84454160351 for ; Tue, 23 Jul 2024 18:11:50 +0000 (UTC) X-FDA: 82371810780.28.A7BEAAE Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf20.hostedemail.com (Postfix) with ESMTP id 1416A1C0017 for ; Tue, 23 Jul 2024 18:11:47 +0000 (UTC) Authentication-Results: imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=p1x1UV6Q; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf20.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=1721758256; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=A1r6kBZevgHq93hz5MIRI7+fBp01WiFGrwg+4UQtr3Y=; b=PYvVxbDOf9k5F56g74zCG7K3MtUUqKv/BxQTgm/NLOZRdm7q3ipfx5DGgQByvi9gMGsd05 96bCqyIbZJxbn5qCxEsc6GgbPtBW8SkxLqLA6i8y5SVP+l6OGANLRxRq8HFSbZWlxrNWgV X1QcuTvmHoUm7FktN/SXBePv+uWm8d0= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758256; a=rsa-sha256; cv=none; b=8aYK2jbfXGtPqpMyGbD12KP9NunPcV5qcqdU2Pf9fM8CqGlNQDo0BtjL0dEc4b/R+IEsmb HhhQ9HhqhwSCkRHOxZOoAhgG3wWMWLkxmlYsL6PQK1sA4ad3F8Y/sucgfvW1IXJcTmLwpm s5MWwVkxOkfOF5YCmfQHNrDXpBTWQNY= ARC-Authentication-Results: i=1; imf20.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=p1x1UV6Q; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf20.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 D9333CE0EA0; Tue, 23 Jul 2024 18:11:44 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id BBEE6C4AF0E; Tue, 23 Jul 2024 18:11:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758304; bh=ITmzVZ1ozdPC3EpkKUw5PXAHmRHl6f/OyV+G/hFt6go=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=p1x1UV6QZQmFQm9ajyXyqUWSDF8heHOtbK3W22bT6fY/vpirKkHlsBsc28w26zpyg IIZ1TnM4Ubox+kwaKEr+69eGZEBh65kwS2yt5KbWIw888g3KGVSvNiGEloahoNvXoO /LjzTfcpJfaK240ZGJr1c+5krXZ/GRU2tNdwU/RS8q9HBp4KgGyLIQRrah+cUXAE7d QHXxwKoctXEF9TB3h+/K3TWfGVY3PfzH3O62bbtYGzANqksggSqNuTJQI5XjSPiLuL IDQ8JPmt0+I5dMCEtBtpcV6VwMo4vYUDY3Od94KgLw2AUbySs16aIFQi/Cxm1I4ZI9 KzUkEqOAKpvlA== 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, acurrid@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 v2 09/23] rust: alloc: implement kernel `Box` Date: Tue, 23 Jul 2024 20:09:58 +0200 Message-ID: <20240723181024.21168-10-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 1416A1C0017 X-Stat-Signature: q9merqufnqyyttd4eicodoxoc6uzqhkj X-Rspam-User: X-HE-Tag: 1721758307-458870 X-HE-Meta: U2FsdGVkX1+UUVIevihjBknoKqceY42hWgfzn8pBWvwcVITZ+BLepUBrknyVZtQ+HR/ZT+pgJO0NSJSOnH0XxSxH8LWqwIlTCoy+fCHp1fhGVFt14Kl+6WWnfd9vSdC7KPokD10ITa4fHwIJLGfuu+auf/S6+NarD7dmZH59Yz+/naH2w5K6k8eDKPuHEeRBTE1gMBAR0loUyWtq7DnRr4qQY6kBvEtWDakTOOPs6PO/L38X/qoV6ziLiWKeKIeE/TNVs8NwDm+tEO1XJESmBhSeJmn5xbzNUtVcMxRsDw//Cz8R+ZosCjTQWKWmoW+sENNPh09citLvFTPw2y+LdFgmYY1AiyTbj26Qa4svVoyo7qAQH1SrQlCo8a6W9lAEM5pew5PXMe3ZNJZ8wjdd6NnHiMMSP/ZosoP9mINI5Jcf62kRky61+EbtifIsBKyS8OXf5rtxTOnpYZ3SWMYRJM/wp0cbvVjttMyX/ay0V1mU11YoSgRVA0C9WMlRDZFC75/MVMO4mpMBqjrunYmfBnAA++7hFg6nDHlxpT00+k4OHMwfRjDCZosbYx6jqOIFZDGu02gfDJy7JRUL7HghpE06D/X860OllEsKmXZbInfD7FS3zQKDB2tU2+9gJ9qF6EJLmn3rN+/g7o8a1dXiIri6HREdBcSNUDZRRRUWQTdoTsL3WkVBdINzYzzcafWBxH62Vg70wG2RGoNrY864dtUYnSkDdfHuDT0IFVKNVAuxeRpXexo53473PSIiQ73+fwn1fFyTT1axGPhwFsuSfjDMJkUOqu8JnUBeYdiXgo7z0znTkY/8LvuSnVzPo4acVB/EfJh4nR49SdMTHdRrcD/fTk7ImXkOHQ3rRyF5tNx0zm6awRfZY/jM+vIpJGtGYG+L2UH0G6ZMFRtqC7fAy0qBjHwM8u9sO3565krVjyAq+f1dLh0pNq/Af81GqhFAiQhTJKh94f35lkcbIcV qrQ3wrJm qmJa1+LmNHiv7qjgLGZ7J46j+7jEzGFnqZXgygRRBUz3U/k8L9S2MxTr3xKZguVskELLtxVDzxJdt1qlj3EYKP+Dg43piWE01gaXwVO1/p3XmcUREpojkEePdLoznJQqyJcco8E3IlH3uDaWsT9smQe/vx8E/QOD+HyGF2isv6ByNW6yZq4q5KVHQLQBdj/YY6udUfHL69bX/Y+hU7TyOmMI3HuKNWuPCDrilUXlOh4pqpPcgDrSNVUuEwEVeVeuTuhTb/AVv1lsQpQTqmI3H3WtwNVuK1hnhQ6iO/dTXU2IvE+Q44GSYziCi9WIGO+uSTajNR56vNPC6rj2d+DGXSIJK8g== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000016, 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 | 330 ++++++++++++++++++++++++++++++++++++++ rust/kernel/init.rs | 32 +++- rust/kernel/prelude.rs | 2 +- rust/kernel/types.rs | 26 +++ 5 files changed, 394 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kbox.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 90ebe79e86cb..d9809368643e 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..eb4a5ff500b8 --- /dev/null +++ b/rust/kernel/alloc/kbox.rs @@ -0,0 +1,330 @@ +// 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; +use core::result::Result; + +use crate::types::Unique; + +/// The kernel's `Box` type named [`Box`]. +/// +/// `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`. +/// +/// For non-zero-sized values, a [`Box`] will use the given allocator `A` for its allocation. For +/// the most common allocators the type aliases `KBox`, `VBox` and `KVBox` exist. +/// +/// It is valid to convert both ways between a [`Box`] and a raw pointer allocated with any +/// `Allocator`, given that the `Layout` used with the allocator is correct for the type. +/// +/// For zero-sized values the [`Box`]' pointer must be `dangling_mut::`; no memory is allocated. +/// +/// So long as `T: Sized`, a `Box` is guaranteed to be represented as a single pointer and is +/// also ABI-compatible with C pointers (i.e. the C type `T*`). +/// +/// # Invariants +/// +/// The [`Box`]' pointer always properly aligned and either points to memory allocated with `A` or, +/// for zero-sized types, is a dangling pointer. +/// +/// # Examples +/// +/// ``` +/// use kernel::alloc::allocator::Kmalloc; +/// +/// let b = KBox::::new(24_u64, GFP_KERNEL)?; +/// +/// assert_eq!(*b, 24_u64); +/// +/// # Ok::<(), Error>(()) +/// ``` +/// +/// ``` +/// use kernel::alloc::allocator::KVmalloc; +/// +/// struct Huge([u8; 1 << 24]); +/// +/// assert!(KVBox::::new_uninit(GFP_KERNEL).is_ok()); +/// ``` +pub struct Box(Unique, 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; + +impl Box +where + T: ?Sized, + A: Allocator, +{ + /// Constructs a `Box` from a raw pointer. + /// + /// # Safety + /// + /// `raw` must point to valid memory, previously allocated with `A`, and at least the size of + /// type `T`. + #[inline] + pub const unsafe fn from_raw_alloc(raw: *mut T, alloc: PhantomData) -> Self { + // SAFETY: Safe by the requirements of this function. + Box(unsafe { Unique::new_unchecked(raw) }, alloc) + } + + /// Consumes the `Box`, returning a wrapped raw pointer and the allocator it was + /// allocated with. + pub fn into_raw_alloc(self) -> (*mut T, PhantomData) { + let b = ManuallyDrop::new(self); + let alloc = unsafe { ptr::read(&b.1) }; + (b.0.as_ptr(), alloc) + } + + /// Constructs a `Box` from a raw pointer. + /// + /// # Safety + /// + /// `raw` must point to valid memory, previously allocated with `A`, and at least the size of + /// type `T`. + #[inline] + pub const unsafe fn from_raw(raw: *mut T) -> Self { + // SAFETY: Validity of `raw` is guaranteed by the safety preconditions of this function. + unsafe { Box::from_raw_alloc(raw, PhantomData::) } + } + + /// Consumes the `Box`, returning a wrapped raw pointer. + /// + /// # 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(self) -> *mut T { + self.into_raw_alloc().0 + } + + /// Consumes and leaks the `Box`, returning a mutable reference, &'a mut T. + #[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>`. + #[inline] + pub fn into_pin(b: Self) -> Pin + where + A: 'static, + { + // SAFETY: It's not possible to move or replace the insides of a `Pin>` when + // `T: !Unpin`, so it's safe to pin it directly without any additional requirements. + unsafe { Pin::new_unchecked(b) } + } +} + +impl Box, A> +where + A: Allocator, +{ + /// Converts to `Box`. + /// + /// # Safety + /// + /// As with MaybeUninit::assume_init, it is up to the caller to guarantee that the value really + /// is in an initialized state. Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + pub unsafe fn assume_init(self) -> Box { + let raw = Box::into_raw(self); + // SAFETY: Reconstruct the `Box, A>` as Box now that has been + // initialized. `raw` and `alloc` are safe by the invariants of `Box`. + unsafe { Box::from_raw(raw as *mut T) } + } + + /// Writes the value and converts to `Box`. + pub fn write(mut boxed: Self, value: T) -> Box { + (*boxed).write(value); + // SAFETY: We've just initialized `boxed`'s value. + unsafe { boxed.assume_init() } + } +} + +impl Box +where + A: Allocator, +{ + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Allocates memory with the allocator `A` and then places `x` into it. + /// + /// This doesn’t actually allocate if T is zero-sized. + pub fn new(x: T, flags: Flags) -> Result { + let b = Self::new_uninit(flags)?; + Ok(Box::write(b, x)) + } + + /// Constructs a new `Box` with uninitialized contents. + /// + /// # 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() { + Unique::dangling() + } else { + let layout = core::alloc::Layout::new::>(); + let ptr = A::alloc(layout, flags)?; + + ptr.cast().into() + }; + + Ok(Box(ptr, PhantomData::)) + } + + /// Constructs a new `Pin>`. If `T` does not implement [`Unpin`], then `x` will be + /// pinned in memory and unable to 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, + A: 'static, +{ + /// Converts a `Box` into a `Pin>`. If `T` does not implement [`Unpin`], then + /// `*boxed` will be pinned in memory and unable to be moved. + /// + /// This conversion does not allocate on the heap and happens in place. + /// + /// This is also available via [`Box::into_pin`]. + /// + /// Constructing and pinning a `Box` with >>::from([Box::new]\(x)) + /// can also be written more concisely using [Box::pin]\(x). + /// This `From` implementation is useful if you already have a `Box`, or you are + /// constructing a (pinned) `Box` in a different way than with [`Box::new`]. + fn from(b: Box) -> Self { + Box::into_pin(b) + } +} + +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 ptr = self.0.as_ptr(); + + // SAFETY: We need to drop `self.0` in place, before we free the backing memory. + unsafe { core::ptr::drop_in_place(ptr) }; + + // SAFETY: `ptr` is always properly aligned, dereferenceable and points to an initialized + // instance of `T`. + if unsafe { core::mem::size_of_val(&*ptr) } != 0 { + // SAFETY: `ptr` was previously allocated with `A`. + unsafe { A::free(self.0.as_non_null().cast()) }; + } + } +} diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 68605b633e73..b34c8127b76d 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -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}, @@ -1183,6 +1183,36 @@ fn try_init(init: impl Init, flags: Flags) -> Result } } +impl InPlaceInit for KBox { + #[inline] + fn try_pin_init(init: impl PinInit, flags: Flags) -> Result, E> + where + E: From, + { + let mut this = KBox::<_>::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 = KBox::<_>::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/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}; diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 9cd20fe41c20..dd602b2efd90 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,6 +2,7 @@ //! Kernel types. +use crate::alloc::Allocator; use crate::init::{self, PinInit}; use alloc::boxed::Box; use core::{ @@ -89,6 +90,31 @@ unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { } } +impl ForeignOwnable for crate::alloc::Box +where + A: Allocator, +{ + type Borrowed<'a> = &'a T; + + fn into_foreign(self) -> *const core::ffi::c_void { + crate::alloc::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 { crate::alloc::Box::from_raw(ptr as _) } + } +} + impl ForeignOwnable for () { type Borrowed<'a> = (); From patchwork Tue Jul 23 18:09: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: 13740254 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 22A88C3DA63 for ; Tue, 23 Jul 2024 18:11:57 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A0F3A6B00A0; Tue, 23 Jul 2024 14:11:56 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 9BEAA6B00A1; Tue, 23 Jul 2024 14:11:56 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 838B16B00A2; Tue, 23 Jul 2024 14:11:56 -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 5B5C96B00A0 for ; Tue, 23 Jul 2024 14:11:56 -0400 (EDT) Received: from smtpin19.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id CF02DC033C for ; Tue, 23 Jul 2024 18:11:55 +0000 (UTC) X-FDA: 82371810990.19.9A35B11 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf19.hostedemail.com (Postfix) with ESMTP id 7E4521A0009 for ; Tue, 23 Jul 2024 18:11:53 +0000 (UTC) Authentication-Results: imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=BVyGfZg9; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf19.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=1721758276; a=rsa-sha256; cv=none; b=6raJqaygGtYDZeqQpWpxG9YdEfj4D4GVUOPNmdKZFhOwHvv/HqJDSDnyCknDqoIr4lhuiy jozGQnvnt77cZyIv+M2a0dh4RkhIADI4If2ead/QEika6KDKZFiSwRaeenNGGbN4Bm6LZj eVFLBiGxurOD8fr66HHT0OJmYPQMGos= ARC-Authentication-Results: i=1; imf19.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=BVyGfZg9; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf19.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=1721758276; 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=knFaUnTtqUnlVmPN+XYtgRaI8AqmyIRkBOprKIsgDz0=; b=tRwGDZF2L/s908HPjDZ2Elc11cIRDUGRmfp04HDp8FGueoME0PWEC7S7w7TGqIlAShNazb JRRetMBfiXG2D36FaUGFutgP5u8FsJwPqed30R7HEzeoDn8Z41BQg15wooS6vaT2FPX085 p0bZdYA/1Tp3B31xl11/ZIq7jofG4ps= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 7E35DCE0EB5; Tue, 23 Jul 2024 18:11:50 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 8D0B3C4AF0A; Tue, 23 Jul 2024 18:11:44 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758309; bh=5g7r2VPtY3bDOuGLZSS4fG/C0++8XYbEf2Kc3K71oVA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=BVyGfZg9BwuMSiRJrU5u3Yg9Fq/8t98ebvlab9kPrBntYbGtdNFL3FQ0vLRgx5+CG mdGJgDIFXFqsf0qPVefQLHALrmEGCD5AvUo/4crl+N5z3oyBInFjL4axXoM2sY+Nh8 Zvxd+DCuCQbwAosh1M8IhtjqTIu0wzbBQj0Z0O71fqckbC/wqpvDVftj4xQlEp5XRx qodVyDjNpiNj3gbmKtV4cZI35/Ro0LuBFLmzAj3DRlnCR72CB9FY6yUo/bxG9bgfzQ sQ7ylymnNA0Qvz1ywYQ2QtBcoQACExyeVFNfW3qBwMM5/BHKZNVdEG1V150QZnCEta ba8W1frLcd+qw== 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, acurrid@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 v2 10/23] rust: treewide: switch to our kernel `Box` type Date: Tue, 23 Jul 2024 20:09:59 +0200 Message-ID: <20240723181024.21168-11-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam12 X-Rspamd-Queue-Id: 7E4521A0009 X-Stat-Signature: in9z91sbso4uqof3bx68r1drhqkqe7hy X-Rspam-User: X-HE-Tag: 1721758313-746898 X-HE-Meta: U2FsdGVkX192bZb+qi0xR93vAJHcA2UQl5j8Kj+nrOec5UTAux5n48PrYVPovYNbVJSbswNG2IjMoLeK2gsKJPdTd9R1zWG7VVw9Fi0Ye9L59l2bS9zdB3qj5ggnnzpIvRzGpMXbv46yQsvX8ouQGPSlckvjf+Kj4WEnMyVyMUWWW8e19HzMomPdij6C4vxDpZY4lDOEn0klHNfo+w7s3EZWREBy/qdi7usCGW+OiO3DBQv0XVSd9UCw3GYH8l0cLZB8yARJljQb+tFZknNvKy1COXsibtafVUF15wnC0o+QQYBl1XMSWHwREKu0o0KxjqxZN5XpJdhNMUldfscV/ukhuKRqaGtnAcSaG8Qo+fR0GHfTWfR9R3MkqtoN0o0v2SKE3UYdCXoIMs3ifWKC7d6lURUyNUevAtlfkcdNk8Ic2sRYsAgnyQNTPF1OoeWzzQ9mBFnz6cDfkojKN56R+X5zM2zyWp/QLRdSTxomZ5kXkPVnAZunRRYCaefDlqH0xw0TXnsYaig2/l71O98Sw3U6RKRSqbLQqfe39g2nNdpyWUXfow2SQ3fiFnDK5g20eZ0vfApqvybDPLyXf8u/NrsMhdstLqDXVI25kexxRt1UdcDk9Qol9GSsZgxIGO0bOtHnSn//gutdvUhdI2uhGX1ooapekC2PaaVBSTesbNWLwo9fLuhgse+wIUXjV9kD+SLpmzrlC68+Wrveei8z5V+hq89DygIk4vHkYiR0+wLvhveOvdOLZa4aJ5dtgUva7SgRypjSRSVSnPt9DYmNd7nV3xliZPtavbC+hZPqT5Kij/Z1KHFCfZ7oF0b4+Pb9rVjy8a1ohuEVTHxh4zU02jwocRj9kI0XKAhWXa3FiP01G0qIDp5isq3lnSIEGzPL0wGqsDutuYIuhUxO94gPYlcRNbLZQEBjnfkTZabg9dSKTmBp8AD+pdaAX0FKlBC7F9GCGagXjmYKSAkY9E5 x1ftTLah BAt9+akPNcoBj7qHnDn/0dM2Xdl1euxYQ+QCzv8MQJgQlZ45aamvoFxeiTL/ZlODALTf34Jzee9rvVE35dsKXu4QSnFy3ngDXJvOcRbHEeXAy/kEIuB9CmsrlRTpz+WqiJ/EnSrXVJ2PboDSKHW4BLP37MEPPpZBxtcE1H/i40vFjksANalD15FKb9hFLvIcgwQMVVjpm4Z0tBFnTsGOgINURb9HWF6C611wr1AT86Y9ItSRZS+YGNUZ1ow3qEJCcjK+Qg+Rr5qW4HWUWPU/zHSDQUDwZfd+v6zJ4T0bhv/3Ivt/pfIrLkFRSkezqSW7EOnpKnZzJK9igICHzoanj71pKVD+OpDTmLTZ6RWUV9TPpxvS9cbDacX8TtGrPa7al8JI42F3hKLsVMoc= 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. Signed-off-by: Danilo Krummrich --- rust/kernel/init.rs | 39 ++++++++++++++++--------------- 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 ++++++++-------- 7 files changed, 43 insertions(+), 43 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index b34c8127b76d..f50b9bfe660f 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -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)?, //! }) //! } //! } @@ -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) /// } @@ -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, @@ -927,7 +927,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, @@ -1013,8 +1013,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( @@ -1351,7 +1352,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 1cec63a2aea8..47c8a3df0b8b 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. @@ -563,7 +563,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, @@ -574,7 +574,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) }; @@ -582,7 +582,7 @@ unsafe impl WorkItemPointer for Pin> } } -unsafe impl RawWorkItem for Pin> +unsafe impl RawWorkItem for Pin> where T: WorkItem, T: HasWork, @@ -596,9 +596,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) }; From patchwork Tue Jul 23 18:10: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: 13740255 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 B9BCCC3DA63 for ; Tue, 23 Jul 2024 18:12:02 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 492186B00A2; Tue, 23 Jul 2024 14:12:02 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 424696B00A3; Tue, 23 Jul 2024 14:12:02 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 26C2C6B00A4; Tue, 23 Jul 2024 14:12:02 -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 069BD6B00A2 for ; Tue, 23 Jul 2024 14:12:02 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 7990280324 for ; Tue, 23 Jul 2024 18:12:01 +0000 (UTC) X-FDA: 82371811242.06.EEA85FE Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf14.hostedemail.com (Postfix) with ESMTP id 2BA7D100015 for ; Tue, 23 Jul 2024 18:11:58 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=e1HhX2TU; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1721758296; 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=hbcoDDPB39nIZKg+WdhpL53uIwhRzTd5UgdP99Nz5ZU=; b=SoxiEj8KOM4FBNe3WT1GR0qdbJ3Nt2bewX8XE4jba66ubj87mNHCEmu1lHx9zeyUcfAeGI 3tvoCZ75qNE6WV7FATsa6jolNQpnop1k4Q8GjzBs/XMX7y/Uo/L8bZmsbDjX1BmS44Aep8 67xIr+fOFuzpZRAqBxf5nj088Ts1ZSA= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=e1HhX2TU; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 145.40.73.55 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758296; a=rsa-sha256; cv=none; b=HpbXRh7/RuZCK7eIx/lBlRTy8N041PfRWZ0wZb9LXnNw84HUAWdBaCbt0RzyPudEksWWyt oOoU+kSQeB7CxdVP/QAqdIaTvvPYsnRA5T6J+dQUrjW/EAu9bKJ5jCNfUujldE3OvQapKt tJl2q9r8+1g4fW49Wm+ke3zHhNP2RWk= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by sin.source.kernel.org (Postfix) with ESMTP id 27A08CE0E92; Tue, 23 Jul 2024 18:11:56 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 33385C4AF0B; Tue, 23 Jul 2024 18:11:50 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758315; bh=WKQ7MgfG0G2WqgFeLi609/hjUACQHn7VtgxgOOJDNdM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=e1HhX2TUsXA5lDi6g8kfBkK3mAIwKt9uoYOQdosNu+OHw1A7jqp8ZDRDhw+k+5wOe bAJnArcHiqoBqCIDImAag+HqFn491JNE26ZBL1A7F0BpHyPj4sWwtulN1JtiUmb4vz jiuBzOZF8ml+0GcUSsvb5UEPTB1YH6DsFjVaNu1r/dvPTI7V7EgriuZtaCsi7dyany 8Jt9U/bjJdqNKzHz4WUdkXW1ojIZp+S2zl6Samuh2aYbtA9q3RaiA2G2JR9SArjhXO /sLXOhPzPVNXn4qNn+pn331ORSDA5pVcKsK7WVscLQGuYTtyk7ef4zys6+KUAmNBp7 LoFtjsayUKEWw== 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, acurrid@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 v2 11/23] rust: alloc: remove `BoxExt` extension Date: Tue, 23 Jul 2024 20:10:00 +0200 Message-ID: <20240723181024.21168-12-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam11 X-Rspamd-Queue-Id: 2BA7D100015 X-Stat-Signature: x7mbooish5buowxbm6xcfopkntxmzyig X-Rspam-User: X-HE-Tag: 1721758318-540762 X-HE-Meta: U2FsdGVkX18k6e5QLhL0RdDlwLKh/7Tt81LaKoT2LVo/XnQ4VYQyy3QhetqHjddLWjJSBkntTIE48A0vYsKD60UbfPrQQ7yTabeZfSs/cjwWuxXXFGwPA1z7Zd6u6eC+c3+zrSQVIbQ2AmfZkqKMkuxglEB74Nax8WkNq4lq1I5/arlgO8iFswVEvLW3r4AsL1VHBwWXDZdwTfMpBVle1PHv1FgqjDlZAR9lklu+9qq7JjkL/puDAtrNvti7PCYl7+248sLVulOdy/2JLs5HsHV0gesADMozfiiFQ6NmmjQ0kDp0b9f34fVPWbYFa2jcuSoFn+Nes/Ky27E1pNj7E6r81g+gfT1ruorjUHFo7CvGlC8mN4EUZDlGkRMP5gWv+kEPhHMP0+VYzkXnlCBX8TV1OTsFqnD/yPxKT82ewuTebfJFJ2fltS1YpP8Obtrf/K78/5jhsyp0A8rSQC8P41VGi/rdEyJRz0YtbbegczopNsHCnSK/TtS6llYl3xWtUmKUjTS+6dRU83DCDASe79hKf2m81nDqTG9b/G4XsOE+J3DTTNW57OJ9eeadJ+reBQ2j+TGXy5fX1Eajq0q4bN556BagcF765KjihsBuI2LnR1fQw5WrCxsJg01esQ2eqkHO5ZHv3k57esZ0M01ZBVeWyXYljpuoNVqo/BiTzGLPDRLHLdJWkfzCeawpTU4SIiU12LVGb2FvfIp8ykQ3iEdsyh72p3wa3TK6xw+W51qnmi8k5GhXoSyBelwUJbHrhYcJq2c5c86NMMv62QQ6pPIbHXsWX1Ri4ihIjOlx+zkxXH7LrGu0wYE0G58zdWsF0TDg8AAcF63NqKJVj07gzgBfQbxpPaBtPDsxBfX2j1LyVTJq5nffJVVxnUJGpijcqKB3r8wiyyCQJWT1PZk9okXtGsH56Lbj5ens9rzqfccARzsgacMwg0ht8a78NofC5QXDz3G2C4uQ9PnNQeQ U4rfjVO0 4zveGDoXwBci3ZScANoHeT97ydoMvgZY/1obyBTVbuW+Q1PnAVkNvHhApQM5w83Wf3+DTvq1aH+XkXGqcoUWIKqcayu5uzxJWP1Z8Pb7jrmgQIgz2PKCqLj/jrWngjtk8QHKTyY8cWdvvTztgI95ueL3+tPfSKqc0L5Ti7cZCelZ7ZAEEu2UNteLwTyqDS6YB7lo/ps8+oK9uBxw3nHibc2EJ/Jpf3tFazzHPVd8nT2ZfTmrhuocPFw2951VrY0GGqaaBi9AfzV3vna46eCYYrNstfJL25GqWVlG8ouAJknRytwnI4NDpIQritw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000003, 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. 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 | 22 -------------- 6 files changed, 3 insertions(+), 115 deletions(-) delete mode 100644 rust/kernel/alloc/box_ext.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index d9809368643e..48c008ab340d 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 f50b9bfe660f..a1cd7ced70f9 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 { @@ -1154,36 +1152,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 KBox { #[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 2cf7c6b6f66b..6ae20a23de46 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 dd602b2efd90..d67b37a5edb8 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -4,7 +4,6 @@ use crate::alloc::Allocator; use crate::init::{self, PinInit}; -use alloc::boxed::Box; use core::{ cell::UnsafeCell, marker::{PhantomData, PhantomPinned}, @@ -68,27 +67,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 crate::alloc::Box where From patchwork Tue Jul 23 18:10: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: 13740256 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 D9459C3DA49 for ; Tue, 23 Jul 2024 18:12:07 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6DC346B00A4; Tue, 23 Jul 2024 14:12:07 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 68A8D6B00A5; Tue, 23 Jul 2024 14:12:07 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 52B9B6B00A6; Tue, 23 Jul 2024 14:12: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 340136B00A4 for ; Tue, 23 Jul 2024 14:12:07 -0400 (EDT) Received: from smtpin22.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id A249B80354 for ; Tue, 23 Jul 2024 18:12:06 +0000 (UTC) X-FDA: 82371811452.22.BF7C6E7 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf05.hostedemail.com (Postfix) with ESMTP id 708E9100028 for ; Tue, 23 Jul 2024 18:12:04 +0000 (UTC) Authentication-Results: imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mz+c3jib; spf=pass (imf05.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=1721758278; 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=Ti17svBMYAUfR9ZfxGdgNbIAVGHYFHfIl4BDg2Ry8vs=; b=cHKIK9Hj0X9URM2kDw8l8RIBCPF9M4nY1ntV89F0EJY8AONfIzdyLXeMTXXpKJCS2+h/rn oNW2fx66YGzensJZv81rzyeGvfOinmGaDcn4ZqxxbqMjaaGJd4xodSj8WXOwGRa/5ajaXh jyFSO/e+h+Q/qJTX2cQewckaltmGaMU= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758278; a=rsa-sha256; cv=none; b=Ffdu1qg+A8Uneq+zuBXXhIOjcFTWL/VqSBYuMydYdoMogqA7m6JU1MgjlZEZ5fY5QQpStN yXBMzch1wrBpmeAcenOdses7YUi65KKwY5wNLg0Lj3EMbbHuVuK15sU2w9O60XcoChYJ9v R+DFTLFE7RFKSH9RO309XsBbkA6IvyY= ARC-Authentication-Results: i=1; imf05.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=mz+c3jib; spf=pass (imf05.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 C0313CE0ECC; Tue, 23 Jul 2024 18:12:01 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C81ECC4AF0A; Tue, 23 Jul 2024 18:11:55 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758321; bh=IsegupDL6dNouhj9LI4K0JPI4QQWWwWlwU04wMc/SwI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=mz+c3jibuWgJwcKZM7aGqSADuz6ejR/ZC+t7GQrirU7NnutbHsXT+uJXKZb4R9isB rHeWk5FliserG8OO84VXZRoBXyHeglwLW8dxd/RWCofCPQVFhOZ2t0qCXAXD0FRNuz Hle+I8HjZ/w5RNPtbZTY0zZTnON2De2BWvXnbDZBFrZKuqwn7iJ+ZbTU+50uGLYEmi Hr07A4LgDXLVHFapDWKC4BU+clELnUWbr7jFSqwK4IzENwCrlbHfypc6v9hOf2LeBg yOnDFA5qpGPFY56bCw6G28x9cbkY+/MIFWO56Xh/+hOnZaMs7pLCyS9C6CxGMoa1in rB73961xp9k5g== 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, acurrid@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 v2 12/23] rust: alloc: add `Box` to prelude Date: Tue, 23 Jul 2024 20:10:01 +0200 Message-ID: <20240723181024.21168-13-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Rspamd-Server: rspam04 X-Rspamd-Queue-Id: 708E9100028 X-Stat-Signature: zc79nxgdgqb4cq7neumpyd7bsg19wrhx X-HE-Tag: 1721758324-440539 X-HE-Meta: U2FsdGVkX19KK7H8WemSYHCDJxhBBt0QwecQcegbB25CBhef5+gIiPY6J3ehEZB69eDBpT/36ByEeMN0yYWslT0tDSTtBe+BWlBqDVGtEV+sR4Lk6Rgi46/yzM9Kw1CXIeH7kokNEzzeh8mo1sDCzNtFAolVJ3vQV9oSGV1jrtUmuV9CSUVYl9HcyJibZiDtTmrQKIQONbgPUeWljlX1f0Rw2dCt10zPoqEJvttiyY6H1w7H1wgL268DbjcTSvNIXSvN/IX5YNN09/HLPLmV9zEuktBjWNp4PieSEnvjddsvc9nFid4XxEdOEy/WELYZ63R2Ivq0y94bggOxk48hbMdTcFRb9b/TQm8+ylbBYITxnI/o3wA2vujFRX07KRoZZooxzcGImVP0BsTpjvBulIFzFxqY6srOWGLYbnccUwws9ldM5ztIkLJMNF4fJ4RCaAph+XXr+QZ8/6Py+Mx4maXALGY4Z4mMurFbSc9tSOlJMo52m7KQFdrrmrbWLoeZ/2D9VEfof2JurAOUAwfNq0mY6MAFLbd6ub5cnWScz+uHO0WfSKpDw5cVix2D8TGgf8JYK5KoT/tdAUrECSI2UMzrR2H9KXBUymR6c5JSqfgcOwVJL1Tb2eRCsE0Ibe5SzClsb6y+28l2WmQG3Q6p2VHFlEDAna8v3CjsTfYeVPi73hNmAwD/EEXbplrX25zPqqB0olyT/UyhglfSKRd0oKZ/xJaJh2EOGcwtpJoNatN+NT76I+TyfWA+38F6DmwmMbKzVsBIQ+5IH4Vamg00g+fcK2Fa8+TiIBW206Yo3ws/AdssJMmpx99uNYGAu5mY8C+gfFRTCElM+xgXV7JKYRjuwm5SzSV7qQD96VDKqlVCaV7I79EYFdbXaPSgMFY/2VfwvE8fLgpz/3MwIwAIOKGHCdDkNDhB3jnX55IUp3u3puxrMo4YlzPUkavMrLOpeJbTvD62BFRhjsX7OwB O1LRuL+r V/zQHQZy7KFYND8G5HiPDg8zeqkdsxSLyPKSDGgRbMQQ2zCN/p0F2KhFnHHRiD46iWQfcoxoQ/xMJkes0jU3sfjeutsictePKf+B5GdMEQbYJGKwWs4h4c6Wgl7xP8SGHWGodzzE7y9YNMxHJW3bL1DYoL8C6fKRQf5ylE8DaYxmOWAapPpGZzQC0fEbyH0eGEdKnFFkIWAqnbvh2yrLLSuzAvSoVXsCFGorHyYykf5KILeoDowJi0M83ssqQLxUiIUYmMOKTicp6A9rrox7nAm6TEl10xn7FXyLXOrLi/QSeekhuR4kSqoHKyQ== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000135, 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. 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 Tue Jul 23 18:10: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: 13740257 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 9CEE0C3DA49 for ; Tue, 23 Jul 2024 18:12:10 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 2BC0F6B00A6; Tue, 23 Jul 2024 14:12:10 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 26BF76B00A7; Tue, 23 Jul 2024 14:12:10 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0C1726B00A8; Tue, 23 Jul 2024 14:12:10 -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 E02D66B00A6 for ; Tue, 23 Jul 2024 14:12:09 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 890DEA2014 for ; Tue, 23 Jul 2024 18:12:09 +0000 (UTC) X-FDA: 82371811578.26.7965EA8 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf23.hostedemail.com (Postfix) with ESMTP id D2DB6140004 for ; Tue, 23 Jul 2024 18:12:07 +0000 (UTC) Authentication-Results: imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=sLoQu3Om; spf=pass (imf23.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=1721758304; 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=enfuyaAqiO5xRtG3CPqMrpQx0/Ig7WkcMI5Ys/LAMD8=; b=6/5mh2Rb9mi3Dl9mGunoYd7HzwANyGeuyvfzIg7bguh0xXNy+hr7QT98KvWGo1ogCrz+Cz vQ6G/lOYx6XIL/xjIDa/YCproyXQLIMtkqOkdpheSOBoihmaOhNd9jI9ePw9Nxqtvtv24s w8EvG77WBXhYDovnpAuSgzC5P2yL6cs= ARC-Authentication-Results: i=1; imf23.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=sLoQu3Om; spf=pass (imf23.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=1721758304; a=rsa-sha256; cv=none; b=cpiML14BBLAnf2zry6N12Gj7+gfGmZ06H2csKyWP0SNnTcGhmn63UCMqd1BjEan1R8CZVA 4f5pOeIFXACQ94VhEcj4EQUx5DoRe7HL+i7lVPrbj+coQN3eDEai4RrU599m7IZ3jNmnE1 tYq/vfbXKOclFEr2HP1QebKOrqmfhU0= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id EB86260DF6; Tue, 23 Jul 2024 18:12:06 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 78AACC4AF0B; Tue, 23 Jul 2024 18:12:01 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758326; bh=/9+EutwFn2+cS9gNKuR0E554iCROCZoKL1CdsGgwb8c=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=sLoQu3OmR4kR03BZ8aJlI9lV2J2cK5q15+YM0g9Mk3OdIv99lwhllIfwFbxAjDPC7 HEnHKhrUzctHyMCZubcBLDIYnasV0oih0b4l8i8KKkDl1cTVVSZeu5e8LCNtXC9umw ePCdXJCWkjhzKSab4zyxHHvCfTN1E96TI1Y98S+fDFoQZzdkh2+NlSOv7IoxINuKCO Zk2LoBFwQLTP4+xHE4wyhAHcPm8YeMUUFW0+qqSp6flIxknGQD42hXLewq85y1cAth FLFbS9W39HLuUQ5Wph9CZsa9pgiQFbH6DqanRCeBaRElTVvTKwdx9dPpacwWGPZdEF c8Bc9x1nNVNmw== 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, acurrid@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 v2 13/23] rust: alloc: import kernel `Box` type in types.rs Date: Tue, 23 Jul 2024 20:10:02 +0200 Message-ID: <20240723181024.21168-14-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: D2DB6140004 X-Stat-Signature: 61qax3ntcrpmzb8qqx1yx1h5br6o3cw8 X-HE-Tag: 1721758327-936974 X-HE-Meta: U2FsdGVkX19lWSG3Zmv3SnoXDfpdy8WTo4SJ3Wwbw9Pw58ifG/XYP+SttgLjn3cIOEr2AQEkXJYEu9TbeFIR6CbJOGbr+EZtlHN7kj2U5B1WpuTQW+/mJuNhAlrCdzKiSwfzibqEc/zunU41bWlhHddceWkKmSZ9fbmIbzlzntNVpYDfbwshQBeK8/pfeqhHtWLc6ds+ibVkeMI9ETxwql6NEouQOAAqBiTxU6Sr0JD5waoo6DZX4S9MZJYS8PhDf833xrrc4Gq5oQpACO/XGISXpDjkIYTlyH7uFfC6j3Dop+Jf4AS1zCKY/2EeyLWL4Pi1M/HQnMQsESwOccNZgOkLrnw69PLoWf2o5SfLi3S6ZcPWN1WUD18sdIaELDVbtDiBQU71BYWVYQWdU++atMRfmKTGXNMKj3HQVC7v7XmLku+IxMc6QjNK7EIrycZ+qAww56wsA8mFgbqIwLwY+B5m2UGYWdZWzdaWBg9ZQxP9p0pUSxSbhX+Ly58QbZLYw7k8lc18u1k9FvxF/iePoYpFfObQ8R3UimTaPzKD7f7mtu3yr/HqnvgiOzfyXY+JCfWK+eVQXnFsqSXepTQEd93d8HIjCYelbuS2QujwCSuQP/7hFJpmZ8qn3LBpy2jMXm77v4sbvWm1qgrIH6crl/aKN8Rk6OlMDKe1e6eTkk6x6XhVz1kTjFyFR/ASGK+VVtyDJiHm3bVuJJ4tYc+i8goj5Ozj+hdnqTegR8kmOKvtQDWhBRmGQIa5YeaYhwnfhPQ6YgLX/oQ72d7lfsLHI9rH9a7/XF+yK+9qJ79WKtSfZ3t2N7OFq/oiPwa1en1Q39GVa0y7hanbjAwNl4WDU9o1PPZuYp0nzq1dDqVZwoC4PJk3joLew1Ld5cpnP8j6wHFFxmpE9NMsU65A/7MWWIE5ED7hmYedhML1Miitk6wwtuBn5XzQBm/kcyWs9wfcS09ngXZZmQu8Y6/uSyA dSUBUfaT VO3pmKHwok/vxORv0k2xvrvbhppaoy8PwUpTfzurhedSjFIBCmVnRFNueQIWmWikJ+PLedzdIVrktV2bpAzO9oBWRGNnY5Wl5E1YI5J29gISpVoA+tLzaERG6xIZME5ZvZrUWlrwX+Yi1KQVjtsT5X8Jl2gla8MbJaCNTWxwW3LXpont4deUOzgNMJW5+jpQRy0LfY+VP2jvGVybReD35d/UovQDoALnvdKeyg8I327IigSCu5FtOtw4adnMlsDCA/VjDyuTPZmEOC0uJkx1+Zqhp32IpWK0XFzz8SGuyDTxnOEj7d29Rl+m8TQ== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000001, 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 types.rs, add the new kernel `Box` type instead. Signed-off-by: Danilo Krummrich --- rust/kernel/types.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index d67b37a5edb8..ee0063a20d89 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -2,7 +2,7 @@ //! Kernel types. -use crate::alloc::Allocator; +use crate::alloc::{Allocator, Box}; use crate::init::{self, PinInit}; use core::{ cell::UnsafeCell, @@ -67,15 +67,14 @@ unsafe fn try_from_foreign(ptr: *const core::ffi::c_void) -> Option { } } - -impl ForeignOwnable for crate::alloc::Box +impl ForeignOwnable for Box where A: Allocator, { type Borrowed<'a> = &'a T; fn into_foreign(self) -> *const core::ffi::c_void { - crate::alloc::Box::into_raw(self) as _ + Box::into_raw(self) as _ } unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { @@ -89,7 +88,7 @@ unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> &'a T { 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 { crate::alloc::Box::from_raw(ptr as _) } + unsafe { Box::from_raw(ptr as _) } } } From patchwork Tue Jul 23 18:10:03 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13740265 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 1C63FC3DA49 for ; Tue, 23 Jul 2024 18:12:20 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9E81F6B007B; Tue, 23 Jul 2024 14:12:19 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 971BB6B0082; Tue, 23 Jul 2024 14:12:19 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 776B46B00A8; Tue, 23 Jul 2024 14:12:19 -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 527F06B007B for ; Tue, 23 Jul 2024 14:12:19 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 18BD8A2028 for ; Tue, 23 Jul 2024 18:12:19 +0000 (UTC) X-FDA: 82371811998.06.B9FD48F Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf30.hostedemail.com (Postfix) with ESMTP id 9FB7B80011 for ; Tue, 23 Jul 2024 18:12:16 +0000 (UTC) Authentication-Results: imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hRmdw7g4; spf=pass (imf30.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=1721758290; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=S9y1ETz+DewV4QIQhsJYVpC3458MIDbkL5RtvgmV3tQ=; b=vpRSSQ4xBY7hyaXRAikaGWke3AMWbgJ0wOJmKlTZqJl1FczRySvs7WNvnypsPI7yQhHCmA fDUJsD3Z3TUQ4fVax7Ys/nZ31GQasxMrrr6s0v6qNujV+V9RFE7KWX2Sxly5Gill1+GFSm LCxnjGemSKq0LKWT6haNE6bf4HsEJQQ= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758290; a=rsa-sha256; cv=none; b=HGajAZoElBMIVSEpnfAHDLapXaZy3tEN3HKHl7Xun/p44qrtttLwWllNbxuPDg7CwQh1D7 P5Z7EFnYh86wlI7tSPpNu3OUzeeVlbsvTRc2d84tH3G4ZP3MyDfoxDv/dKRTuqQ1EPEv3u nyB5cXGcYR/C5/U4laAkGf36V0RrndQ= ARC-Authentication-Results: i=1; imf30.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hRmdw7g4; spf=pass (imf30.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 32B28CE0E92; Tue, 23 Jul 2024 18:12:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1D9AFC4AF09; Tue, 23 Jul 2024 18:12:06 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758332; bh=bZNDSa939dmJFDRhKIU+Bh6SyOAqA59VXE7BB2QVuYY=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hRmdw7g4ZHQEAB54I74N5jNbb7BYLMiZZjW0RmyrvhGUSnHwvEAepyIP6SgELeSof boD2uZxja24NGRFQiD7u/F1pfEG4fq5vcRW5mKNKm7ELlrHsV9XWUPhScJCHUGVKZp zDq1Y1ffxQTd3S+ikuqGnfQxiXtINa2c5RmW/zntn9xPAvK4ae3Rni101D433R/gGV 68GC+SMSckZr+Q/cWxD6hgtAVGBOvAaohKVlCyTs8ewatkaKEoTAJxhbNbjGKquxG6 Y5jSnol/aiy24ZW4JmSXu/NVVfhMblyRYAYpKPpnd6U3brpGmtrPEPfVGOZ87yrKDT 1XbX9yMViGeHg== 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, acurrid@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 v2 14/23] rust: alloc: implement kernel `Vec` type Date: Tue, 23 Jul 2024 20:10:03 +0200 Message-ID: <20240723181024.21168-15-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: 7omx5z141smf6sue6dn384fsh6usasqt X-Rspamd-Queue-Id: 9FB7B80011 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1721758336-404069 X-HE-Meta: U2FsdGVkX193kRHa3Yorw+FmKf/D5NM/wkvorg65AHaVEhtWB9vUI05FWOjwcJS62v+Vki1cIk9dsWuvpmteMdYAdA7jvpxjYtTFPtJrZmgTZSa2wautKaacM2Kp28TURWTS5YbGFykikPibxpqkQbphpRr3pmSytwrmm5bbKmu56RMKa4RgrFBWQg+ZjiCkB8q0uVz5exI8/hq0Tf7r75RbQirxHiHM4tm9RtBZeOzFYl8LI92yfWt4rRbrR8HRf381vACEDHyAQ3S17wAnuBUUOZWKjEMXO8oDmuJtAU3oCBUdn7vUJHpZlyGALMjCkLCQoQsN+fmRKQP3npJP49vwhWaS0/YVU1s3zg8TlwouFO+AIL80+xmYeGZpBU+pyiZrTJRTCXa//mYi0bfz16JvmuGvQ1SQxI2NhLy0C0xi0bwz+iLsidKo5Si4FgDAvYCVgsBw39l+RmVnAMpxqyKBPucWevos9JPblco9vHfiJytIVSqrwPE2wsH5GsqWGqsuBvTr7GxGsrQf3wLAHtqC2+Ta0Z1+0Xj1HM9WF3DeZy/OFdsZGVxXKAosOxUH477FnFK2zAldexZEx/ouOKG68Ww6S4WvGGbgq/9qB7sOYsncU99K7YhRN8mx+Y2cAlGzK2EGwO3A9AqbAlpRGobNkCJrq4g6q7yStUNzN3Wv3GyuAmpuPf0cxXDVJpuMp3yVpY1cka59kQxFegxcLrA9SYBM7JuLYsTFskMEFZ6nvJ0Mr/Su9UD15fJPqm1yQT7sD0FIrEmmyJs/2Asb4RDdhRA0CfNjEcKVQmquRcVbdo7zfmC9VSylnVk5Jh5Ak6Ewmtw0iR3yLzxQpeUbcGBBgSVmu6Gskt230uhlZ7g5ipVVQqrfduicBijZ6BZMIHeVQAWe0TJ2sx+NXWV6uYW2yoVF3eKCCdCe/FVLDJbIGsLlb3WchACwlLv/ZjzB4W2nfF8ToaHZ8LB2fiQ aeOfHxB+ 5WaIzt3QgvxGqtS3Pz9Sd7ugTdCy7vEB6ClFHxJfWI0sqjST8CDD5cDOyjSsn1UvM93sSZsWYdJbYVT6XKHRg7fN3cG2gal3ShNfHKnm9TPvkFZbt3NZuowwckDlGxRmwpKIn9f6WWXl1oN37bQLLMsUPUd2nPd7A1XPHGKeMcQ/RVutV+m0chw0+Liy9t5kwhDR5SvbFOx00wD0udRQX+MnvOeQoKK3egld//d6lOOTRjlKVyzQRmqNlSHYezBe4Ksxv16CCD1gMn8mo/QgSnOshvutT74Lykk4/UUYm1uVAVXFVfFdRDRpQ3jbTJ2ctXQOTkpGIa7cI2z+H4Ytr5vfns1IrAAHMDkdx 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 | 580 ++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 4 files changed, 602 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/alloc/kvec.rs diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 48c008ab340d..827922e1f1d1 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 eb4a5ff500b8..d7b0b790a424 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; @@ -173,6 +173,20 @@ pub fn into_pin(b: Self) -> Pin } } +impl Box<[T; N], A> +where + A: Allocator, +{ + /// Convert a `Box<[T], A>` to a `Vec`. + pub fn into_vec(self) -> Vec { + let len = self.len(); + unsafe { + let ptr = self.into_raw(); + 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..58b3f679ad83 --- /dev/null +++ b/rust/kernel/alloc/kvec.rs @@ -0,0 +1,580 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Implementation of [`Vec`]. + +use super::{AllocError, Allocator, Flags}; +use crate::types::Unique; +use core::{ + fmt, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ops::Deref, + ops::DerefMut, + ops::Index, + ops::IndexMut, + ptr, 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 named [`Vec`]. +/// +/// 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` 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 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` of the vector is the exact allocator the backing buffer was allocated with (and +/// must be freed with). +pub struct Vec { + ptr: Unique, + /// Never used for ZSTs; it's `capacity()`'s responsibility to return usize::MAX in that case. + /// + /// # Safety + /// + /// `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; + +impl Vec +where + A: Allocator, +{ + #[inline] + fn is_zst() -> bool { + core::mem::size_of::() == 0 + } + + /// Returns a reference to the underlying allocator. + #[inline] + pub fn allocator(&self) -> &PhantomData { + &self._p + } + + /// Returns the total number of elements the vector can hold without + /// reallocating. + pub fn capacity(&self) -> usize { + if Self::is_zst() { + usize::MAX + } else { + self.cap + } + } + + /// Returns the number of elements in the vector, also referred to + /// as its 'length'. + #[inline] + pub fn len(&self) -> usize { + self.len + } + + /// Forces the length of the vector to new_len. + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`Self::capacity()`]. + /// - The elements at `old_len..new_len` must be initialized. + #[inline] + pub unsafe fn set_len(&mut self, new_len: usize) { + self.len = new_len; + } + + /// Extracts a slice containing the entire vector. + /// + /// Equivalent to `&s[..]`. + #[inline] + pub fn as_slice(&self) -> &[T] { + self + } + + /// Extracts a mutable slice of the entire vector. + /// + /// Equivalent to `&mut s[..]`. + #[inline] + pub fn as_mut_slice(&mut self) -> &mut [T] { + self + } + + /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling + /// raw pointer valid for zero sized reads if the vector didn't allocate. + #[inline] + pub fn as_mut_ptr(&self) -> *mut T { + self.ptr.as_ptr() + } + + /// Returns a raw pointer to the slice's buffer. + #[inline] + pub fn as_ptr(&self) -> *const T { + self.as_mut_ptr() + } + + /// Returns `true` if the vector contains no elements. + /// + /// # 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 + } + + /// Like `new`, but parameterized over the choice of allocator for the returned `Vec`. + #[inline] + pub const fn new() -> Self { + Self { + ptr: Unique::dangling(), + cap: 0, + len: 0, + _p: PhantomData::, + } + } + + fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // Note: + // This method is not implemented in terms of `split_at_spare_mut`, + // to prevent invalidation of pointers to the buffer. + 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 directly from a pointer, a length, a capacity, and an allocator. + /// + /// # Safety + /// + /// This is highly unsafe, due to the number of invariants that aren’t checked: + /// + /// - `ptr` must be currently allocated via the given allocator `alloc`. + /// - `T` needs to have the same alignment as what `ptr` was allocated with. (`T` having a less + /// strict alignment is not sufficient, the alignment really needs to be equal to satisfy the + /// `dealloc` requirement that memory must be allocated and deallocated with the same layout.) + /// - The size of `T` times the `capacity` (i.e. the allocated size in bytes) needs to be + /// smaller or equal the size the pointer was allocated with. + /// - `length` needs to be less than or equal to `capacity`. + /// - The first `length` values must be properly initialized values of type `T`. + /// - The allocated size in bytes must be no larger than `isize::MAX`. See the safety + /// documentation of `pointer::offset`. + /// + /// # Examples + /// + /// ``` + /// let mut v = kernel::kvec![1, 2, 3]?; + /// v.reserve(1, GFP_KERNEL)?; + /// + /// let (mut ptr, mut len, cap) = v.into_raw_parts(); + /// + /// unsafe { ptr.add(len).write(4) }; + /// len += 1; + /// + /// 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 { + ptr: unsafe { Unique::new_unchecked(ptr) }, + cap, + len: length, + _p: PhantomData::, + } + } + + /// Decomposes a `Vec` into its raw components: (`pointer`, `length`, `capacity`). + 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 `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)?; + + // 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.as_non_null().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().into(); + 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)?; + + unsafe { + let mut ptr = self.as_mut_ptr().add(self.len()); + + // Write all elements except the last one + for _ in 1..n { + ptr::write(ptr, value.clone()); + ptr = ptr.add(1); + } + + if n > 0 { + // We can write the last element directly without cloning needlessly + ptr::write(ptr, 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.as_non_null().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] { + 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] { + 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 Tue Jul 23 18:10: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: 13740266 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 C5B6BC3DA7F for ; Tue, 23 Jul 2024 18:12:21 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 3F5A56B0082; Tue, 23 Jul 2024 14:12:21 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 37DDE6B00A9; Tue, 23 Jul 2024 14:12:21 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 1D1136B00AA; Tue, 23 Jul 2024 14:12:21 -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 F0A296B0082 for ; Tue, 23 Jul 2024 14:12:20 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id A834C140336 for ; Tue, 23 Jul 2024 18:12:20 +0000 (UTC) X-FDA: 82371812040.03.BECEC77 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf14.hostedemail.com (Postfix) with ESMTP id 075EC100015 for ; Tue, 23 Jul 2024 18:12:18 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ASoYC5Ro; spf=pass (imf14.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=1721758276; 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=fiQJi6a8L56jq90iVV1ruKgfsSxkPxSv6lIunMWfd/c=; b=mMPaN5wmOjnUrkbQ3agWSviGHaHOlZ3gylDn6W+xJaxopU3YZPZaxOIMnj78viBxBYEpKJ nFHpOjX+T3J1566N+DIznBRk3y+fU9c2jY8A/5nKaZHO+bDdNYRLrGi0Fs/rYFvR5BlL4n K+5RxnCiEb7ns94KbWvpwnzFS1gYkto= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=ASoYC5Ro; spf=pass (imf14.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=1721758276; a=rsa-sha256; cv=none; b=4HlEw2lXoyLlVK1mNZslACPpA+LBVTTBRBPH9Z5U7Abnqq7ND7Zs1GTL4aOz95ShormzVN A2NR2Ne8PkpuYNtSdsPtwD0GrZgTvrW4g1M9vaRxAQ8vfnu558DwCxOlbIcbpRtuAQIntG PPK3ZfUC862zMcTLr5NHg0faU3ECXbM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 2035E60E00; Tue, 23 Jul 2024 18:12:18 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id B70FCC4AF0A; Tue, 23 Jul 2024 18:12:12 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758337; bh=c3QAEBZXl3M1WsOmfNh19vNXUNzyZvBix2UsBjiGOtI=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=ASoYC5RoyFxVt1qORsF7cKfWeydOo+meew08vpzJjAAxJiB8eIifrdSo9n0K9QN88 IoR3tEeo+y4EqksYwvQz/OPsRDe2OKxBfrdZqgY2g15Rto6/wMtHsHnQVuqZjxJpE3 KH20JQVp77kvTCJtWlrgxNSVDtLNhAbGePPbfNAXZ4ymEhnejSzwc4/FbCVWCKCSTX AyFoOjfoq4hoZtQf4lMM7MoYvUN5hxC3Y8SPnyYCC9yZKsJw+pp5CvjJf9r7+H5ps6 7JHpY+kwXX6Fo9b6XB4J/ZSkQoczgRAQ1O1ijBoprzvvG0tXCxOlUxbM6IfGA8tU2n W4T0bgS7ldmbQ== 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, acurrid@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 v2 15/23] rust: alloc: implement `IntoIterator` for `Vec` Date: Tue, 23 Jul 2024 20:10:04 +0200 Message-ID: <20240723181024.21168-16-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 075EC100015 X-Stat-Signature: a1b7a758idm3mt8uik4dg54z1bn1npgm X-Rspam-User: X-HE-Tag: 1721758338-140499 X-HE-Meta: U2FsdGVkX18V7yJeT9vkTwozZry5Rx/q9eqkGfVWsOfhGknvcc8I9EkWsYcZPQc+Rq3rstZP5s5KzsqdCJSKly+qvpdwbUwX6GuU/5xXYibOMgOmF5v/FAkaY7b2GE9zXeoiFAehYjdCEf2YJfS5kM7WRuG7jLgR6Wecbaq0mTcNnXqb6hRyXPKaGfpnJ56HUOyutOyDBmAXlKv1DccF+iQY9jTewQre3Q8F+fadZPk3OC3SxbRKeHDvRaSRwoSorWBoBoa/KWvci+GfohQiREbE1ZcBwTqv6VSFspqmcPgAt7ltZbyOr1SXb7s4I/AfXaxUr1JK3kov77uF9gOUZOO5b7zbU5iYOV3p0/kLREcQ8Yw0CFQNRw398gTrJMFhKabQolrqRdf8qRagVYtXvecpZMOF+zv709E2pacAfVMlfSmrzT1wEKIEaiehxsR7MQ7x/kHdhpVD7JRpdlxYi/EgeAX6v6MSFVEOtB/QkMniy7XPJAzj/IbdvWchqCyPDjW10KOtKIoR+XkZ+QVTBYjK7zhyQzVbb0itOaj5VYoDwK65alpP2ulk20vtzLDVFY/UB8TUP9oap0NE73JuBok6qTiNgC5hqgYWr7kqTU+sqXHYMVGFTVhgeSPDE25XBOs/9fBd3VInczvzZ/hcVtuScNdJ2i/6pF9033f8DKBO+dA3T9pGQKiKYQrl8AoAoNB0eP6sZJkpe/kybPcHemYKZhQj9QrmP3Bxmw/WZOJShXwnoUIeGLhTd3UH0hTe6vFFvm5LzrDLImFqlUcTNe1unwwgVrZ6qs9dYGp6EQZRpA7da1604yv58HfFE8Y0Kokt3uuAw8WTQsJE1eyjNxToM/hiaytZvR3HfgGSQxZbq4KUOF9xE8Wm5/sVDOQwyWMaQdHEA3t9wVK0x1gAKQfu8sFxfganhoB+qDnNm6a6nHe49/Wze4MGvr/SUy6pPV+d51GYSkpCOZWEBXm CAwnCjY5 Ki2PmEHtIQe1mTF7Q/SHlU7p1NiFKkVTiN+77goHBVKGIWXpYqVppvDPEaH/9/7CL3kXPSfEdIGDVsivk5+HCrJ7CvuAN9JAjnlghuvJooHcIzS/eBAJD1/8FNTlSD4hfYgAiHENeKHv528NCbW+4AKt+NiQQqS3aGAerf9y/led5diINopceA0lol1do4CTlphHcGXgAgsW2emklGZ0ixLaowNxkJwyA8R+BSgYmNsm+ArExR1uI6AOUSIOeijVIxYF03rekRTI7Y49J3Ruk9cRCyCdjG3w+bxCT6KNXygx79K8wLBewrxbO/O6XP9m6E6i1eygZemdju4PSt7R64YtX5A== 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 | 175 +++++++++++++++++++++++++++++++++++++- 2 files changed, 175 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index 827922e1f1d1..19e0ad0bf98b 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 58b3f679ad83..fbfb755b252d 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -12,7 +12,9 @@ ops::DerefMut, ops::Index, ops::IndexMut, - ptr, slice, + ptr, + ptr::NonNull, + slice, slice::SliceIndex, }; @@ -578,3 +580,174 @@ 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 that moves out of a vector. +/// +/// This `struct` is created by the `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; + + /// Creates a consuming iterator, that is, one that moves each value out of + /// the vector (from start to end). The vector cannot be used after calling + /// this. + /// + /// # 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>(()) + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let (ptr, len, cap) = self.into_raw_parts(); + + IntoIter { + ptr, + buf: unsafe { NonNull::new_unchecked(ptr) }, + len, + cap, + _p: PhantomData::, + } + } +} From patchwork Tue Jul 23 18:10: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: 13740267 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 CE371C3DA63 for ; Tue, 23 Jul 2024 18:12:30 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 555DA6B00AC; Tue, 23 Jul 2024 14:12:30 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 505D26B00AB; Tue, 23 Jul 2024 14:12:30 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 358526B00AC; Tue, 23 Jul 2024 14:12:30 -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 E3F066B00A9 for ; Tue, 23 Jul 2024 14:12:29 -0400 (EDT) Received: from smtpin26.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 9FC341C0A1F for ; Tue, 23 Jul 2024 18:12:29 +0000 (UTC) X-FDA: 82371812418.26.A2D60A4 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf29.hostedemail.com (Postfix) with ESMTP id 4FEF7120005 for ; Tue, 23 Jul 2024 18:12:26 +0000 (UTC) Authentication-Results: imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=b6wl7t6V; spf=pass (imf29.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=1721758300; 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=lE/7nuqyVKQjk+p/Al1d7AqOwfZe5RxQ1Di6Mhjy0EY=; b=DP1RBS1tAfzcICZFOwJ9l+QSsaW21HUZvsM6fPw8poutqN/wSS0QigEHsny5SR8KDdqpHW MTbiT2fp7p+zmxIBFCHhjcE7i+ppkFvYAaU/HL2LUmNY0/xz7Rd+9Ovg7kKY29LxTv7ANZ c89kjS9J+Z054eWaIIJ1GDVr6sCRwRk= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758300; a=rsa-sha256; cv=none; b=qcPGkU6NwdGh5UGSteAojlHyawdjWGrswqr4vM+yaEcrXs2vwzisO/w0tD2C5tbWDrpXdz SBsnrJFfh73yy1S5IohndBqHNh8QqfjkLBK89xex6XIcjDzPnxyXTLIrEUSut4iyA41lis +PgeoaHx612Zu351iwgnc/ihcLU5Bqo= ARC-Authentication-Results: i=1; imf29.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=b6wl7t6V; spf=pass (imf29.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 5BDE4CE0E92; Tue, 23 Jul 2024 18:12:24 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 65FCAC4AF0E; Tue, 23 Jul 2024 18:12:18 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758343; bh=ycTccZRzwhnWmuZYl2yN5kvt/i9Cmr0VW9EfC/7UA54=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=b6wl7t6Vnx/yEyZvnuZI8xejX+EMDqYiC6oixtqi/wC6OK3zAe8IYO6hbfIV8Ma17 RLaPGrXo7rmTxgNQsHHTld9g3PEBCvQv37hOE6l4eGRycKf3zDA6Ds91DfzKciIRJa xrJISI+8CpDkcJvGGqsiv2f8NIOZoQaebEQGdV8TPKFui73DeJNhn/C0DdSKZD+W1N EWZuuocRtFqpv8tzGfD4nbDUCqzsDaPU0a8cpGlp1G6UQn08G1EvnJDiAkj/QNDeRa 4r+Y1p3whwd4s+LMBVGqd0ARazU1VyOY7jVc6P2Sel5BoUB+gK/Nn+ud9PeO7QF458 d5aCwheSsNJqw== 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, acurrid@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 v2 16/23] rust: alloc: implement `collect` for `IntoIter` Date: Tue, 23 Jul 2024 20:10:05 +0200 Message-ID: <20240723181024.21168-17-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Stat-Signature: f8sq3zr8aoci4z1ubxhow1r4awiy3ri3 X-Rspamd-Queue-Id: 4FEF7120005 X-Rspam-User: X-Rspamd-Server: rspam08 X-HE-Tag: 1721758346-788220 X-HE-Meta: U2FsdGVkX1/NAAI0nJNC4Y5DEmwZfQZeF/j4ZQxBdbn37lYC2wLTm5Wv48q80G25Vh0pOqd9nnk/Mjy0sCCx5A96RD/+sCa+K0Bvkev1oKhpPiGvX5ir3aH7CxS8M+OatX/PCql1KsZTSZ6XWZ9ErBtqwSoMINjVqUfaRqQlf0v6bqeoyZdm0XybjCcfX76VoccO4X2dqO0zBYweFus+h4HHxLS1GOGyn48bpAeiadArdW1mqkalCSPMLThOgZCIrmGhEF5cVicAUkE9gLJs0GOAjPGpMsBjg1HNhVD8JL9BqgjDE4ub3huHUdG3L+00qpc3UaoKt2P0gm4Hn4yOAFUO7bAg4m2n/BRAy9tpwSa6YonYhCctaZlqxLtXbV4zgqMMa+s+yJLy5Jz2DkQjJJaSgzXgWEHRKU/uRkturIlIeb4AMoEgOjN4+WSjTnfhpxJEijhkwVh0vjrHcvjMdLKXMTeEUEC5ot3OErY+G4XHN7T6zcxcEUrFFvZ+VerqBRMEcGtdbgD4OplYIzGHvFsRmnwqgmEjz884dmOqBh2dz2dbVcP9HaYjt7NC7OfpgYwIjKTx3c2qhevGSVxS3odzl2wqAIKPLh/AcSKbGOQ/dd2uTXBzp/NZofd8CFwQZdIzGG3O3AUv/u39DWosy1CxVCdQdrjLVchO948szPIWATye5p2vVgC6qmCBp7mf/pXSxQNOP8Dc6QtkMPY7H50os4JLJyrXjPG1rP719XExl5wmo8z5i3z+EhSwhD8qQVRlqdMHySmUDH7mYUkTdQ/pFOGsNKuvBl2Ik1hmyQvlmlFlA9dVaK7QmmNi0+SbjESf88s1NPqDDxBtkuPNuUk//olNwZhqgTbB/bEe22tiklyvunTTvrIn9vtudcH0XOvnh0Gl6KAjpNMQE9+OX4r9Nld6D0Dkl9y3f0yOXNhv7K81i9VtUdh5afogOTvE8CeUj6OYwyu6v/RsjHj GmSKALgy C80AxTXMj/31Jq8ZSrBjQudXL/x3aavohglE7xl57jufVm1geR8L7kapTYPALPcbjbOnDw1cwILv4qTUmsk+yQ2KIhOK2AG8ILi7O++EoDyqMkUgbtAB48HczYA8NgPrWF5LafYvmh6I1vnicSRxQHnnxXhRCZsCmjYtSWDCaAt8k8y6OSQ3SFMnh+4cfJ7BEDhpA6l79G1jNpuJIImR3NXVfaPqSTiAS3FccWjsGjHnDj8DL8Iz5ifq0cxbZUXkiAgsBjANmHvmdUylFtIa5k1lFZgbDgqJxbtTmQ5lzL01gb3Q4HEfD8v4AWoKhmXrcF+bJKgvPUh5lrkM4wbb0l0TQbw== 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. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 80 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index fbfb755b252d..5c317931e14c 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -2,7 +2,7 @@ //! Implementation of [`Vec`]. -use super::{AllocError, Allocator, Flags}; +use super::{flags::*, AllocError, Allocator, Flags}; use crate::types::Unique; use core::{ fmt, @@ -633,6 +633,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(); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn collect(self) -> 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, GFP_KERNEL) } { + // 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 Tue Jul 23 18:10: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: 13740268 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 DC315C3DA63 for ; Tue, 23 Jul 2024 18:12:35 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6B43B6B0085; Tue, 23 Jul 2024 14:12:35 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 6642B6B00AB; Tue, 23 Jul 2024 14:12:35 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 4DE226B00AD; Tue, 23 Jul 2024 14:12:35 -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 2C4986B0085 for ; Tue, 23 Jul 2024 14:12:35 -0400 (EDT) Received: from smtpin19.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay03.hostedemail.com (Postfix) with ESMTP id D885DA0305 for ; Tue, 23 Jul 2024 18:12:34 +0000 (UTC) X-FDA: 82371812628.19.36038B1 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf03.hostedemail.com (Postfix) with ESMTP id 931E420002 for ; Tue, 23 Jul 2024 18:12:32 +0000 (UTC) Authentication-Results: imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="RV28c3//"; spf=pass (imf03.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=1721758307; 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=oebRsF15AzQ24+fB1SiATNDCryLueJvFEQGm4nTfKlI=; b=swmHwVkvb2YuXVX6SU02u5BbG6/4zCcTLZl5DZ9kB5uYU6dtrrv/5CfvBk2SCmID3Q7dZy hP1BqAtruS8ESiedcQ82+xNLOkrulE2AO9CvvQd5weR5DBA/ifi9W+GG8qKcKmMhtdwiBF dbBTTeE0OwzPf6Fsr51TSmL3YJxCLX8= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758307; a=rsa-sha256; cv=none; b=pkr8kdSbNVLQsObiT7IVr+GVP1cLQbQvPI+4alzPp+w5adihdQVrL6bgAkUJF5JTgc/U9U /0KF3cLm+En95IUSlmm4WmNlThCqG8n1IlpjzEkEFqo+vWF0vBiQlakKpNTZLlStXWPiUd /MPuzugxUa1NwEUGjH1OmBBdf/FBaFg= ARC-Authentication-Results: i=1; imf03.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b="RV28c3//"; spf=pass (imf03.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 05A07CE0ED0; Tue, 23 Jul 2024 18:12:30 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 124D9C4AF0A; Tue, 23 Jul 2024 18:12:23 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758349; bh=ZR4Fo+HZj9co1hH1bISCrg/JiIevl/irl2SNGK/8Ii4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=RV28c3//uLcAxuxyQ4q2PzPazVc7pkV/uDYzo584ecF2wHHFrQu1m5aYbduVs8IXV 3a9VimG5b8laP5/9+vN/6hKebRM5UOo85EsqOvFtKaKCWD6oSv78iUsKjGz0tvxyOz 7jRFR5awXL0QQTpgcB7UbgMw4rjF9FmpijHFYBCFSEKqVGenxjo2296lW9rSQxf+bm n/hwej7dKn+JCDtCXjKInZEjFJeal1gEigVrHxw86rZP18+xeMk8EYmH9T/EzdiQuS 4ErY6STPAia77ZCcEkMs2vB764hDJWzWGznqPy4VgOjoLgE2tJtsAMPqJU2XtMZ7Bd zmaR24IdxV2sg== 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, acurrid@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 v2 17/23] rust: treewide: switch to the kernel `Vec` type Date: Tue, 23 Jul 2024 20:10:06 +0200 Message-ID: <20240723181024.21168-18-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 931E420002 X-Stat-Signature: tj7w38hd3rpzjyhqyppboc7xaqs78c5w X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1721758352-761274 X-HE-Meta: U2FsdGVkX1/dG3QiVU/kBn3KjKDX5us6CuCqEXJTlADkkua0ac5XsHjiHxSLjTMtwVe0gCniYcB5gTA++xmk6kn9nKruIWgt7n2ijiKOHRvTR6zFP2gsjOUmpVNYjudeKmTX33VyU2XBfsomfMiQFGGmMHz9b/HRFuysWkiLQFRxNdu6Ggaa6Q9rsHT+Dyc/LPmB/WBXys1RIj4W60miB+hkMNGVdm6UYZOIFV6j+fheligrpU9HyDjJ9oEvxGvX+XkMU+74+uSN5qJmpXSvURMHYZvWevAwlKQiRHsMaIlvRTZAi7mARz4MDKFr8egZoWVdC/Anv7/wCjZCPn3mU1nv67XS4Zf1lJdN0Zd9QmlBWq4B9DExMOCsF7mWFatuHIslOehggRNf5WGg4t9I4CFYFRs3V1e8iHmQX8ANC2p21i/1b+ISn8CvD8DkcBQb22ktJtck+aaHguRbNlnq62gTRbSx1Rh80twQgLi8j4ecvV4DuAr9wq99W98xePXSi1idJ3KVuimAQnV8IQB4zafre2ifE+B+ozkQ4dMUSXmV+odlx+Kczc/kENj42CPieZfLovd2tkUqnjMyUJ3/keoCdIbX8StHgKY3Z5dgdUDKHYE49jYEdNCB3MLkdEZEAHNA87c4Y+rFh4Nf4bj9YWYqYULfrzTkcFbb8azKphV/74Y6mdKU6WaTZjz8R1bFoUNAvrn0/GRvtymto5SjPguo21vZ+5RlQLKnAGNW/BAREAWfa0nRRwGUnKCaRhY53fxZIEKU4oW6Z9bP11NM0zDWfp9bGGNjzbUJPrY5Lu8pFsdrxDr+SxD5qsnacCTb2iz2ntoN/OwCKyfq5ucf60gJXhNTm1bPsMWpIgwzx0MzqotK9OqUz99a9yC3hTkzlqlD4r+tStQGQcCEoijtIAnMdrBks3QE0YCBR2mIXJ4WAgas+6l+2ire8MONTuGe07z//9dMWGRw5/6I8ba BTycf7LM gpvH3DlhkLOTafFa9LwQNybxkG3OtUR1xMnkdMMMZShBYRwCrtxvOuZTMAmRmyRZVNfhk8soTN39q9KBxcvQ17VZ8PLW0fOiMhOndYu+4ZGWr0ceQ4agm3SsNhgXMT3Fyw/X8ggLMzYAkySr7nS/URadoGl9Fl0ZctQT7mYqaA9CJSdKwZ8vqs6DOsHpSILVFLRhhpqHKED2Ir70dXnmiUAKj0DyW21yIzmYR02sn88FPeLy97fcCRit6BaduRkgAfm/teIFlMgaRhia+Tq9mWw6F9heHckheTHeCUK5V8Al/mpU0ne+YaIyGGg== 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. Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 12 +++++------- rust/kernel/sync/locked_by.rs | 2 +- rust/kernel/types.rs | 2 +- samples/rust/rust_minimal.rs | 4 ++-- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index bb8d4f41475b..0b6ffbade521 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)?; + KVec::extend_from_slice(&mut buf, 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 ee0063a20d89..05521403ed2c 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -158,7 +158,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/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 Tue Jul 23 18:10: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: 13740269 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 DBA62C3DA63 for ; Tue, 23 Jul 2024 18:12:38 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 6B5926B00AE; Tue, 23 Jul 2024 14:12:38 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 63DC66B00AF; Tue, 23 Jul 2024 14:12:38 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 4B86B6B00B0; Tue, 23 Jul 2024 14:12:38 -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 2002F6B00AE for ; Tue, 23 Jul 2024 14:12:38 -0400 (EDT) Received: from smtpin12.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id C5DFB14033D for ; Tue, 23 Jul 2024 18:12:37 +0000 (UTC) X-FDA: 82371812754.12.954500A Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf09.hostedemail.com (Postfix) with ESMTP id F05BE14002D for ; Tue, 23 Jul 2024 18:12:35 +0000 (UTC) Authentication-Results: imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=VnjfxRKx; spf=pass (imf09.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1721758333; 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=Kdq9VDrvBjrGZtyTOC22gYFaM/r60ZEwBEChzA1M6PY=; b=zZjjMc3KJFcjiFr7mUi0bEhyMHmt/dZG24nIxC8Mn8mro55Od/meIXx//OdFZroiwnK6mj qWKYgznRjFENRF6eH2xVSXKbsRaCPCiv+x7m9V3gaNIIW3xB4QyJtey63oDNxRIqeKYlSO vttirGYJtwBZDkRTxgd0eeyMGA2nL8o= ARC-Authentication-Results: i=1; imf09.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=VnjfxRKx; spf=pass (imf09.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=none) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758333; a=rsa-sha256; cv=none; b=vhbVwxmDvOxHlb2K6b+CzkvRlTzVwMCPhT4bq2L6M1mhDvEVNSWmTuQRINfXtSgC3TVsvl AvYYMhV2G8UPAcK5Bxy6nTLTiQBDCZikxXrQC+vsyZxNQ0WFiBMser4b1kwLvzjpFDuFbV PkgCKSjCEpM/b2vm6i1YhukZCGBXsOU= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 2D81E60DEF; Tue, 23 Jul 2024 18:12:35 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id AF969C4AF0B; Tue, 23 Jul 2024 18:12:29 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758354; bh=v+FEyM3f1W9pgO4n2QEpRohKmGGAf1lyhUx0wNLCTZ8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=VnjfxRKxJbjIo7fDXiWg8utw/tN1yQVjbRBRa7Gnkz5fHAQLnzcQup0oPSK2MVhXG OsH7P2CHWUArVtYdY6TCQ41C1E/BqzweQZmFJXPBzPDMzP6/61s4if+nhHMGxK4387 A7YnlMmPTi8w9gCpdE38+uwnWho7eTYj+SR43XtcbTqYujaBI2B09piLyuS3ZzJyN7 STTdiHR5y01vzyyDU1jAiHzhmZyQdLjT5MIxxg0Xsqv/n7mhoQdAZBE/XWo0HpVJKB LzfucShQemHBvNAvy+rXO9pGQmD6BJFIXV03h1hdB7+4SIdb5+O6vDwmj/P513zPNP 0um2jlDS9sxMg== 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, acurrid@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 v2 18/23] rust: alloc: remove `VecExt` extension Date: Tue, 23 Jul 2024 20:10:07 +0200 Message-ID: <20240723181024.21168-19-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: F05BE14002D X-Stat-Signature: i3hjd83aijsw95xrwko4cf9r5zndt816 X-HE-Tag: 1721758355-965324 X-HE-Meta: U2FsdGVkX1+UWSvxCdaW5TV3hFDxfglrca1PlJofEq/3Z9nv/4U6Bk+zJ8jDzu7CUnH0cCMsbNdwdQS5fEiDJEYOjMvZEAXRh7oucYH6emXQXS/UUPBDdhh/vRUat6YrKgTSSrblx0FmPQSBAz+zLqQpY6ZzEKn76Mv/K20yzhZwdykkr37OaGPHsMhd2KPIGQx2l33RIltRUNgi7GzhKKPfDPeOcOhPLGAR3BZjxyKe2SEbKrVRCumt+AN2wUV/V41IejGxUdFqTD6eDF3ZQqenoEn5NDoESkzSF/M+GoJm9ZZMJNV1BFqUj1/sVUleGFOFbYGx3/FV3/IoQkt+yx1GfJzVVNKoYp7vwQb+RmLOu7b6zDGCr7r/hvdKw7UfUKiz+e1kY1RaYpBtoynkEDpDOf0CHdvX1ePvzF3HyetYQvx4qCMFLXdM66LP4D8FIob3uJnqGJfEd281qTPOz3x9pWL9vulzODz8gX12dHXUuYGDpkw9CeRCNGD60IPqXaSPtC/PvTCNSSk/I+sFCjPD3lH4AUwwzK6h9ED0tre+VCSaU+Yj0caWJp+0iBulzN2eMIslk4NyDsfVq0Qyy4SylIBhMS9KC1tdJiPMzU0VHvTFlxTVFlflIDqYf5SYmMkzX/kVtpcAy54wBWlJeUcnsVkZWi33W3Y0BmCalM2qG5fTnM5uf5BxcG/VVBgV//Vftm9CKeYerMTawnkKyQM8bOTace4j0c1Waj1fpShMqSYlPZVRPlucnFxP54B3dyR1BkU0rAxMtcO/zzhIfXHIh9meUiyh+jlxs5ZDZob3NLEjWY6/Huha7Yzz+t1P1/B3vsNFnmrhNZsUcTdFpARPIxKVfe8JFFXDiCGpKD7gYA147/HQFbHsJgnyEKCLPsuc56LSiS2qUioXnlCEh7d1RTJuzOxQdVv6XpC29phzML2ysgo36kcAMHKMKAFV1qaY9MQlwnr/E0nnZWs 23ELumSp ktVHpSv3rfS4fi3VMxUHOaUGhxpzFDoxXH+2MStACV7qmPPs+Stj4HLh1SGlGELqtgICv+6M4PHzSbmG0jfWIOkntxdAlXHm5HHzckrT5Y40IYMGeSi3ooYHOgWdavJrSCc4334m4DGDzg+a7X0+6khzTBpGaz6oocXqkzgENkm7MXKQ5FbIpi3ayItxqawe7OUplr5jOzpgLYhnh58rXztP5DV5RPHTJp/23uMhxetOPTq3GrrcLNNihbYP6mHRrEUpMiALwrSeR/UvhIzTFUoOmbjKmsm3ogminexTw+gjYMHKBP7Fb2m7EhA== 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. 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 19e0ad0bf98b..62838738f409 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 Tue Jul 23 18:10: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: 13740270 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 7124CC3DA63 for ; Tue, 23 Jul 2024 18:12:44 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id ECAA36B00AF; Tue, 23 Jul 2024 14:12:43 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id E7A816B00B1; Tue, 23 Jul 2024 14:12:43 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id CF54F6B00B2; Tue, 23 Jul 2024 14:12:43 -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 AF5B16B00AF for ; Tue, 23 Jul 2024 14:12:43 -0400 (EDT) Received: from smtpin21.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 6A22940337 for ; Tue, 23 Jul 2024 18:12:43 +0000 (UTC) X-FDA: 82371813006.21.F496866 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf17.hostedemail.com (Postfix) with ESMTP id B01FC40030 for ; Tue, 23 Jul 2024 18:12:41 +0000 (UTC) Authentication-Results: imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=dF0TMqoc; spf=pass (imf17.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=1721758338; 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=V3RV8SQZBp3cdXNz8SMSCfTp6xtcwDI9ECD1In1etJo=; b=8DJ87u5+REG7CV18Ag7rrVDa5iikcvyVnNmAQHJMvJCdv/9zB49srGpw9qxrh5PR04AiQg kn8BJrok0zWXx88ryHWyuRe+n0clPZ6nVlkGWOaZGIQ+pcTdgkiKC8GQb3dhCTXEiKcZWa s9nmAiJVP4m8xTjg1qYRng7E41GuF7w= ARC-Authentication-Results: i=1; imf17.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=dF0TMqoc; spf=pass (imf17.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=1721758338; a=rsa-sha256; cv=none; b=6fgE33dyzJPyBRGIM+Aelw0d+7dsbWik2wrbZ9LF8o9cBhqRCaP5U58LdId14Zhtudpuuy fT/NXOPeidtfdfIN58kr4t41GLFv2upM7cnzJOhl3RpKaBz1kDdhvBPxLbpgBcHVK+Dw/2 rXgUD1JLlEPeUC/pcLk9Eq6ScrfHV58= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id CD82260E00; Tue, 23 Jul 2024 18:12:40 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 57B0AC4AF09; Tue, 23 Jul 2024 18:12:35 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758360; bh=x0JvvRfi87BBCBI94b39MtnQOfc5sS9njBcl08nLwWQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=dF0TMqocS5E0+WZ7U2tM4lCRj0VbkcHUh59kSwlafs/iP9FjkjwpShpZM0QwzVErE wr9urpHSVBr6lLNiqiL2kb+LUULbHpammoO8zdEmAkI2EesoB13TN0O+lOdaZIltvk KJ+wmaDX91QSC7JkZdJfG0MpyOCY01MofbIG5bu0mMKN7UY/2jghk5Nl4RtORfL4p0 sYyIl54YuE2r13obYVbDCfxyfLSB0xtNbK8bItOcY2BglI5tbcYd8Au8ax6Zg2Nt9K 2HS0o1kAJuKwdrf4nVZ9vviO/dhPbGQjYYDxMzpgfHytCXlSjj6+YPqD6foRlzNRhv zhkVkTY6S7ilw== 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, acurrid@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 v2 19/23] rust: alloc: add `Vec` to prelude Date: Tue, 23 Jul 2024 20:10:08 +0200 Message-ID: <20240723181024.21168-20-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: B01FC40030 X-Stat-Signature: yox5iny5b7ja5qrat5emftqh9sop9ueb X-HE-Tag: 1721758361-211291 X-HE-Meta: U2FsdGVkX183rVPXM/fOBSLEkcP1fcgTlQamIWaPolRAuKIkDBEfYUpSqmWEbve99sSMnu6EAwf18ufp/u253C2Du7FX8UMXQf6W+Aef3sWXcybJlG4N03c4JZW6eQCIwgKKB/UUUvOD53WnR6CpFJSD/Nb+4A2ff5l+xA+0KUS6iUNNnS099vruW3JjCvNpBQlgbwCKdkoE+WBlcAFiKpI57mjfRdbV82AECZo6F8aq3cKS8yWn2m5wWUnfSSJZxBzCbeuj7a08ej70EKvKqF35Xd6YcbbGmJGCYLt/DA+jUtvt0rgwBRGWvy9gHQE/luth0G2EM+O0HHQZF5zTjFcgAgp63x3AyS/biGVRAf3ZOxXBTO4bHdr9BhQ9as+vqaauzKaa5179CDaJzw2eAbHRdhbld8ir0GpyRDO6KxLaZKgIpK8UKzygblTTKS4qKV6kTyb/tDzSN1H9dmzTE0z+JekkZ5Ibz5wrVjWFpMPE7+6ttdwFRvB+FDSvM8OoPUo1j8q4IP8YTnEx6ZQUNx4EVi9o89Q3Ui0FZjebDalsvOcoEhSCoE3kQQWKoS7aMqvgcSNHNQwM1cQ6Z0kW8gNobcNfvXOsz96N7PIQRkjh7Ovg/SFK9luxfmq9kE7Wn5oCVtQVvlz8kXuixnCqQtWOqM4Rr7uvVuJ+HqHLstZjGaN727wSZq6UvXNv5Dvv8cgyvrpXD+FNEVvT0/NiPezYEX1kFCXwV2zrmW9HWSnNJBLM0bou/yqUGG5Wv4+7ErHZRuXYopycIt3iG7ZyDuh7NZ/cXuMcvf0jxCFBxtZ2Ya4jF8/8j6WQH6fCMuGkrFmQ+VrMKX1CUGlOUE+mjXstrk5rlTXR8Q89zz4yjYGmVzZpJoTmIjXRBppxz0eBEC1xg/BtzoRkXnc7tFi0HdL9+y9/GlmGzJ44BWw4IMvjBB2HDUmi0+9pcfEM1PUoiav/XN2LqWi+WIiSn75 +hOddY3l MtG//M5YmkMMwWSqc9AV73L08BM00EA70ABZkrbpWgoQzA8Nz2nzeAzgZLsaUgTp7BPVi2cUDgS9tkseOSoq57+faQJZe1yNLTejqzD6KkcTbh61WlIWy9q8fY7YT4E23QVRvaFZj5dWPxE+0ZPFsoUKmTfoPP1osnOKaN4fEksHNdZ3MVqAggojqUUw0sURYE6Or2m9oICb+VIIb818KMjru/4RAtph+oPNE7w1A8LU1OzoF7AIir3Hk/xtHAd2FR+CSjVujKo3JiOZDmd3NJDc3ZcrWT9TEcIHZGoDoGOYsqmuxN0C8xn/obw== 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. 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 Tue Jul 23 18:10: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: 13740271 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 DA818C3DA49 for ; Tue, 23 Jul 2024 18:12:49 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 667EE6B00B1; Tue, 23 Jul 2024 14:12:49 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 616E76B00B3; Tue, 23 Jul 2024 14:12:49 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 4B7876B00B4; Tue, 23 Jul 2024 14:12:49 -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 2A2DA6B00B1 for ; Tue, 23 Jul 2024 14:12:49 -0400 (EDT) Received: from smtpin28.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay08.hostedemail.com (Postfix) with ESMTP id D9D2914033E for ; Tue, 23 Jul 2024 18:12:48 +0000 (UTC) X-FDA: 82371813216.28.15A09D1 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf16.hostedemail.com (Postfix) with ESMTP id 4471D18001A for ; Tue, 23 Jul 2024 18:12:47 +0000 (UTC) Authentication-Results: imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QrqjLlOl; spf=pass (imf16.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=1721758305; 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=yLl6nSqaJL4J1JLoizhVMMWA8rjQy+MNayRc9dzj7U0=; b=g4TkbOVc1bYyqGtgrMtsLzWjR0wQSBoQOojTLO9M0tdvy6+PGfgpS2F0PTIyJCKJH3Uczp pZY5t+5t1xyhf1Q7NEe3VDWik2deyBsvl2rhCBSJJ1qcZBhWVLgpHpqn7Q61hWYjea7nRb a42Xr/0mm+slyyr6jhLBzOwEoPeFr8c= ARC-Authentication-Results: i=1; imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=QrqjLlOl; spf=pass (imf16.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=1721758305; a=rsa-sha256; cv=none; b=1eF9sgzuMeq7h/lkAJFQRVUquD9hTlgx9E8YJssI4f4ZYd2/Fh8aM7UA4pP2KYQ2MhLWxN xRvBFX9HNKSCHOYpYItEQ42EjoTfjGCpPJPz0Rhud9bSA8ASOfEA1MEW0plZ/pX8LUBkyB JiqRoKpPTJErl1xxFOitO//0IF3/54g= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 7639360DC6; Tue, 23 Jul 2024 18:12:46 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 01C23C4AF0F; Tue, 23 Jul 2024 18:12:40 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758366; bh=hs6yx2vsssnsC1cMGPjQ8GCbMEe+TcUfgVzllRdmHcQ=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=QrqjLlOlUH7v2hvkeiyaOJgc8Oh7GHD2if+LolauVZpdSjXJUzYAuQSO2G/BzwM5a AiiIxDaMskwTxGJy7m1wRE3mRn+MgcsrMoFfCM2jX0p1VeXsMAdcuVKwrBcxbtAVap N8yVJHcsAAoTB1CKwwVVjKF9duYwYdIOfsGllMFjDQI0TlX/+Nvm54Os3pUOrmTdvp 8QwWTfKrIcqQDSHMODvSnN7m7+O4chstkokwWJnPrzXHLHbSa4PcpOpxKw9Spm5ecv SK/gnFUPteAQ6WvAFwlrrE4SkuWjarVlw4ifOSDMcOzGALc0arYSU0kyzasYjAL0MR aSvxiwry37BOQ== 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, acurrid@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 v2 20/23] rust: alloc: remove `GlobalAlloc` and `krealloc_aligned` Date: Tue, 23 Jul 2024 20:10:09 +0200 Message-ID: <20240723181024.21168-21-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam06 X-Rspamd-Queue-Id: 4471D18001A X-Stat-Signature: 66uotomy66q3bwuhxxyw3pou3uxr4qsb X-Rspam-User: X-HE-Tag: 1721758367-330775 X-HE-Meta: U2FsdGVkX1+ClTJ1F72NYQXRWsO1qSeKEQDCYK5ZZ79RZcSCcwHcKjJFX43g99uJ+yFm1Njt8aGrMf4HMDpajUq5wmYvwbYap1S55bqn832ZpFO2T3wvuXMV5Z6RtAjr/hbFLs1thSHs8zoMfOWYe9ovhIlNGhKfsBKXIsYcM/o9D4dybng4Mdll3VCq5n1rSAxJLU1tjzbuMTYL7XMklUVyPUiKU31noqAtM1zCnsKCI0c/O8/BLXUjjUoGqPSO2oHBf7A7smLD5s4ozBoDMqTETq5mR5hTP9j28qMEcS8wzlVi7hbx7v3HxAzfFHlKB1IwfTEGtdD62rvCfWLV2lY4uORZIZ1D6GfpyDngSaXucOEc10qbzLzl8XbEi7F+GAGwM7voO3mX7Bsax7IYwdva7pY0is4/ksLwL1jGMl2XCT7Ejq2LlZ+2c7s+F/6XKzuJuEzit0cihFZwRZRgpmBaSzbqiO+x/hkdivwVTuBBVnlj8y8ic2ywIGpdhYK+AAaOsnb0I5OWGSZqQum00+Er+Nf8EnrhYdll9owCpE5jjRjudFMpnO7+M0moep+tybsHyKMceS8xxk9qxQwQnjKbWE550I+D5iDZWhW16sY9rKOXeWtcfTnt8+iw7rtCOviNBk0fMSCN94g7xpgnZin05INbKONFAk3fMAAd9J6ToVVPmtPyWLirycJBTAZIOEKyE0ueeNfUzytIBd9mj7D2SKSGzDsqknXERGj59F1CXPzJl++QdYadKUySQhmmAodWAevqK5uJao69z6yFObpmkeBpXkJutZljb0idUiOToAtPYNAQSbiNwvkewSEV7aBizo90ScZVAv7j7snYdJ7VX4lYES2rktM+HQQxEVbeS/iKYUffvkZFKzN2Bn5fCWEwZ8pMJzllFAthf/1ufBTnBMpu6ExHQAr8ypaqHJ34O34IzXvfDLT2ATY7wrQA0H+HaaUpLTsBdIjn+Kb hdt87+8D t2/l1qvFK3hD0mHzKot1IH34bE6oCkj+SbUZlxZWIdnQ/jF+QR3iXbzyv6OHCZkjlnKL3nl9oVCCFsOBgVLr3ZBujf3oOCO8ORb4A+R0PbofEbeaZk2B2pUJXU6UFaYPY+6O/cmFUkivRAahGKQ7GsxGe3y0orc8GBNrp31MdvxaVIkmusNd4S+1gRMiJMpGoo7qQpiwzfCzbrp3fQyK51Vj5wnsGXbvTQayKt/YrKP44p/WO71XMv0YSi2dqZEs4vVdlW05oLg+kacZbwH0A13NdWrgpIXM9c6gDluAcuESeWCmwN9HpZFadDIDrMDQciEXrv8p8FrwvMctEvL+KA6Gi6f1AxoBmtqslnY+8h9WooJDGIcFnJElNhcDS1coslLI8 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 all the `Allocator`s and the kernel `Box` and `Vec` implementations in place, remove `GlobalAlloc` and `krealloc_aligned`. Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/allocator.rs | 63 ++-------------------------------- 1 file changed, 2 insertions(+), 61 deletions(-) diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 1e53f149db96..fbee89ac3be4 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; @@ -39,27 +39,6 @@ fn aligned_size(new_layout: Layout) -> usize { layout.size() } -/// Calls `krealloc` with a proper size to alloc a new object. -/// -/// # 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 { - // 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, - aligned_size(new_layout), - flags.0, - ) as *mut u8 - } -} - struct ReallocFunc( // INVARIANT: One of the following `krealloc`, `vrealloc`, `kvrealloc`. unsafe extern "C" fn(*const core::ffi::c_void, usize, u32) -> *mut core::ffi::c_void, @@ -121,41 +100,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>, @@ -184,9 +128,6 @@ unsafe fn realloc( } } -#[global_allocator] -static ALLOCATOR: Kmalloc = Kmalloc; - // See . #[no_mangle] static __rust_no_alloc_shim_is_unstable: u8 = 0; From patchwork Tue Jul 23 18:10: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: 13740272 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 1C989C3DA63 for ; Tue, 23 Jul 2024 18:12:56 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id A5E4D6B00B3; Tue, 23 Jul 2024 14:12:55 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id A11826B00B5; Tue, 23 Jul 2024 14:12:55 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8B2946B00B6; Tue, 23 Jul 2024 14:12:55 -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 4BA906B00B3 for ; Tue, 23 Jul 2024 14:12:55 -0400 (EDT) Received: from smtpin16.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id EF99DA201D for ; Tue, 23 Jul 2024 18:12:54 +0000 (UTC) X-FDA: 82371813468.16.57E65D7 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf21.hostedemail.com (Postfix) with ESMTP id 0CA051C002B for ; Tue, 23 Jul 2024 18:12:52 +0000 (UTC) Authentication-Results: imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hdTrNimT; spf=pass (imf21.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=1721758350; 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=JiNiq3w86fsb6pYyZWDbsYIgV8yRol5xnlA84a758XE=; b=8Oo7Za3H1lBD1vTH/6lvXrZwHf4x1easMR3T123Tm3Y/Q+0t7jejmk18n74eOkItw2CMuK UmzPpB6f2VqC2tPeMOzTuqSsbhaQpuEDMmuCM15DClRnYW1MPPyM4j8o012Nutdpss4xzn 7b25ZiZN0MuW0ggn9gYuQywATLxfYqs= ARC-Authentication-Results: i=1; imf21.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=hdTrNimT; spf=pass (imf21.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=1721758350; a=rsa-sha256; cv=none; b=uil9r9PIor+sJDCEu3ilwfuSKuVswkxSJxUCKkcueH1nTcw0eGM3yo7C3OS5Tsfh345KDc Q4/5ZjCf5VY1cbygiu0DMQ1EldDTQCCuN5OFMvedHBT75VFvmBpTxF3OoTY3DkTGrGvteO /V7tLm9aOpbR+r6HFB9Kw+EisVigq7U= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id 2446960E71; Tue, 23 Jul 2024 18:12:52 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 9BDDAC4AF09; Tue, 23 Jul 2024 18:12:46 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758371; bh=ifLa6ui520OxD4tx6GpOL1mZtUOCjuqJJxFCxi3qo5o=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=hdTrNimTX0/gfTHgSGZoFmyF1daiFhFp3RcVFXy3Z1FWilSHjnN5DFRMjhFSO6rbd qgu6sUkW92cLIqvrtJFtPWeF1TILjkgG42fMbLGKsBZSPcbXQBiM/t0QcJamXj5lY5 wR8QhjcGGIUaBUSxDPcWTaXp8/EQ5aYE/eIIeBx6RcX4JNYqQwGeoz3pgtjD975Z3y L5fvLLI7EeXF1LtxDngf/2iwXpEeiKjBWktrSadsuMQFLf3XU6GzkSABFzV92OhF0o 3qfWeDp9ONMjDc7tGt3Vmlc9VT509onYY9nqkJCQ11DguV42LBzkkPySGyQAeaIL+W OP4Xqx2ia0+sQ== 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, acurrid@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 v2 21/23] rust: error: use `core::alloc::LayoutError` Date: Tue, 23 Jul 2024 20:10:10 +0200 Message-ID: <20240723181024.21168-22-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 0CA051C002B X-Stat-Signature: 5s34hhkkeuryk4qjtdrou1z8o6hwt4p1 X-HE-Tag: 1721758372-41293 X-HE-Meta: U2FsdGVkX1+h9mUGv4m4E0k7l3hEboGijzY/xILvsLQoh/rZwBjSxI4bGuAWNdLJTYQZh4PZBPm55nZ5BZzKcwVV3kVMMXBPfJfpMh8Gsp+TCBARZZTOXIMf8eHj4DeJGRHjT4+ClNarzsHEcjWa1jvgq9PkPfnX2KsPDEJ1HYbMrxCQdYY2AyYVfp1vxPqOfjVBJgHTOl3tqO5Enf5wwdm5PknBqGo1SJvaG+UTqrxildJqrS6dd+UgMuQrE++9YjB70NQlZ6HCRLw5skLPZJbqD8E9WOEU/nZrRYGflGgWqolUKfjL2NqLNEwPe+jLcR7XL1E0eXGABXndBj1CMDywuRH3bht2Xgi8ODiTkA4iI7i8E/6iX7+VKiYc6l4zksdYdbb6mYuZlonAKjcBD0YXVmjQ+2HyUN00b0Mx/pQMAjOH7M0l2wzS3ybqTQB6G8MAuG4Wty+I+cnptHwQF9Hgcsrwd0P2CdvDvgJXAImNEF6YDmu+jXSY2oo9Qwsn99bFiFoZnyljkNbRCTb/0FvIvgNaMaNspa1Iv+p/ku0B0UmhsZtb4nXU8yzxQ/+v7N+6qmO0MzNN7lBNWtqgOPfDJQDkKM2P9HSuJgfn2S90X0gpYXh1dbZvvGrfYni5DhG0ZMEJqSEacrTaEHU+K6IVYEKbkxPcB4RfVFFX6IgeOpnfUcRxT+iywGNQUTex4kxxVRwuh1DwXqwemIapMHrCJ3U/O0cWAKZJa1v1UrfTCrzqjB8Hv3dsyAcZKQsOV1pzuQSC/vUiKMa+QGqaqWeejWQ8mYbV0C0kHSimXGsqu0gSreJ6A2z6x0o/BsOkt7KZzOgtsMfCzF/X+MOTn9d0I4nGhrZ6GP6mKU11oYBWSxZsGysW4q8BZA6dEEy/4i4hzepbjp7T8DveNU0APY6JefioSeNCRAa5nHomt6AplxhY44f8bw+Jz5sPdJ2cuPI01I1TV+9fOCM3vLC MdMvvEzt nuZtaYYdFAPzin/xsgk+e/ViZYKGDsiuzHXdvODnGMD6ppSU+HA1oHn97mEGIfAMbfONK50B/UmfMl16RwX2rnl6AuhbQiAjFUMeVuSFIsCix7/yLlDt7CcByalww6DvhV3wQ1CPh4FurJI9O/QUAlSBqepDjLegpz47gQx7TeqpcgU4plj52lFQ8GBQ1zq8XZ9H+VTmSbMpiZUiDGbS6KD+GTWHOzu0BIzgN/8Doqfp3PgpGs/z+6eCvWn3U/c5MwraAtaJTHJS1hlfskY1WwdJIL0TVav/lCHNgZTHq/errnCwslBQDjbMBiQ== 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. 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 Tue Jul 23 18:10: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: 13740273 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 7F75CC3DA7F for ; Tue, 23 Jul 2024 18:13:01 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 0C12F6B00B5; Tue, 23 Jul 2024 14:13:01 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 071E86B00B7; Tue, 23 Jul 2024 14:13:01 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E53EE6B00B8; Tue, 23 Jul 2024 14:13:00 -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 C00A46B00B5 for ; Tue, 23 Jul 2024 14:13:00 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 42B32A1FCC for ; Tue, 23 Jul 2024 18:13:00 +0000 (UTC) X-FDA: 82371813720.23.FBE8C48 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf16.hostedemail.com (Postfix) with ESMTP id 9905E180002 for ; Tue, 23 Jul 2024 18:12:58 +0000 (UTC) Authentication-Results: imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=J0RXP0db; spf=pass (imf16.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=1721758355; 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=kcX4qbBcCzJj1u3+EdQ+OskijfGpr/4rSqwVh4l9oXk=; b=Gcql0qNE8PBMOY/TPflQjxE9dL1B6Ougg8fpAueaYpth5JRQjZMJ0/o8hIfRYKoIeeqnkS jmEIbLf8FdWS32l7p+TqTeTsybpMNoJ8rhm2562o+CUBOGwv909j17XPgHsjPhMibELlPM Yq6S/+f14/hcUksSr17JQPj8ZK/LbG0= ARC-Authentication-Results: i=1; imf16.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=J0RXP0db; spf=pass (imf16.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=1721758355; a=rsa-sha256; cv=none; b=ElwBrP68VSRm4eBG/Xw3W+T6H9iSAYDBXE0I2TvMh5ONOJyczVHI+FGAhNOf7S//hfHLp3 3RX9Q0H6aV6PuTMwTBveexKV8S0Aqq2WAVdPWORIJlEREH/ebjDJgt7x4cjQpsHGLwMvLs jt/79CJjyk9KjHEH9D6o94dAazk0kgM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id C43FF60DEF; Tue, 23 Jul 2024 18:12:57 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 4AFC6C4AF0B; Tue, 23 Jul 2024 18:12:52 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758377; bh=T1EttxerGLScRoG6GW0jYhIkm3ad2nbCx6FWpPy4fh4=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=J0RXP0dbPwGzR+rORI/s2uRU5IGUpMivgIb5y0Am/yl8eA32+7NG9CPLBs6JsISP+ Pv723LUGJdQxGRf9xDdWrzBujCnAShAT1yjsnxaA/yjBOI1l3D4LvZd4l51gvJbDQl 3R6fdXefl3BpmHurcim61dOTdk3cbHf/k5zWSFbMbBLELXXTDnADzrxvTC/3QuqK/L dhF0fWDxWnhntIsInBNPgUYtHsm4/UqrNMyBoDbuAot0v/lPxBeGrU9koUaTZ2Ru67 wMxeC7muSNLYaueEb4/YrzDLpcjhh7Cr2wOC1EH9d52fqOXT9gF+kjU/G6y2f55w3Z szHse+m56vEbg== 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, acurrid@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 v2 22/23] rust: str: test: replace `alloc::format` Date: Tue, 23 Jul 2024 20:10:11 +0200 Message-ID: <20240723181024.21168-23-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam03 X-Rspam-User: X-Rspamd-Queue-Id: 9905E180002 X-Stat-Signature: 8h77u7qi6t89cbf7b6m5kjuoxxoq87f5 X-HE-Tag: 1721758378-311441 X-HE-Meta: U2FsdGVkX1/CeS9mhJw/7B61UhXU7utdk5cDFnH1uioT32A/51a9xFzz090vaL3lEDM7gCxZs/NdgffoF1DgwplXQL9AHgC+CKX5vxwTwK2UdShOx/H0dwocZynqkJ2Zklth5ao3uQbLzCyHDoHLVBYl5yM/72jDWFAjwH/MFO6sE9EvzfWZLl3whGOC1WLcI7PYuW2CWucryBs1o2/Cqek985DeBVqIA5maU/euTqB4p9amh9HKcpj+aO6n0prdruYIIUJDxgw6wujE5AbFsdeHH4otU0D11nGPIxT2VoZ81dZbRMQC3xpuZbvSi7j36jSIddK0FqemsamUzKA28AitZ4mdBLG77Fi/UFyyZP6JwRr1GI42kWF6COA/SdEh8rV/7DS6i9Y8v2hu2QR885XHJq6QaKO9/3fZSwJi6A/XH2P/mEoK1tzRIwRLj6N7mtvb9FlrVVwZ8mYf1vH+GMQgZwDeLyT55qloE2FULN1TaF8vh2gEVgJogF/I/W4lDdkq+VH10ExaxyWLyAM4mv80XUAcPHt8A505qP0yKKLbbANvF3hd+IsjU8jTJZvSkgEoJGZoEGi1ZYOkjWChNoU4+Z9WkTBBSCpiRaOY9kxvKDtzn36N2yX6fjICmg2XdNTjt5k6rjDebuT+xilW5BsSR4YApho7Mt8G+7EXGS7VIj+29GSFSJInNDHLKDYQfYN15ueF1YYb22fYflSvKBuU8r8/C30HGKk5u2OyN+blPHsNuUa3nebydw4xQYLaf7x1gQi78vcpxqnhldq7SkvXhtCrTdag4ADceck8igeCeaa2k5LhnuSNvNgHKg3txIbg6/5AxVHsfyAiKhhjKXZvgVM+ENsHc5KP365Ylr6NrlyJjzjU84BUNGAVNmdlE57U0HybN4Y8Jtzwy7td8gg5yV0DMQr8lvWO3bRdMObJQFyz1ZrqbBMskXbnJbVGmOpqfc/lcMQ8Or/Ig3I YC3uon1w cPtaifae69CZUNSb8g0ZmhLmsxeAfllIu6THRvHGK2zF11yhFgeZzYsknlLgWzJUeW4qy5fbOfr0UVOH6B/cRBOLbUQKPWX4cLIS3djEocUugd1Ll2saXlHSsyiKtxtSMDyCq6bHTLnORmmAdX5Sv7i39hi9D5IwBpYWc+APGQ3p+LqmbQOKuqggRPjm7gvh99Hf2RwTMfK1jXNmy9nLfhdgAqsk5we7/H2fh81eEu4Mzl9CDi/AcJGIZ5TSJaWNJLeKv1fwh873uH+cYLAagA+Mt2EaeTVZ6QpnV6sMkEiSVjSY8l0vk3QA1qA== 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, we could implement `format!` for `CString`, however `CString` uses the kernel `Vec` type and hence the kernel allocators, which can't be used for tests run in userspace. Instead, implement `fmt_assert_eq`, which formats strings into a stack allocated buffer for comparison with a `&str`. Signed-off-by: Danilo Krummrich --- rust/kernel/str.rs | 66 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 0b6ffbade521..539be40754f4 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -523,7 +523,6 @@ macro_rules! c_str { #[cfg(test)] mod tests { use super::*; - use alloc::format; const ALL_ASCII_CHARS: &'static str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ @@ -539,6 +538,33 @@ mod tests { \\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\ \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"; + fn format_into_buf<'a>(args: fmt::Arguments<'_>, buf: &'a mut [u8]) -> Result<&'a str, Error> { + let mut f = RawFormatter::new(); + f.write_fmt(args)?; + let size = f.bytes_written(); + + assert!(buf.len() >= size); + + // SAFETY: `buf` has at least a size of `size` bytes and is valid for writes. + let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; + f.write_fmt(args)?; + + Ok(core::str::from_utf8(&buf[0..size])?) + } + + macro_rules! fmt_assert_eq { + ($str:expr, $($f:tt)*) => ({ + let mut buf = [0_u8; ALL_ASCII_CHARS.len()]; + + let s = match format_into_buf(kernel::fmt!($($f)*), &mut buf) { + Ok(s) => s, + Err(_) => panic!("Could not format into buffer."), + }; + + assert_eq!($str, s); + }) + } + #[test] fn test_cstr_to_str() { let good_bytes = b"\xf0\x9f\xa6\x80\0"; @@ -566,13 +592,13 @@ fn test_cstr_as_str_unchecked() { #[test] fn test_cstr_display() { let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); - assert_eq!(format!("{}", hello_world), "hello, world!"); + fmt_assert_eq!("hello, world!", "{}", hello_world); let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); - assert_eq!(format!("{}", non_printables), "\\x01\\x09\\x0a"); + fmt_assert_eq!("\\x01\\x09\\x0a", "{}", non_printables); let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); - assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); + fmt_assert_eq!("d\\xe9j\\xe0 vu", "{}", non_ascii); let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); - assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + fmt_assert_eq!("\\xf0\\x9f\\xa6\\x80", "{}", good_bytes); } #[test] @@ -583,47 +609,47 @@ fn test_cstr_display_all_bytes() { bytes[i as usize] = i.wrapping_add(1); } let cstr = CStr::from_bytes_with_nul(&bytes).unwrap(); - assert_eq!(format!("{}", cstr), ALL_ASCII_CHARS); + fmt_assert_eq!(ALL_ASCII_CHARS, "{}", cstr); } #[test] fn test_cstr_debug() { let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); - assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); + fmt_assert_eq!("\"hello, world!\"", "{:?}", hello_world); let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); - assert_eq!(format!("{:?}", non_printables), "\"\\x01\\x09\\x0a\""); + fmt_assert_eq!("\"\\x01\\x09\\x0a\"", "{:?}", non_printables); let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); - assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); + fmt_assert_eq!("\"d\\xe9j\\xe0 vu\"", "{:?}", non_ascii); let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); - assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); + fmt_assert_eq!("\"\\xf0\\x9f\\xa6\\x80\"", "{:?}", good_bytes); } #[test] fn test_bstr_display() { let hello_world = BStr::from_bytes(b"hello, world!"); - assert_eq!(format!("{}", hello_world), "hello, world!"); + fmt_assert_eq!("hello, world!", "{}", hello_world); let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); - assert_eq!(format!("{}", escapes), "_\\t_\\n_\\r_\\_'_\"_"); + fmt_assert_eq!("_\\t_\\n_\\r_\\_'_\"_", "{}", escapes); let others = BStr::from_bytes(b"\x01"); - assert_eq!(format!("{}", others), "\\x01"); + fmt_assert_eq!("\\x01", "{}", others); let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu"); - assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); + fmt_assert_eq!("d\\xe9j\\xe0 vu", "{}", non_ascii); let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); - assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); + fmt_assert_eq!("\\xf0\\x9f\\xa6\\x80", "{}", good_bytes); } #[test] fn test_bstr_debug() { let hello_world = BStr::from_bytes(b"hello, world!"); - assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); + fmt_assert_eq!("\"hello, world!\"", "{:?}", hello_world); let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); - assert_eq!(format!("{:?}", escapes), "\"_\\t_\\n_\\r_\\\\_'_\\\"_\""); + fmt_assert_eq!("\"_\\t_\\n_\\r_\\\\_'_\\\"_\"", "{:?}", escapes); let others = BStr::from_bytes(b"\x01"); - assert_eq!(format!("{:?}", others), "\"\\x01\""); + fmt_assert_eq!("\"\\x01\"", "{:?}", others); let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu"); - assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); + fmt_assert_eq!("\"d\\xe9j\\xe0 vu\"", "{:?}", non_ascii); let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); - assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); + fmt_assert_eq!("\"\\xf0\\x9f\\xa6\\x80\"", "{:?}", good_bytes); } } From patchwork Tue Jul 23 18:10: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: 13740274 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 30789C3DA49 for ; Tue, 23 Jul 2024 18:13:10 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id BBDEF6B00B7; Tue, 23 Jul 2024 14:13:09 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id B6CE16B00B9; Tue, 23 Jul 2024 14:13:09 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id A354F6B00BA; Tue, 23 Jul 2024 14:13:09 -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 7D1AC6B00B7 for ; Tue, 23 Jul 2024 14:13:09 -0400 (EDT) Received: from smtpin17.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 45A6FA1F9A for ; Tue, 23 Jul 2024 18:13:09 +0000 (UTC) X-FDA: 82371814098.17.112DA08 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf26.hostedemail.com (Postfix) with ESMTP id E45FC140021 for ; Tue, 23 Jul 2024 18:13:06 +0000 (UTC) Authentication-Results: imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GDrEwRtU; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf26.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=1721758335; 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=5s5GEXrpUgqZMN60+rFjwSSmYaOC2eDMeD9YyF521H0=; b=2jyioTh1I4t5vJdlCObX9YbK42Rh/PovewpNZusP6aSLMSvDg5ns8S3y0wUDLrWQ2nfuih eJunrDvaPGGH4TQBuPlTK9sCBP/54txYlL10+m1yTnDZKk35DWy8QYusOec2wPUuvCGotl IWPN9fK8B7MmUTVyzQhQrbbqTgRp51U= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1721758335; a=rsa-sha256; cv=none; b=EqpOGMR7fHMbQK7xT5cb9a5TStsyhiosJNvsGHpRJQJ3T/6FpUBQ+saEvrVLyD1RzElAzl 1EkxmYmNv69EGeIiQje4SejZr1D6r/HA6zb+unMEHfrtbeZ2bzVTXdri+y4Zb0xesn+nWI yPv0cZMke9ZVPlk5AfuYCJ80khwHjHU= ARC-Authentication-Results: i=1; imf26.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=GDrEwRtU; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf26.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 383B0CE0E90; Tue, 23 Jul 2024 18:13:04 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E76F7C4AF0E; Tue, 23 Jul 2024 18:12:57 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1721758383; bh=HhWO+rhzutQW6+RMZ9ncpHmhaR4fD68LK5Csi2zjXug=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=GDrEwRtU2FwzMwAPQUuxnZ8qfEDD+lPzQTCAk85GkkQHagtelzU+hW543pFjAZTWG U8bDqvgxafueyad167YsF8/VUBKrF/B83jgnmVC+LYyZu58G5w5bH3uAIGrVFka3sQ rtaTjf/THkXAqHZbCwGTm4waG9woowf6iW+TFtslGJwd/1N/jM/eh7a2NhV0+zNvmr leS6rELow94lTrR46+nD2cOC+AK2Kjw8LW2lL4wrobTXU5G2vV6n2Shv4BpmYC3rEK b6aPKKoPLuqb2+0PwImS92Cbwa8uy/3ZHe8b0iAJhAf7NANbyxs3ufiPmemUdfdCin 3bDQGBYuBRiiw== 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, acurrid@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 v2 23/23] kbuild: rust: remove the `alloc` crate Date: Tue, 23 Jul 2024 20:10:12 +0200 Message-ID: <20240723181024.21168-24-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240723181024.21168-1-dakr@kernel.org> References: <20240723181024.21168-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: E45FC140021 X-Stat-Signature: kkbucytbztgtwfwzbxbuawcp6egaamo3 X-Rspam-User: X-HE-Tag: 1721758386-120211 X-HE-Meta: U2FsdGVkX1+5jOh116xCaCc+F92hFQh1UqOrLxhtUYcA2kmhHjz731tKa96Hdu1LqZjyL44DlWH74II/WBwFlZ38yqu7i49ITdjqD1u46zityMcWU6cqBLdcCqdYbirPytlB3uyTY6EOfCn/9CXtC6Y0NoURt/DSoq+tWeoDSm62kK5GVU0jGVJ1RzhK7hNThUiugh/F83/NyjIPdBVObU11acpT16LFZnXdKQ17rJGanbDRXZjhcJ6FiSQuOB5FqfstMpihcT2kDKxhuB/M9m6jkD7wTEiE29pJNeV6fN2XUJvqtopzRqHk+odJOdrUsXUq7qKz/XttdKyM013C31r9JfA6uVO1HfamBH+st8edaCjI2vPvWzBcYNofk1SladqC1AckCEHP18TjnbXzsYrqyU/7oA1pEw8m1U2SJUjvrfbzlfGpgrxjQyFbCzKB7XwIJmkl82SXXNuLiq2XaxXIdK5l55z2eGW9uH6Y4fJOnJliTS5Vo+QgyG4YmG93mxEcjGk9ZAVS6z/SVHjNx6DcjE14LT6E7RL+zL12LwShOTVtYbdtnTGHbx+2z5f2yPqWz0RzlfNG/WY6eEoQdgjMg5WUaGxorcv0q+DA+E2F4gpDnqYm0YLd9xFk7N5DsTv1DN+1viWsHvPXO7+Syk8KUE4az4/pG9F+GES8/fTVMUQRiWPvz9GhsfKq5Mlrz75aNqNc93Smz61LynQM/WrdzCfRIvOawhmAGqTiZSpFH/f7u2/6Nr0+evDnI7OZfgaUabugMNq6bjApZjjU+jcwCM3i5cM8lkgKNYulh0Uq6s1+jkkwlrogzYTBgjYLJJEY6MXvnZcme4uZFHh9BYasd1MvZARF96kHlkCCzwMHKU69K7hE0tor4qELw92xyfXh73oXOYsH9nBBqedGYh333O11fzPP/4o+owppekDHmCZld9WNu6XihMiWbDwU+s4uBhiNvQlu4CNJf2a tSVSVhBu 8VMN8PsrFmQPj012DckLtmaMA2d7NvoqWh40B83SIuQkvgyPyrKSG19tp01A+IKt+samwPk5Mj8bkEWIKW0HS128tEh8ALx7khFEZ0O1FA1dVPLWG8qhV88Sat/VjrGKm/Dt88oM8BsN2FPJqvT7mNnZdTEgZkLqLGghYBdaTL39r6HzfIM39RnAVGT/Ww90AbTnqD5c6n/nfsSgGkqxLFnMMrmCrMdYdPVdz49hsHb7nfW8vcZwc7EwaX0gTb7pOX4rGAzZM7UosvyZXG8WJFgxevG35J6iGAzqD7Qcd2gJ6QyeAm80O4NY8mg== 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 corresponding unstable features. Signed-off-by: Danilo Krummrich --- rust/Makefile | 44 ++++++++++-------------------------------- rust/exports.c | 1 - scripts/Makefile.build | 7 +------ 3 files changed, 11 insertions(+), 41 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index f70d5e244fee..409be08ad09a 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 @@ -60,11 +59,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)) \ @@ -87,7 +81,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 \ @@ -111,20 +105,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) @@ -169,7 +154,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 \ @@ -251,7 +236,7 @@ rusttest-macros: $(src)/macros/lib.rs rusttest-prepare 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 rusttest-prepare \ rusttestlib-build_error rusttestlib-macros rusttestlib-bindings \ @@ -364,9 +349,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) @@ -402,7 +384,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 @@ -434,12 +416,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 = -Dunreachable_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) @@ -454,9 +430,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/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 \