From patchwork Mon Aug 12 18:23:01 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13760932 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from kanga.kvack.org (kanga.kvack.org [205.233.56.17]) by smtp.lore.kernel.org (Postfix) with ESMTP id 1E3E3C52D7C for ; Mon, 12 Aug 2024 18:25:33 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 9ADD96B0083; Mon, 12 Aug 2024 14:25:32 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 956A66B00C0; Mon, 12 Aug 2024 14:25:32 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 7D0446B00C1; Mon, 12 Aug 2024 14:25:32 -0400 (EDT) X-Delivered-To: linux-mm@kvack.org Received: from relay.hostedemail.com (smtprelay0011.hostedemail.com [216.40.44.11]) by kanga.kvack.org (Postfix) with ESMTP id 5E2226B0083 for ; Mon, 12 Aug 2024 14:25:32 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay06.hostedemail.com (Postfix) with ESMTP id 239EBA5BC0 for ; Mon, 12 Aug 2024 18:25:32 +0000 (UTC) X-FDA: 82444421304.06.11687AE Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf24.hostedemail.com (Postfix) with ESMTP id 77F30180027 for ; Mon, 12 Aug 2024 18:25:30 +0000 (UTC) Authentication-Results: imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aUAfrY2L; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723487079; a=rsa-sha256; cv=none; b=RdPGGamiqMRjmmBZyGI8bqQ0UVVFzn2EHAqxN1hHo7hpg5Y6WpeNHOksLNYVxdMuZ88DNi ZKFF1XD2Zk5MpDje8YweHBCXNUQRoVc+70kX3R6AMQxlTozQFJjMWyfXMm0jV+FGvXA6Ka kRUirjaqYqyGrJ8hQxWrGObIIXOPKY4= ARC-Authentication-Results: i=1; imf24.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=aUAfrY2L; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf24.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1723487079; h=from:from:sender:reply-to:subject:subject:date:date: message-id:message-id:to:to:cc:cc:mime-version:mime-version: content-type:content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references:dkim-signature; bh=TjEjT5zmijLvv4lboYXherII1LZULW9T9sIInQkB9nU=; b=uWgosJnhSLRfzsub3hYzwpqESjjPYFox28KLQugJteSHU59UuQ9jp6y99UmBl2gwP85g0l ScDmJORaSii9flq+99A3rgKKChBh8ibDMasS85rkanXEewIJXBlhgsn8WpAknmFj9oCGaK cXnqi9Tcboh8PBVKBl45SG7i4vB1VoI= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id AAB506145D; Mon, 12 Aug 2024 18:25:29 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 6C829C4AF0F; Mon, 12 Aug 2024 18:25:24 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723487129; bh=mGfLMacmI9WDRKwXe7Dbjq2onMgKyS4ooeQ6tXyvXVU=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=aUAfrY2LujU/UqM2eFzPgifWU2KN+zf4RZN2dHFqJ+3IFJko9zyAO+izB4L54XRR2 LwvFMGpAflvg4EvIkKuiaJfGM1D7tphFfc1Shb/m/I4CmkcSpApOJVX2JXT5MoCdt8 juPxgQNxSF60Xomyz0tTsocIX23l55U2zkGayA9RwpTgrUGEIU8ZGlYzGYs606VbG5 SZdo+LCGAg6LbZl+8ti45727MdmV8ltrSNRmTZp28Inuodv+in4hWC26wjTF+ZffDn sZjNiVEon9nWrjyN4sqITxTgCUIrfDIeYX0hYqnHkx5HqnQBeMMuY1so0J4SRXZBSA baU3gqDD0ASyQ== From: Danilo Krummrich To: ojeda@kernel.org, alex.gaynor@gmail.com, wedsonaf@gmail.com, boqun.feng@gmail.com, gary@garyguo.net, bjorn3_gh@protonmail.com, benno.lossin@proton.me, a.hindborg@samsung.com, aliceryhl@google.com, akpm@linux-foundation.org Cc: daniel.almeida@collabora.com, faith.ekstrand@collabora.com, boris.brezillon@collabora.com, lina@asahilina.net, mcanal@igalia.com, zhiw@nvidia.com, cjia@nvidia.com, jhubbard@nvidia.com, airlied@redhat.com, ajanulgu@redhat.com, lyude@redhat.com, linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-mm@kvack.org, Danilo Krummrich Subject: [PATCH v5 15/26] rust: alloc: implement `collect` for `IntoIter` Date: Mon, 12 Aug 2024 20:23:01 +0200 Message-ID: <20240812182355.11641-16-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240812182355.11641-1-dakr@kernel.org> References: <20240812182355.11641-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 77F30180027 X-Rspam-User: X-Rspamd-Server: rspam05 X-Stat-Signature: d5m8nf7dasrjdfwspmmcx4qdcjs5xk7u X-HE-Tag: 1723487130-407899 X-HE-Meta: U2FsdGVkX1+l7P4KqOfswEnSuUdElppLiscPx4gQPlYTR6o225gncruUHnIvFmWz42yNK6A3wbuSoR8UGhRQSZjmoEfmB+jZeIUzzmbGlLzXNf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88MlxxSIoBzzAn0gHSLYAx/cAEUwhNrTMCxUg6wutBIo2atMyQ+MZ0HxU4o7Y/NBLVovIaxekaWoqy4R61EGgsKZ/A+sneSSOajZE60w3Jx4/U1AiviU0dW26a07rJRSA9Ug6cdGiRMb17GfvbrP7lzc2RMEpw== X-Bogosity: Ham, tests=bogofilter, spamicity=0.000000, version=1.2.4 Sender: owner-linux-mm@kvack.org Precedence: bulk X-Loop: owner-majordomo@kvack.org List-ID: List-Subscribe: List-Unsubscribe: Currently, we can't implement `FromIterator`. There are a couple of issues with this trait in the kernel, namely: - Rust's specialization feature is unstable. This prevents us to optimze for the special case where `I::IntoIter` equals `Vec`'s `IntoIter` type. - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` doesn't require this type to be `'static`. - `FromIterator::from_iter` does return `Self` instead of `Result`, hence we can't properly handle allocation failures. - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation flags. Instead, provide `IntoIter::collect`, such that we can at least convert `IntoIter` into a `Vec` again. Reviewed-by: Alice Ryhl Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 78 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index cc8f3c555d1e..db58e764db4b 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -665,6 +665,84 @@ impl IntoIter fn as_raw_mut_slice(&mut self) -> *mut [T] { ptr::slice_from_raw_parts_mut(self.ptr, self.len) } + + fn into_raw_parts(self) -> (*mut T, NonNull, usize, usize) { + let me = ManuallyDrop::new(self); + let ptr = me.ptr; + let buf = me.buf; + let len = me.len; + let cap = me.cap; + (ptr, buf, len, cap) + } + + /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`. + /// + /// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait + /// in the kernel, namely: + /// + /// - Rust's specialization feature is unstable. This prevents us to optimze for the special + /// case where `I::IntoIter` equals `Vec`'s `IntoIter` type. + /// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` + /// doesn't require this type to be `'static`. + /// - `FromIterator::from_iter` does return `Self` instead of `Result`, hence + /// we can't properly handle allocation failures. + /// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation + /// flags. + /// + /// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a + /// `Vec` again. + /// + /// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing + /// buffer. However, this backing buffer may be shrunk to the actual count of elements. + /// + /// # Examples + /// + /// ``` + /// let v = kernel::kvec![1, 2, 3]?; + /// let mut it = v.into_iter(); + /// + /// assert_eq!(it.next(), Some(1)); + /// + /// let v = it.collect(GFP_KERNEL); + /// assert_eq!(v, [2, 3]); + /// + /// # Ok::<(), Error>(()) + /// ``` + pub fn collect(self, flags: Flags) -> Vec { + let (mut ptr, buf, len, mut cap) = self.into_raw_parts(); + let has_advanced = ptr != buf.as_ptr(); + + if has_advanced { + // SAFETY: Copy the contents we have advanced to at the beginning of the buffer. + // `ptr` is guaranteed to be between `buf` and `buf.add(cap)` and `ptr.add(len)` is + // guaranteed to be smaller than `buf.add(cap)`. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr = buf.as_ptr(); + } + + // This can never fail, `len` is guaranteed to be smaller than `cap`. + let layout = core::alloc::Layout::array::(len).unwrap(); + + // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be + // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves + // it as it is. + ptr = match unsafe { A::realloc(Some(buf.cast()), layout, flags) } { + // If we fail to shrink, which likely can't even happen, continue with the existing + // buffer. + Err(_) => ptr, + Ok(ptr) => { + cap = len; + ptr.as_ptr().cast() + } + }; + + // SAFETY: If the iterator has been advanced, the advanced elements have been copied to + // the beginning of the buffer and `len` has been adjusted accordingly. `ptr` is guaranteed + // to point to the start of the backing buffer. `cap` is either the original capacity or, + // after shrinking the buffer, equal to `len`. `alloc` is guaranteed to be unchanged since + // `into_iter` has been called on the original `Vec`. + unsafe { Vec::from_raw_parts(ptr, len, cap) } + } } impl Iterator for IntoIter