From patchwork Fri Aug 16 00:10: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: 13765296 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 98B7BC52D7D for ; Fri, 16 Aug 2024 00:13:51 +0000 (UTC) Received: by kanga.kvack.org (Postfix) id 287498D001F; Thu, 15 Aug 2024 20:13:51 -0400 (EDT) Received: by kanga.kvack.org (Postfix, from userid 40) id 2375D8D0002; Thu, 15 Aug 2024 20:13:51 -0400 (EDT) X-Delivered-To: int-list-linux-mm@kvack.org Received: by kanga.kvack.org (Postfix, from userid 63042) id 0FFC78D001F; Thu, 15 Aug 2024 20:13:51 -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 E3FC08D0002 for ; Thu, 15 Aug 2024 20:13:50 -0400 (EDT) Received: from smtpin01.hostedemail.com (a10.router.float.18 [10.200.18.1]) by unirelay05.hostedemail.com (Postfix) with ESMTP id 934084192B for ; Fri, 16 Aug 2024 00:13:50 +0000 (UTC) X-FDA: 82456185420.01.8CACF2A Received: from sin.source.kernel.org (sin.source.kernel.org [145.40.73.55]) by imf02.hostedemail.com (Postfix) with ESMTP id 5C88180024 for ; Fri, 16 Aug 2024 00:13:48 +0000 (UTC) Authentication-Results: imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=YN169jcj; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf02.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=1723767147; 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=1VC2CVQJSqrMoMHasis1jC/Ivf36FyK9ueVk50Zc+7o=; b=tUPRdvR5FntstCCIL1gRv4xWSgivS10Li7yWOgW+VRvCDjdbApuL/piq+GMxRhJwv+JAti hrHQPTCVizEgAppOg+6fhpmat1/NFvgMn1Qqwj+2hD0ieJI1jw7rJC/nPgwrWcTv7xZstR ShjlTfNJyMHquvASg8jNwvry5S5g0rw= ARC-Seal: i=1; s=arc-20220608; d=hostedemail.com; t=1723767147; a=rsa-sha256; cv=none; b=LkXtzLcuiR/0fSeP++clv8x+C7M1cNuWWspr4CukKjFbAQkwyKUDAsg0FbQ+5rmv0uFroH umV91QPXCuXYIbRbNTzkhPH6+p4zbGg5vrG0Lyg2hWqIe8eRpTjWWYgSA0nXyxxgTv61tt bSw69SiTu3wVh1qAmge5NQ/CVGBmfDw= ARC-Authentication-Results: i=1; imf02.hostedemail.com; dkim=pass header.d=kernel.org header.s=k20201202 header.b=YN169jcj; dmarc=pass (policy=none) header.from=kernel.org; spf=pass (imf02.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 93CD2CE1E8F; Fri, 16 Aug 2024 00:13:45 +0000 (UTC) Received: by smtp.kernel.org (Postfix) with ESMTPSA id E8C35C4AF09; Fri, 16 Aug 2024 00:13:39 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org; s=k20201202; t=1723767224; bh=I6cUolcDKGiOxN2jlE3/L4Zfc5m68bEHs0e/qmkx1fA=; h=From:To:Cc:Subject:Date:In-Reply-To:References:From; b=YN169jcjN81Cmi6OKpdlT7HPyJDRt6/wiY2aKNkcvQL4eo/KLCVl8/ZBlAuASgG7W 5igkBN3w9Dr1JcrgOrglgcb7FhUOPrn6KPAkgLoMT8Mf+m6qWrvzEkdxOfRrsg5x6D HlpqJH2geyzU4Rb7k4tkg8op+ExRtO4eqi8Yh9DXUs+RGy9kVnGHqUq5N0m8t67CkK YAPnH/iKSYdpk59cNGm5lAZR2tSRqRL7PEaReigmEtyCOuvmiwHE30XEgEebteZkII 1GZXiOyJNWR0VwcgYig+oFSYY6nYQjsRvnXw7d4Kn4Bwv11UFuTLqooJbqLsK61760 3ymAtnrv26/0g== 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 v6 15/26] rust: alloc: implement `collect` for `IntoIter` Date: Fri, 16 Aug 2024 02:10:57 +0200 Message-ID: <20240816001216.26575-16-dakr@kernel.org> X-Mailer: git-send-email 2.46.0 In-Reply-To: <20240816001216.26575-1-dakr@kernel.org> References: <20240816001216.26575-1-dakr@kernel.org> MIME-Version: 1.0 X-Rspamd-Server: rspam07 X-Rspamd-Queue-Id: 5C88180024 X-Stat-Signature: xi3iecmhhrge7kk394ekijeyc49yo39h X-Rspam-User: X-HE-Tag: 1723767228-836344 X-HE-Meta: U2FsdGVkX1/729nHXlAVF/pbHQp8gGssLt86XBv0ljS701+zDPWfz9syTLbjta/t3r/R3er2tgIaFQmjxSHjwpY7mIPu5y/OpUjBvABbE/4CV9K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L0rN1/NeSNnkzvJy+9nGfsK8aWnEP9l0cTImVaimYlJCc4ZeSrOl2x/0yQlRNmvPCHPRHg4cW9RGZbBfA0d+ZuLkBzBaXIInq9+aXv9U58k3aUmhCtzl6cUBGDEHCk= 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 3b79f977b65e..ad96f4c3af9e 100644 --- a/rust/kernel/alloc/kvec.rs +++ b/rust/kernel/alloc/kvec.rs @@ -681,6 +681,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