From patchwork Fri Oct 4 15:41:22 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13822629 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 7C82CCF884B for ; Fri, 4 Oct 2024 15:43:50 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 120C16B0096; Fri, 4 Oct 2024 11:43:50 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 0826D6B0098; Fri, 4 Oct 2024 11:43:50 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id E3E406B00A2; Fri, 4 Oct 2024 11:43:49 -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 C26526B0096 for ; Fri, 4 Oct 2024 11:43:49 -0400 (EDT) Received: from smtpin06.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay10.hostedemail.com (Postfix) with ESMTP id 7B952C10AD for ; Fri, 4 Oct 2024 15:43:49 +0000 (UTC) X-FDA: 82636340178.06.1AFA0F2 Received: from dfw.source.kernel.org (dfw.source.kernel.org [139.178.84.217]) by imf07.hostedemail.com (Postfix) with ESMTP id D4D9240010 for ; Fri, 4 Oct 2024 15:43:47 +0000 (UTC) Authentication-Results: imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qHqXPqqt; spf=pass (imf07.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=hostedemail.com; s=arc-20220608; t=1728056587; 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=SaaR12E+gQuJeSgI5+LDALCaKYVQL5s+x2o4IDO480I=; b=1w/NbdABDxs5xR4+ob7FUSagVLaD90HNtG5h+cMTa4uKGD2q5C1Ig+JpvvFKTNbbRPrOGT zyeORXaO+U4G9HtxkbnbbzCFmHmVzx2etuZEXjaWoqI1DaI4osFDfMvC+vkhzlqk/OcqR9 5Z3H+xRUsCcq1mf1K6O3iYytzacwWgc= ARC-Authentication-Results: i=1; imf07.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=qHqXPqqt; spf=pass (imf07.hostedemail.com: domain of dakr@kernel.org designates 139.178.84.217 as permitted sender) smtp.mailfrom=dakr@kernel.org; dmarc=pass (policy=quarantine) header.from=kernel.org ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1728056587; a=rsa-sha256; cv=none; b=M8WL+QzkUwswhsyMYqKh/Mr3xw72H7AJZxEWe47dmDjH3TOK3DoX0G4+ZZ9osMoHMA5NNz haxj0JvWRfBwbxpKlAidTD/wsHHB1PKM8GxNRKaznfpfkd4CAAvsqNdOHskZ9ohM6rTNkX HVvIc+mkndq+EN4g7WQi3ao8AfJRbhM= Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by dfw.source.kernel.org (Postfix) with ESMTP id DADAF5C5EB3; Fri, 4 Oct 2024 15:43:40 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id 56752C4CECE; Fri, 4 Oct 2024 15:43:38 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1728056623; bh=AaRhWJzhXeNmb7koJrUIhcIZp+NJ7YnTtkDq/65dn0w=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=qHqXPqqtK505FnU3TTT6/Ji6dpr2PBjGmIlIN7KTNr7b/n8nmzyALSiHSoiLUQoNb KtUvqcut7lfST4w7g9rLwKr9uH386s/XGHuPMY2lMezaoM/i4dPAolBGABBTcYq/hk uDdhPGfUf8SR858gmtd9UZlfuO3ndAZchUHfRPwFdZwQk5LoRnsBB1xcrrGre3MkD8 gaYPhS97lcGwbRYMOC6v+jXUJ5WydyEO/G0w69lm2Xx9WcRshRlUVHLnRS8moapyaA YnuBVVZiJT+mwr1eLbJM/5tuGkT/xjhcDrKa38LRZxLVzsEouk1asvDeB6WXKelqZ2 brqZEsq6FxgXw== 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 v9 18/29] rust: alloc: implement `collect` for `IntoIter` Date: Fri, 4 Oct 2024 17:41:22 +0200 Message-ID: <20241004154149.93856-19-dakr@kernel.org> X-Mailer: git-send-email 2.46.1 In-Reply-To: <20241004154149.93856-1-dakr@kernel.org> References: <20241004154149.93856-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspam-User: X-Stat-Signature: tq6y8ce356fatwbi8fio6qhb15xkyiiq X-Rspamd-Queue-Id: D4D9240010 X-Rspamd-Server: rspam11 X-HE-Tag: 1728056627-361367 X-HE-Meta: U2FsdGVkX185S+fOb5q7f/gMn5SJ4Enp7D1zNwpv3PPDiHODqc3D6nUAcCi9JtRW0/CG8Cj1S0uvJHokUIhcQXy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XWC5wLadyTQSkey7UH6+sYV7PiJBOFMMZoGtqPtQ16otXsgnvV9eT6H7V1Zuz+VnkT0voKAaya7fyPNqHjvl9wgbf3H4+bXhEuXkRQWZaaQkH8ZX7knEtHUDy8AT/c3XfCXygplfGOA/B4ECiDfcuOJ8Pd+2/f08= 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 Reviewed-by: Benno Lossin Signed-off-by: Danilo Krummrich --- rust/kernel/alloc/kvec.rs | 94 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index 86382827f576..119b5a4dbf77 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -694,6 +694,100 @@ pub struct IntoIter { _p: PhantomData, } +impl IntoIter +where + A: Allocator, +{ + 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.layout.len(); + (ptr, buf, len, cap) + } + + /// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`. + /// + /// # 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>(()) + /// ``` + /// # Implementation Details + /// + /// 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. + pub fn collect(self, flags: Flags) -> Vec { + let old_layout = self.layout; + let (mut ptr, buf, len, mut cap) = self.into_raw_parts(); + let has_advanced = ptr != buf.as_ptr(); + + if has_advanced { + // Copy the contents we have advanced to at the beginning of the buffer. + // + // SAFETY: + // - `ptr` is valid for reads of `len * size_of::()` bytes, + // - `buf.as_ptr()` is valid for writes of `len * size_of::()` bytes, + // - `ptr` and `buf.as_ptr()` are not be subject to aliasing restrictions relative to + // each other, + // - both `ptr` and `buf.ptr()` are properly aligned. + unsafe { ptr::copy(ptr, buf.as_ptr(), len) }; + ptr = buf.as_ptr(); + + // SAFETY: `len` is guaranteed to be smaller than `self.layout.len()`. + let layout = unsafe { ArrayLayout::::new_unchecked(len) }; + + // 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.into(), old_layout.into(), 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 where A: Allocator,