From patchwork Wed Jul 19 14:20:57 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Patchwork-Submitter: Benno Lossin X-Patchwork-Id: 122661 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:c923:0:b0:3e4:2afc:c1 with SMTP id j3csp2486358vqt; Wed, 19 Jul 2023 07:41:27 -0700 (PDT) X-Google-Smtp-Source: APBJJlHzLxW3Jr4kOb4eGTQ78wPbfaSfSIp6Hl6Qmsiz/yDsYJJwmMrl6O0JcS3r1v6Xt9DAdIgQ X-Received: by 2002:a17:902:dac7:b0:1b8:87dc:3371 with SMTP id q7-20020a170902dac700b001b887dc3371mr17234256plx.67.1689777686790; Wed, 19 Jul 2023 07:41:26 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1689777686; cv=none; d=google.com; s=arc-20160816; b=ZZYH5JOlGVEYyFNg2gsL5NU2uK+QHa6d1xY0KrTpw7ARVMybYfTma/YN+QKwBte0WV T+f+RryW2KLkDxp2+xVM1aaLwnHVDYN0q6qOaIEweKcT2CW2RcIgp5nH67TxHiFzQPBh jjJEc7RSvf8BaFJGF/7MMIqGa2EmFsQBa29nlR7G2YGzzO9N9JjzI0ncnU0Vi6veVypk mTNrA6/irIDOjEbksQmJMNhz+Vw8HoK1h95iSuO99FnGioI9bm80Ti0+n4GlZgauC6Is u/lANSLbKrAot5JS7eg/q7UuvZl9U0dzW7/1zPBiInlEeT+awagmfPF6MMXlS7LXUxQi a9eQ== 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=ocaw+Jg23eMbqrHzK2iWdBrvi4VvFs/SPBCP4KfLQJI=; fh=ahHPrvxY+ty2HIuIPh5QXslVmwB1wHeJjzGZ+GeRryw=; b=XkS7v54AiP4xxSnUlLMeWF0zh4WyoTA0Bl4Y1QgZ6kSyIat14KoyDxWNxMEaMjc9bt +4ASCNv2kWfyyquynfn8WUWKvPHIod1DlD8ionoLlIPI+NHIivGdxj17LgXq7KE92fqB 08wCcb4r1T3FfKGnjCMeDzvZ+HSpTdhL6M7sTU4QKRaHsDeFjJk6UWqQpCx+YftL5b81 UjYTBO0DaT/nHwN8y2Qnf/MFj+8Sp/t8TO1zRysdcc4I1gu/E9LNFp1hrArROE8/7pcC 7lhxK8s4LNwMcNYToeEtz7mCNZVGAmBtlSvpY2GY/mi0v7iN2g6LEi5Ttdty7LzNDrYV Tzbg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@proton.me header.s=protonmail header.b=gK1ISIfe; 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 l20-20020a170903005400b001b9c34985e1si3516671pla.497.2023.07.19.07.41.12; Wed, 19 Jul 2023 07:41:26 -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=protonmail header.b=gK1ISIfe; 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 S231516AbjGSOVi (ORCPT + 99 others); Wed, 19 Jul 2023 10:21:38 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:51746 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230375AbjGSOVe (ORCPT ); Wed, 19 Jul 2023 10:21:34 -0400 Received: from mail-4316.protonmail.ch (mail-4316.protonmail.ch [185.70.43.16]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id D1CBF270F for ; Wed, 19 Jul 2023 07:21:05 -0700 (PDT) Date: Wed, 19 Jul 2023 14:20:57 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=proton.me; s=protonmail; t=1689776463; x=1690035663; bh=ocaw+Jg23eMbqrHzK2iWdBrvi4VvFs/SPBCP4KfLQJI=; 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=gK1ISIfeWnjFtMpoaYRH7GnrQ1vT8LMld6UrLQmh9V7bcBAA6Bn2dtmYxpZrTSclX oT7nEDYzQXAJMcvgCJ3c1GPr5LVwaiYcvuZeAPgbWWlXEyZNTQNK1t632sK8JtBm89 AsPMCN4Z3uN/lJR9oDe9RYcluSFZy696clmyjDdgfHZX7AExnKP5pqooI2+zDO9iLY oZG0w0GZ48nKTfoo8BKV/2dvfMsZx7Z3SngYAydmsNQ7Rmzf8woa3OP2f9BwUMxI2q Dt0v5ZK1F11b7pL5nf9sFhV5e61Y7Ub0HeMpTKtPnpY6Lr93AoDDwYBegH2d/MJGJZ IbVZL2LIyggnQ== 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, Asahi Lina Subject: [PATCH v2 07/12] rust: init: Add functions to create array initializers Message-ID: <20230719141918.543938-8-benno.lossin@proton.me> In-Reply-To: <20230719141918.543938-1-benno.lossin@proton.me> References: <20230719141918.543938-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_DNSWL_BLOCKED, RCVD_IN_MSPIKE_H5,RCVD_IN_MSPIKE_WL,SPF_HELO_PASS,SPF_PASS, T_SCC_BODY_TEXT_LINE,URIBL_BLOCKED autolearn=unavailable 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: 1771860327634486888 X-GMAIL-MSGID: 1771860327634486888 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 Signed-off-by: Benno Lossin Reviewed-by: Alice Ryhl --- 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 | 86 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 460f808ebf84..fa1ebdbf5f4b 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -875,6 +875,92 @@ 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_000_000]>= Box::init::(init_array_from_fn(|i| i)).unwrap(); +/// pr_info!("{array:?}"); +/// ``` +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::(); + 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. + match unsafe { init.__init(ptr) } { + Ok(()) => {} + Err(e) => { + // 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)) }; + return Err(e); + } + } + } + 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_000_000]>= +/// Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i))).unwrap(); +/// pr_info!("{}", array.len()); +/// ``` +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::(); + 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 `__pinned_init` + // requirements. + match unsafe { init.__pinned_init(ptr) } { + Ok(()) => {} + Err(e) => { + // We now have to free every element that has been initialized before, since we + // have to abide by the drop guarantee. + // 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)) }; + return Err(e); + } + } + } + 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> {