From patchwork Mon Aug 14 08:47:15 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Benno Lossin X-Patchwork-Id: 135320 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:b824:0:b0:3f2:4152:657d with SMTP id z4csp2647051vqi; Mon, 14 Aug 2023 03:28:00 -0700 (PDT) X-Google-Smtp-Source: AGHT+IH1tpzcZgT1pY04sDhrjPmykcrkaXtu8RjErU/7f/Vx95l7367cP7grK51/PNXOIa/vWff6 X-Received: by 2002:a05:6a20:8e1f:b0:142:8731:bed1 with SMTP id y31-20020a056a208e1f00b001428731bed1mr9952819pzj.41.1692008879952; Mon, 14 Aug 2023 03:27:59 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1692008879; cv=none; d=google.com; s=arc-20160816; b=hxIAKc9RTWiyp5QLY0bPrznWUJ/PyDng7cJbFZ1kBxPmaUFSx4my6p3FMUuMtmKfg+ lcR3jnXHM20QhOMc8rSF71iKY9uCy1O6rs51KFEFeJys/ynMtg+9GhALDiLdYoMhplut KGHe4AV/Ymh86q7hSksBkAVClXPIcYs29EERXsPA2j5qgLahksJV7WaNJ02yKwBeSuZH r1YIjO658K/vW55TDSZ1VnDP0wncWRwb3fp3uboND41JaPnKbQxr6DUyPQipz2c7BZyw IHpmaVStwpAoGsZ1RoDSZCyRp/mt2j/YDPcUmKLwj6HMC6s47YlN3NJGmpDgTrDmH8/e eAhA== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816; h=list-id:precedence:content-transfer-encoding:mime-version :feedback-id:references:in-reply-to:message-id:subject:cc:from:to :dkim-signature:date; bh=FtpwglMZkGsk6Cq7uG4CBizP3n1NDqFHuFg1fsdOfrA=; fh=h3KS08NeBaYH5bCiXUF1yMk4NKDs2FHNIfHsq8atlgQ=; b=eb1cX9GLGwFbI3AEebE+VcS6sOck076ll5lzeSizcc2I01tDe/5XEN4sfSzrz7MKj6 IXhgi+Q4RNS7VcceOC7KRIHZbdwDpf6neTtpbWkM/61gqdsB/F9HGOWsL6HO1XTEGjJi 11LB+8G5DorjIM7qtDebgP+MHtclSaam1hGhVHRpA3G80PBdRLJt6FgetXxnWCGdx6uH F1OBLIT1of0vZqCY04Ia+MlQA0fSv2HPZHLzEtXi6nH6C6hs4w0wzib5eelDswBs2nse it28XVdoJmqQmwE+vH0TXL60IFCzscHbkiNbDv4lcLE3rUASUMnJsAnmi+juo+1RWhsT dd2g== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@proton.me header.s=c3ehzphaojh3tmfhfoidalwfii.protonmail header.b=Xa+gIRKh; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=QUARANTINE sp=QUARANTINE dis=NONE) header.from=proton.me Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id ch11-20020a056a00288b00b006872db70705si7995143pfb.375.2023.08.14.03.27.46; Mon, 14 Aug 2023 03:27:59 -0700 (PDT) Received-SPF: pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) client-ip=2620:137:e000::1:20; Authentication-Results: mx.google.com; dkim=pass header.i=@proton.me header.s=c3ehzphaojh3tmfhfoidalwfii.protonmail header.b=Xa+gIRKh; spf=pass (google.com: domain of linux-kernel-owner@vger.kernel.org designates 2620:137:e000::1:20 as permitted sender) smtp.mailfrom=linux-kernel-owner@vger.kernel.org; dmarc=pass (p=QUARANTINE sp=QUARANTINE dis=NONE) header.from=proton.me Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231730AbjHNIrx (ORCPT + 99 others); Mon, 14 Aug 2023 04:47:53 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:55684 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S235105AbjHNIrc (ORCPT ); Mon, 14 Aug 2023 04:47:32 -0400 Received: from mail-4316.protonmail.ch (mail-4316.protonmail.ch [185.70.43.16]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 1FEAD1BD for ; Mon, 14 Aug 2023 01:47:26 -0700 (PDT) Date: Mon, 14 Aug 2023 08:47:15 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=proton.me; s=c3ehzphaojh3tmfhfoidalwfii.protonmail; t=1692002844; x=1692262044; bh=FtpwglMZkGsk6Cq7uG4CBizP3n1NDqFHuFg1fsdOfrA=; h=Date:To:From:Cc:Subject:Message-ID:In-Reply-To:References: Feedback-ID:From:To:Cc:Date:Subject:Reply-To:Feedback-ID: Message-ID:BIMI-Selector; b=Xa+gIRKh6q1Oa69K6I+pgABGtdkERf9oJ46KJRMnqaWH019BrDoZVQBvsJC1XsvlY cL/6BtfO3agfXPu+r9+v5wI+z6vETwK2ju/+PstvuGMGXpI/eiMdHIdSrOj/mFto+I sTzCCOyfyurQh3tniudsoZmGTyvpp32kHxZ7/Xf8ocuovOZw4cYkzkUoXP4PEs9sgd nq1uWTOjzcCxxLr4x5+LBDT7BwJfTVRwJfDFoXHHJ3jpof1FfWgQuk2j3Zw7Fis8Am qD1AYbBUR/QOJtqHCST/Qjydszw18rkHua7oYoKE7RM1tNaYTG/6qFV9v5eEo4RygI WtBV8gm9Ywzjw== To: Miguel Ojeda , Wedson Almeida Filho , Alex Gaynor From: Benno Lossin Cc: Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Benno Lossin , Alice Ryhl , Andreas Hindborg , rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org, patches@lists.linux.dev, Asahi Lina , Martin Rodriguez Reboredo Subject: [PATCH v4 08/13] rust: init: Add functions to create array initializers Message-ID: <20230814084602.25699-9-benno.lossin@proton.me> In-Reply-To: <20230814084602.25699-1-benno.lossin@proton.me> References: <20230814084602.25699-1-benno.lossin@proton.me> Feedback-ID: 71780778:user:proton MIME-Version: 1.0 X-Spam-Status: No, score=-2.1 required=5.0 tests=BAYES_00,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,RCVD_IN_MSPIKE_H5, RCVD_IN_MSPIKE_WL,SPF_HELO_PASS,SPF_PASS autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on lindbergh.monkeyblade.net Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org X-getmail-retrieved-from-mailbox: INBOX X-GMAIL-THRID: 1774199903446353902 X-GMAIL-MSGID: 1774199903446353902 Add two functions `pin_init_array_from_fn` and `init_array_from_fn` that take a function that generates initializers for `T` from usize, the added functions then return an initializer for `[T; N]` where every element is initialized by an element returned from the generator function. Suggested-by: Asahi Lina Reviewed-by: Björn Roy Baron Reviewed-by: Alice Ryhl Reviewed-by: Martin Rodriguez Reboredo Signed-off-by: Benno Lossin --- v3 -> v4: - changed example size from 1_000_000_000 to 1_000, - made functions unwind-safe by using a ScopeGuard, - added Reviewed-by from Martin. v2 -> v3: - changed doctest: instead of printing the array, assert the length, - added Reviewed-by's from Alice. v1 -> v2: - fix warnings and errors in doctests, - replace dropping loop with `drop_in_place` and `slice_from_raw_parts_mut` inside of `{pin_}init_array_from_fn` functions. rust/kernel/init.rs | 88 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 460f808ebf84..b54f32017d00 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -212,6 +212,7 @@ use crate::{ error::{self, Error}, sync::UniqueArc, + types::ScopeGuard, }; use alloc::boxed::Box; use core::{ @@ -875,6 +876,93 @@ pub fn uninit() -> impl Init, E> { unsafe { init_from_closure(|_| Ok(())) } } +/// Initializes an array by initializing each element via the provided initializer. +/// +/// # Examples +/// +/// ```rust +/// use kernel::{error::Error, init::init_array_from_fn}; +/// let array: Box<[usize; 1_000]>= Box::init::(init_array_from_fn(|i| i)).unwrap(); +/// assert_eq!(array.len(), 1_000); +/// ``` +pub fn init_array_from_fn( + mut make_init: impl FnMut(usize) -> I, +) -> impl Init<[T; N], E> +where + I: Init, +{ + let init = move |slot: *mut [T; N]| { + let slot = slot.cast::(); + // Counts the number of initialized elements and when dropped drops that many elements from + // `slot`. + let mut init_count = ScopeGuard::new_with_data(0, |i| { + // We now free every element that has been initialized before: + // SAFETY: The loop initialized exactly the values from 0..i and since we + // return `Err` below, the caller will consider the memory at `slot` as + // uninitialized. + unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; + }); + for i in 0..N { + let init = make_init(i); + // SAFETY: since 0 <= `i` < N, it is still in bounds of `[T; N]`. + let ptr = unsafe { slot.add(i) }; + // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` + // requirements. + unsafe { init.__init(ptr) }?; + *init_count += 1; + } + init_count.dismiss(); + Ok(()) + }; + // SAFETY: The initializer above initializes every element of the array. On failure it drops + // any initialized elements and returns `Err`. + unsafe { init_from_closure(init) } +} + +/// Initializes an array by initializing each element via the provided initializer. +/// +/// # Examples +/// +/// ```rust +/// use kernel::{sync::{Arc, Mutex}, init::pin_init_array_from_fn, new_mutex}; +/// let array: Arc<[Mutex; 1_000]>= +/// Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i))).unwrap(); +/// assert_eq!(array.len(), 1_000); +/// ``` +pub fn pin_init_array_from_fn( + mut make_init: impl FnMut(usize) -> I, +) -> impl PinInit<[T; N], E> +where + I: PinInit, +{ + let init = move |slot: *mut [T; N]| { + let slot = slot.cast::(); + // Counts the number of initialized elements and when dropped drops that many elements from + // `slot`. + let mut init_count = ScopeGuard::new_with_data(0, |i| { + // We now free every element that has been initialized before: + // SAFETY: The loop initialized exactly the values from 0..i and since we + // return `Err` below, the caller will consider the memory at `slot` as + // uninitialized. + unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; + }); + for i in 0..N { + let init = make_init(i); + // SAFETY: since 0 <= `i` < N, it is still in bounds of `[T; N]`. + let ptr = unsafe { slot.add(i) }; + // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` + // requirements. + unsafe { init.__pinned_init(ptr) }?; + *init_count += 1; + } + init_count.dismiss(); + Ok(()) + }; + // SAFETY: The initializer above initializes every element of the array. On failure it drops + // any initialized elements and returns `Err`. + unsafe { pin_init_from_closure(init) } +} + // SAFETY: Every type can be initialized by-value. unsafe impl Init for T { unsafe fn __init(self, slot: *mut T) -> Result<(), E> {