From patchwork Wed Sep 11 22:52: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: 13801188 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 31C00EE57D7 for ; Wed, 11 Sep 2024 22:56:24 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id B1F578D0005; Wed, 11 Sep 2024 18:56:23 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id A80C68D0001; Wed, 11 Sep 2024 18:56:23 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 8FA628D0005; Wed, 11 Sep 2024 18:56:23 -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 71FA38D0001 for ; Wed, 11 Sep 2024 18:56:23 -0400 (EDT) Received: from smtpin03.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay01.hostedemail.com (Postfix) with ESMTP id 39D6F1C6376 for ; Wed, 11 Sep 2024 22:56:23 +0000 (UTC) X-FDA: 82553967846.03.AAAE845 Received: from nyc.source.kernel.org (nyc.source.kernel.org [147.75.193.91]) by imf14.hostedemail.com (Postfix) with ESMTP id 9F39410000A for ; Wed, 11 Sep 2024 22:56:21 +0000 (UTC) Authentication-Results: imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HNs5tm92; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 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=1726095265; 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=3EJIaQOVxknEqZYdKuXN3g88B/BL47pO9NfuJlE1ZQo=; b=tCPqCcBS3+kRQqBzZVqcjn3zgLHhPpiILnfM3fdVj/tJuhJNTe7wu4Y8WzO2a/DreMSHwr Ro8EXLy5I0rnngLs8I4FIcK84rytXp2s8orQIsvV9ovYJ7SW6fedkS4KsaIkwoVDzB8Zy6 IAWqzYQhs3Zp1CpuMqn8Kwlgl6S00sg= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1726095265; a=rsa-sha256; cv=none; b=M36ihiu1K2Pfxbi7dAETREn9ZTiWe30hfyKDhUKWKxwbsyldFP9UCSut/tUYkKUSWLSPyo pQS4echdcuN3XDfmlIMsuxIRyfJ346srgFrfTy+dHoFGdes23QSf04BRUTm09MIb/hVmot MLqo29AzARmEgBlD7DUTwlAQ+DXUE4Y= ARC-Authentication-Results: i=1; imf14.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=HNs5tm92; dmarc=pass (policy=quarantine) header.from=kernel.org; spf=pass (imf14.hostedemail.com: domain of dakr@kernel.org designates 147.75.193.91 as permitted sender) smtp.mailfrom=dakr@kernel.org Received: from smtp.kernel.org (transwarp.subspace.kernel.org [100.75.92.58]) by nyc.source.kernel.org (Postfix) with ESMTP id 6528FA45527; Wed, 11 Sep 2024 22:56:13 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id CD080C4CEC0; Wed, 11 Sep 2024 22:56:15 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1726095380; bh=d0GTO9ovdr9mLJZ1kH3EJFt21UVQxchmojeAlHWWgj8=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=HNs5tm92QKne4wWPulUe3fcINVeehDTsWYP7OKbBuDAFJioQkoDs4xtPbMxWiphQb PZ2Xb2cE86reASaruvlmCSipU1rMPqObS0eRNUwsW3pQIH8bTigMxzP0QNorxbtwi8 hKr2oRBWsQAcxalCvk4SXGAdIuxQQwKJ55ChGFBQ9wdJEpSw8/TByF2JJfW8LlU+vH CAmR/f1U71SlL4T+Om9uVQWQFDPHSwlZ/trHlxvTVa6bmYEB2DMK7/UVMEpjm0Vexc Svc8EMpnLgkW2ZbarbI+b/qasorJz8jaeNpZWcGpm/AUYy3l9X/e/y/DOhuqfGCJKZ t8uAn5K+Ub5pQ== 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 v7 15/26] rust: alloc: implement `collect` for `IntoIter` Date: Thu, 12 Sep 2024 00:52:51 +0200 Message-ID: <20240911225449.152928-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240911225449.152928-1-dakr@kernel.org> References: <20240911225449.152928-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 9F39410000A X-Stat-Signature: riduqjgfmq4p3owrpsqmwzfkfi9m97rs X-Rspam-User: X-HE-Tag: 1726095381-511750 X-HE-Meta: U2FsdGVkX1/a7QIoIAgtBoFIvNcaodVeW72+Xz+RnzkHvDhD5V1W/XNhxPIL4ZDRgvvTGaLGe+2lLmScgGrs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soQz4knGrOPwqi2Gvwi44r5gB4C6ntEY8zIyiQPlfwyC/OZdnxNyvnQ57ihq1i1SXQWIB/Wbaj0WBq4rbRZ/cRn4ZrDOZ9GjxaZ08VkJhGhVedMkumQSxFgoSGvsC2CreUg90wFyFEtno8BTLWgpseUrPwqekyEctgsVv22hWPyFrIPVE= 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 Reviewed-by: Benno Lossin --- rust/kernel/alloc/kvec.rs | 86 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs index e91761c5c52d..686e969463f8 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -690,6 +690,92 @@ 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`. + /// + /// # 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 (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(); + } + + // 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