From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 42504EB64DD for ; Tue, 11 Jul 2023 09:36:34 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231180AbjGKJgc (ORCPT ); Tue, 11 Jul 2023 05:36:32 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:56534 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229939AbjGKJg1 (ORCPT ); Tue, 11 Jul 2023 05:36:27 -0400 Received: from mail-ej1-x649.google.com (mail-ej1-x649.google.com [IPv6:2a00:1450:4864:20::649]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id DD083100 for ; Tue, 11 Jul 2023 02:36:25 -0700 (PDT) Received: by mail-ej1-x649.google.com with SMTP id a640c23a62f3a-993d500699fso252842766b.1 for ; Tue, 11 Jul 2023 02:36:25 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689068184; x=1691660184; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=tpNSgka6HOUQbghNI4iad00TiEGE4hqZSL3kST/OC3w=; b=Ti91ZX6MJ0NfZLQYe73Us+V/cCtLmivVf32T6Xf2KspuQN/HTcSSA9g2lebAH2TQhN M917g/IJ0yYA7BsuE+fY6jib84ff2BbHeYYHdD7GCus1Tood8iq9pudMXIAGApmDtGd4 opZTY0ahW5qJWmjOk9a1uReY5/8HIlRkuYvOrXDOGLvxRlc5ETES8cHD8upbUCEwyrcV cmQJcqZwgLshmeP2cWEXLeRyZ6F8E1+DqwshQI+h7PS6PaokWygqwzkipVev6NfY6ooi xIzWgbc1lDZuygb5OF4iCT/R0P81bIE5xWiiPhwHzB8T3R1bNjKNR5n/xG+vnkTxNVEt 5QkQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689068184; x=1691660184; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=tpNSgka6HOUQbghNI4iad00TiEGE4hqZSL3kST/OC3w=; b=AbRQW/+/fYcJSFB8vOSHnKgmPQ0/r1ao7t/bdoM1cVd2ThV87VkCV+W5Tcd+rlA7O6 Rogb1GLjc7+w0PpFBRZ1VQcRk0xY5QAr24apJakj2f/AxyX2g2A9GPxJzi2108+QEuRo YD1XR1/nwoHXcIxJ2+LarcFXr+/ufxh7NhgAwKEZnzDbn7OyIG22EIKcSN73YEK+9RQt C53LIoXSGtN748RTlrbtdcjhBkbsp8yO4sMe7YwCVF6FmVKFurtTHnWshZNA94C8W0qf O+vKcaIQ8Lsy02dzfj6GSoz8lsjx6fM3LtlAI2p54rC0r80m5bz8YfMTLRqU0KNMECSy Ay6w== X-Gm-Message-State: ABy/qLb4cmHKOLei3HiVtcggYCTjEwAoCLkBhho5om3Yc29BLyCF62sb lapHzDSJL7Go4Z8McVt3eTlLQU2C4Hprcm4= X-Google-Smtp-Source: APBJJlEXPkfvK066yngPvjteqmRRMhHSgThqq79DkRpbbWFOsk+9nVl2pGFxKPX6/WUYw7K3M70B7cmLZ6KJrJk= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a17:907:763a:b0:98e:2b63:9f78 with SMTP id jy26-20020a170907763a00b0098e2b639f78mr48893ejc.0.1689068183762; Tue, 11 Jul 2023 02:36:23 -0700 (PDT) Date: Tue, 11 Jul 2023 09:32:55 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-2-aliceryhl@google.com> Subject: [PATCH v3 1/9] rust: add offset_of! macro From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Wedson Almeida Filho , Martin Rodriguez Reboredo Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Wedson Almeida Filho This macro is used to compute the offset of a field in a struct. This commit enables an unstable feature that is necessary for using the macro in a constant. However, this is not a problem as the macro will become available from the Rust standard library soon [1]. The unstable feature can be disabled again once that happens. The macro in this patch does not support sub-fields. That is, you cannot write `offset_of!(MyStruct, field.sub_field)` to get the offset of `sub_field` with `field`'s type being a struct with a field called `sub_field`. This is because `field` might be a `Box`, which means that you would be trying to compute the offset to something in an entirely different allocation. There's no easy way to fix the current macro to support subfields, but the version being added to the standard library should support it, so the limitation is temporary and not a big deal. Link: https://github.com/rust-lang/rust/issues/106655 [1] Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Gary Guo Reviewed-by: Benno Lossin --- v2 -> v3: * Add comment as suggested in https://lore.kernel.org/rust-for-linux/875y8= 62lr7.fsf@metaspace.dk/ * Added Reviewed-by from Gary and Benno. rust/kernel/lib.rs | 37 +++++++++++++++++++++++++++++++++++++ scripts/Makefile.build | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 85b261209977..788914fd935f 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -14,6 +14,7 @@ #![no_std] #![feature(allocator_api)] #![feature(coerce_unsized)] +#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] #![feature(receiver_trait)] @@ -97,3 +98,39 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! { // instead of `!`. See . loop {} } + +/// Calculates the offset of a field from the beginning of the struct it b= elongs to. +/// +/// # Examples +/// +/// ``` +/// #[repr(C)] +/// struct Test { +/// a: u64, +/// b: u32, +/// } +/// +/// assert_eq!(kernel::offset_of!(Test, b), 8); +/// ``` +#[macro_export] +macro_rules! offset_of { + ($type:path, $field:ident) =3D> {{ + // Statically ensure that the type has a field of the given name. = This ensures that no + // deref coercion is happening. + let $type { $field: _, .. }; + let tmp =3D ::core::mem::MaybeUninit::<$type>::uninit(); + let outer =3D tmp.as_ptr(); + // To avoid warnings when nesting `unsafe` blocks. + #[allow(unused_unsafe)] + // SAFETY: The pointer is valid and aligned, just not initialised;= `addr_of` ensures that + // we don't actually read from `outer` (which would be UB) nor cre= ate an intermediate + // reference. + let inner =3D unsafe { ::core::ptr::addr_of!((*outer).$field) } as= *const u8; + // To avoid warnings when nesting `unsafe` blocks. + #[allow(unused_unsafe)] + // SAFETY: The two pointers are within the same allocation block. + unsafe { + inner.offset_from(outer as *const u8) as usize + } + }}; +} diff --git a/scripts/Makefile.build b/scripts/Makefile.build index 78175231c969..819510694769 100644 --- a/scripts/Makefile.build +++ b/scripts/Makefile.build @@ -277,7 +277,7 @@ $(obj)/%.lst: $(src)/%.c FORCE # Compile Rust sources (.rs) # ------------------------------------------------------------------------= --- =20 -rust_allowed_features :=3D new_uninit +rust_allowed_features :=3D const_refs_to_cell,new_uninit =20 rust_common_cmd =3D \ RUST_MODFILE=3D$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \ --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 67F7DEB64DC for ; Tue, 11 Jul 2023 09:39:16 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230058AbjGKJjO (ORCPT ); Tue, 11 Jul 2023 05:39:14 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:59296 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230254AbjGKJjJ (ORCPT ); Tue, 11 Jul 2023 05:39:09 -0400 Received: from mail-ed1-x54a.google.com (mail-ed1-x54a.google.com [IPv6:2a00:1450:4864:20::54a]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id EBE3610D4 for ; Tue, 11 Jul 2023 02:38:37 -0700 (PDT) Received: by mail-ed1-x54a.google.com with SMTP id 4fb4d7f45d1cf-518676b6d09so3259222a12.1 for ; Tue, 11 Jul 2023 02:38:37 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689068316; x=1691660316; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=MBgmP0PJ2iUxFozvmmmYwZcxD6aJZ5z3cAsE+Xf1as4=; b=ZW2z8hOF1WRo80QrafK0JkXI57zkP9C7rM4fPyaa1AxBIiYredVLSA46iO2WpKHuUc +geNJaQzzi4cADrIqii2oBP5uLE/koheH+H1dMZyW8g5P9DFudIKPnlIzlwxlbWP54xt x6BbXLcZAVMRHMd+S6GmIEOg64evUP91Wj0dubwkkXgIVikM48pkRssOCeOwdeiI6bvT Jd1XfA7QMJ5YTREszwAJD9SPurKXk6nAfSemFpFTVlt9+TveOlmzcZxNfHAc1HQzr5pc s+HBC/OZwUOw33LF1YhiwJbMowsX/6i0a4QjDkKySJUXnHVTvlV6uJVuyzYybavzJcs7 a3wg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689068316; x=1691660316; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=MBgmP0PJ2iUxFozvmmmYwZcxD6aJZ5z3cAsE+Xf1as4=; b=Rs1hvq14Vnk2xKLr17AcXhkkYICSblx1mbotHjE6gIK5uHuPGWswvnYPygbmEOT0yL sHjKQl5k0ZVZM4u8UNxAKBK6g9sBkQylKsPzmXUoMFLXssJennCmBUy1aSudMMZzMn7V wR6I73hqqviVU4lRpBA07Ystf9Nph3oCjMGyRTiM3Rws7uLg/Ys3TBt1F66ALzmga2WF 3h/T1z+K0y6B6MtTxWQ9OvsMtBl/TUfkoxK+ua5+UcEw0PUOwrKKvvib+TiAhMUUjliT HPUwHnVMybEuZeEhDTXCgnxkVSrD68fnAARJOw7acNoR3g8mThTSbD9cq/9NUSrIo2E7 YBlQ== X-Gm-Message-State: ABy/qLYLY5Kdw+xn/Y2lsS70yZSiHBKJDKYAczsFlKsAaYbcUakKGpWz D/GYFYFJiLnucaTnlgDUnsB3iZlFPR1GJyw= X-Google-Smtp-Source: APBJJlHRkdAxXDJOzU6GNe5HqX7AK0yIjF3AgFRk6eKq/3smS8Hc+PazHrra3a28syJBLWIV2m+lLAmY5hhiBQU= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a17:907:a047:b0:98e:4e80:f0e3 with SMTP id gz7-20020a170907a04700b0098e4e80f0e3mr50726ejc.9.1689068316182; Tue, 11 Jul 2023 02:38:36 -0700 (PDT) Date: Tue, 11 Jul 2023 09:32:56 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-3-aliceryhl@google.com> Subject: [PATCH v3 2/9] rust: sync: add `Arc::{from_raw, into_raw}` From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Wedson Almeida Filho Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Wedson Almeida Filho These methods can be used to turn an `Arc` into a raw pointer and back, in a way that preserves the metadata for fat pointers. This is done using the unstable ptr_metadata feature [1]. However, it could also be done using the unstable pointer_byte_offsets feature [2], which is likely to have a shorter path to stabilization than ptr_metadata. Link: https://github.com/rust-lang/rust/issues/81513 [1] Link: https://github.com/rust-lang/rust/issues/96283 [2] Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl Reviewed-by: Gary Guo Reviewed-by: Andreas Hindborg Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo --- v2 -> v3: * Use `transmute_copy` to convert metadata. * Use `add` instead of `wrapping_add`. * Dropped Reviewed-by from Martin and Benno due to changes. rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 49 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 788914fd935f..6963d11092c4 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -17,6 +17,7 @@ #![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] =20 diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index a89843cacaad..4046b534e53b 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -24,13 +24,13 @@ }; use alloc::boxed::Box; use core::{ - alloc::AllocError, + alloc::{AllocError, Layout}, fmt, marker::{PhantomData, Unsize}, mem::{ManuallyDrop, MaybeUninit}, ops::{Deref, DerefMut}, pin::Pin, - ptr::NonNull, + ptr::{NonNull, Pointee}, }; use macros::pin_data; =20 @@ -212,6 +212,51 @@ unsafe fn from_inner(inner: NonNull>) -> S= elf { } } =20 + /// Convert the [`Arc`] into a raw pointer. + /// + /// The raw pointer has ownership of the refcount that this Arc object= owned. + pub fn into_raw(self) -> *const T { + let ptr =3D self.ptr.as_ptr(); + core::mem::forget(self); + // SAFETY: The pointer is valid. + unsafe { core::ptr::addr_of!((*ptr).data) } + } + + /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::= into_raw`]. + /// + /// This code relies on the `repr(C)` layout of structs as described in + /// . + /// + /// # Safety + /// + /// `ptr` must have been returned by a previous call to [`Arc::into_ra= w`]. Additionally, it + /// can only be called once for each previous call to [`Arc::into_raw`= ]. + pub unsafe fn from_raw(ptr: *const T) -> Self { + let refcount_layout =3D Layout::new::(); + // SAFETY: The caller guarantees that the pointer is valid. + let val_layout =3D Layout::for_value(unsafe { &*ptr }); + // SAFETY: We're computing the layout of a real struct that existe= d when compiling this + // binary, so its layout is not so large that it can trigger arith= metic overflow. + let val_offset =3D unsafe { refcount_layout.extend(val_layout).unw= rap_unchecked().1 }; + + let metadata: ::Metadata =3D core::ptr::metadata(ptr= ); + // SAFETY: The metadata of `T` and `ArcInner` is the same becau= se `ArcInner` is a struct + // with `T` as its last field. + // + // This is documented at: + // . + let metadata: as Pointee>::Metadata =3D + unsafe { core::mem::transmute_copy(&metadata) }; + // SAFETY: The pointer is in-bounds of an allocation both before a= nd after offsetting the + // pointer, since it originates from a previous call to `Arc::into= _raw` and is still valid. + let ptr =3D unsafe { (ptr as *mut u8).sub(val_offset) as *mut () }; + let ptr =3D core::ptr::from_raw_parts_mut(ptr, metadata); + + // SAFETY: By the safety requirements we know that `ptr` came from= `Arc::into_raw`, so the + // reference count held then will be owned by the new `Arc` object. + unsafe { Self::from_inner(NonNull::new_unchecked(ptr)) } + } + /// Returns an [`ArcBorrow`] from the given [`Arc`]. /// /// This is useful when the argument of a function call is an [`ArcBor= row`] (e.g., in a method --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 32A84EB64DD for ; Tue, 11 Jul 2023 09:40:57 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230286AbjGKJkz (ORCPT ); Tue, 11 Jul 2023 05:40:55 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:59776 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229626AbjGKJk3 (ORCPT ); Tue, 11 Jul 2023 05:40:29 -0400 Received: from mail-ej1-x649.google.com (mail-ej1-x649.google.com [IPv6:2a00:1450:4864:20::649]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id B44C810E3 for ; Tue, 11 Jul 2023 02:40:21 -0700 (PDT) Received: by mail-ej1-x649.google.com with SMTP id a640c23a62f3a-992e6840901so661125066b.0 for ; Tue, 11 Jul 2023 02:40:21 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689068420; x=1691660420; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=v6WKBzYvERNDuknj+tWtM9bgJ0GurLsMS9RlnUyPmrc=; b=EpcSNWvY8BCvobBorJKTq6sFdxH+VChpySoX1MC6xQdxotL6dpArX2aHBbt8VwonAw 5U4nkKAdAsXsBjRDjn6EJ/x8bsMuu1doFFJvH1xZRhMq2Oiz20TKlliU+WA6sROLYe+w UndpaFiDN9F35Dagtj3aF/edBjBBMAKbbZkhFlBWv4Kaj53V2N4T/s7wsTWL4v90UKNE oozF7LlHEEr/6kgi4O2vKtbfvhppt5Arfmrca6t5//9RahqDBJW7JnxkqhX2YB6vYrKZ uy6eDDQmJHIAJuEuULa55PMfNx33dz8BOSoG7musUOFxBivEQpP0x6mWwB6qBCUpYUrH zU+w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689068420; x=1691660420; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=v6WKBzYvERNDuknj+tWtM9bgJ0GurLsMS9RlnUyPmrc=; b=Nj249I/mSsPnEjKv159CF5b0t9TSLvxAx9gJFzLH2Tli7g10TzvNZik9+nN8T/kbqL CpvG+z6sDkOWIEjrcfnedeDOrwRCZPDdabHkIzf9QPNjdasZqxfik4SPaF1CMtXbu2nz 1Bh934CWgNluMgL3NLHj8QCFUVaNrerc8KaC5Rh7fgmKXb12gpmKxVV5WrD7GWuDmxoT 3YeQ11EsuYZTOzRKGSrPWfkXlp0gAUeuQNMrg5Itb1W41kE2he0EWXTcHrzVn6pvtO35 wXIBoNhd4WaPTT3kccrAPVp9PKI1zkrzzTGag8B5TlVcBfswQwH3XZT7C9GO5lMymNZC pPGQ== X-Gm-Message-State: ABy/qLbFnoDf3qY2HA8UCsfRU6hDI8t8Gjs4q8ftir83fDHb7uWQDWGM ZE00sN4aUrsnPMXi0rsQpzmf3mQrKLWvn54= X-Google-Smtp-Source: APBJJlHUsXdQJBPhZBUFRWRdsnO9qm0rj0hfuTLUWJ7cX2ZVGox7Jbt0ZPt5Sv3Bt/Ndtv9MLq3FEJQ9TCS0QmA= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a17:906:9f26:b0:98e:46da:bfec with SMTP id fy38-20020a1709069f2600b0098e46dabfecmr101085ejc.1.1689068420362; Tue, 11 Jul 2023 02:40:20 -0700 (PDT) Date: Tue, 11 Jul 2023 09:32:57 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-4-aliceryhl@google.com> Subject: [PATCH 3/9] workqueue: introduce `__INIT_WORK_WITH_KEY` From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Wedson Almeida Filho Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Wedson Almeida Filho A Rust helper (introduced in a later patch) needs to call `__INIT_WORK` with a passed key, rather than define one in place. In order to do that, this moves the initialization code from the `__INIT_WORK` macro into a new `__INIT_WORK_WITH_KEY` macro which takes the key as an extra parameter. Co-developed-by: Alex Gaynor Signed-off-by: Alex Gaynor Signed-off-by: Wedson Almeida Filho Co-developed-by: Miguel Ojeda Signed-off-by: Miguel Ojeda Acked-by: Tejun Heo Signed-off-by: Alice Ryhl Acked-by taken from [2]. Reviewed-by: Martin Rodriguez Reboredo --- Taken from [1]. Wedson's email updated at Wedson's request. Tejun's Acked-by taken from [2]. [1]: https://lore.kernel.org/rust-for-linux/20220802015052.10452-7-ojeda@ke= rnel.org/ [2]: https://lore.kernel.org/rust-for-linux/Yvq3IfK4+C94AeE2@slm.duckdns.or= g/ include/linux/workqueue.h | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/include/linux/workqueue.h b/include/linux/workqueue.h index 3992c994787f..c91a84a4723d 100644 --- a/include/linux/workqueue.h +++ b/include/linux/workqueue.h @@ -221,24 +221,31 @@ static inline unsigned int work_static(struct work_st= ruct *work) { return 0; } * to generate better code. */ #ifdef CONFIG_LOCKDEP +#define __INIT_WORK_WITH_KEY(_work, _func, _onstack, _key) \ + do { \ + __init_work((_work), _onstack); \ + (_work)->data =3D (atomic_long_t) WORK_DATA_INIT(); \ + lockdep_init_map(&(_work)->lockdep_map, "(work_completion)"#_work, _key,= 0); \ + INIT_LIST_HEAD(&(_work)->entry); \ + (_work)->func =3D (_func); \ + } while (0) + #define __INIT_WORK(_work, _func, _onstack) \ do { \ static struct lock_class_key __key; \ - \ - __init_work((_work), _onstack); \ - (_work)->data =3D (atomic_long_t) WORK_DATA_INIT(); \ - lockdep_init_map(&(_work)->lockdep_map, "(work_completion)"#_work, &__ke= y, 0); \ - INIT_LIST_HEAD(&(_work)->entry); \ - (_work)->func =3D (_func); \ + __INIT_WORK_WITH_KEY(_work, _func, _onstack, &__key); \ } while (0) #else +#define __INIT_WORK_WITH_KEY(_work, _func, _onstack, _key) \ + do { \ + __init_work((_work), _onstack); \ + (_work)->data =3D (atomic_long_t) WORK_DATA_INIT(); \ + INIT_LIST_HEAD(&(_work)->entry); \ + (_work)->func =3D (_func); \ + } while (0) + #define __INIT_WORK(_work, _func, _onstack) \ - do { \ - __init_work((_work), _onstack); \ - (_work)->data =3D (atomic_long_t) WORK_DATA_INIT(); \ - INIT_LIST_HEAD(&(_work)->entry); \ - (_work)->func =3D (_func); \ - } while (0) + __INIT_WORK_WITH_KEY(_work, _func, _onstack, NULL) #endif =20 #define INIT_WORK(_work, _func) \ --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 4B4A3EB64DD for ; Tue, 11 Jul 2023 09:42:44 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230387AbjGKJmn (ORCPT ); Tue, 11 Jul 2023 05:42:43 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:34156 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S230397AbjGKJmh (ORCPT ); Tue, 11 Jul 2023 05:42:37 -0400 Received: from mail-ej1-x649.google.com (mail-ej1-x649.google.com [IPv6:2a00:1450:4864:20::649]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id CBDD7A8 for ; Tue, 11 Jul 2023 02:42:26 -0700 (PDT) Received: by mail-ej1-x649.google.com with SMTP id a640c23a62f3a-993d41cbc31so269033366b.1 for ; Tue, 11 Jul 2023 02:42:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689068545; x=1691660545; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=f7HLpFtiTSWw0ZxSifV85XuGL1lfgvJblX5DGQd7aZg=; b=rn6KFEzfYPUPKzeY5cQR9Bk5tjkbVHfgCbbsmC9+vaf9B/2jTg/G+kxUDkEVhnnUKY 6ituUWa6qX4KfIU1hTNSnYfZLeUIMvi/qwGapwmTAdLAEO9MWnWyBcvCuBZ0Vw6rwM0t 2BpB27CEsT5oMh7hw/6OR/Da6YVFpyX2u3kMJ5BDquicAt/R+GyU1zds1crLxR/rS5CK jQrtdS1LcVEe/fuKqGhI5Ol27ZA/T4yb0HGT0B9XgMhFKuLj4CzwYT64EU0T1tGX5Qiu g5X20m+QQGmoj65d15hRUfrxcvF6pgg3a6kmqDIN9hrb9mPU82LU8N7OjiChZgfYdiUB 6FLQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689068545; x=1691660545; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=f7HLpFtiTSWw0ZxSifV85XuGL1lfgvJblX5DGQd7aZg=; b=Z5i+ghJODtyBiJU5B7Zx6ezPM9Dckab5nr3e6QGM/GNCfMvnDhkDtVRno873ppJM2Q eutKJJ0EqlMAC95ktWwXnbJZFW49ixKQF5TnmkYvdTeLe6107HCZrUtStkt459zvibCc 200KDz4dMPuaKgMitRS61g35xGu61fV29nzvhJQ5DNM2uMJeU0+2o0phzJcO/vdYxofC Vsgx/pnAtuIYRYT/O1RoMD6gc9BDiTMxEuJR/ahGqihSzJk9wL8hSnpJbJu+MmgxJj0i JwAm9MG/cBeUNFBSuoD8CHh34QitmlKUHomXTwzKHDC1zVTfYBBcUy4MuwzkI1hJVqBS oEHA== X-Gm-Message-State: ABy/qLYCAlhOCvkO2/IhcxWssfWk5EAh64SSzosgiT2r9K5R+E/yfONG 82O98b184llcRAnA1nsEgzUJ9SV0T0W4B3U= X-Google-Smtp-Source: APBJJlHVM3p8FBFgUsh1AAogwf8OnjJiwtgazoiqRv+wwkOPAoCVMmUM2zuYBOGgpSpw33EdVOcNf1tb1nowtSU= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a17:906:9be6:b0:98e:413a:477b with SMTP id de38-20020a1709069be600b0098e413a477bmr55880ejc.10.1689068545276; Tue, 11 Jul 2023 02:42:25 -0700 (PDT) Date: Tue, 11 Jul 2023 09:32:58 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-5-aliceryhl@google.com> Subject: [PATCH v3 4/9] rust: workqueue: add low-level workqueue bindings From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Martin Rodriguez Reboredo , Andreas Hindborg Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" Define basic low-level bindings to a kernel workqueue. The API defined here can only be used unsafely. Later commits will provide safe wrappers. Co-developed-by: Gary Guo Signed-off-by: Gary Guo Signed-off-by: Alice Ryhl Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Andreas Hindborg (Samsung) Reviewed-by: Benno Lossin Reviewed-by: Boqun Feng --- v2 -> v3: * Update documentation to say "guarantees section". * Add Reviewed-by from Martin, Andreas, Benno. rust/bindings/bindings_helper.h | 1 + rust/kernel/lib.rs | 1 + rust/kernel/workqueue.rs | 108 ++++++++++++++++++++++++++++++++ 3 files changed, 110 insertions(+) create mode 100644 rust/kernel/workqueue.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 3e601ce2548d..4e1c0938c8cb 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -11,6 +11,7 @@ #include #include #include +#include =20 /* `bindgen` gets confused at certain things. */ const gfp_t BINDINGS_GFP_KERNEL =3D GFP_KERNEL; diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 6963d11092c4..6d63f4f6bb8a 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -45,6 +45,7 @@ pub mod sync; pub mod task; pub mod types; +pub mod workqueue; =20 #[doc(hidden)] pub use bindings; diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs new file mode 100644 index 000000000000..060d26dfcc7d --- /dev/null +++ b/rust/kernel/workqueue.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Work queues. +//! +//! C header: [`include/linux/workqueue.h`](../../../../include/linux/work= queue.h) + +use crate::{bindings, types::Opaque}; + +/// A kernel work queue. +/// +/// Wraps the kernel's C `struct workqueue_struct`. +/// +/// It allows work items to be queued to run on thread pools managed by th= e kernel. Several are +/// always available, for example, `system`, `system_highpri`, `system_lon= g`, etc. +#[repr(transparent)] +pub struct Queue(Opaque); + +// SAFETY: Kernel workqueues are usable from any thread. +unsafe impl Send for Queue {} +unsafe impl Sync for Queue {} + +impl Queue { + /// Use the provided `struct workqueue_struct` with Rust. + /// + /// # Safety + /// + /// The caller must ensure that the provided raw pointer is not dangli= ng, that it points at a + /// valid workqueue, and that it remains valid until the end of 'a. + pub unsafe fn from_raw<'a>(ptr: *const bindings::workqueue_struct) -> = &'a Queue { + // SAFETY: The `Queue` type is `#[repr(transparent)]`, so the poin= ter cast is valid. The + // caller promises that the pointer is not dangling. + unsafe { &*(ptr as *const Queue) } + } + + /// Enqueues a work item. + /// + /// This may fail if the work item is already enqueued in a workqueue. + /// + /// The work item will be submitted using `WORK_CPU_UNBOUND`. + pub fn enqueue(&self, w: W) -> W::EnqueueOutput + where + W: RawWorkItem + Send + 'static, + { + let queue_ptr =3D self.0.get(); + + // SAFETY: We only return `false` if the `work_struct` is already = in a workqueue. The other + // `__enqueue` requirements are not relevant since `W` is `Send` a= nd static. + // + // The call to `bindings::queue_work_on` will dereference the prov= ided raw pointer, which + // is ok because `__enqueue` guarantees that the pointer is valid = for the duration of this + // closure. + // + // Furthermore, if the C workqueue code accesses the pointer after= this call to + // `__enqueue`, then the work item was successfully enqueued, and = `bindings::queue_work_on` + // will have returned true. In this case, `__enqueue` promises tha= t the raw pointer will + // stay valid until we call the function pointer in the `work_stru= ct`, so the access is ok. + unsafe { + w.__enqueue(move |work_ptr| { + bindings::queue_work_on(bindings::WORK_CPU_UNBOUND as _, q= ueue_ptr, work_ptr) + }) + } + } +} + +/// A raw work item. +/// +/// This is the low-level trait that is designed for being as general as p= ossible. +/// +/// The `ID` parameter to this trait exists so that a single type can prov= ide multiple +/// implementations of this trait. For example, if a struct has multiple `= work_struct` fields, then +/// you will implement this trait once for each field, using a different i= d for each field. The +/// actual value of the id is not important as long as you use different i= ds for different fields +/// of the same struct. (Fields of different structs need not use differen= t ids.) +/// +/// Note that the id is used only to select the right method to call durin= g compilation. It wont be +/// part of the final executable. +/// +/// # Safety +/// +/// Implementers must ensure that any pointers passed to a `queue_work_on`= closure by `__enqueue` +/// remain valid for the duration specified in the guarantees section of t= he documentation for +/// `__enqueue`. +pub unsafe trait RawWorkItem { + /// The return type of [`Queue::enqueue`]. + type EnqueueOutput; + + /// Enqueues this work item on a queue using the provided `queue_work_= on` method. + /// + /// # Guarantees + /// + /// If this method calls the provided closure, then the raw pointer is= guaranteed to point at a + /// valid `work_struct` for the duration of the call to the closure. I= f the closure returns + /// true, then it is further guaranteed that the pointer remains valid= until someone calls the + /// function pointer stored in the `work_struct`. + /// + /// # Safety + /// + /// The provided closure may only return `false` if the `work_struct` = is already in a workqueue. + /// + /// If the work item type is annotated with any lifetimes, then you mu= st not call the function + /// pointer after any such lifetime expires. (Never calling the functi= on pointer is okay.) + /// + /// If the work item type is not [`Send`], then the function pointer m= ust be called on the same + /// thread as the call to `__enqueue`. + unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput + where + F: FnOnce(*mut bindings::work_struct) -> bool; +} --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 618D1C001B0 for ; Tue, 11 Jul 2023 09:44:40 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S229987AbjGKJoj (ORCPT ); Tue, 11 Jul 2023 05:44:39 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:35390 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231154AbjGKJog (ORCPT ); Tue, 11 Jul 2023 05:44:36 -0400 Received: from mail-yw1-x1149.google.com (mail-yw1-x1149.google.com [IPv6:2607:f8b0:4864:20::1149]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id C8C8FE56 for ; Tue, 11 Jul 2023 02:44:32 -0700 (PDT) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-5706641dda9so58536287b3.3 for ; Tue, 11 Jul 2023 02:44:32 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689068672; x=1691660672; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=DnWC54SA5C43dBWBZ5WUeTUepGdecHVPir9nVhbTPfs=; b=pFt/A5hE+tHwPhG/vQTUr4kvstBbCWSzSLnioI5Xu66+C+AWhzML21sFWR8XVStzeF 0wRGxUkDMyyBLV3icf4r6VX2vGeeR4uCecxUxYvJ9zfs42pnWCSIGAAkxhpoeMJWP4oR Th52jB4y46IhDAv6CAQOCUzz6GVjHy+3AUSezWpl2nAhSHYYRPh3Y8DWkr0X97j9CcqX fbw9l15c8mpBVTeboeZOYwWazNhqnOvLa7kV1+K2XEhnjt+g3d7g7/jiuFcqxVyFT1m8 T3Kc/xEiMt+wWCJGIJHLzWCKBxLAWqHOyDSTuXKA6hOOtxaUKLZDHbBhcJmmdT55KEjn KW4w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689068672; x=1691660672; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=DnWC54SA5C43dBWBZ5WUeTUepGdecHVPir9nVhbTPfs=; b=iRci+tJJeoq4a3iF7iuxixXIHOrdBpoyyTcfyWlY7hAXfg47earEh7EciOn9bae125 QpZ9En6MvWePToqrJ5TtE6cfpWkFJxA/kqDe7olto6NzkxZO60oTU89qs+wyxo1/GXKM Gzez483YR2NS4EnpgcPGGAgIXsNSCZFl9eBpVBl6da0AjRj/LGxcMrwfLNyuxEetIUJX yKPf9TnrnEzgAf9ylDBvlIgKja8i8J3TCc0JHQqhUCzwKF0tP30HaAPopk0bGFVR44Oc DNY412QkqSTACCU+b/5WFD+OpTRPG9oJFMPyQLuiDo29dsewfY56u7x5LI83jspv6eEL 74Lw== X-Gm-Message-State: ABy/qLbBxp+kdku3neAyRYufI+wlWzEviKxKXVNoCIRaH+7i8mwp6trI 8u/hm18vsRoe/DINbfaHQKNZvncut7VR/2w= X-Google-Smtp-Source: APBJJlE1heVdhciWDeiDz6Fk0FD2epw/QZh55eA7ghY22nT05sA9Hga/GURTh1B908T+JbpSXu2qKVF2avUaRag= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a81:4312:0:b0:579:fa4c:1f25 with SMTP id q18-20020a814312000000b00579fa4c1f25mr126504ywa.7.1689068671975; Tue, 11 Jul 2023 02:44:31 -0700 (PDT) Date: Tue, 11 Jul 2023 09:32:59 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-6-aliceryhl@google.com> Subject: [PATCH v3 5/9] rust: workqueue: define built-in queues From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Wedson Almeida Filho , Martin Rodriguez Reboredo , Andreas Hindborg Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Wedson Almeida Filho We provide these methods because it lets us access these queues from Rust without using unsafe code. These methods return `&'static Queue`. References annotated with the 'static lifetime are used when the referent will stay alive forever. That is ok for these queues because they are global variables and cannot be destroyed. Signed-off-by: Wedson Almeida Filho Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Gary Guo Reviewed-by: Andreas Hindborg (Samsung) Reviewed-by: Benno Lossin --- v2 -> v3: * Explain what a freezable workqueue is. * Add Reviewed-by from Gary, Andreas, Benno. rust/kernel/workqueue.rs | 71 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 060d26dfcc7d..cad039dfc5a9 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -106,3 +106,74 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Self= ::EnqueueOutput where F: FnOnce(*mut bindings::work_struct) -> bool; } + +/// Returns the system work queue (`system_wq`). +/// +/// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU mult= i-threaded. There are +/// users which expect relatively short queue flush time. +/// +/// Callers shouldn't queue work items which can run for too long. +pub fn system() -> &'static Queue { + // SAFETY: `system_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_wq) } +} + +/// Returns the system high-priority work queue (`system_highpri_wq`). +/// +/// It is similar to the one returned by [`system`] but for work items whi= ch require higher +/// scheduling priority. +pub fn system_highpri() -> &'static Queue { + // SAFETY: `system_highpri_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_highpri_wq) } +} + +/// Returns the system work queue for potentially long-running work items = (`system_long_wq`). +/// +/// It is similar to the one returned by [`system`] but may host long runn= ing work items. Queue +/// flushing might take relatively long. +pub fn system_long() -> &'static Queue { + // SAFETY: `system_long_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_long_wq) } +} + +/// Returns the system unbound work queue (`system_unbound_wq`). +/// +/// Workers are not bound to any specific CPU, not concurrency managed, an= d all queued work items +/// are executed immediately as long as `max_active` limit is not reached = and resources are +/// available. +pub fn system_unbound() -> &'static Queue { + // SAFETY: `system_unbound_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_unbound_wq) } +} + +/// Returns the system freezable work queue (`system_freezable_wq`). +/// +/// It is equivalent to the one returned by [`system`] except that it's fr= eezable. +/// +/// A freezable workqueue participates in the freeze phase of the system s= uspend operations. Work +/// items on the workqueue are drained and no new work item starts executi= on until thawed. +pub fn system_freezable() -> &'static Queue { + // SAFETY: `system_freezable_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_freezable_wq) } +} + +/// Returns the system power-efficient work queue (`system_power_efficient= _wq`). +/// +/// It is inclined towards saving power and is converted to "unbound" vari= ants if the +/// `workqueue.power_efficient` kernel parameter is specified; otherwise, = it is similar to the one +/// returned by [`system`]. +pub fn system_power_efficient() -> &'static Queue { + // SAFETY: `system_power_efficient_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_power_efficient_wq) } +} + +/// Returns the system freezable power-efficient work queue (`system_freez= able_power_efficient_wq`). +/// +/// It is similar to the one returned by [`system_power_efficient`] except= that is freezable. +/// +/// A freezable workqueue participates in the freeze phase of the system s= uspend operations. Work +/// items on the workqueue are drained and no new work item starts executi= on until thawed. +pub fn system_freezable_power_efficient() -> &'static Queue { + // SAFETY: `system_freezable_power_efficient_wq` is a C global, always= available. + unsafe { Queue::from_raw(bindings::system_freezable_power_efficient_wq= ) } +} --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 15CC8EB64DC for ; Tue, 11 Jul 2023 09:47:21 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231452AbjGKJrT (ORCPT ); Tue, 11 Jul 2023 05:47:19 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:37128 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231510AbjGKJrK (ORCPT ); Tue, 11 Jul 2023 05:47:10 -0400 Received: from mail-ed1-x549.google.com (mail-ed1-x549.google.com [IPv6:2a00:1450:4864:20::549]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 2A2F2A4 for ; Tue, 11 Jul 2023 02:47:03 -0700 (PDT) Received: by mail-ed1-x549.google.com with SMTP id 4fb4d7f45d1cf-51836731bfbso2966769a12.3 for ; Tue, 11 Jul 2023 02:47:03 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689068821; x=1691660821; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=byeQRg9wMfh8yysYKRK6+a5IcPGEEJ19WpkHoNK4TKk=; b=7SJiwh3Nwsx+fRHer0AymGXM84gSsAdDhbqu3yy0DnA+CbreWmaAfUaZw13Ma5rVS5 QagEEGMILZsXeLezA9BFbZN3t9aXRlxgp4TvXsSOhE3SOBeVrrpEXWI+t2SJ3qdary1V 0x333up/a0MSVrMjRjGcQlHBu3ZYc61UW61NXOXU6iNIpUSgoVfRPXCnMmWot2awhpNB 3PtPFHwMR+uShJ+Whp0M0M/x+JXu68f6HBel3IeFxsQFiOh/7pwm+jbrOoqIQMCaT7Uv ctU1+hsRU5sCBkgazOzp9h43+1TNhEXTch5uHVVuTmTaOspP50HbP45XJVsueCc0XcQL 9R8Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689068821; x=1691660821; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=byeQRg9wMfh8yysYKRK6+a5IcPGEEJ19WpkHoNK4TKk=; b=S1PBPMy0AtsPa+djHOdIidmH3g74Z1Slb3QUDTxG2pnEk1/dmobV4AAxtzGu1bMNt1 vP9O26kOMbZiTlSj0Fy01pqdoVM4Rc8gYCmmphNyKFjzzDT5NnonjGSGtN3Lv7EJ9/4X kWQY81WVnt23Ks9pmNmBaXrrauYIZpOccZl0cmbPeojKKpjhpZ7oZmhOwufLR/YdLjwt wKoFaqYI91Khzn7RpJ9MSLM2WD/6J+2b+rwicMZozo6DIiFxdozxdV4eTV5O3wsBP5Nl YouWj5yc6C3mI2lE3JcFedQ7zs9Q98u0cuzSQQrIFcK26QyKTBF4sYOjp/2FY808Bvcu p8Xg== X-Gm-Message-State: ABy/qLZ79lmYmkzp89yN4n0FSDBW5Jyhkpy66BV2oAft7Endyx0IeCY3 kpOZV0qGrRhAt/5NJAnQRdPBMuyIJEc+juU= X-Google-Smtp-Source: APBJJlGUZ045c5rFnF3yXb2RaUh4JdQF7OIgNjlGieWNZ6IGpoAo1gQx27JYtc0uPpn4IbFx5t02ykBz//H1Lps= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a50:c353:0:b0:51e:162f:d616 with SMTP id q19-20020a50c353000000b0051e162fd616mr83019edb.8.1689068821303; Tue, 11 Jul 2023 02:47:01 -0700 (PDT) Date: Tue, 11 Jul 2023 09:33:00 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-7-aliceryhl@google.com> Subject: [PATCH v3 6/9] rust: workqueue: add helper for defining work_struct fields From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" The main challenge with defining `work_struct` fields is making sure that the function pointer stored in the `work_struct` is appropriate for the work item type it is embedded in. It needs to know the offset of the `work_struct` field being used (even if there are several!) so that it can do a `container_of`, and it needs to know the type of the work item so that it can call into the right user-provided code. All of this needs to happen in a way that provides a safe API to the user, so that users of the workqueue cannot mix up the function pointers. There are three important pieces that are relevant when doing this: * The pointer type. * The work item struct. This is what the pointer points at. * The `work_struct` field. This is a field of the work item struct. This patch introduces a separate trait for each piece. The pointer type is given a `WorkItemPointer` trait, which pointer types need to implement to be usable with the workqueue. This trait will be implemented for `Arc` and `Box` in a later patch in this patchset. Implementing this trait is unsafe because this is where the `container_of` operation happens, but user-code will not need to implement it themselves. The work item struct should then implement the `WorkItem` trait. This trait is where user-code specifies what they want to happen when a work item is executed. It also specifies what the correct pointer type is. Finally, to make the work item struct know the offset of its `work_struct` field, we use a trait called `HasWork`. If a type implements this trait, then the type declares that, at the given offset, there is a field of type `Work`. The trait is marked unsafe because the OFFSET constant must be correct, but we provide an `impl_has_work!` macro that can safely implement `HasWork` on a type. The macro expands to something that only compiles if the specified field really has the type `Work`. It is used like this: ``` struct MyWorkItem { work_field: Work, } impl_has_work! { impl HasWork for MyWorkItem { self.work_field } } ``` Note that since the `Work` type is annotated with an id, you can have several `work_struct` fields by using a different id for each one. Co-developed-by: Gary Guo Signed-off-by: Gary Guo Signed-off-by: Alice Ryhl --- v2 -> v3: * Use __INIT_WORK_WITH_KEY instead of __INIT_WORK. * Expand documentation for WorkItemPointer. * Expand documentation for HasWork. * Removed PhantomPinned from Work. This depends on [1] for correctness. * Dropped Reviewed-by annotations due to changes. [1]: https://lore.kernel.org/all/20230630150216.109789-1-benno.lossin@proto= n.me/ rust/helpers.c | 8 ++ rust/kernel/workqueue.rs | 240 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 247 insertions(+), 1 deletion(-) diff --git a/rust/helpers.c b/rust/helpers.c index bb594da56137..f7a04a266f46 100644 --- a/rust/helpers.c +++ b/rust/helpers.c @@ -27,6 +27,7 @@ #include #include #include +#include =20 __noreturn void rust_helper_BUG(void) { @@ -135,6 +136,13 @@ void rust_helper_put_task_struct(struct task_struct *t) } EXPORT_SYMBOL_GPL(rust_helper_put_task_struct); =20 +void rust_helper___INIT_WORK_WITH_KEY(struct work_struct *work, work_func_= t func, + bool on_stack, struct lock_class_key *key) +{ + __INIT_WORK_WITH_KEY(work, func, on_stack, key); +} +EXPORT_SYMBOL_GPL(rust_helper___INIT_WORK_WITH_KEY); + /* * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` ty= pe * as the Rust `usize` type, so we can use it in contexts where Rust diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index cad039dfc5a9..a7c972bda0ed 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -2,9 +2,34 @@ =20 //! Work queues. //! +//! This file has two components: The raw work item API, and the safe work= item API. +//! +//! One pattern that is used in both APIs is the `ID` const generic, which= exists to allow a single +//! type to define multiple `work_struct` fields. This is done by choosing= an id for each field, +//! and using that id to specify which field you wish to use. (The actual = value doesn't matter, as +//! long as you use different values for different fields of the same stru= ct.) Since these IDs are +//! generic, they are used only at compile-time, so they shouldn't exist i= n the final binary. +//! +//! # The raw API +//! +//! The raw API consists of the `RawWorkItem` trait, where the work item n= eeds to provide an +//! arbitrary function that knows how to enqueue the work item. It should = usually not be used +//! directly, but if you want to, you can use it without using the pieces = from the safe API. +//! +//! # The safe API +//! +//! The safe API is used via the `Work` struct and `WorkItem` traits. Furt= hermore, it also includes +//! a trait called `WorkItemPointer`, which is usually not used directly b= y the user. +//! +//! * The `Work` struct is the Rust wrapper for the C `work_struct` type. +//! * The `WorkItem` trait is implemented for structs that can be enqueue= d to a workqueue. +//! * The `WorkItemPointer` trait is implemented for the pointer type tha= t points at a something +//! that implements `WorkItem`. +//! //! C header: [`include/linux/workqueue.h`](../../../../include/linux/work= queue.h) =20 -use crate::{bindings, types::Opaque}; +use crate::{bindings, prelude::*, sync::LockClassKey, types::Opaque}; +use core::marker::PhantomData; =20 /// A kernel work queue. /// @@ -107,6 +132,219 @@ unsafe fn __enqueue(self, queue_work_on: F) -> Sel= f::EnqueueOutput F: FnOnce(*mut bindings::work_struct) -> bool; } =20 +/// Defines the method that should be called directly when a work item is = executed. +/// +/// This trait is implemented by `Pin>` and `Arc`, and is mainly= intended to be +/// implemented for smart pointer types. For your own structs, you would i= mplement [`WorkItem`] +/// instead. The `run` method on this trait will usually just perform the = appropriate +/// `container_of` translation and then call into the `run` method from th= e [`WorkItem`] trait. +/// +/// This trait is used when the `work_struct` field is defined using the [= `Work`] helper. +/// +/// # Safety +/// +/// Implementers must ensure that [`__enqueue`] uses a `work_struct` initi= alized with the [`run`] +/// method of this trait as the function pointer. +/// +/// [`__enqueue`]: RawWorkItem::__enqueue +/// [`run`]: WorkItemPointer::run +pub unsafe trait WorkItemPointer: RawWorkItem { + /// Run this work item. + /// + /// # Safety + /// + /// The provided `work_struct` pointer must originate from a previous = call to `__enqueue` where + /// the `queue_work_on` closure returned true, and the pointer must st= ill be valid. + unsafe extern "C" fn run(ptr: *mut bindings::work_struct); +} + +/// Defines the method that should be called when this work item is execut= ed. +/// +/// This trait is used when the `work_struct` field is defined using the [= `Work`] helper. +pub trait WorkItem { + /// The pointer type that this struct is wrapped in. This will typical= ly be `Arc` or + /// `Pin>`. + type Pointer: WorkItemPointer; + + /// The method that should be called when this work item is executed. + fn run(this: Self::Pointer); +} + +/// Links for a work item. +/// +/// This struct contains a function pointer to the `run` function from the= [`WorkItemPointer`] +/// trait, and defines the linked list pointers necessary to enqueue a wor= k item in a workqueue. +/// +/// Wraps the kernel's C `struct work_struct`. +/// +/// This is a helper type used to associate a `work_struct` with the [`Wor= kItem`] that uses it. +#[repr(transparent)] +pub struct Work { + work: Opaque, + _inner: PhantomData, +} + +// SAFETY: Kernel work items are usable from any thread. +// +// We do not need to constrain `T` since the work item does not actually c= ontain a `T`. +unsafe impl Send for Work {} +// SAFETY: Kernel work items are usable from any thread. +// +// We do not need to constrain `T` since the work item does not actually c= ontain a `T`. +unsafe impl Sync for Work {} + +impl Work { + /// Creates a new instance of [`Work`]. + #[inline] + #[allow(clippy::new_ret_no_self)] + pub fn new(key: &'static LockClassKey) -> impl PinInit + where + T: WorkItem, + { + // SAFETY: The `WorkItemPointer` implementation promises that `run= ` can be used as the work + // item function. + unsafe { + kernel::init::pin_init_from_closure(move |slot| { + let slot =3D Self::raw_get(slot); + bindings::__INIT_WORK_WITH_KEY(slot, Some(T::Pointer::run)= , false, key.as_ptr()); + Ok(()) + }) + } + } + + /// Get a pointer to the inner `work_struct`. + /// + /// # Safety + /// + /// The provided pointer must not be dangling and must be properly ali= gned. (But the memory + /// need not be initialized.) + #[inline] + pub unsafe fn raw_get(ptr: *const Self) -> *mut bindings::work_struct { + // SAFETY: The caller promises that the pointer is aligned and not= dangling. + // + // A pointer cast would also be ok due to `#[repr(transparent)]`. = We use `addr_of!` so that + // the compiler does not complain that the `work` field is unused. + unsafe { Opaque::raw_get(core::ptr::addr_of!((*ptr).work)) } + } +} + +/// Declares that a type has a [`Work`] field. +/// +/// The intended way of using this trait is via the [`impl_has_work!`] mac= ro. You can use the macro +/// like this: +/// +/// ```no_run +/// use kernel::prelude::*; +/// use kernel::workqueue::Work; +/// +/// struct MyWorkItem { +/// work_field: Work, +/// } +/// +/// impl_has_work! { +/// impl HasWork for MyWorkItem { self.work_field } +/// } +/// ``` +/// +/// Note that since the `Work` type is annotated with an id, you can have = several `work_struct` +/// fields by using a different id for each one. +/// +/// # Safety +/// +/// The [`OFFSET`] constant must be the offset of a field in Self of type = [`Work`]. The methods on +/// this trait must have exactly the behavior that the definitions given b= elow have. +/// +/// [`Work`]: Work +/// [`impl_has_work!`]: crate::impl_has_work +/// [`OFFSET`]: HasWork::OFFSET +pub unsafe trait HasWork { + /// The offset of the [`Work`] field. + /// + /// [`Work`]: Work + const OFFSET: usize; + + /// Returns the offset of the [`Work`] field. + /// + /// This method exists because the [`OFFSET`] constant cannot be acces= sed if the type is not Sized. + /// + /// [`Work`]: Work + /// [`OFFSET`]: HasWork::OFFSET + #[inline] + fn get_work_offset(&self) -> usize { + Self::OFFSET + } + + /// Returns a pointer to the [`Work`] field. + /// + /// # Safety + /// + /// The provided pointer must point at a valid struct of type `Self`. + /// + /// [`Work`]: Work + #[inline] + unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work { + // SAFETY: The caller promises that the pointer is valid. + unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work } + } + + /// Returns a pointer to the struct containing the [`Work`] fie= ld. + /// + /// # Safety + /// + /// The pointer must point at a [`Work`] field in a struct of t= ype `Self`. + /// + /// [`Work`]: Work + #[inline] + unsafe fn work_container_of(ptr: *mut Work) -> *mut Self + where + Self: Sized, + { + // SAFETY: The caller promises that the pointer points at a field = of the right type in the + // right kind of struct. + unsafe { (ptr as *mut u8).sub(Self::OFFSET) as *mut Self } + } +} + +/// Used to safely implement the [`HasWork`] trait. +/// +/// # Examples +/// +/// ``` +/// use kernel::sync::Arc; +/// +/// struct MyStruct { +/// work_field: Work, +/// } +/// +/// impl_has_work! { +/// impl HasWork for MyStruct { self.work_field } +/// } +/// ``` +/// +/// [`HasWork`]: HasWork +#[macro_export] +macro_rules! impl_has_work { + ($(impl$(<$($implarg:ident),*>)? + HasWork<$work_type:ty $(, $id:tt)?> + for $self:ident $(<$($selfarg:ident),*>)? + { self.$field:ident } + )*) =3D> {$( + // SAFETY: The implementation of `raw_get_work` only compiles if t= he field has the right + // type. + unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_ty= pe $(, $id)?> for $self $(<$($selfarg),*>)? { + const OFFSET: usize =3D $crate::offset_of!(Self, $field) as us= ize; + + #[inline] + unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workque= ue::Work<$work_type $(, $id)?> { + // SAFETY: The caller promises that the pointer is not dan= gling. + unsafe { + ::core::ptr::addr_of_mut!((*ptr).$field) + } + } + } + )*}; +} + /// Returns the system work queue (`system_wq`). /// /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU mult= i-threaded. There are --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 9E995EB64DC for ; Tue, 11 Jul 2023 09:49:40 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231720AbjGKJti (ORCPT ); Tue, 11 Jul 2023 05:49:38 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:38144 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231558AbjGKJtc (ORCPT ); Tue, 11 Jul 2023 05:49:32 -0400 Received: from mail-yb1-xb49.google.com (mail-yb1-xb49.google.com [IPv6:2607:f8b0:4864:20::b49]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 7C83EA9 for ; Tue, 11 Jul 2023 02:49:31 -0700 (PDT) Received: by mail-yb1-xb49.google.com with SMTP id 3f1490d57ef6-c4e77129acfso6680126276.3 for ; Tue, 11 Jul 2023 02:49:31 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689068970; x=1691660970; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=/EqMekonA8uGHFD/lDqj3wOWtQfGKVNTfQouXEykc8E=; b=IhDUOhT0+DvvMgAAceahZcV7aUb3Zv9bWU0qe0g6pEouMuHOgruEFQzK3tcCGz0fY0 dNS22UXL6tq2hBKNniRASmkbPF+d7fQXIRahB/BzW81ZQx4nJ09+2qAuZc7MquRblvcu B16dRYK5dohuej1KyH+5cySONL8YFRLl1Q4FqpPX0X8h3AiNYRFM0VgPDnlAdkr4qpm/ aO71pzpqHLppLt/f+32LBAs2DjfHYu5qKmdBH+7BtfMChJq6jooxLy9I1mphNkfG77LK IxnqMigeSRhV5KTLFgtb17TR6635l4Rc3+dg1lFsZhZiQHhaTjpgXH3XCCbgqJ6YFuCn pqOg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689068970; x=1691660970; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=/EqMekonA8uGHFD/lDqj3wOWtQfGKVNTfQouXEykc8E=; b=UM18nGpiVTkr8x3Hp02mkyUeP39xNULE7vfEbDQZrs7ZD29cvQYGMq22V1kvJ+RZkL oFA9D8CYtFyWHxDhC+jJOIOo7ynXcPkUKUgIDeRxi2jkMFUyuHz3KFiUfu2jff//mUZE MrswG0/Mwf/Wlk8abWLbp3omhx2bxfmtjYprlQlLqvPBu/+8HGxshxWZqAlCOdT0X30W dRdywX7pacnFp1yQR2JVJEgc7ej3/dssrFROHrUErDxxgUQ/Rd+X+knIvqVYdxQMLNEZ Rqw4HLv56dQRG0S7nor6Iw/pCAZT7wVk1BNwzpOFeBZMQTuURSPrQusauJp/VxjwWjSK mz8A== X-Gm-Message-State: ABy/qLagypgRP2Lpt8WMzX+Dju+Wme6inJjNnZVhI6Omj+FbvYYYCc6z swlDKpMrgUDHll2EBJlXN8jXUmH1y+1eFBE= X-Google-Smtp-Source: APBJJlHEHcRVDUW4+Y0GUJSVpFZcA3B0pSPwgs7AJhZbg/V8hUXtvAnY3gg+gxzZTCY2shizts2jw+x1sE8BMX0= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a25:cd09:0:b0:c6c:6122:5b69 with SMTP id d9-20020a25cd09000000b00c6c61225b69mr107979ybf.8.1689068970724; Tue, 11 Jul 2023 02:49:30 -0700 (PDT) Date: Tue, 11 Jul 2023 09:33:01 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-8-aliceryhl@google.com> Subject: [PATCH v3 7/9] rust: workqueue: implement `WorkItemPointer` for pointer types From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Martin Rodriguez Reboredo , Andreas Hindborg Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This implements the `WorkItemPointer` trait for the pointer types that you are likely to use the workqueue with. The `Arc` type is for reference counted objects, and the `Pin>` type is for objects where the caller has exclusive ownership of the object. Co-developed-by: Gary Guo Signed-off-by: Gary Guo Signed-off-by: Alice Ryhl Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Andreas Hindborg (Samsung) Reviewed-by: Benno Lossin --- v2 -> v3: * Use `cast_mut` to cast pointer in `impl RawWorkItem for Arc` * Add Reviewed-by from Martin, Andreas, Benno. rust/kernel/workqueue.rs | 97 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index a7c972bda0ed..e760040762bd 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -28,8 +28,10 @@ //! //! C header: [`include/linux/workqueue.h`](../../../../include/linux/work= queue.h) =20 -use crate::{bindings, prelude::*, sync::LockClassKey, types::Opaque}; +use crate::{bindings, prelude::*, sync::Arc, sync::LockClassKey, types::Op= aque}; +use alloc::boxed::Box; use core::marker::PhantomData; +use core::pin::Pin; =20 /// A kernel work queue. /// @@ -345,6 +347,99 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate:= :workqueue::Work<$work_typ )*}; } =20 +unsafe impl WorkItemPointer for Arc +where + T: WorkItem, + T: HasWork, +{ + unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { + // SAFETY: The `__enqueue` method always uses a `work_struct` stor= ed in a `Work`. + let ptr =3D ptr as *mut Work; + // SAFETY: This computes the pointer that `__enqueue` got from `Ar= c::into_raw`. + let ptr =3D unsafe { T::work_container_of(ptr) }; + // SAFETY: This pointer comes from `Arc::into_raw` and we've been = given back ownership. + let arc =3D unsafe { Arc::from_raw(ptr) }; + + T::run(arc) + } +} + +unsafe impl RawWorkItem for Arc +where + T: WorkItem, + T: HasWork, +{ + type EnqueueOutput =3D Result<(), Self>; + + unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput + where + F: FnOnce(*mut bindings::work_struct) -> bool, + { + // Casting between const and mut is not a problem as long as the p= ointer is a raw pointer. + let ptr =3D Arc::into_raw(self).cast_mut(); + + // SAFETY: Pointers into an `Arc` point at a valid value. + let work_ptr =3D unsafe { T::raw_get_work(ptr) }; + // SAFETY: `raw_get_work` returns a pointer to a valid value. + let work_ptr =3D unsafe { Work::raw_get(work_ptr) }; + + if queue_work_on(work_ptr) { + Ok(()) + } else { + // SAFETY: The work queue has not taken ownership of the point= er. + Err(unsafe { Arc::from_raw(ptr) }) + } + } +} + +unsafe impl WorkItemPointer for Pin> +where + T: WorkItem, + T: HasWork, +{ + unsafe extern "C" fn run(ptr: *mut bindings::work_struct) { + // SAFETY: The `__enqueue` method always uses a `work_struct` stor= ed in a `Work`. + let ptr =3D ptr as *mut Work; + // SAFETY: This computes the pointer that `__enqueue` got from `Ar= c::into_raw`. + let ptr =3D unsafe { T::work_container_of(ptr) }; + // SAFETY: This pointer comes from `Arc::into_raw` and we've been = given back ownership. + let boxed =3D unsafe { Box::from_raw(ptr) }; + // SAFETY: The box was already pinned when it was enqueued. + let pinned =3D unsafe { Pin::new_unchecked(boxed) }; + + T::run(pinned) + } +} + +unsafe impl RawWorkItem for Pin> +where + T: WorkItem, + T: HasWork, +{ + type EnqueueOutput =3D (); + + unsafe fn __enqueue(self, queue_work_on: F) -> Self::EnqueueOutput + where + F: FnOnce(*mut bindings::work_struct) -> bool, + { + // SAFETY: We're not going to move `self` or any of its fields, so= its okay to temporarily + // remove the `Pin` wrapper. + let boxed =3D unsafe { Pin::into_inner_unchecked(self) }; + let ptr =3D Box::into_raw(boxed); + + // SAFETY: Pointers into a `Box` point at a valid value. + let work_ptr =3D unsafe { T::raw_get_work(ptr) }; + // SAFETY: `raw_get_work` returns a pointer to a valid value. + let work_ptr =3D unsafe { Work::raw_get(work_ptr) }; + + if !queue_work_on(work_ptr) { + // SAFETY: This method requires exclusive ownership of the box= , so it cannot be in a + // workqueue. + unsafe { ::core::hint::unreachable_unchecked() } + } + } +} + /// Returns the system work queue (`system_wq`). /// /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU mult= i-threaded. There are --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 5901EC001B0 for ; Tue, 11 Jul 2023 09:51:48 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S231784AbjGKJvr (ORCPT ); Tue, 11 Jul 2023 05:51:47 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:39980 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S231439AbjGKJvo (ORCPT ); Tue, 11 Jul 2023 05:51:44 -0400 Received: from mail-ed1-x54a.google.com (mail-ed1-x54a.google.com [IPv6:2a00:1450:4864:20::54a]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id 599ADA9 for ; Tue, 11 Jul 2023 02:51:42 -0700 (PDT) Received: by mail-ed1-x54a.google.com with SMTP id 4fb4d7f45d1cf-51e2497eeefso3588521a12.3 for ; Tue, 11 Jul 2023 02:51:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689069101; x=1691661101; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=zbG7B9nIgqjfOv4qsNLCa5ebcFdm5P+XcawO//zctYU=; b=7Xc/ddVUS0wM3GZO2B4AprynVg9zdVzLcyIeszTINkZEhMbnLLiUtLRsb31FPVbX+v reQxDAqLJm+3phY6MBudaf4zuQd3YTfi3efTF+dNuZZPIMi/HvDNP4c9t15xV+K4FS8g bPzRHP1jHv7jqqPKvzwHsdoUsaCbRef/eh2j0FzqjsqyDcUO58KAGbPPrzd6DCPoqkZq L96g8upUP6Gt22M0M29/DcrWSC4naOOb1Png3Bexwc5Jat8/ZKWqUtvKMqIktDrjeDB7 3pMGuxOJDNc9X/dC13LsiOoPu86DyMohr6aEJhuJwhn+ud67Cv5yGn7RgjgL3hmjY1NS dCVA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689069101; x=1691661101; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=zbG7B9nIgqjfOv4qsNLCa5ebcFdm5P+XcawO//zctYU=; b=EJ/BvM2c0tFHhCxjtpIgK4LzRdX795klQTbAAF9IKloekHPJP/8hxYnNqSkoJZyMIo j/oHMb1zIP38Ct+f0AXtCCt76Z5/0qDLjJeuCLjmHkFLXjjTsvLRRJD2LA2uZDFN4er2 wVuwVJVAEI3lFL/chvB+rUCzENmVXPFEwZ2XY5KbaBpHs26WdlPvJybInwx52W0c38tA Pup754vW6G7VE7O5v5gSjvWx5wO63bvP4cN2ZGl4I+PWMkzkizMi8jtrtLa6ts99PczH eTLxrIBS73OkyGb0pTFFITlxku7vy4tHsYQ9Sw4IikgFs+q7i9z7nhHkjFlGJfdJeNVZ RrCA== X-Gm-Message-State: ABy/qLb4Z6okQWxy7QgdJZcsKgSJxztBs/HZ4VSjkM3jSnOAG/DH+9qy AH5ttYuUqo6kg2r5YLFbGdq8n9+Eiud5NSs= X-Google-Smtp-Source: APBJJlE4smX4x/n67nbfyh8iudWSD9Gcs4zDhbXl2mIlHlCvPXFVOvfDZHgJiam+NfqpPVdh/Liaa42mYVELhI4= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a50:cd0f:0:b0:51b:e4c5:547c with SMTP id z15-20020a50cd0f000000b0051be4c5547cmr79456edi.4.1689069100681; Tue, 11 Jul 2023 02:51:40 -0700 (PDT) Date: Tue, 11 Jul 2023 09:33:02 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-9-aliceryhl@google.com> Subject: [PATCH v3 8/9] rust: workqueue: add `try_spawn` helper method From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Martin Rodriguez Reboredo , Andreas Hindborg Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This adds a convenience method that lets you spawn a closure for execution on a workqueue. This will be the most convenient way to use workqueues, but it is fallible because it needs to allocate memory. Co-developed-by: Gary Guo Signed-off-by: Gary Guo Signed-off-by: Alice Ryhl Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Andreas Hindborg (Samsung) Reviewed-by: Benno Lossin --- v2 -> v3: * Use a LockClassKey when constructing `ClosureWork`. * Add Reviewed-by from Martin, Andreas, Benno. rust/kernel/workqueue.rs | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index e760040762bd..3a3a8b52bfd9 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -29,6 +29,7 @@ //! C header: [`include/linux/workqueue.h`](../../../../include/linux/work= queue.h) =20 use crate::{bindings, prelude::*, sync::Arc, sync::LockClassKey, types::Op= aque}; +use alloc::alloc::AllocError; use alloc::boxed::Box; use core::marker::PhantomData; use core::pin::Pin; @@ -87,6 +88,44 @@ pub fn enqueue(&self, w: W) -> W::Enqu= eueOutput }) } } + + /// Tries to spawn the given function or closure as a work item. + /// + /// This method can fail because it allocates memory to store the work= item. + pub fn try_spawn(&self, func: T) -> Resu= lt<(), AllocError> { + let init =3D pin_init!(ClosureWork { + work <- Work::new(kernel::static_lock_class!()), + func: Some(func), + }); + + self.enqueue(Box::pin_init(init).map_err(|_| AllocError)?); + Ok(()) + } +} + +/// A helper type used in `try_spawn`. +#[pin_data] +struct ClosureWork { + #[pin] + work: Work>, + func: Option, +} + +impl ClosureWork { + fn project(self: Pin<&mut Self>) -> &mut Option { + // SAFETY: The `func` field is not structurally pinned. + unsafe { &mut self.get_unchecked_mut().func } + } +} + +impl WorkItem for ClosureWork { + type Pointer =3D Pin>; + + fn run(mut this: Pin>) { + if let Some(func) =3D this.as_mut().project().take() { + (func)() + } + } } =20 /// A raw work item. @@ -347,6 +386,10 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate:= :workqueue::Work<$work_typ )*}; } =20 +impl_has_work! { + impl HasWork for ClosureWork { self.work } +} + unsafe impl WorkItemPointer for Arc where T: WorkItem, --=20 2.41.0.255.g8b1d071c50-goog From nobody Sun Feb 8 08:43:01 2026 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 vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id C01B7C0015E for ; Tue, 11 Jul 2023 09:56:55 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S230361AbjGKJ4y (ORCPT ); Tue, 11 Jul 2023 05:56:54 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:42536 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S229890AbjGKJ4t (ORCPT ); Tue, 11 Jul 2023 05:56:49 -0400 Received: from mail-yw1-x1149.google.com (mail-yw1-x1149.google.com [IPv6:2607:f8b0:4864:20::1149]) by lindbergh.monkeyblade.net (Postfix) with ESMTPS id C4667A1 for ; Tue, 11 Jul 2023 02:56:48 -0700 (PDT) Received: by mail-yw1-x1149.google.com with SMTP id 00721157ae682-5707177ff8aso61162887b3.2 for ; Tue, 11 Jul 2023 02:56:48 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20221208; t=1689069408; x=1691661408; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=WVqEtgaoR84mlWb1xo2bD1CrEq4VPJW4ZXsIrXT2SxY=; b=JiS7r4oSjpoYeZAQokPiDZbRIRNXbzoWPZL7NF+5rzbH6mH2Rcy5+beBc9ND3C54Cz Aus5Cg913qXuDxwKJCGdRWmHr05KJU0rJAHeg88AZD7kauK/bKXdTeDKY4hHqsiAXQQL giwWgikoRtreQUO/DBn4FxwrAoqmcTXpHQalZUi4p2Udagcl0C2V8fzJ4YAZqbRHjs39 J4t57iEQpS8/MHp0zwe9jwefzUlWJejQ8XzKTLzsg3oq45gSz8Ajf7nQvIF4XLItT28/ qIgL6zZDPEwioH0kLhbOCQCI7+NjZMZFYtDBdbaMW78mZpZzOwkCwthKHdajV8J2epzt 5zxA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20221208; t=1689069408; x=1691661408; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=WVqEtgaoR84mlWb1xo2bD1CrEq4VPJW4ZXsIrXT2SxY=; b=dE808fUW3KNq1mRx1MIHhP0KnUoc6AIUEb/XO4mSOJw0XM0EZFYgEMNKbJscV20UpW m2aw6/mgdYGH43ZwpT5byV2OK2EH7PmbtvrfNMi8s30kT9wv7KRehkL+Jzn3mSAztsPG UOHFdcyD1hMVBWC86GyPi+7V43Hw7BznCx+Ii/XIHTA1V1AufvNjruw37TVAdJyD5Qws Pu/VwQuqv7pRbt9O+wtKf3E6IlNkV/uN46lvSa5wvJGsn2QtYR0/sAIzHvv6JfUc5BQq GGW3eatd2Id6xWVSi5AaccUUkynJQRO8O8eKwfbHb7q9dKWw3Ax4tM2dDnC0CE8xorvX iRCw== X-Gm-Message-State: ABy/qLY4wnmtodj8AxEGqVAf6WwjTNCLImAgw6cQr5f1ots6j35fyiur sYrHJ9B2SEK1UWBzUnHSLsENsFhjSjAOVQQ= X-Google-Smtp-Source: APBJJlFwdJ2E18U3JX8SbmAFB8eni9sLplKZ6ovLgHTWvsced2a62emZj0SesAoyMkw4Bdoxegyik2qJMVn43mc= X-Received: from aliceryhl.c.googlers.com ([fda3:e722:ac3:cc00:31:98fb:c0a8:6c8]) (user=aliceryhl job=sendgmr) by 2002:a81:764f:0:b0:57a:141f:b4f5 with SMTP id j15-20020a81764f000000b0057a141fb4f5mr139132ywk.7.1689069408101; Tue, 11 Jul 2023 02:56:48 -0700 (PDT) Date: Tue, 11 Jul 2023 09:33:03 +0000 In-Reply-To: <20230711093303.1433770-1-aliceryhl@google.com> Mime-Version: 1.0 References: <20230711093303.1433770-1-aliceryhl@google.com> X-Mailer: git-send-email 2.41.0.255.g8b1d071c50-goog Message-ID: <20230711093303.1433770-10-aliceryhl@google.com> Subject: [PATCH v3 9/9] rust: workqueue: add examples From: Alice Ryhl To: rust-for-linux@vger.kernel.org, Tejun Heo , Miguel Ojeda Cc: Lai Jiangshan , Wedson Almeida Filho , Alex Gaynor , Boqun Feng , Gary Guo , "=?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?=" , Benno Lossin , Alice Ryhl , linux-kernel@vger.kernel.org, patches@lists.linux.dev, Martin Rodriguez Reboredo , Andreas Hindborg Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" This adds two examples of how to use the workqueue. The first example shows how to use it when you only have one `work_struct` field, and the second example shows how to use it when you have multiple `work_struct` fields. Signed-off-by: Alice Ryhl Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Gary Guo Reviewed-by: Andreas Hindborg (Samsung) Reviewed-by: Benno Lossin --- v2 -> v3: * Use LockClassKey in constructors in examples. * Add Reviewed-by from Martin, Gary, Andreas, Benno. rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 3a3a8b52bfd9..482d3eeae7d8 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -26,6 +26,110 @@ //! * The `WorkItemPointer` trait is implemented for the pointer type tha= t points at a something //! that implements `WorkItem`. //! +//! ## Example +//! +//! This example defines a struct that holds an integer and can be schedul= ed on the workqueue. When +//! the struct is executed, it will print the integer. Since there is only= one `work_struct` field, +//! we do not need to specify ids for the fields. +//! +//! ``` +//! use kernel::prelude::*; +//! use kernel::sync::Arc; +//! use kernel::workqueue::{self, Work, WorkItem}; +//! +//! #[pin_data] +//! struct MyStruct { +//! value: i32, +//! #[pin] +//! work: Work, +//! } +//! +//! impl_has_work! { +//! impl HasWork for MyStruct { self.work } +//! } +//! +//! impl MyStruct { +//! fn new(value: i32) -> Result> { +//! Arc::pin_init(pin_init!(MyStruct { +//! value, +//! work <- Work::new(kernel::static_lock_class!()), +//! })) +//! } +//! } +//! +//! impl WorkItem for MyStruct { +//! type Pointer =3D Arc; +//! +//! fn run(this: Arc) { +//! pr_info!("The value is: {}", this.value); +//! } +//! } +//! +//! /// This method will enqueue the struct for execution on the system wo= rkqueue, where its value +//! /// will be printed. +//! fn print_later(val: Arc) { +//! let _ =3D workqueue::system().enqueue(val); +//! } +//! ``` +//! +//! The following example shows how multiple `work_struct` fields can be u= sed: +//! +//! ``` +//! use kernel::prelude::*; +//! use kernel::sync::Arc; +//! use kernel::workqueue::{self, Work, WorkItem}; +//! +//! #[pin_data] +//! struct MyStruct { +//! value_1: i32, +//! value_2: i32, +//! #[pin] +//! work_1: Work, +//! #[pin] +//! work_2: Work, +//! } +//! +//! impl_has_work! { +//! impl HasWork for MyStruct { self.work_1 } +//! impl HasWork for MyStruct { self.work_2 } +//! } +//! +//! impl MyStruct { +//! fn new(value_1: i32, value_2: i32) -> Result> { +//! Arc::pin_init(pin_init!(MyStruct { +//! value_1, +//! value_2, +//! work_1 <- Work::new(kernel::static_lock_class!()), +//! work_2 <- Work::new(kernel::static_lock_class!()), +//! })) +//! } +//! } +//! +//! impl WorkItem<1> for MyStruct { +//! type Pointer =3D Arc; +//! +//! fn run(this: Arc) { +//! pr_info!("The value is: {}", this.value_1); +//! } +//! } +//! +//! impl WorkItem<2> for MyStruct { +//! type Pointer =3D Arc; +//! +//! fn run(this: Arc) { +//! pr_info!("The second value is: {}", this.value_2); +//! } +//! } +//! +//! fn print_1_later(val: Arc) { +//! let _ =3D workqueue::system().enqueue::, 1>(val); +//! } +//! +//! fn print_2_later(val: Arc) { +//! let _ =3D workqueue::system().enqueue::, 2>(val); +//! } +//! ``` +//! //! C header: [`include/linux/workqueue.h`](../../../../include/linux/work= queue.h) =20 use crate::{bindings, prelude::*, sync::Arc, sync::LockClassKey, types::Op= aque}; --=20 2.41.0.255.g8b1d071c50-goog