From patchwork Mon Aug 14 08:47:48 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Benno Lossin X-Patchwork-Id: 135341 Return-Path: Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:b824:0:b0:3f2:4152:657d with SMTP id z4csp2660312vqi; Mon, 14 Aug 2023 03:59:30 -0700 (PDT) X-Google-Smtp-Source: AGHT+IEUqJqz1eBfOjbSmIrlGOEBDacm7PFzcYmnMmc4H4GHEydGvVT1x0QOBDwJ06IiL/hjebUC X-Received: by 2002:a05:6a00:138b:b0:66c:6678:3776 with SMTP id t11-20020a056a00138b00b0066c66783776mr11540315pfg.7.1692010770195; Mon, 14 Aug 2023 03:59:30 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1692010770; cv=none; d=google.com; s=arc-20160816; b=vx0qIVq2FKExgT7/JtnGYDnbmGAJQHocwyOb+07wOumuuSLK8gIIlS0nLXAjY2IfAm eoJZQJfh7IT/YcGpG3cH0KFHLyOxFkfegY/Xnku78iJA159BMzjS1xAXnox51en7VPk7 k012QGTCJBP5m8Jv6QczmWI6KUXlDPfd2ydQ4z1n2Hf/+axfflTSLORzpqXECYTHaqf1 q4oyljI3mwYSOkMFa//Emzf6Eyr4Mg/8TnyKmPROOpDprKJrS1WRfNDUVBGkkvuV5iC3 jphwvSNv33YuO6J2WODPyUoXatD3vX2LA3ZCJupfVGoca+tYvG7zIsVZBJ28wUfhqH2K 4RQg== 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=hkVBT1/HhXlC0vpOSaCkYCiuk6RG/epKqCA50EBxt0s=; fh=h3KS08NeBaYH5bCiXUF1yMk4NKDs2FHNIfHsq8atlgQ=; b=ww+WbNAiuKYzlqKM86Gw3K7bzGhHOyrQNsmQr2TEPi/fwLLMGPJvcB10LLU2LjhKJV XzitNb4+0fqBdrWMup16HEUsmANF/1AMJ4QGAk9LI9kY/oixa325sgvUMkvuT52xGTBt R0nMNATrs5M0c3VeiF8W3nGSX6U3ijuyuiBOH8ikeNKHOj0tAfJv9ocWsq/2D+Niev8B sCKUDc20wFRZ/6t+Sq4aXQTG96jLawgFCkcqvY/vhB4vCYBBAPWiOp5OK4FL3vbMS6Z0 16w4sq6eBYXII5vZoE4V+huynhyrpKu8EYkc/pcDRs19aUWM5Ukit9G/TC8wVRzRPbsk KLbg== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@proton.me header.s=protonmail header.b=H6TSHj0o; 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 k6-20020a634b46000000b00557447d5721si7764010pgl.768.2023.08.14.03.59.16; Mon, 14 Aug 2023 03:59:30 -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=H6TSHj0o; 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 S231788AbjHNIsv (ORCPT + 99 others); Mon, 14 Aug 2023 04:48:51 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:33586 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S234977AbjHNIsW (ORCPT ); Mon, 14 Aug 2023 04:48:22 -0400 Received: from mail-40133.protonmail.ch (mail-40133.protonmail.ch [185.70.40.133]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 0DEDD170C; Mon, 14 Aug 2023 01:48:04 -0700 (PDT) Date: Mon, 14 Aug 2023 08:47:48 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=proton.me; s=protonmail; t=1692002882; x=1692262082; bh=hkVBT1/HhXlC0vpOSaCkYCiuk6RG/epKqCA50EBxt0s=; 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=H6TSHj0ovbEmRBAYnTfOmitCd0goCXOvTFW1CiF7GfTonLxQXS+KR4Hig9ISdxZ71 8Xl4r130KWm4xNvRHnSgN5EBw3g9+GvpBJm6P00B7KlfSzcHunr4vFJaaltiNFCYT8 3d4Exm1EEHD6E+8Yh/5KQ9snDxMhEuiaQanEL6ScJaMhqchCq8qVwfiHSEuwGZL1a4 7fs3Fx6l1FxLd6LXZDflI33fFCG0aNngyVHynKZztdI0V4U2zESeTU4udaMT6gjk9y t0LWKvnFfuxOKeDdrTS7BOP6IHc65TIGuBk4koptQ+CJuwCrDrCVt6Etksq4KTpiUF aY0ci2xSPLhng== 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 12/13] rust: init: add `{pin_}chain` functions to `{Pin}Init` Message-ID: <20230814084602.25699-13-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_DNSWL_BLOCKED, 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: 1774201885157071441 X-GMAIL-MSGID: 1774201885157071441 The `{pin_}chain` functions extend an initializer: it not only initializes the value, but also executes a closure taking a reference to the initialized value. This allows to do something with a value directly after initialization. Suggested-by: Asahi Lina Reviewed-by: Martin Rodriguez Reboredo Signed-off-by: Benno Lossin --- v3 -> v4: - added Reviewed-by from Martin. v2 -> v3: - clarify that if `f` errors, the already initialized value will be dropped in both functions. rust/kernel/init.rs | 142 +++++++++++++++++++++++++++++++++ rust/kernel/init/__internal.rs | 2 +- 2 files changed, 143 insertions(+), 1 deletion(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index a15fb5ddbc7d..d75220c8b3f1 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -775,6 +775,79 @@ pub unsafe trait PinInit: Sized { /// deallocate. /// - `slot` will not move until it is dropped, i.e. it will be pinned. unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>; + + /// First initializes the value using `self` then calls the function `f` with the initialized + /// value. + /// + /// If `f` returns an error the value is dropped and the initializer will forward the error. + /// + /// # Examples + /// + /// ```rust + /// # #![allow(clippy::disallowed_names)] + /// use kernel::{types::Opaque, init::pin_init_from_closure}; + /// #[repr(C)] + /// struct RawFoo([u8; 16]); + /// extern { + /// fn init_foo(_: *mut RawFoo); + /// } + /// + /// #[pin_data] + /// struct Foo { + /// #[pin] + /// raw: Opaque, + /// } + /// + /// impl Foo { + /// fn setup(self: Pin<&mut Self>) { + /// pr_info!("Setting up foo"); + /// } + /// } + /// + /// let foo = pin_init!(Foo { + /// raw <- unsafe { + /// Opaque::ffi_init(|s| { + /// init_foo(s); + /// }) + /// }, + /// }).pin_chain(|foo| { + /// foo.setup(); + /// Ok(()) + /// }); + /// ``` + fn pin_chain(self, f: F) -> ChainPinInit + where + F: FnOnce(Pin<&mut T>) -> Result<(), E>, + { + ChainPinInit(self, f, PhantomData) + } +} + +/// An initializer returned by [`PinInit::pin_chain`]. +pub struct ChainPinInit(I, F, __internal::Invariant<(E, Box)>); + +// SAFETY: the `__pinned_init` function is implemented such that it +// - returns `Ok(())` on successful initialization, +// - returns `Err(err)` on error and in this case `slot` will be dropped. +// - considers `slot` pinned. +unsafe impl PinInit for ChainPinInit +where + I: PinInit, + F: FnOnce(Pin<&mut T>) -> Result<(), E>, +{ + unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { + // SAFETY: all requirements fulfilled since this function is `__pinned_init`. + unsafe { self.0.__pinned_init(slot)? }; + // SAFETY: The above call initialized `slot` and we still have unique access. + let val = unsafe { &mut *slot }; + // SAFETY: `slot` is considered pinned + let val = unsafe { Pin::new_unchecked(val) }; + (self.1)(val).map_err(|e| { + // SAFETY: `slot` was initialized above. + unsafe { core::ptr::drop_in_place(slot) }; + e + }) + } } /// An initializer for `T`. @@ -816,6 +889,75 @@ pub unsafe trait Init: PinInit { /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to /// deallocate. unsafe fn __init(self, slot: *mut T) -> Result<(), E>; + + /// First initializes the value using `self` then calls the function `f` with the initialized + /// value. + /// + /// If `f` returns an error the value is dropped and the initializer will forward the error. + /// + /// # Examples + /// + /// ```rust + /// # #![allow(clippy::disallowed_names)] + /// use kernel::{types::Opaque, init::{self, init_from_closure}}; + /// struct Foo { + /// buf: [u8; 1_000_000], + /// } + /// + /// impl Foo { + /// fn setup(&mut self) { + /// pr_info!("Setting up foo"); + /// } + /// } + /// + /// let foo = init!(Foo { + /// buf <- init::zeroed() + /// }).chain(|foo| { + /// foo.setup(); + /// Ok(()) + /// }); + /// ``` + fn chain(self, f: F) -> ChainInit + where + F: FnOnce(&mut T) -> Result<(), E>, + { + ChainInit(self, f, PhantomData) + } +} + +/// An initializer returned by [`Init::chain`]. +pub struct ChainInit(I, F, __internal::Invariant<(E, Box)>); + +// SAFETY: the `__init` function is implemented such that it +// - returns `Ok(())` on successful initialization, +// - returns `Err(err)` on error and in this case `slot` will be dropped. +unsafe impl Init for ChainInit +where + I: Init, + F: FnOnce(&mut T) -> Result<(), E>, +{ + unsafe fn __init(self, slot: *mut T) -> Result<(), E> { + // SAFETY: all requirements fulfilled since this function is `__init`. + unsafe { self.0.__pinned_init(slot)? }; + // SAFETY: The above call initialized `slot` and we still have unique access. + (self.1)(unsafe { &mut *slot }).map_err(|e| { + // SAFETY: `slot` was initialized above. + unsafe { core::ptr::drop_in_place(slot) }; + e + }) + } +} + +// SAFETY: `__pinned_init` behaves exactly the same as `__init`. +unsafe impl PinInit for ChainInit +where + I: Init, + F: FnOnce(&mut T) -> Result<(), E>, +{ + unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { + // SAFETY: `__init` has less strict requirements compared to `__pinned_init`. + unsafe { self.__init(slot) } + } } /// Creates a new [`PinInit`] from the given closure. diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.rs index 12e195061525..db3372619ecd 100644 --- a/rust/kernel/init/__internal.rs +++ b/rust/kernel/init/__internal.rs @@ -13,7 +13,7 @@ /// /// [nomicon]: https://doc.rust-lang.org/nomicon/subtyping.html /// [this table]: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns -type Invariant = PhantomData *mut T>; +pub(super) type Invariant = PhantomData *mut T>; /// This is the module-internal type implementing `PinInit` and `Init`. It is unsafe to create this /// type, since the closure needs to fulfill the same safety requirement as the