From patchwork Thu Aug 1 00:02:16 2024 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Danilo Krummrich X-Patchwork-Id: 13749356 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 82DF2C3DA64 for ; Thu, 1 Aug 2024 00:08:32 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 1A9FD6B00B2; Wed, 31 Jul 2024 20:08:32 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 159686B00B4; Wed, 31 Jul 2024 20:08:32 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 020C66B00B5; Wed, 31 Jul 2024 20:08:31 -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 D65276B00B2 for ; Wed, 31 Jul 2024 20:08:31 -0400 (EDT) Received: from smtpin23.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay09.hostedemail.com (Postfix) with ESMTP id 91D4D80827 for ; Thu, 1 Aug 2024 00:08:31 +0000 (UTC) X-FDA: 82401740022.23.5FEF7A1 Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf13.hostedemail.com (Postfix) with ESMTP id 4CC6120029 for ; Thu, 1 Aug 2024 00:08:28 +0000 (UTC) Authentication-Results: imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cfkdalvu; spf=pass (imf13.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=1722470854; 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=e2vTv0v1PKHoTtMrANr1QT42n0js2jn0FwIFujzfHWE=; b=7mZSj1pVVSDzvg5QS7cDrZKylRY70sSJ12sxk7VGAOtiCI+BPyH3Zd+xCFiX8dputSVsgO 8jxBquP4MQ484wJQaQvuQaag1UyYarLJocSEDX2NLEh5vZq0A70+07Xf8UD4VGPrnpqMoo STNQBOQPDgSqq+yXaqHCVwDhvNE3bZo= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1722470854; a=rsa-sha256; cv=none; b=Q3KmGMN9Gh/xKJmedKBv4kGhTIlQUl/3lnTDQ7kfdNTqP89qEIWHj7BGKDnj1ZhP/bUW+4 Xa3j1MhtcSyeWRtqhxcsgUji1QlIpWK8mKmC95/ZMSKp+yGD6KdNpghn8yV1JXYVnxVXQf ltheuXC3AGCcpjvPu5UBJ54ilTKqleg= ARC-Authentication-Results: i=1; imf13.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=cfkdalvu; spf=pass (imf13.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 7DF16CE1864; Thu, 1 Aug 2024 00:08:26 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id C747CC116B1; Thu, 1 Aug 2024 00:08:20 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1722470905; bh=ya7gCjOyLIf+BXMFI3ReM5Yjgni5ExXPOwDEfypgmCM=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=cfkdalvu2BIweYpQssrcwA5J5s887qnF4a9CDA0S02Ei57c1u5ZpK8mxhrMNdDs1G o528UVlNzMO7n2gZuc4a1wyzHQHbE3h+713SMxMQbVQVQWhTNxhhHLZ/kcfpqoXBJG NBwlhJl1p9Fb+oGTm7O7Zdee/+T0SS/TvMGD1wu5nxUVfsXlAo16vcblidYbM4GAOG Su6itro6vrd84BDLH+pzhbNPdwrk6DFYzWqeA6jAzCqumZtEppqgXhj7o+TffxYBwF sMW4nec2uBGommHu9GQPK1QD5fStrfcnqX7BPj7vIsfp7mSIgAOuv/QFObpmyOjI7X oRvraIYa/r0FA== 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 v3 17/25] rust: alloc: implement `collect` for `IntoIter` Date: Thu, 1 Aug 2024 02:02:16 +0200 Message-ID: <20240801000641.1882-18-dakr@kernel.org> X-Mailer: git-send-email 2.45.2 In-Reply-To: <20240801000641.1882-1-dakr@kernel.org> References: <20240801000641.1882-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Queue-Id: 4CC6120029 X-Stat-Signature: xfk4k1rsgfonee5f16k7rs5sxisiux5m X-Rspamd-Server: rspam09 X-Rspam-User: X-HE-Tag: 1722470908-956996 X-HE-Meta: U2FsdGVkX1+FnhFTWjGSmP2BayyBXUXWvRfHLL5HzBZP2GOYDaYZ3/Jf2PrsCJGXVA8A/BxW0Fgya/r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XNwbWkhFpr8pE1s0J/snh/30I/MsDk8qptzH1HJsU36mpTkaWhW6x3YBKDVPyrIYfwmtDhWkKHdglK7EmJzEZMo8M4FIiuQINWVvR5Emj+KVQfvZhV9bL7XvEGLb/y4cyLC+W8mEdtYkVWLp3pMSBYFxFxhZk7nQXGAqd4XUGxNRv82E0pXjgHg== 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 Reviewed-by: Alice Ryhl --- 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 50e7705e5686..6f151ef5c988 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -636,6 +636,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