Received: by 2002:a05:6358:7058:b0:131:369:b2a3 with SMTP id 24csp8291775rwp; Wed, 19 Jul 2023 07:55:24 -0700 (PDT) X-Google-Smtp-Source: APBJJlHoVJuB5CsA4xpO67HNEYSmDdsyvanqJ009CYnAI35Nb3o3tih7LVqHqK38LsCd1AV0oFKP X-Received: by 2002:a17:903:25ce:b0:1b5:5a5f:369b with SMTP id jc14-20020a17090325ce00b001b55a5f369bmr1392887plb.65.1689778524526; Wed, 19 Jul 2023 07:55:24 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1689778524; cv=none; d=google.com; s=arc-20160816; b=k7+6lqsziQCG/GyX2uvTnTJnVOWgzI54OseRw9fw/2QfXXliOWfz0RwXiofbxrAEEA 083//D+2cwPGwRc7YfMgXPqDq8sHrYJQb3KemjsWxxFVsaY0gpoC5Ia+GgbGSUKSlk9b qZozpdc2XWwJADXJHKBXEJqqHUNv6l0vsBwV18WUQPiSqxG5x4jIQi1wvHAuHxj21+3e q++D7ZylZlCODYqzJP6YL3cQ3OahZ9V06mWU7R2tttXs8gvhcej8NgF3e1I8/C7OlZQz A2sm2Tmk6G4RQrT0o86loxryQcAlss6xvbp/zOmmAiakCiHSMSC6jg3s50cblA7GxR/A Gmyg== 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=ROflUBJ/yKtDmmZ5v/yBBaWjNh5JrBS62VSefriDUlI=; fh=ahHPrvxY+ty2HIuIPh5QXslVmwB1wHeJjzGZ+GeRryw=; b=CvOmDsdBOykw/1sZunU4odjPHtVbirxbvliFpnDvCafjEuZwGWwJZ9ewU0qMHRmpoZ 8urIWCWtO0k6nK3Bpygeova8AUOZCYL8kfqLotlmJl5a6Apk5QlFm3QnSfg3Xul8Ae6R 6dWajc7tcnq6Az+dwB5KDjXQQVT5US5i/TXa553RFxtgl3F/E0WKgtSDIgV+9ye59QVs OaeoS2YVbBwExRf6YkkMTdmR2V60autO9EdRVOt9vKk0lDY6DF9HxZHIKUH4O70k/SrC ShQhYMfdw2mZb1d3U7aHtJ8HSjiK6Uh3pBANy1uEw67tX9KsRg3nTJ95fgYb9+Rr++qO 2Xbw== ARC-Authentication-Results: i=1; mx.google.com; dkim=pass header.i=@proton.me header.s=protonmail header.b="XfOf/Qvc"; 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 Return-Path: Received: from out1.vger.email (out1.vger.email. [2620:137:e000::1:20]) by mx.google.com with ESMTP id cp1-20020a170902e78100b001b5006b87c0si3568987plb.139.2023.07.19.07.55.11; Wed, 19 Jul 2023 07:55:24 -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="XfOf/Qvc"; 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 S231536AbjGSOWL (ORCPT + 99 others); Wed, 19 Jul 2023 10:22:11 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:52372 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231538AbjGSOWJ (ORCPT ); Wed, 19 Jul 2023 10:22:09 -0400 Received: from mail-4316.protonmail.ch (mail-4316.protonmail.ch [185.70.43.16]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 6F92A173B; Wed, 19 Jul 2023 07:21:47 -0700 (PDT) Date: Wed, 19 Jul 2023 14:21:23 +0000 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=proton.me; s=protonmail; t=1689776489; x=1690035689; bh=ROflUBJ/yKtDmmZ5v/yBBaWjNh5JrBS62VSefriDUlI=; 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=XfOf/Qvc4tNpKfp9Ta7VvfL3+x92B6TlWAlOwPOiGBCimGIkakNppevaXnj/7QTaK GVo2UdqRFqVenr9KU4Sa6s2wbFnA801q6Yw4dn33++EjkR1MpTfVqN2hvAAzGHOMdb +egWXh5B/3RNUYknoHkbTV4EbL3pvtYoGPXfOzc/BgCXrnT3AlStm9F53/reZvmk6k dWH2BhWsvw9LAzhFNhIBg7tFGTJEdNALVIam2lZrfZOVJuHAA3BG6iDdtRKhmmcbz3 vyVh9Mo1g4A4E6pI5XceSpWY8qpMXqVfaoJ+nDYv7HxUgYQoFKJMCWAecZrKHpSl8P 4Fgim/gemo7nQ== 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 11/12] rust: init: add `{pin_}chain` functions to `{Pin}Init` Message-ID: <20230719141918.543938-12-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 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable 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=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 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 Signed-off-by: Benno Lossin --- rust/kernel/init.rs | 138 +++++++++++++++++++++++++++++++++ rust/kernel/init/__internal.rs | 2 +- 2 files changed, 139 insertions(+), 1 deletion(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 3c7cd36a424b..3b0df839f64c 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -773,6 +773,77 @@ 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. + /// + /// # 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 =3D 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 `__pi= nned_init`. + unsafe { self.0.__pinned_init(slot)? }; + // SAFETY: The above call initialized `slot` and we still have uni= que access. + let val =3D unsafe { &mut *slot }; + // SAFETY: `slot` is considered pinned + let val =3D unsafe { Pin::new_unchecked(val) }; + (self.1)(val).map_err(|e| { + // SAFETY: `slot` was initialized above. + unsafe { core::ptr::drop_in_place(slot) }; + e + }) + } } =20 /// An initializer for `T`. @@ -814,6 +885,73 @@ pub unsafe trait Init: Pi= nInit { /// - the caller does not touch `slot` when `Err` is returned, they ar= e 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. + /// + /// # 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 =3D 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, B= ox)>); + +// 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 `__in= it`. + unsafe { self.0.__pinned_init(slot)? }; + // SAFETY: The above call initialized `slot` and we still have uni= que 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 `__pi= nned_init`. + unsafe { self.__init(slot) } + } } =20 /// Creates a new [`PinInit`] from the given closure. diff --git a/rust/kernel/init/__internal.rs b/rust/kernel/init/__internal.r= s 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#tabl= e-of-phantomdata-patterns -type Invariant =3D PhantomData *mut T>; +pub(super) type Invariant =3D PhantomData *mut T>; =20 /// 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 a= s the --=20 2.41.0