patches.lists.linux.dev archive mirror
 help / color / mirror / Atom feed
* [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue
@ 2023-06-01 13:49 Alice Ryhl
  2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
                   ` (7 more replies)
  0 siblings, 8 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches

This patchset contains bindings for the kernel workqueue.

One of the primary goals behind the design used in this patch is that we
must support embedding the `work_struct` as a field in user-provided
types, because this allows you to submit things to the workqueue without
having to allocate, making the submission infallible. If we didn't have
to support this, then the patch would be much simpler. One of the main
things that make it complicated is that we must ensure that the function
pointer in the `work_struct` is compatible with the struct it is
contained within.

The original version of the workqueue bindings was written by Wedson,
but I have rewritten much of it so that it uses the pin-init
infrastructure and can be used with containers other than `Arc`.

Changes since v1:

Most of this patchset was rewritten based on Gary's example for how
field projections can be used with the workqueue.

I have also added some examples of how the workqueue bindings will be
used. You can find those in the last patch of this patchset.

v1: https://lore.kernel.org/all/20230517203119.3160435-1-aliceryhl@google.com/

Alice Ryhl (5):
  rust: workqueue: add low-level workqueue bindings
  rust: workqueue: add helper for defining work_struct fields
  rust: workqueue: implement `WorkItemPointer` for pointer types
  rust: workqueue: add `try_spawn` helper method
  rust: workqueue: add examples

Wedson Almeida Filho (3):
  rust: add offset_of! macro
  rust: sync: add `Arc::{from_raw, into_raw}`
  rust: workqueue: define built-in queues

 rust/bindings/bindings_helper.h |   1 +
 rust/helpers.c                  |   8 +
 rust/kernel/lib.rs              |  37 ++
 rust/kernel/sync/arc.rs         |  42 ++-
 rust/kernel/workqueue.rs        | 631 ++++++++++++++++++++++++++++++++
 scripts/Makefile.build          |   2 +-
 6 files changed, 719 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/workqueue.rs


base-commit: d09a61024f6b78c6a08892fc916cdafd87b50365
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply	[flat|nested] 53+ messages in thread

* [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 14:29   ` Martin Rodriguez Reboredo
                     ` (3 more replies)
  2023-06-01 13:49 ` [PATCH v2 2/8] rust: add offset_of! macro Alice Ryhl
                   ` (6 subsequent siblings)
  7 siblings, 4 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches

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 <gary@garyguo.net>
Signed-off-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/lib.rs              |   1 +
 rust/kernel/workqueue.rs        | 107 ++++++++++++++++++++++++++++++++
 3 files changed, 109 insertions(+)
 create mode 100644 rust/kernel/workqueue.rs

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 50e7a76d5455..ae2e8f018268 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -10,6 +10,7 @@
 #include <linux/refcount.h>
 #include <linux/wait.h>
 #include <linux/sched.h>
+#include <linux/workqueue.h>
 
 /* `bindgen` gets confused at certain things. */
 const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL;
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 85b261209977..eaded02ffb01 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -43,6 +43,7 @@
 pub mod sync;
 pub mod task;
 pub mod types;
+pub mod workqueue;
 
 #[doc(hidden)]
 pub use bindings;
diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
new file mode 100644
index 000000000000..9c630840039b
--- /dev/null
+++ b/rust/kernel/workqueue.rs
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Work queues.
+//!
+//! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.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 the kernel. Several are
+/// always available, for example, `system`, `system_highpri`, `system_long`, etc.
+#[repr(transparent)]
+pub struct Queue(Opaque<bindings::workqueue_struct>);
+
+// 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 dangling, 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 pointer 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<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
+    where
+        W: RawWorkItem<ID> + Send + 'static,
+    {
+        let queue_ptr = 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` and static.
+        //
+        // The call to `bindings::queue_work_on` will dereference the provided 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 that the raw pointer will
+        // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
+        unsafe {
+            w.__enqueue(move |work_ptr| {
+                bindings::queue_work_on(bindings::WORK_CPU_UNBOUND as _, queue_ptr, work_ptr)
+            })
+        }
+    }
+}
+
+/// A raw work item.
+///
+/// This is the low-level trait that is designed for being as general as possible.
+///
+/// The `ID` parameter to this trait exists so that a single type can provide 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 id for each field. The
+/// actual value of the id is not important as long as you use different ids for different fields
+/// of the same struct. (Fields of different structs need not use different ids.)
+///
+/// Note that the id is used only to select the right method to call during 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 documentation for `__enqueue`.
+pub unsafe trait RawWorkItem<const ID: u64> {
+    /// 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. If 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 must not call the function
+    /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
+    ///
+    /// If the work item type is not [`Send`], then the function pointer must be called on the same
+    /// thread as the call to `__enqueue`.
+    unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
+    where
+        F: FnOnce(*mut bindings::work_struct) -> bool;
+}
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* [PATCH v2 2/8] rust: add offset_of! macro
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
  2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 17:17   ` Gary Guo
                     ` (2 more replies)
  2023-06-01 13:49 ` [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}` Alice Ryhl
                   ` (5 subsequent siblings)
  7 siblings, 3 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo

From: Wedson Almeida Filho <walmeida@microsoft.com>

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<SubStruct>`, 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 <walmeida@microsoft.com>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
---
 rust/kernel/lib.rs     | 35 +++++++++++++++++++++++++++++++++++
 scripts/Makefile.build |  2 +-
 2 files changed, 36 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index eaded02ffb01..7ea777b731e6 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)]
@@ -98,3 +99,37 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
     // instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
     loop {}
 }
+
+/// Calculates the offset of a field from the beginning of the struct it belongs 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) => {{
+        let $type { $field: _, .. };
+        let tmp = ::core::mem::MaybeUninit::<$type>::uninit();
+        let outer = 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 create an intermediate
+        // reference.
+        let inner = 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)
 # ---------------------------------------------------------------------------
 
-rust_allowed_features := new_uninit
+rust_allowed_features := const_refs_to_cell,new_uninit
 
 rust_common_cmd = \
 	RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
  2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
  2023-06-01 13:49 ` [PATCH v2 2/8] rust: add offset_of! macro Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 17:26   ` Gary Guo
                     ` (2 more replies)
  2023-06-01 13:49 ` [PATCH v2 4/8] rust: workqueue: define built-in queues Alice Ryhl
                   ` (4 subsequent siblings)
  7 siblings, 3 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo

From: Wedson Almeida Filho <walmeida@microsoft.com>

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 <walmeida@microsoft.com>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
---
 rust/kernel/lib.rs      |  1 +
 rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 42 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 7ea777b731e6..ad9142928fb1 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)]
 
diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
index a89843cacaad..684be9f73aca 100644
--- a/rust/kernel/sync/arc.rs
+++ b/rust/kernel/sync/arc.rs
@@ -24,7 +24,7 @@
 };
 use alloc::boxed::Box;
 use core::{
-    alloc::AllocError,
+    alloc::{AllocError, Layout},
     fmt,
     marker::{PhantomData, Unsize},
     mem::{ManuallyDrop, MaybeUninit},
@@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
         }
     }
 
+    /// 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 = 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
+    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
+    ///
+    /// # Safety
+    ///
+    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
+        // SAFETY: The caller guarantees that the pointer is valid.
+        let val_layout = unsafe { Layout::for_value(&*ptr) };
+        // SAFETY: We're computing the layout of a real struct that existed when compiling this
+        // binary, so its layout is not so large that it can trigger arithmetic overflow.
+        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
+
+        // This preserves the metadata in the pointer, if any.
+        //
+        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
+        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
+        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);
+        let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
+        let ptr = 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 [`ArcBorrow`] (e.g., in a method
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* [PATCH v2 4/8] rust: workqueue: define built-in queues
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
                   ` (2 preceding siblings ...)
  2023-06-01 13:49 ` [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}` Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 17:30   ` Gary Guo
                     ` (2 more replies)
  2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
                   ` (3 subsequent siblings)
  7 siblings, 3 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo

From: Wedson Almeida Filho <walmeida@microsoft.com>

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 <walmeida@microsoft.com>
Co-developed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
---
 rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 65 insertions(+)

diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
index 9c630840039b..e37820f253f6 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -105,3 +105,68 @@ unsafe fn __enqueue<F>(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 multi-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 which 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 running 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, and 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 freezable.
+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" variants 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_freezable_power_efficient_wq`).
+///
+/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
+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) }
+}
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
                   ` (3 preceding siblings ...)
  2023-06-01 13:49 ` [PATCH v2 4/8] rust: workqueue: define built-in queues Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 14:50   ` Martin Rodriguez Reboredo
                     ` (4 more replies)
  2023-06-01 13:49 ` [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types Alice Ryhl
                   ` (2 subsequent siblings)
  7 siblings, 5 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches

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<T, ID>`. If a type
implements this trait, then the type declares that, at the given offset,
there is a field of type `Work<T, ID>`. 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<T>` on a type.
The macro expands to something that only compiles if the specified field
really has the type `Work<T>`. It is used like this:

```
struct MyWorkItem {
    work_field: Work<MyWorkItem, 1>,
}

impl_has_work! {
    impl HasWork<MyWorkItem, 1> 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 <gary@garyguo.net>
Signed-off-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/helpers.c           |   8 ++
 rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++-
 2 files changed, 226 insertions(+), 1 deletion(-)

diff --git a/rust/helpers.c b/rust/helpers.c
index 81e80261d597..7f0c2fe2fbeb 100644
--- a/rust/helpers.c
+++ b/rust/helpers.c
@@ -26,6 +26,7 @@
 #include <linux/spinlock.h>
 #include <linux/sched/signal.h>
 #include <linux/wait.h>
+#include <linux/workqueue.h>
 
 __noreturn void rust_helper_BUG(void)
 {
@@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
 }
 EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
 
+void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
+			     bool on_stack)
+{
+	__INIT_WORK(work, func, on_stack);
+}
+EXPORT_SYMBOL_GPL(rust_helper___INIT_WORK);
+
 /*
  * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` type
  * 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 e37820f253f6..dbf0aab29a85 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -2,9 +2,34 @@
 
 //! 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 struct.) Since these IDs are
+//! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
+//!
+//! # The raw API
+//!
+//! The raw API consists of the `RawWorkItem` trait, where the work item needs 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. Furthermore, it also includes
+//! a trait called `WorkItemPointer`, which is usually not used directly by 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 enqueued to a workqueue.
+//!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
+//!    that implements `WorkItem`.
+//!
 //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
 
-use crate::{bindings, types::Opaque};
+use crate::{bindings, prelude::*, types::Opaque};
+use core::marker::{PhantomData, PhantomPinned};
 
 /// A kernel work queue.
 ///
@@ -106,6 +131,198 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
         F: FnOnce(*mut bindings::work_struct) -> bool;
 }
 
+/// Defines the method that should be called directly when a work item is executed.
+///
+/// Typically you would implement [`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 the [`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` initialized with the [`run`]
+/// method of this trait as the function pointer.
+///
+/// [`__enqueue`]: RawWorkItem::__enqueue
+/// [`run`]: WorkItemPointer::run
+pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
+    /// 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 still be valid.
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
+}
+
+/// Defines the method that should be called when this work item is executed.
+///
+/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
+pub trait WorkItem<const ID: u64 = 0> {
+    /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
+    /// `Pin<Box<Self>>`.
+    type Pointer: WorkItemPointer<ID>;
+
+    /// 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 work 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 [`WorkItem`] that uses it.
+#[repr(transparent)]
+pub struct Work<T: ?Sized, const ID: u64 = 0> {
+    work: Opaque<bindings::work_struct>,
+    _pin: PhantomPinned,
+    _inner: PhantomData<T>,
+}
+
+// SAFETY: Kernel work items are usable from any thread.
+//
+// We do not need to constrain `T` since the work item does not actually contain a `T`.
+unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
+// SAFETY: Kernel work items are usable from any thread.
+//
+// We do not need to constrain `T` since the work item does not actually contain a `T`.
+unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
+
+impl<T: ?Sized, const ID: u64> Work<T, ID> {
+    /// Creates a new instance of [`Work`].
+    #[inline]
+    #[allow(clippy::new_ret_no_self)]
+    pub fn new() -> impl PinInit<Self>
+    where
+        T: WorkItem<ID>,
+    {
+        // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work
+        // item function.
+        unsafe {
+            kernel::init::pin_init_from_closure(move |slot| {
+                bindings::__INIT_WORK(Self::raw_get(slot), Some(T::Pointer::run), false);
+                Ok(())
+            })
+        }
+    }
+
+    /// Get a pointer to the inner `work_struct`.
+    ///
+    /// # Safety
+    ///
+    /// The provided pointer must not be dangling and must be properly aligned. (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<T, ID>`] field.
+///
+/// # Safety
+///
+/// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
+/// this trait must have exactly the behavior that the definitions given below have.
+///
+/// [`Work<T, ID>`]: Work
+/// [`OFFSET`]: HasWork::OFFSET
+pub unsafe trait HasWork<T, const ID: u64 = 0> {
+    /// The offset of the [`Work<T, ID>`] field.
+    ///
+    /// [`Work<T, ID>`]: Work
+    const OFFSET: usize;
+
+    /// Returns the offset of the [`Work<T, ID>`] field.
+    ///
+    /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized.
+    ///
+    /// [`Work<T, ID>`]: Work
+    /// [`OFFSET`]: HasWork::OFFSET
+    #[inline]
+    fn get_work_offset(&self) -> usize {
+        Self::OFFSET
+    }
+
+    /// Returns a pointer to the [`Work<T, ID>`] field.
+    ///
+    /// # Safety
+    ///
+    /// The provided pointer must point at a valid struct of type `Self`.
+    ///
+    /// [`Work<T, ID>`]: Work
+    #[inline]
+    unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
+        // SAFETY: The caller promises that the pointer is valid.
+        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
+    }
+
+    /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
+    ///
+    /// # Safety
+    ///
+    /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
+    ///
+    /// [`Work<T, ID>`]: Work
+    #[inline]
+    unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *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<T, ID>`] trait.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::sync::Arc;
+///
+/// struct MyStruct {
+///     work_field: Work<MyStruct, 17>,
+/// }
+///
+/// impl_has_work! {
+///     impl HasWork<MyStruct, 17> for MyStruct { self.work_field }
+/// }
+/// ```
+///
+/// [`HasWork<T, ID>`]: 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 }
+    )*) => {$(
+        // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
+        // type.
+        unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? {
+            const OFFSET: usize = $crate::offset_of!(Self, $field) as usize;
+
+            #[inline]
+            unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
+                // SAFETY: The caller promises that the pointer is not dangling.
+                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 multi-threaded. There are
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
                   ` (4 preceding siblings ...)
  2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 14:51   ` Martin Rodriguez Reboredo
                     ` (2 more replies)
  2023-06-01 13:49 ` [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method Alice Ryhl
  2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
  7 siblings, 3 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches

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<Box<T>>` type is for objects
where the caller has exclusive ownership of the object.

Co-developed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 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 dbf0aab29a85..f06a2f036d8b 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -28,8 +28,10 @@
 //!
 //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
 
-use crate::{bindings, prelude::*, types::Opaque};
+use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
+use alloc::boxed::Box;
 use core::marker::{PhantomData, PhantomPinned};
+use core::pin::Pin;
 
 /// A kernel work queue.
 ///
@@ -323,6 +325,99 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ
     )*};
 }
 
+unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
+where
+    T: WorkItem<ID, Pointer = Self>,
+    T: HasWork<T, ID>,
+{
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
+        let ptr = ptr as *mut Work<T, ID>;
+        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
+        let ptr = unsafe { T::work_container_of(ptr) };
+        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
+        let arc = unsafe { Arc::from_raw(ptr) };
+
+        T::run(arc)
+    }
+}
+
+unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
+where
+    T: WorkItem<ID, Pointer = Self>,
+    T: HasWork<T, ID>,
+{
+    type EnqueueOutput = Result<(), Self>;
+
+    unsafe fn __enqueue<F>(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 pointer is a raw pointer.
+        let ptr = Arc::into_raw(self) as *mut T;
+
+        // SAFETY: Pointers into an `Arc` point at a valid value.
+        let work_ptr = unsafe { T::raw_get_work(ptr) };
+        // SAFETY: `raw_get_work` returns a pointer to a valid value.
+        let work_ptr = unsafe { Work::raw_get(work_ptr) };
+
+        if queue_work_on(work_ptr) {
+            Ok(())
+        } else {
+            // SAFETY: The work queue has not taken ownership of the pointer.
+            Err(unsafe { Arc::from_raw(ptr) })
+        }
+    }
+}
+
+unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
+where
+    T: WorkItem<ID, Pointer = Self>,
+    T: HasWork<T, ID>,
+{
+    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
+        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
+        let ptr = ptr as *mut Work<T, ID>;
+        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
+        let ptr = unsafe { T::work_container_of(ptr) };
+        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
+        let boxed = unsafe { Box::from_raw(ptr) };
+        // SAFETY: The box was already pinned when it was enqueued.
+        let pinned = unsafe { Pin::new_unchecked(boxed) };
+
+        T::run(pinned)
+    }
+}
+
+unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
+where
+    T: WorkItem<ID, Pointer = Self>,
+    T: HasWork<T, ID>,
+{
+    type EnqueueOutput = ();
+
+    unsafe fn __enqueue<F>(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 = unsafe { Pin::into_inner_unchecked(self) };
+        let ptr = Box::into_raw(boxed);
+
+        // SAFETY: Pointers into a `Box` point at a valid value.
+        let work_ptr = unsafe { T::raw_get_work(ptr) };
+        // SAFETY: `raw_get_work` returns a pointer to a valid value.
+        let work_ptr = 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 multi-threaded. There are
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
                   ` (5 preceding siblings ...)
  2023-06-01 13:49 ` [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 14:53   ` Martin Rodriguez Reboredo
                     ` (2 more replies)
  2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
  7 siblings, 3 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches

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 <gary@garyguo.net>
Signed-off-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
---
 rust/kernel/workqueue.rs | 43 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 43 insertions(+)

diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
index f06a2f036d8b..c302e8b8624b 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -29,6 +29,7 @@
 //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
 
 use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
+use alloc::alloc::AllocError;
 use alloc::boxed::Box;
 use core::marker::{PhantomData, PhantomPinned};
 use core::pin::Pin;
@@ -87,6 +88,44 @@ pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
             })
         }
     }
+
+    /// 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<T: 'static + Send + FnOnce()>(&self, func: T) -> Result<(), AllocError> {
+        let init = pin_init!(ClosureWork {
+            work <- Work::new(),
+            func: Some(func),
+        });
+
+        self.enqueue(Box::pin_init(init).map_err(|_| AllocError)?);
+        Ok(())
+    }
+}
+
+/// A helper type used in `try_spawn`.
+#[pin_data]
+struct ClosureWork<T> {
+    #[pin]
+    work: Work<ClosureWork<T>>,
+    func: Option<T>,
+}
+
+impl<T> ClosureWork<T> {
+    fn project(self: Pin<&mut Self>) -> &mut Option<T> {
+        // SAFETY: The `func` field is not structurally pinned.
+        unsafe { &mut self.get_unchecked_mut().func }
+    }
+}
+
+impl<T: FnOnce()> WorkItem for ClosureWork<T> {
+    type Pointer = Pin<Box<Self>>;
+
+    fn run(mut this: Pin<Box<Self>>) {
+        if let Some(func) = this.as_mut().project().take() {
+            (func)()
+        }
+    }
 }
 
 /// A raw work item.
@@ -325,6 +364,10 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ
     )*};
 }
 
+impl_has_work! {
+    impl<T> HasWork<Self> for ClosureWork<T> { self.work }
+}
+
 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
 where
     T: WorkItem<ID, Pointer = Self>,
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
                   ` (6 preceding siblings ...)
  2023-06-01 13:49 ` [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method Alice Ryhl
@ 2023-06-01 13:49 ` Alice Ryhl
  2023-06-01 14:58   ` Martin Rodriguez Reboredo
                     ` (4 more replies)
  7 siblings, 5 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-01 13:49 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, Alice Ryhl, linux-kernel, patches

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 <aliceryhl@google.com>
---
 rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)

diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
index c302e8b8624b..cefcf43ff40e 100644
--- a/rust/kernel/workqueue.rs
+++ b/rust/kernel/workqueue.rs
@@ -26,6 +26,110 @@
 //!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
 //!    that implements `WorkItem`.
 //!
+//! ## Example
+//!
+//! This example defines a struct that holds an integer and can be scheduled 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<MyStruct>,
+//! }
+//!
+//! impl_has_work! {
+//!     impl HasWork<Self> for MyStruct { self.work }
+//! }
+//!
+//! impl MyStruct {
+//!     fn new(value: i32) -> Result<Arc<Self>> {
+//!         Arc::pin_init(pin_init!(MyStruct {
+//!             value,
+//!             work <- Work::new(),
+//!         }))
+//!     }
+//! }
+//!
+//! impl WorkItem for MyStruct {
+//!     type Pointer = Arc<MyStruct>;
+//!
+//!     fn run(this: Arc<MyStruct>) {
+//!         pr_info!("The value is: {}", this.value);
+//!     }
+//! }
+//!
+//! /// This method will enqueue the struct for execution on the system workqueue, where its value
+//! /// will be printed.
+//! fn print_later(val: Arc<MyStruct>) {
+//!     let _ = workqueue::system().enqueue(val);
+//! }
+//! ```
+//!
+//! The following example shows how multiple `work_struct` fields can be used:
+//!
+//! ```
+//! 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<MyStruct, 1>,
+//!     #[pin]
+//!     work_2: Work<MyStruct, 2>,
+//! }
+//!
+//! impl_has_work! {
+//!     impl HasWork<Self, 1> for MyStruct { self.work_1 }
+//!     impl HasWork<Self, 2> for MyStruct { self.work_2 }
+//! }
+//!
+//! impl MyStruct {
+//!     fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
+//!         Arc::pin_init(pin_init!(MyStruct {
+//!             value_1,
+//!             value_2,
+//!             work_1 <- Work::new(),
+//!             work_2 <- Work::new(),
+//!         }))
+//!     }
+//! }
+//!
+//! impl WorkItem<1> for MyStruct {
+//!     type Pointer = Arc<MyStruct>;
+//!
+//!     fn run(this: Arc<MyStruct>) {
+//!         pr_info!("The value is: {}", this.value_1);
+//!     }
+//! }
+//!
+//! impl WorkItem<2> for MyStruct {
+//!     type Pointer = Arc<MyStruct>;
+//!
+//!     fn run(this: Arc<MyStruct>) {
+//!         pr_info!("The second value is: {}", this.value_2);
+//!     }
+//! }
+//!
+//! fn print_1_later(val: Arc<MyStruct>) {
+//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
+//! }
+//!
+//! fn print_2_later(val: Arc<MyStruct>) {
+//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
+//! }
+//! ```
+//!
 //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
 
 use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
-- 
2.41.0.rc0.172.g3f132b7071-goog


^ permalink raw reply related	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
  2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
@ 2023-06-01 14:29   ` Martin Rodriguez Reboredo
  2023-06-02 14:39   ` Andreas Hindborg (Samsung)
                     ` (2 subsequent siblings)
  3 siblings, 0 replies; 53+ messages in thread
From: Martin Rodriguez Reboredo @ 2023-06-01 14:29 UTC (permalink / raw)
  To: Alice Ryhl, rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On 6/1/23 10:49, Alice Ryhl wrote:
> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
> [...]

My Reviewed-by is missing.

Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
@ 2023-06-01 14:50   ` Martin Rodriguez Reboredo
  2023-06-01 18:44   ` Boqun Feng
                     ` (3 subsequent siblings)
  4 siblings, 0 replies; 53+ messages in thread
From: Martin Rodriguez Reboredo @ 2023-06-01 14:50 UTC (permalink / raw)
  To: Alice Ryhl, rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On 6/1/23 10:49, Alice Ryhl wrote:
> 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<T, ID>`. If a type
> implements this trait, then the type declares that, at the given offset,
> there is a field of type `Work<T, ID>`. 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<T>` on a type.
> The macro expands to something that only compiles if the specified field
> really has the type `Work<T>`. It is used like this:
> 
> ```
> struct MyWorkItem {
>      work_field: Work<MyWorkItem, 1>,
> }
> 
> impl_has_work! {
>      impl HasWork<MyWorkItem, 1> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
> [...]

Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types
  2023-06-01 13:49 ` [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types Alice Ryhl
@ 2023-06-01 14:51   ` Martin Rodriguez Reboredo
  2023-06-02 14:42   ` Andreas Hindborg (Samsung)
  2023-06-11 16:01   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Martin Rodriguez Reboredo @ 2023-06-01 14:51 UTC (permalink / raw)
  To: Alice Ryhl, rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On 6/1/23 10:49, Alice Ryhl wrote:
> 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<Box<T>>` type is for objects
> where the caller has exclusive ownership of the object.
> 
> Co-developed-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
> [...]

Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method
  2023-06-01 13:49 ` [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method Alice Ryhl
@ 2023-06-01 14:53   ` Martin Rodriguez Reboredo
  2023-06-02 14:43   ` Andreas Hindborg (Samsung)
  2023-06-11 16:10   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Martin Rodriguez Reboredo @ 2023-06-01 14:53 UTC (permalink / raw)
  To: Alice Ryhl, rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On 6/1/23 10:49, Alice Ryhl wrote:
> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
> [...]

Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
@ 2023-06-01 14:58   ` Martin Rodriguez Reboredo
  2023-06-01 17:32   ` Gary Guo
                     ` (3 subsequent siblings)
  4 siblings, 0 replies; 53+ messages in thread
From: Martin Rodriguez Reboredo @ 2023-06-01 14:58 UTC (permalink / raw)
  To: Alice Ryhl, rust-for-linux
  Cc: Miguel Ojeda, Wedson Almeida Filho, Tejun Heo, Lai Jiangshan,
	Alex Gaynor, Boqun Feng, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On 6/1/23 10:49, Alice Ryhl wrote:
> 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 <aliceryhl@google.com>
> ---
> [...]

Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 2/8] rust: add offset_of! macro
  2023-06-01 13:49 ` [PATCH v2 2/8] rust: add offset_of! macro Alice Ryhl
@ 2023-06-01 17:17   ` Gary Guo
  2023-06-02 10:33   ` Andreas Hindborg (Samsung)
  2023-06-11 15:47   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Gary Guo @ 2023-06-01 17:17 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches, Wedson Almeida Filho,
	Martin Rodriguez Reboredo

On Thu,  1 Jun 2023 13:49:40 +0000
Alice Ryhl <aliceryhl@google.com> wrote:

> From: Wedson Almeida Filho <walmeida@microsoft.com>
> 
> 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<SubStruct>`, 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

Reviewed-by: Gary Guo <gary@garyguo.net>

> ---
>  rust/kernel/lib.rs     | 35 +++++++++++++++++++++++++++++++++++
>  scripts/Makefile.build |  2 +-
>  2 files changed, 36 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index eaded02ffb01..7ea777b731e6 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)]
> @@ -98,3 +99,37 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
>      // instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
>      loop {}
>  }
> +
> +/// Calculates the offset of a field from the beginning of the struct it belongs 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) => {{
> +        let $type { $field: _, .. };
> +        let tmp = ::core::mem::MaybeUninit::<$type>::uninit();
> +        let outer = 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 create an intermediate
> +        // reference.
> +        let inner = 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)
>  # ---------------------------------------------------------------------------
>  
> -rust_allowed_features := new_uninit
> +rust_allowed_features := const_refs_to_cell,new_uninit
>  
>  rust_common_cmd = \
>  	RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-01 13:49 ` [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}` Alice Ryhl
@ 2023-06-01 17:26   ` Gary Guo
  2023-06-02 10:51   ` Andreas Hindborg (Samsung)
  2023-06-11 15:48   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Gary Guo @ 2023-06-01 17:26 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches, Wedson Almeida Filho,
	Martin Rodriguez Reboredo

On Thu,  1 Jun 2023 13:49:41 +0000
Alice Ryhl <aliceryhl@google.com> wrote:

> From: Wedson Almeida Filho <walmeida@microsoft.com>
> 
> 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

Reviewed-by: Gary Guo <gary@garyguo.net>

> ---
>  rust/kernel/lib.rs      |  1 +
>  rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
>  2 files changed, 42 insertions(+), 1 deletion(-)

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
  2023-06-01 13:49 ` [PATCH v2 4/8] rust: workqueue: define built-in queues Alice Ryhl
@ 2023-06-01 17:30   ` Gary Guo
  2023-06-01 17:52     ` Martin Rodriguez Reboredo
  2023-06-02  8:32     ` Alice Ryhl
  2023-06-02 14:46   ` Andreas Hindborg (Samsung)
  2023-06-11 15:49   ` Benno Lossin
  2 siblings, 2 replies; 53+ messages in thread
From: Gary Guo @ 2023-06-01 17:30 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches, Wedson Almeida Filho,
	Martin Rodriguez Reboredo

On Thu,  1 Jun 2023 13:49:42 +0000
Alice Ryhl <aliceryhl@google.com> wrote:

> From: Wedson Almeida Filho <walmeida@microsoft.com>
> 
> 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

This looks fine to me, so:

Reviewed-by: Gary Guo <gary@garyguo.net>

Just one question about style: would people prefer:

	kernel::workqueue::system().enqueue(...)

or

	use kernel::workqueue::Queue;
	Queue::system().enqueue(...)

?

> ---
>  rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 65 insertions(+)
> 
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index 9c630840039b..e37820f253f6 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -105,3 +105,68 @@ unsafe fn __enqueue<F>(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 multi-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 which 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 running 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, and 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 freezable.
> +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" variants 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_freezable_power_efficient_wq`).
> +///
> +/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
> +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) }
> +}


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
  2023-06-01 14:58   ` Martin Rodriguez Reboredo
@ 2023-06-01 17:32   ` Gary Guo
  2023-06-02  9:39     ` Alice Ryhl
  2023-06-02 14:44   ` Andreas Hindborg (Samsung)
                     ` (2 subsequent siblings)
  4 siblings, 1 reply; 53+ messages in thread
From: Gary Guo @ 2023-06-01 17:32 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On Thu,  1 Jun 2023 13:49:46 +0000
Alice Ryhl <aliceryhl@google.com> wrote:

> 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 <aliceryhl@google.com>
> ---
>  rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++
>  1 file changed, 104 insertions(+)
> 
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index c302e8b8624b..cefcf43ff40e 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -26,6 +26,110 @@
>  //!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
>  //!    that implements `WorkItem`.
>  //!
> +//! ## Example
> +//!
> +//! This example defines a struct that holds an integer and can be scheduled 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<MyStruct>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self> for MyStruct { self.work }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value,
> +//!             work <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value);
> +//!     }
> +//! }
> +//!
> +//! /// This method will enqueue the struct for execution on the system workqueue, where its value
> +//! /// will be printed.
> +//! fn print_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue(val);
> +//! }
> +//! ```
> +//!
> +//! The following example shows how multiple `work_struct` fields can be used:
> +//!
> +//! ```
> +//! 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<MyStruct, 1>,
> +//!     #[pin]
> +//!     work_2: Work<MyStruct, 2>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self, 1> for MyStruct { self.work_1 }
> +//!     impl HasWork<Self, 2> for MyStruct { self.work_2 }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value_1,
> +//!             value_2,
> +//!             work_1 <- Work::new(),
> +//!             work_2 <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<1> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value_1);
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<2> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The second value is: {}", this.value_2);
> +//!     }
> +//! }
> +//!
> +//! fn print_1_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);

Nothing bad about explicit, but I just want to confirm that you could
write

	let _ = workqueue::system().enqueue::<_, 1>(val);

here, right?

Reviewed-by: Gary Guo <gary@garyguo.net>

> +//! }
> +//!
> +//! fn print_2_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
> +//! }
> +//! ```
> +//!
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
>  use crate::{bindings, prelude::*, sync::Arc, types::Opaque};


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
  2023-06-01 17:30   ` Gary Guo
@ 2023-06-01 17:52     ` Martin Rodriguez Reboredo
  2023-06-02  8:32     ` Alice Ryhl
  1 sibling, 0 replies; 53+ messages in thread
From: Martin Rodriguez Reboredo @ 2023-06-01 17:52 UTC (permalink / raw)
  To: Gary Guo, Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches, Wedson Almeida Filho

On 6/1/23 14:30, Gary Guo wrote:
> On Thu,  1 Jun 2023 13:49:42 +0000
> Alice Ryhl <aliceryhl@google.com> wrote:
> 
>> From: Wedson Almeida Filho <walmeida@microsoft.com>
>>
>> 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 <walmeida@microsoft.com>
>> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
>> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
>> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
> 
> This looks fine to me, so:
> 
> Reviewed-by: Gary Guo <gary@garyguo.net>
> 
> Just one question about style: would people prefer:
> 
> 	kernel::workqueue::system().enqueue(...)
> 
> or
> 
> 	use kernel::workqueue::Queue;
> 	Queue::system().enqueue(...)
> 
> ?

I can compare the first with `std::thread::spawn` and the second
with enqueuing an executor with a future. Both makes sense to me so
I can't decide.

> [...]

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
  2023-06-01 14:50   ` Martin Rodriguez Reboredo
@ 2023-06-01 18:44   ` Boqun Feng
  2023-06-02  8:38     ` Alice Ryhl
  2023-06-01 21:09   ` Boqun Feng
                     ` (2 subsequent siblings)
  4 siblings, 1 reply; 53+ messages in thread
From: Boqun Feng @ 2023-06-01 18:44 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On Thu, Jun 01, 2023 at 01:49:43PM +0000, Alice Ryhl wrote:
> 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<T, ID>`. If a type
> implements this trait, then the type declares that, at the given offset,
> there is a field of type `Work<T, ID>`. 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<T>` on a type.
> The macro expands to something that only compiles if the specified field
> really has the type `Work<T>`. It is used like this:
> 
> ```
> struct MyWorkItem {
>     work_field: Work<MyWorkItem, 1>,
> }
> 
> impl_has_work! {
>     impl HasWork<MyWorkItem, 1> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
>  rust/helpers.c           |   8 ++
>  rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++-
>  2 files changed, 226 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/helpers.c b/rust/helpers.c
> index 81e80261d597..7f0c2fe2fbeb 100644
> --- a/rust/helpers.c
> +++ b/rust/helpers.c
> @@ -26,6 +26,7 @@
>  #include <linux/spinlock.h>
>  #include <linux/sched/signal.h>
>  #include <linux/wait.h>
> +#include <linux/workqueue.h>
>  
>  __noreturn void rust_helper_BUG(void)
>  {
> @@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
>  }
>  EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
>  
> +void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
> +			     bool on_stack)
> +{
> +	__INIT_WORK(work, func, on_stack);

Note here all the work items in Rust will share the same lockdep class.
That could be problematic: the lockdep classes for work are for
detecting deadlocks in the following scenario:

step 1: queue a work "foo", whose work function is:

	mutex_lock(&bar);
	do_something(...);
	mutex_unlock(&bar);

step 2: in another thread do:

	mutex_lock(&bar);
	flush_work(foo);	// wait until work "foo" is finished.

if this case, if step 2 get the lock "bar" first, it's a deadlock.

With the current implementation, all the work items share the same
lockdep class, so the following will be treated as deadlock:

	<in work "work1">
	mutex_lock(&bar);
	do_something(...);
	mutex_unlock(&bar);

	<in another thread>
	mutex_lock(&bar);
	flush_work(work2);	// flush work2 intead of work1.

which is a false positive. We at least need some changes in C side to
make it work:

	https://lore.kernel.org/rust-for-linux/20220802015052.10452-7-ojeda@kernel.org/

however, that still has the disadvantage that all Rust work items have
the same name for the lockdep classes.. maybe we should extend that for
an extra "name" parameter. And then it's not necessary to be a macro.
	
Regards,
Boqun

> +}
> +EXPORT_SYMBOL_GPL(rust_helper___INIT_WORK);
> +
>  /*
>   * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` type
>   * 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 e37820f253f6..dbf0aab29a85 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -2,9 +2,34 @@
>  
>  //! 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 struct.) Since these IDs are
> +//! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
> +//!
> +//! # The raw API
> +//!
> +//! The raw API consists of the `RawWorkItem` trait, where the work item needs 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. Furthermore, it also includes
> +//! a trait called `WorkItemPointer`, which is usually not used directly by 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 enqueued to a workqueue.
> +//!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
> +//!    that implements `WorkItem`.
> +//!
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
> -use crate::{bindings, types::Opaque};
> +use crate::{bindings, prelude::*, types::Opaque};
> +use core::marker::{PhantomData, PhantomPinned};
>  
>  /// A kernel work queue.
>  ///
> @@ -106,6 +131,198 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
>          F: FnOnce(*mut bindings::work_struct) -> bool;
>  }
>  
> +/// Defines the method that should be called directly when a work item is executed.
> +///
> +/// Typically you would implement [`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 the [`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` initialized with the [`run`]
> +/// method of this trait as the function pointer.
> +///
> +/// [`__enqueue`]: RawWorkItem::__enqueue
> +/// [`run`]: WorkItemPointer::run
> +pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
> +    /// 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 still be valid.
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
> +}
> +
> +/// Defines the method that should be called when this work item is executed.
> +///
> +/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
> +pub trait WorkItem<const ID: u64 = 0> {
> +    /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
> +    /// `Pin<Box<Self>>`.
> +    type Pointer: WorkItemPointer<ID>;
> +
> +    /// 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 work 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 [`WorkItem`] that uses it.
> +#[repr(transparent)]
> +pub struct Work<T: ?Sized, const ID: u64 = 0> {
> +    work: Opaque<bindings::work_struct>,
> +    _pin: PhantomPinned,
> +    _inner: PhantomData<T>,
> +}
> +
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
> +
> +impl<T: ?Sized, const ID: u64> Work<T, ID> {
> +    /// Creates a new instance of [`Work`].
> +    #[inline]
> +    #[allow(clippy::new_ret_no_self)]
> +    pub fn new() -> impl PinInit<Self>
> +    where
> +        T: WorkItem<ID>,
> +    {
> +        // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work
> +        // item function.
> +        unsafe {
> +            kernel::init::pin_init_from_closure(move |slot| {
> +                bindings::__INIT_WORK(Self::raw_get(slot), Some(T::Pointer::run), false);
> +                Ok(())
> +            })
> +        }
> +    }
> +
> +    /// Get a pointer to the inner `work_struct`.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must not be dangling and must be properly aligned. (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<T, ID>`] field.
> +///
> +/// # Safety
> +///
> +/// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
> +/// this trait must have exactly the behavior that the definitions given below have.
> +///
> +/// [`Work<T, ID>`]: Work
> +/// [`OFFSET`]: HasWork::OFFSET
> +pub unsafe trait HasWork<T, const ID: u64 = 0> {
> +    /// The offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    const OFFSET: usize;
> +
> +    /// Returns the offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    /// [`OFFSET`]: HasWork::OFFSET
> +    #[inline]
> +    fn get_work_offset(&self) -> usize {
> +        Self::OFFSET
> +    }
> +
> +    /// Returns a pointer to the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must point at a valid struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
> +        // SAFETY: The caller promises that the pointer is valid.
> +        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
> +    }
> +
> +    /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *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<T, ID>`] trait.
> +///
> +/// # Examples
> +///
> +/// ```
> +/// use kernel::sync::Arc;
> +///
> +/// struct MyStruct {
> +///     work_field: Work<MyStruct, 17>,
> +/// }
> +///
> +/// impl_has_work! {
> +///     impl HasWork<MyStruct, 17> for MyStruct { self.work_field }
> +/// }
> +/// ```
> +///
> +/// [`HasWork<T, ID>`]: 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 }
> +    )*) => {$(
> +        // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
> +        // type.
> +        unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? {
> +            const OFFSET: usize = $crate::offset_of!(Self, $field) as usize;
> +
> +            #[inline]
> +            unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
> +                // SAFETY: The caller promises that the pointer is not dangling.
> +                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 multi-threaded. There are
> -- 
> 2.41.0.rc0.172.g3f132b7071-goog
> 

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
  2023-06-01 14:50   ` Martin Rodriguez Reboredo
  2023-06-01 18:44   ` Boqun Feng
@ 2023-06-01 21:09   ` Boqun Feng
  2023-06-02  9:37     ` Alice Ryhl
  2023-06-02 14:41   ` Andreas Hindborg (Samsung)
  2023-06-11 15:59   ` Benno Lossin
  4 siblings, 1 reply; 53+ messages in thread
From: Boqun Feng @ 2023-06-01 21:09 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On Thu, Jun 01, 2023 at 01:49:43PM +0000, Alice Ryhl wrote:
> 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<T, ID>`. If a type
> implements this trait, then the type declares that, at the given offset,
> there is a field of type `Work<T, ID>`. 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<T>` on a type.
> The macro expands to something that only compiles if the specified field
> really has the type `Work<T>`. It is used like this:
> 
> ```
> struct MyWorkItem {
>     work_field: Work<MyWorkItem, 1>,
> }
> 
> impl_has_work! {
>     impl HasWork<MyWorkItem, 1> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> ---
>  rust/helpers.c           |   8 ++
>  rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++-
>  2 files changed, 226 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/helpers.c b/rust/helpers.c
> index 81e80261d597..7f0c2fe2fbeb 100644
> --- a/rust/helpers.c
> +++ b/rust/helpers.c
> @@ -26,6 +26,7 @@
>  #include <linux/spinlock.h>
>  #include <linux/sched/signal.h>
>  #include <linux/wait.h>
> +#include <linux/workqueue.h>
>  
>  __noreturn void rust_helper_BUG(void)
>  {
> @@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
>  }
>  EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
>  
> +void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
> +			     bool on_stack)
> +{
> +	__INIT_WORK(work, func, on_stack);
> +}
> +EXPORT_SYMBOL_GPL(rust_helper___INIT_WORK);
> +
>  /*
>   * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` type
>   * 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 e37820f253f6..dbf0aab29a85 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -2,9 +2,34 @@
>  
>  //! 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 struct.) Since these IDs are
> +//! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
> +//!
> +//! # The raw API
> +//!
> +//! The raw API consists of the `RawWorkItem` trait, where the work item needs 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. Furthermore, it also includes
> +//! a trait called `WorkItemPointer`, which is usually not used directly by 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 enqueued to a workqueue.
> +//!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
> +//!    that implements `WorkItem`.
> +//!
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
> -use crate::{bindings, types::Opaque};
> +use crate::{bindings, prelude::*, types::Opaque};
> +use core::marker::{PhantomData, PhantomPinned};
>  
>  /// A kernel work queue.
>  ///
> @@ -106,6 +131,198 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
>          F: FnOnce(*mut bindings::work_struct) -> bool;
>  }
>  
> +/// Defines the method that should be called directly when a work item is executed.
> +///
> +/// Typically you would implement [`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 the [`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` initialized with the [`run`]
> +/// method of this trait as the function pointer.
> +///
> +/// [`__enqueue`]: RawWorkItem::__enqueue
> +/// [`run`]: WorkItemPointer::run
> +pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
> +    /// 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 still be valid.
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
> +}
> +
> +/// Defines the method that should be called when this work item is executed.
> +///
> +/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
> +pub trait WorkItem<const ID: u64 = 0> {
> +    /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
> +    /// `Pin<Box<Self>>`.
> +    type Pointer: WorkItemPointer<ID>;

This being an associate type makes me wonder how do we want to support
the following (totally made-up by me, but I think it makes sense)?:

Say we have a struct

	pub struct Foo {
		work: Work<Foo>,
		data: Data,
	}

	impl Foo {
		pub fn do_sth(&self) {
			...
		}
	}

and we want to queue both Pin<Box<Foo>> and Arc<Foo> as work items, but
the following doesn't work:

	// Pin<Box<Foo>> can be queued.
	impl WorkItem for Foo {
		type Pointer = Pin<Box<Foo>>;
		fn run(ptr: Self::Pointer) {
			ptr.do_sth();
		}
	}

	// Arc<Foo> can also be queued.
	impl WorkItem for Foo {
		type Pointer = Arc<Foo>;
		fn run(ptr: Self::Pointer) {
			ptr.do_sth();
		}
	}



Of course, we can use new type idiom, but that's not really great, and
we may have more smart pointer types in the future.

Am I missing something here?

Regards,
Boqun

> +
> +    /// 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 work 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 [`WorkItem`] that uses it.
> +#[repr(transparent)]
> +pub struct Work<T: ?Sized, const ID: u64 = 0> {
> +    work: Opaque<bindings::work_struct>,
> +    _pin: PhantomPinned,
> +    _inner: PhantomData<T>,
> +}
> +
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
> +
> +impl<T: ?Sized, const ID: u64> Work<T, ID> {
> +    /// Creates a new instance of [`Work`].
> +    #[inline]
> +    #[allow(clippy::new_ret_no_self)]
> +    pub fn new() -> impl PinInit<Self>
> +    where
> +        T: WorkItem<ID>,
> +    {
> +        // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work
> +        // item function.
> +        unsafe {
> +            kernel::init::pin_init_from_closure(move |slot| {
> +                bindings::__INIT_WORK(Self::raw_get(slot), Some(T::Pointer::run), false);
> +                Ok(())
> +            })
> +        }
> +    }
> +
> +    /// Get a pointer to the inner `work_struct`.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must not be dangling and must be properly aligned. (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<T, ID>`] field.
> +///
> +/// # Safety
> +///
> +/// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
> +/// this trait must have exactly the behavior that the definitions given below have.
> +///
> +/// [`Work<T, ID>`]: Work
> +/// [`OFFSET`]: HasWork::OFFSET
> +pub unsafe trait HasWork<T, const ID: u64 = 0> {
> +    /// The offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    const OFFSET: usize;
> +
> +    /// Returns the offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    /// [`OFFSET`]: HasWork::OFFSET
> +    #[inline]
> +    fn get_work_offset(&self) -> usize {
> +        Self::OFFSET
> +    }
> +
> +    /// Returns a pointer to the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must point at a valid struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
> +        // SAFETY: The caller promises that the pointer is valid.
> +        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
> +    }
> +
> +    /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *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<T, ID>`] trait.
> +///
> +/// # Examples
> +///
> +/// ```
> +/// use kernel::sync::Arc;
> +///
> +/// struct MyStruct {
> +///     work_field: Work<MyStruct, 17>,
> +/// }
> +///
> +/// impl_has_work! {
> +///     impl HasWork<MyStruct, 17> for MyStruct { self.work_field }
> +/// }
> +/// ```
> +///
> +/// [`HasWork<T, ID>`]: 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 }
> +    )*) => {$(
> +        // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
> +        // type.
> +        unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? {
> +            const OFFSET: usize = $crate::offset_of!(Self, $field) as usize;
> +
> +            #[inline]
> +            unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
> +                // SAFETY: The caller promises that the pointer is not dangling.
> +                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 multi-threaded. There are
> -- 
> 2.41.0.rc0.172.g3f132b7071-goog
> 

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
  2023-06-01 17:30   ` Gary Guo
  2023-06-01 17:52     ` Martin Rodriguez Reboredo
@ 2023-06-02  8:32     ` Alice Ryhl
  1 sibling, 0 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-02  8:32 UTC (permalink / raw)
  To: gary
  Cc: alex.gaynor, aliceryhl, benno.lossin, bjorn3_gh, boqun.feng,
	jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux, tj,
	walmeida, wedsonaf, yakoyoku

Gary Guo <gary@garyguo.net> writes:
> On Thu,  1 Jun 2023 13:49:42 +0000
> Alice Ryhl <aliceryhl@google.com> wrote:
>> From: Wedson Almeida Filho <walmeida@microsoft.com>
>> 
>> 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 <walmeida@microsoft.com>
>> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
>> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
>> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
> 
> This looks fine to me, so:
> 
> Reviewed-by: Gary Guo <gary@garyguo.net>
> 
> Just one question about style: would people prefer:
> 
> 	kernel::workqueue::system().enqueue(...)
> 
> or
> 
> 	use kernel::workqueue::Queue;
> 	Queue::system().enqueue(...)
> 
> ?

I prefer the first version.

Alice

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 18:44   ` Boqun Feng
@ 2023-06-02  8:38     ` Alice Ryhl
  2023-06-02 16:32       ` Boqun Feng
  0 siblings, 1 reply; 53+ messages in thread
From: Alice Ryhl @ 2023-06-02  8:38 UTC (permalink / raw)
  To: boqun.feng
  Cc: alex.gaynor, aliceryhl, benno.lossin, bjorn3_gh, gary,
	jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux, tj,
	wedsonaf

Boqun Feng <boqun.feng@gmail.com> writes:
> On Thu, Jun 01, 2023 at 01:49:43PM +0000, Alice Ryhl wrote:
>> diff --git a/rust/helpers.c b/rust/helpers.c
>> index 81e80261d597..7f0c2fe2fbeb 100644
>> --- a/rust/helpers.c
>> +++ b/rust/helpers.c
>> @@ -26,6 +26,7 @@
>>  #include <linux/spinlock.h>
>>  #include <linux/sched/signal.h>
>>  #include <linux/wait.h>
>> +#include <linux/workqueue.h>
>>  
>>  __noreturn void rust_helper_BUG(void)
>>  {
>> @@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
>>  }
>>  EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
>>  
>> +void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
>> +			     bool on_stack)
>> +{
>> +	__INIT_WORK(work, func, on_stack);
> 
> Note here all the work items in Rust will share the same lockdep class.
> That could be problematic: the lockdep classes for work are for
> detecting deadlocks in the following scenario:
> 
> step 1: queue a work "foo", whose work function is:
> 
> 	mutex_lock(&bar);
> 	do_something(...);
> 	mutex_unlock(&bar);
> 
> step 2: in another thread do:
> 
> 	mutex_lock(&bar);
> 	flush_work(foo);	// wait until work "foo" is finished.
> 
> if this case, if step 2 get the lock "bar" first, it's a deadlock.
> 
> With the current implementation, all the work items share the same
> lockdep class, so the following will be treated as deadlock:
> 
> 	<in work "work1">
> 	mutex_lock(&bar);
> 	do_something(...);
> 	mutex_unlock(&bar);
> 
> 	<in another thread>
> 	mutex_lock(&bar);
> 	flush_work(work2);	// flush work2 intead of work1.
> 
> which is a false positive. We at least need some changes in C side to
> make it work:
> 
> 	https://lore.kernel.org/rust-for-linux/20220802015052.10452-7-ojeda@kernel.org/
> 
> however, that still has the disadvantage that all Rust work items have
> the same name for the lockdep classes.. maybe we should extend that for
> an extra "name" parameter. And then it's not necessary to be a macro.

Yeah, I did know about this issue, but I didn't know what the best way
to fix it is. What solution would you like me to use?

Alice

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 21:09   ` Boqun Feng
@ 2023-06-02  9:37     ` Alice Ryhl
  0 siblings, 0 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-02  9:37 UTC (permalink / raw)
  To: boqun.feng
  Cc: alex.gaynor, aliceryhl, benno.lossin, bjorn3_gh, gary,
	jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux, tj,
	wedsonaf

Boqun Feng <boqun.feng@gmail.com> writes:
> On Thu, Jun 01, 2023 at 01:49:43PM +0000, Alice Ryhl wrote:
>> +/// Defines the method that should be called directly when a work item is executed.
>> +///
>> +/// Typically you would implement [`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 the [`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` initialized with the [`run`]
>> +/// method of this trait as the function pointer.
>> +///
>> +/// [`__enqueue`]: RawWorkItem::__enqueue
>> +/// [`run`]: WorkItemPointer::run
>> +pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
>> +    /// 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 still be valid.
>> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
>> +}
>> +
>> +/// Defines the method that should be called when this work item is executed.
>> +///
>> +/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
>> +pub trait WorkItem<const ID: u64 = 0> {
>> +    /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
>> +    /// `Pin<Box<Self>>`.
>> +    type Pointer: WorkItemPointer<ID>;
> 
> This being an associate type makes me wonder how do we want to support
> the following (totally made-up by me, but I think it makes sense)?:
> 
> Say we have a struct
> 
> 	pub struct Foo {
> 		work: Work<Foo>,
> 		data: Data,
> 	}
> 
> 	impl Foo {
> 		pub fn do_sth(&self) {
> 			...
> 		}
> 	}
> 
> and we want to queue both Pin<Box<Foo>> and Arc<Foo> as work items, but
> the following doesn't work:
> 
> 	// Pin<Box<Foo>> can be queued.
> 	impl WorkItem for Foo {
> 		type Pointer = Pin<Box<Foo>>;
> 		fn run(ptr: Self::Pointer) {
> 			ptr.do_sth();
> 		}
> 	}
> 
> 	// Arc<Foo> can also be queued.
> 	impl WorkItem for Foo {
> 		type Pointer = Arc<Foo>;
> 		fn run(ptr: Self::Pointer) {
> 			ptr.do_sth();
> 		}
> 	}
> 
> Of course, we can use new type idiom, but that's not really great, and
> we may have more smart pointer types in the future.
> 
> Am I missing something here?

Basically, you're asking "is it possible to use the same `work_struct`
field for several different pointer types"?

When creating the function pointer to store in the `work_struct`, the
function pointer _must_ know what the pointer type is. Otherwise it
cannot call the right `WorkItem::run` method or perform the correct
`container_of` operation. (E.g. an `Arc` embeds a `refcount_t` before
the struct, but a `Box` does not.)

With an associated type there is no problem with that. Associated types
force you to make a choice, which means that the `work_struct` knows
what the pointer type is when you create it. Supporting what you suggest
means that we must be able to change the function pointer stored in the
`work_struct` after initializing it.

This is rather tricky because you can call `enqueue` from several
threads in parallel; just setting the function pointer before you call
`queue_work_on` would be a data race. I suppose you could do it by
implementing our own `queue_work_on` that sets the function pointer
_after_ successfully setting the `WORK_STRUCT_PENDING_BIT`, but I don't
think this patchset should do that.

Alice

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-01 17:32   ` Gary Guo
@ 2023-06-02  9:39     ` Alice Ryhl
  0 siblings, 0 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-02  9:39 UTC (permalink / raw)
  To: gary
  Cc: alex.gaynor, aliceryhl, benno.lossin, bjorn3_gh, boqun.feng,
	jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux, tj,
	wedsonaf

Gary Guo <gary@garyguo.net> writes:
> On Thu,  1 Jun 2023 13:49:46 +0000
> Alice Ryhl <aliceryhl@google.com> wrote:
>> 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 <aliceryhl@google.com>
>> ---
>>  rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++
>>  1 file changed, 104 insertions(+)
>> 
>> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
>> index c302e8b8624b..cefcf43ff40e 100644
>> --- a/rust/kernel/workqueue.rs
>> +++ b/rust/kernel/workqueue.rs
>> @@ -26,6 +26,110 @@
>>  //!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
>>  //!    that implements `WorkItem`.
>>  //!
>> +//! ## Example
>> +//!
>> +//! This example defines a struct that holds an integer and can be scheduled 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<MyStruct>,
>> +//! }
>> +//!
>> +//! impl_has_work! {
>> +//!     impl HasWork<Self> for MyStruct { self.work }
>> +//! }
>> +//!
>> +//! impl MyStruct {
>> +//!     fn new(value: i32) -> Result<Arc<Self>> {
>> +//!         Arc::pin_init(pin_init!(MyStruct {
>> +//!             value,
>> +//!             work <- Work::new(),
>> +//!         }))
>> +//!     }
>> +//! }
>> +//!
>> +//! impl WorkItem for MyStruct {
>> +//!     type Pointer = Arc<MyStruct>;
>> +//!
>> +//!     fn run(this: Arc<MyStruct>) {
>> +//!         pr_info!("The value is: {}", this.value);
>> +//!     }
>> +//! }
>> +//!
>> +//! /// This method will enqueue the struct for execution on the system workqueue, where its value
>> +//! /// will be printed.
>> +//! fn print_later(val: Arc<MyStruct>) {
>> +//!     let _ = workqueue::system().enqueue(val);
>> +//! }
>> +//! ```
>> +//!
>> +//! The following example shows how multiple `work_struct` fields can be used:
>> +//!
>> +//! ```
>> +//! 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<MyStruct, 1>,
>> +//!     #[pin]
>> +//!     work_2: Work<MyStruct, 2>,
>> +//! }
>> +//!
>> +//! impl_has_work! {
>> +//!     impl HasWork<Self, 1> for MyStruct { self.work_1 }
>> +//!     impl HasWork<Self, 2> for MyStruct { self.work_2 }
>> +//! }
>> +//!
>> +//! impl MyStruct {
>> +//!     fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
>> +//!         Arc::pin_init(pin_init!(MyStruct {
>> +//!             value_1,
>> +//!             value_2,
>> +//!             work_1 <- Work::new(),
>> +//!             work_2 <- Work::new(),
>> +//!         }))
>> +//!     }
>> +//! }
>> +//!
>> +//! impl WorkItem<1> for MyStruct {
>> +//!     type Pointer = Arc<MyStruct>;
>> +//!
>> +//!     fn run(this: Arc<MyStruct>) {
>> +//!         pr_info!("The value is: {}", this.value_1);
>> +//!     }
>> +//! }
>> +//!
>> +//! impl WorkItem<2> for MyStruct {
>> +//!     type Pointer = Arc<MyStruct>;
>> +//!
>> +//!     fn run(this: Arc<MyStruct>) {
>> +//!         pr_info!("The second value is: {}", this.value_2);
>> +//!     }
>> +//! }
>> +//!
>> +//! fn print_1_later(val: Arc<MyStruct>) {
>> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
> 
> Nothing bad about explicit, but I just want to confirm that you could
> write
> 
> 	let _ = workqueue::system().enqueue::<_, 1>(val);
> 
> here, right?

Yes, you can also do that.

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 2/8] rust: add offset_of! macro
  2023-06-01 13:49 ` [PATCH v2 2/8] rust: add offset_of! macro Alice Ryhl
  2023-06-01 17:17   ` Gary Guo
@ 2023-06-02 10:33   ` Andreas Hindborg (Samsung)
  2023-06-07 15:15     ` Alice Ryhl
  2023-06-11 15:47   ` Benno Lossin
  2 siblings, 1 reply; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 10:33 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo


Alice Ryhl <aliceryhl@google.com> writes:

> From: Wedson Almeida Filho <walmeida@microsoft.com>
>
> 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<SubStruct>`, 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
> ---
>  rust/kernel/lib.rs     | 35 +++++++++++++++++++++++++++++++++++
>  scripts/Makefile.build |  2 +-
>  2 files changed, 36 insertions(+), 1 deletion(-)
>
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index eaded02ffb01..7ea777b731e6 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)]
> @@ -98,3 +99,37 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
>      // instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
>      loop {}
>  }
> +
> +/// Calculates the offset of a field from the beginning of the struct it belongs 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) => {{

Could we add a descriptive comment?

           // Prevent deref coersion to `$field` by requiring `$type`
           // has a field named `$field`

BR Andreas

> +        let $type { $field: _, .. };
> +        let tmp = ::core::mem::MaybeUninit::<$type>::uninit();
> +        let outer = 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 create an intermediate
> +        // reference.
> +        let inner = 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)
>  # ---------------------------------------------------------------------------
>  
> -rust_allowed_features := new_uninit
> +rust_allowed_features := const_refs_to_cell,new_uninit
>  
>  rust_common_cmd = \
>  	RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-01 13:49 ` [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}` Alice Ryhl
  2023-06-01 17:26   ` Gary Guo
@ 2023-06-02 10:51   ` Andreas Hindborg (Samsung)
  2023-06-05 14:31     ` Gary Guo
  2023-06-11 15:48   ` Benno Lossin
  2 siblings, 1 reply; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 10:51 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo


Alice Ryhl <aliceryhl@google.com> writes:

> From: Wedson Almeida Filho <walmeida@microsoft.com>
>
> 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
> ---
>  rust/kernel/lib.rs      |  1 +
>  rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
>  2 files changed, 42 insertions(+), 1 deletion(-)
>
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 7ea777b731e6..ad9142928fb1 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)]
>  
> diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
> index a89843cacaad..684be9f73aca 100644
> --- a/rust/kernel/sync/arc.rs
> +++ b/rust/kernel/sync/arc.rs
> @@ -24,7 +24,7 @@
>  };
>  use alloc::boxed::Box;
>  use core::{
> -    alloc::AllocError,
> +    alloc::{AllocError, Layout},
>      fmt,
>      marker::{PhantomData, Unsize},
>      mem::{ManuallyDrop, MaybeUninit},
> @@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
>          }
>      }
>  
> +    /// 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 = 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
> +    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
> +        // SAFETY: The caller guarantees that the pointer is valid.
> +        let val_layout = unsafe { Layout::for_value(&*ptr) };
> +        // SAFETY: We're computing the layout of a real struct that existed when compiling this
> +        // binary, so its layout is not so large that it can trigger arithmetic overflow.
> +        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
> +
> +        // This preserves the metadata in the pointer, if any.
> +        //
> +        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
> +        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
> +        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);

Thanks for updating the comment with the link. I looked into this and I
find that what we are doing here, even though it works, does not feel
right at all. We should be able to do this:

        let metadata = core::ptr::metadata(ptr);
        let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
        let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);

but the way `Pointee::Metadata` is defined will not allow this, even
though we know it is valid. I would suggest the following instead:

        let metadata = core::ptr::metadata(ptr);
        // Convert <T as Pointee>::Metadata to <ArcInner<T> as
        // Pointee>::Metadata. We know they have identical representation and thus this is OK.
        let metadata: <ArcInner<T> as Pointee>::Metadata = *unsafe {
            &*((&metadata as *const <T as Pointee>::Metadata as *const ())
                as *const <ArcInner<T> as Pointee>::Metadata)
        };
        let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
        let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);

Even though it is a bit more complex, it captures what we are trying to
do better.

Best regards,
Andreas

> +        let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
> +        let ptr = 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 [`ArcBorrow`] (e.g., in a method


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
  2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
  2023-06-01 14:29   ` Martin Rodriguez Reboredo
@ 2023-06-02 14:39   ` Andreas Hindborg (Samsung)
  2023-06-06 23:36   ` Boqun Feng
  2023-06-11 15:45   ` Benno Lossin
  3 siblings, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 14:39 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches


Alice Ryhl <aliceryhl@google.com> writes:

> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Reviewed-by: Andreas Hindborg (Samsung) <nmi@metaspace.dk>

> ---
>  rust/bindings/bindings_helper.h |   1 +
>  rust/kernel/lib.rs              |   1 +
>  rust/kernel/workqueue.rs        | 107 ++++++++++++++++++++++++++++++++
>  3 files changed, 109 insertions(+)
>  create mode 100644 rust/kernel/workqueue.rs
>
> diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
> index 50e7a76d5455..ae2e8f018268 100644
> --- a/rust/bindings/bindings_helper.h
> +++ b/rust/bindings/bindings_helper.h
> @@ -10,6 +10,7 @@
>  #include <linux/refcount.h>
>  #include <linux/wait.h>
>  #include <linux/sched.h>
> +#include <linux/workqueue.h>
>  
>  /* `bindgen` gets confused at certain things. */
>  const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL;
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 85b261209977..eaded02ffb01 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -43,6 +43,7 @@
>  pub mod sync;
>  pub mod task;
>  pub mod types;
> +pub mod workqueue;
>  
>  #[doc(hidden)]
>  pub use bindings;
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> new file mode 100644
> index 000000000000..9c630840039b
> --- /dev/null
> +++ b/rust/kernel/workqueue.rs
> @@ -0,0 +1,107 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +//! Work queues.
> +//!
> +//! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.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 the kernel. Several are
> +/// always available, for example, `system`, `system_highpri`, `system_long`, etc.
> +#[repr(transparent)]
> +pub struct Queue(Opaque<bindings::workqueue_struct>);
> +
> +// 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 dangling, 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 pointer 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<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
> +    where
> +        W: RawWorkItem<ID> + Send + 'static,
> +    {
> +        let queue_ptr = 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` and static.
> +        //
> +        // The call to `bindings::queue_work_on` will dereference the provided 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 that the raw pointer will
> +        // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
> +        unsafe {
> +            w.__enqueue(move |work_ptr| {
> +                bindings::queue_work_on(bindings::WORK_CPU_UNBOUND as _, queue_ptr, work_ptr)
> +            })
> +        }
> +    }
> +}
> +
> +/// A raw work item.
> +///
> +/// This is the low-level trait that is designed for being as general as possible.
> +///
> +/// The `ID` parameter to this trait exists so that a single type can provide 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 id for each field. The
> +/// actual value of the id is not important as long as you use different ids for different fields
> +/// of the same struct. (Fields of different structs need not use different ids.)
> +///
> +/// Note that the id is used only to select the right method to call during 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 documentation for `__enqueue`.
> +pub unsafe trait RawWorkItem<const ID: u64> {
> +    /// 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. If 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 must not call the function
> +    /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
> +    ///
> +    /// If the work item type is not [`Send`], then the function pointer must be called on the same
> +    /// thread as the call to `__enqueue`.
> +    unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
> +    where
> +        F: FnOnce(*mut bindings::work_struct) -> bool;
> +}


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
                     ` (2 preceding siblings ...)
  2023-06-01 21:09   ` Boqun Feng
@ 2023-06-02 14:41   ` Andreas Hindborg (Samsung)
  2023-06-11 15:59   ` Benno Lossin
  4 siblings, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 14:41 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches


Alice Ryhl <aliceryhl@google.com> writes:

> 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<T, ID>`. If a type
> implements this trait, then the type declares that, at the given offset,
> there is a field of type `Work<T, ID>`. 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<T>` on a type.
> The macro expands to something that only compiles if the specified field
> really has the type `Work<T>`. It is used like this:
>
> ```
> struct MyWorkItem {
>     work_field: Work<MyWorkItem, 1>,
> }
>
> impl_has_work! {
>     impl HasWork<MyWorkItem, 1> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Reviewed-by: Andreas Hindborg (Samsung) <nmi@metaspace.dk>

> ---
>  rust/helpers.c           |   8 ++
>  rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++-
>  2 files changed, 226 insertions(+), 1 deletion(-)
>
> diff --git a/rust/helpers.c b/rust/helpers.c
> index 81e80261d597..7f0c2fe2fbeb 100644
> --- a/rust/helpers.c
> +++ b/rust/helpers.c
> @@ -26,6 +26,7 @@
>  #include <linux/spinlock.h>
>  #include <linux/sched/signal.h>
>  #include <linux/wait.h>
> +#include <linux/workqueue.h>
>  
>  __noreturn void rust_helper_BUG(void)
>  {
> @@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
>  }
>  EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
>  
> +void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
> +			     bool on_stack)
> +{
> +	__INIT_WORK(work, func, on_stack);
> +}
> +EXPORT_SYMBOL_GPL(rust_helper___INIT_WORK);
> +
>  /*
>   * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` type
>   * 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 e37820f253f6..dbf0aab29a85 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -2,9 +2,34 @@
>  
>  //! 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 struct.) Since these IDs are
> +//! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
> +//!
> +//! # The raw API
> +//!
> +//! The raw API consists of the `RawWorkItem` trait, where the work item needs 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. Furthermore, it also includes
> +//! a trait called `WorkItemPointer`, which is usually not used directly by 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 enqueued to a workqueue.
> +//!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
> +//!    that implements `WorkItem`.
> +//!
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
> -use crate::{bindings, types::Opaque};
> +use crate::{bindings, prelude::*, types::Opaque};
> +use core::marker::{PhantomData, PhantomPinned};
>  
>  /// A kernel work queue.
>  ///
> @@ -106,6 +131,198 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
>          F: FnOnce(*mut bindings::work_struct) -> bool;
>  }
>  
> +/// Defines the method that should be called directly when a work item is executed.
> +///
> +/// Typically you would implement [`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 the [`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` initialized with the [`run`]
> +/// method of this trait as the function pointer.
> +///
> +/// [`__enqueue`]: RawWorkItem::__enqueue
> +/// [`run`]: WorkItemPointer::run
> +pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
> +    /// 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 still be valid.
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
> +}
> +
> +/// Defines the method that should be called when this work item is executed.
> +///
> +/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
> +pub trait WorkItem<const ID: u64 = 0> {
> +    /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
> +    /// `Pin<Box<Self>>`.
> +    type Pointer: WorkItemPointer<ID>;
> +
> +    /// 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 work 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 [`WorkItem`] that uses it.
> +#[repr(transparent)]
> +pub struct Work<T: ?Sized, const ID: u64 = 0> {
> +    work: Opaque<bindings::work_struct>,
> +    _pin: PhantomPinned,
> +    _inner: PhantomData<T>,
> +}
> +
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
> +
> +impl<T: ?Sized, const ID: u64> Work<T, ID> {
> +    /// Creates a new instance of [`Work`].
> +    #[inline]
> +    #[allow(clippy::new_ret_no_self)]
> +    pub fn new() -> impl PinInit<Self>
> +    where
> +        T: WorkItem<ID>,
> +    {
> +        // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work
> +        // item function.
> +        unsafe {
> +            kernel::init::pin_init_from_closure(move |slot| {
> +                bindings::__INIT_WORK(Self::raw_get(slot), Some(T::Pointer::run), false);
> +                Ok(())
> +            })
> +        }
> +    }
> +
> +    /// Get a pointer to the inner `work_struct`.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must not be dangling and must be properly aligned. (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<T, ID>`] field.
> +///
> +/// # Safety
> +///
> +/// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
> +/// this trait must have exactly the behavior that the definitions given below have.
> +///
> +/// [`Work<T, ID>`]: Work
> +/// [`OFFSET`]: HasWork::OFFSET
> +pub unsafe trait HasWork<T, const ID: u64 = 0> {
> +    /// The offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    const OFFSET: usize;
> +
> +    /// Returns the offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    /// [`OFFSET`]: HasWork::OFFSET
> +    #[inline]
> +    fn get_work_offset(&self) -> usize {
> +        Self::OFFSET
> +    }
> +
> +    /// Returns a pointer to the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must point at a valid struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
> +        // SAFETY: The caller promises that the pointer is valid.
> +        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
> +    }
> +
> +    /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *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<T, ID>`] trait.
> +///
> +/// # Examples
> +///
> +/// ```
> +/// use kernel::sync::Arc;
> +///
> +/// struct MyStruct {
> +///     work_field: Work<MyStruct, 17>,
> +/// }
> +///
> +/// impl_has_work! {
> +///     impl HasWork<MyStruct, 17> for MyStruct { self.work_field }
> +/// }
> +/// ```
> +///
> +/// [`HasWork<T, ID>`]: 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 }
> +    )*) => {$(
> +        // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
> +        // type.
> +        unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? {
> +            const OFFSET: usize = $crate::offset_of!(Self, $field) as usize;
> +
> +            #[inline]
> +            unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
> +                // SAFETY: The caller promises that the pointer is not dangling.
> +                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 multi-threaded. There are


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types
  2023-06-01 13:49 ` [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types Alice Ryhl
  2023-06-01 14:51   ` Martin Rodriguez Reboredo
@ 2023-06-02 14:42   ` Andreas Hindborg (Samsung)
  2023-06-11 16:01   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 14:42 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches


Alice Ryhl <aliceryhl@google.com> writes:

> 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<Box<T>>` type is for objects
> where the caller has exclusive ownership of the object.
>
> Co-developed-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Reviewed-by: Andreas Hindborg (Samsung) <nmi@metaspace.dk>

> ---
>  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 dbf0aab29a85..f06a2f036d8b 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -28,8 +28,10 @@
>  //!
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
> -use crate::{bindings, prelude::*, types::Opaque};
> +use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
> +use alloc::boxed::Box;
>  use core::marker::{PhantomData, PhantomPinned};
> +use core::pin::Pin;
>  
>  /// A kernel work queue.
>  ///
> @@ -323,6 +325,99 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ
>      )*};
>  }
>  
> +unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
> +        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
> +        let ptr = ptr as *mut Work<T, ID>;
> +        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
> +        let ptr = unsafe { T::work_container_of(ptr) };
> +        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
> +        let arc = unsafe { Arc::from_raw(ptr) };
> +
> +        T::run(arc)
> +    }
> +}
> +
> +unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    type EnqueueOutput = Result<(), Self>;
> +
> +    unsafe fn __enqueue<F>(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 pointer is a raw pointer.
> +        let ptr = Arc::into_raw(self) as *mut T;
> +
> +        // SAFETY: Pointers into an `Arc` point at a valid value.
> +        let work_ptr = unsafe { T::raw_get_work(ptr) };
> +        // SAFETY: `raw_get_work` returns a pointer to a valid value.
> +        let work_ptr = unsafe { Work::raw_get(work_ptr) };
> +
> +        if queue_work_on(work_ptr) {
> +            Ok(())
> +        } else {
> +            // SAFETY: The work queue has not taken ownership of the pointer.
> +            Err(unsafe { Arc::from_raw(ptr) })
> +        }
> +    }
> +}
> +
> +unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
> +        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
> +        let ptr = ptr as *mut Work<T, ID>;
> +        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
> +        let ptr = unsafe { T::work_container_of(ptr) };
> +        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
> +        let boxed = unsafe { Box::from_raw(ptr) };
> +        // SAFETY: The box was already pinned when it was enqueued.
> +        let pinned = unsafe { Pin::new_unchecked(boxed) };
> +
> +        T::run(pinned)
> +    }
> +}
> +
> +unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    type EnqueueOutput = ();
> +
> +    unsafe fn __enqueue<F>(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 = unsafe { Pin::into_inner_unchecked(self) };
> +        let ptr = Box::into_raw(boxed);
> +
> +        // SAFETY: Pointers into a `Box` point at a valid value.
> +        let work_ptr = unsafe { T::raw_get_work(ptr) };
> +        // SAFETY: `raw_get_work` returns a pointer to a valid value.
> +        let work_ptr = 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 multi-threaded. There are


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method
  2023-06-01 13:49 ` [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method Alice Ryhl
  2023-06-01 14:53   ` Martin Rodriguez Reboredo
@ 2023-06-02 14:43   ` Andreas Hindborg (Samsung)
  2023-06-11 16:10   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 14:43 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches


Alice Ryhl <aliceryhl@google.com> writes:

> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Reviewed-by: Andreas Hindborg (Samsung) <nmi@metaspace.dk>

> ---
>  rust/kernel/workqueue.rs | 43 ++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 43 insertions(+)
>
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index f06a2f036d8b..c302e8b8624b 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -29,6 +29,7 @@
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
>  use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
> +use alloc::alloc::AllocError;
>  use alloc::boxed::Box;
>  use core::marker::{PhantomData, PhantomPinned};
>  use core::pin::Pin;
> @@ -87,6 +88,44 @@ pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
>              })
>          }
>      }
> +
> +    /// 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<T: 'static + Send + FnOnce()>(&self, func: T) -> Result<(), AllocError> {
> +        let init = pin_init!(ClosureWork {
> +            work <- Work::new(),
> +            func: Some(func),
> +        });
> +
> +        self.enqueue(Box::pin_init(init).map_err(|_| AllocError)?);
> +        Ok(())
> +    }
> +}
> +
> +/// A helper type used in `try_spawn`.
> +#[pin_data]
> +struct ClosureWork<T> {
> +    #[pin]
> +    work: Work<ClosureWork<T>>,
> +    func: Option<T>,
> +}
> +
> +impl<T> ClosureWork<T> {
> +    fn project(self: Pin<&mut Self>) -> &mut Option<T> {
> +        // SAFETY: The `func` field is not structurally pinned.
> +        unsafe { &mut self.get_unchecked_mut().func }
> +    }
> +}
> +
> +impl<T: FnOnce()> WorkItem for ClosureWork<T> {
> +    type Pointer = Pin<Box<Self>>;
> +
> +    fn run(mut this: Pin<Box<Self>>) {
> +        if let Some(func) = this.as_mut().project().take() {
> +            (func)()
> +        }
> +    }
>  }
>  
>  /// A raw work item.
> @@ -325,6 +364,10 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ
>      )*};
>  }
>  
> +impl_has_work! {
> +    impl<T> HasWork<Self> for ClosureWork<T> { self.work }
> +}
> +
>  unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
>  where
>      T: WorkItem<ID, Pointer = Self>,


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
  2023-06-01 14:58   ` Martin Rodriguez Reboredo
  2023-06-01 17:32   ` Gary Guo
@ 2023-06-02 14:44   ` Andreas Hindborg (Samsung)
  2023-06-02 14:48   ` Andreas Hindborg (Samsung)
  2023-06-11 16:15   ` Benno Lossin
  4 siblings, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 14:44 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches


Alice Ryhl <aliceryhl@google.com> writes:

> 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 <aliceryhl@google.com>

Reviewed-by: Andreas Hindborg (Samsung) <nmi@metaspace.dk>

> ---
>  rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++
>  1 file changed, 104 insertions(+)
>
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index c302e8b8624b..cefcf43ff40e 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -26,6 +26,110 @@
>  //!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
>  //!    that implements `WorkItem`.
>  //!
> +//! ## Example
> +//!
> +//! This example defines a struct that holds an integer and can be scheduled 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<MyStruct>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self> for MyStruct { self.work }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value,
> +//!             work <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value);
> +//!     }
> +//! }
> +//!
> +//! /// This method will enqueue the struct for execution on the system workqueue, where its value
> +//! /// will be printed.
> +//! fn print_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue(val);
> +//! }
> +//! ```
> +//!
> +//! The following example shows how multiple `work_struct` fields can be used:
> +//!
> +//! ```
> +//! 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<MyStruct, 1>,
> +//!     #[pin]
> +//!     work_2: Work<MyStruct, 2>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self, 1> for MyStruct { self.work_1 }
> +//!     impl HasWork<Self, 2> for MyStruct { self.work_2 }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value_1,
> +//!             value_2,
> +//!             work_1 <- Work::new(),
> +//!             work_2 <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<1> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value_1);
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<2> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The second value is: {}", this.value_2);
> +//!     }
> +//! }
> +//!
> +//! fn print_1_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
> +//! }
> +//!
> +//! fn print_2_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
> +//! }
> +//! ```
> +//!
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
>  use crate::{bindings, prelude::*, sync::Arc, types::Opaque};


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
  2023-06-01 13:49 ` [PATCH v2 4/8] rust: workqueue: define built-in queues Alice Ryhl
  2023-06-01 17:30   ` Gary Guo
@ 2023-06-02 14:46   ` Andreas Hindborg (Samsung)
  2023-06-11 15:49   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 14:46 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo


Alice Ryhl <aliceryhl@google.com> writes:

> From: Wedson Almeida Filho <walmeida@microsoft.com>
>
> 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

I would suggest adding the description to freezable:

"A freezable wq participates in the freeze phase of the system suspend
operations. Work items on the wq are drained and no new work item starts
execution until thawed."

But otherwise 👍

Reviewed-by: Andreas Hindborg (Samsung) <nmi@metaspace.dk>

> ---
>  rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 65 insertions(+)
>
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index 9c630840039b..e37820f253f6 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -105,3 +105,68 @@ unsafe fn __enqueue<F>(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 multi-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 which 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 running 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, and 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 freezable.
> +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" variants 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_freezable_power_efficient_wq`).
> +///
> +/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
> +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) }
> +}


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
                     ` (2 preceding siblings ...)
  2023-06-02 14:44   ` Andreas Hindborg (Samsung)
@ 2023-06-02 14:48   ` Andreas Hindborg (Samsung)
  2023-06-11 16:15   ` Benno Lossin
  4 siblings, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-02 14:48 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches


Alice Ryhl <aliceryhl@google.com> writes:

> 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 <aliceryhl@google.com>

Reviewed-by: Andreas Hindborg (Samsung) <nmi@metaspace.dk>

> ---
>  rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++
>  1 file changed, 104 insertions(+)
>
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index c302e8b8624b..cefcf43ff40e 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -26,6 +26,110 @@
>  //!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
>  //!    that implements `WorkItem`.
>  //!
> +//! ## Example
> +//!
> +//! This example defines a struct that holds an integer and can be scheduled 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<MyStruct>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self> for MyStruct { self.work }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value,
> +//!             work <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value);
> +//!     }
> +//! }
> +//!
> +//! /// This method will enqueue the struct for execution on the system workqueue, where its value
> +//! /// will be printed.
> +//! fn print_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue(val);
> +//! }
> +//! ```
> +//!
> +//! The following example shows how multiple `work_struct` fields can be used:
> +//!
> +//! ```
> +//! 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<MyStruct, 1>,
> +//!     #[pin]
> +//!     work_2: Work<MyStruct, 2>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self, 1> for MyStruct { self.work_1 }
> +//!     impl HasWork<Self, 2> for MyStruct { self.work_2 }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value_1,
> +//!             value_2,
> +//!             work_1 <- Work::new(),
> +//!             work_2 <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<1> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value_1);
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<2> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The second value is: {}", this.value_2);
> +//!     }
> +//! }
> +//!
> +//! fn print_1_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
> +//! }
> +//!
> +//! fn print_2_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
> +//! }
> +//! ```
> +//!
>  //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
>  
>  use crate::{bindings, prelude::*, sync::Arc, types::Opaque};


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-02  8:38     ` Alice Ryhl
@ 2023-06-02 16:32       ` Boqun Feng
  0 siblings, 0 replies; 53+ messages in thread
From: Boqun Feng @ 2023-06-02 16:32 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: alex.gaynor, benno.lossin, bjorn3_gh, gary, jiangshanlai,
	linux-kernel, ojeda, patches, rust-for-linux, tj, wedsonaf

On Fri, Jun 02, 2023 at 08:38:56AM +0000, Alice Ryhl wrote:
> Boqun Feng <boqun.feng@gmail.com> writes:
> > On Thu, Jun 01, 2023 at 01:49:43PM +0000, Alice Ryhl wrote:
> >> diff --git a/rust/helpers.c b/rust/helpers.c
> >> index 81e80261d597..7f0c2fe2fbeb 100644
> >> --- a/rust/helpers.c
> >> +++ b/rust/helpers.c
> >> @@ -26,6 +26,7 @@
> >>  #include <linux/spinlock.h>
> >>  #include <linux/sched/signal.h>
> >>  #include <linux/wait.h>
> >> +#include <linux/workqueue.h>
> >>  
> >>  __noreturn void rust_helper_BUG(void)
> >>  {
> >> @@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
> >>  }
> >>  EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
> >>  
> >> +void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
> >> +			     bool on_stack)
> >> +{
> >> +	__INIT_WORK(work, func, on_stack);
> > 
> > Note here all the work items in Rust will share the same lockdep class.
> > That could be problematic: the lockdep classes for work are for
> > detecting deadlocks in the following scenario:
> > 
> > step 1: queue a work "foo", whose work function is:
> > 
> > 	mutex_lock(&bar);
> > 	do_something(...);
> > 	mutex_unlock(&bar);
> > 
> > step 2: in another thread do:
> > 
> > 	mutex_lock(&bar);
> > 	flush_work(foo);	// wait until work "foo" is finished.
> > 
> > if this case, if step 2 get the lock "bar" first, it's a deadlock.
> > 
> > With the current implementation, all the work items share the same
> > lockdep class, so the following will be treated as deadlock:
> > 
> > 	<in work "work1">
> > 	mutex_lock(&bar);
> > 	do_something(...);
> > 	mutex_unlock(&bar);
> > 
> > 	<in another thread>
> > 	mutex_lock(&bar);
> > 	flush_work(work2);	// flush work2 intead of work1.
> > 
> > which is a false positive. We at least need some changes in C side to
> > make it work:
> > 
> > 	https://lore.kernel.org/rust-for-linux/20220802015052.10452-7-ojeda@kernel.org/
> > 
> > however, that still has the disadvantage that all Rust work items have
> > the same name for the lockdep classes.. maybe we should extend that for
> > an extra "name" parameter. And then it's not necessary to be a macro.
> 
> Yeah, I did know about this issue, but I didn't know what the best way
> to fix it is. What solution would you like me to use?
> 

Having a init_work_with_key() function in C side:

void init_work_with_key(struct work_struct *work, bool onstack,
			const char *name, struct lock_class_key *key)
{
	__init_work(work, onstack);				\
	work->data = (atomic_long_t) WORK_DATA_INIT();	\
	lockdep_init_map(&work->lockdep_map, name, key, 0); \
	INIT_LIST_HEAD(&work->entry);			\
	work->func = func;				\
}

, and provide class key and name from Rust side.

Thoughts?

Regards,
Boqun

> Alice

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-02 10:51   ` Andreas Hindborg (Samsung)
@ 2023-06-05 14:31     ` Gary Guo
  2023-06-05 14:49       ` Andreas Hindborg (Samsung)
  2023-06-05 15:00       ` Boqun Feng
  0 siblings, 2 replies; 53+ messages in thread
From: Gary Guo @ 2023-06-05 14:31 UTC (permalink / raw)
  To: Andreas Hindborg (Samsung)
  Cc: Alice Ryhl, rust-for-linux, Miguel Ojeda, Wedson Almeida Filho,
	Tejun Heo, Lai Jiangshan, Alex Gaynor, Boqun Feng,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo

On Fri, 02 Jun 2023 12:51:08 +0200
"Andreas Hindborg (Samsung)" <nmi@metaspace.dk> wrote:

> Alice Ryhl <aliceryhl@google.com> writes:
> 
> > From: Wedson Almeida Filho <walmeida@microsoft.com>
> >
> > 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 <walmeida@microsoft.com>
> > Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> > Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> > Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
> > ---
> >  rust/kernel/lib.rs      |  1 +
> >  rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
> >  2 files changed, 42 insertions(+), 1 deletion(-)
> >
> > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> > index 7ea777b731e6..ad9142928fb1 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)]
> >  
> > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
> > index a89843cacaad..684be9f73aca 100644
> > --- a/rust/kernel/sync/arc.rs
> > +++ b/rust/kernel/sync/arc.rs
> > @@ -24,7 +24,7 @@
> >  };
> >  use alloc::boxed::Box;
> >  use core::{
> > -    alloc::AllocError,
> > +    alloc::{AllocError, Layout},
> >      fmt,
> >      marker::{PhantomData, Unsize},
> >      mem::{ManuallyDrop, MaybeUninit},
> > @@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
> >          }
> >      }
> >  
> > +    /// 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 = 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
> > +    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
> > +    ///
> > +    /// # Safety
> > +    ///
> > +    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
> > +        // SAFETY: The caller guarantees that the pointer is valid.
> > +        let val_layout = unsafe { Layout::for_value(&*ptr) };
> > +        // SAFETY: We're computing the layout of a real struct that existed when compiling this
> > +        // binary, so its layout is not so large that it can trigger arithmetic overflow.
> > +        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
> > +
> > +        // This preserves the metadata in the pointer, if any.
> > +        //
> > +        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
> > +        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
> > +        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);  
> 
> Thanks for updating the comment with the link. I looked into this and I
> find that what we are doing here, even though it works, does not feel
> right at all. We should be able to do this:
> 
>         let metadata = core::ptr::metadata(ptr);
>         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
>         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
> 
> but the way `Pointee::Metadata` is defined will not allow this, even
> though we know it is valid. I would suggest the following instead:
> 
>         let metadata = core::ptr::metadata(ptr);
>         // Convert <T as Pointee>::Metadata to <ArcInner<T> as
>         // Pointee>::Metadata. We know they have identical representation and thus this is OK.
>         let metadata: <ArcInner<T> as Pointee>::Metadata = *unsafe {
>             &*((&metadata as *const <T as Pointee>::Metadata as *const ())
>                 as *const <ArcInner<T> as Pointee>::Metadata)
>         };

This could just be a `transmute_copy`.

>         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
>         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
> 
> Even though it is a bit more complex, it captures what we are trying to
> do better.

I agree this captures the semantics better.

Best,
Gary

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-05 14:31     ` Gary Guo
@ 2023-06-05 14:49       ` Andreas Hindborg (Samsung)
  2023-06-05 15:00       ` Boqun Feng
  1 sibling, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-05 14:49 UTC (permalink / raw)
  To: Gary Guo
  Cc: Alice Ryhl, rust-for-linux, Miguel Ojeda, Wedson Almeida Filho,
	Tejun Heo, Lai Jiangshan, Alex Gaynor, Boqun Feng,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo


Gary Guo <gary@garyguo.net> writes:

> On Fri, 02 Jun 2023 12:51:08 +0200
> "Andreas Hindborg (Samsung)" <nmi@metaspace.dk> wrote:
>
>> Alice Ryhl <aliceryhl@google.com> writes:
>> 
>> > From: Wedson Almeida Filho <walmeida@microsoft.com>
>> >
>> > 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 <walmeida@microsoft.com>
>> > Co-developed-by: Alice Ryhl <aliceryhl@google.com>
>> > Signed-off-by: Alice Ryhl <aliceryhl@google.com>
>> > Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
>> > ---
>> >  rust/kernel/lib.rs      |  1 +
>> >  rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
>> >  2 files changed, 42 insertions(+), 1 deletion(-)
>> >
>> > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
>> > index 7ea777b731e6..ad9142928fb1 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)]
>> >  
>> > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
>> > index a89843cacaad..684be9f73aca 100644
>> > --- a/rust/kernel/sync/arc.rs
>> > +++ b/rust/kernel/sync/arc.rs
>> > @@ -24,7 +24,7 @@
>> >  };
>> >  use alloc::boxed::Box;
>> >  use core::{
>> > -    alloc::AllocError,
>> > +    alloc::{AllocError, Layout},
>> >      fmt,
>> >      marker::{PhantomData, Unsize},
>> >      mem::{ManuallyDrop, MaybeUninit},
>> > @@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
>> >          }
>> >      }
>> >  
>> > +    /// 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 = 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
>> > +    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
>> > +    ///
>> > +    /// # Safety
>> > +    ///
>> > +    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
>> > +        // SAFETY: The caller guarantees that the pointer is valid.
>> > +        let val_layout = unsafe { Layout::for_value(&*ptr) };
>> > +        // SAFETY: We're computing the layout of a real struct that existed when compiling this
>> > +        // binary, so its layout is not so large that it can trigger arithmetic overflow.
>> > +        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
>> > +
>> > +        // This preserves the metadata in the pointer, if any.
>> > +        //
>> > +        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
>> > +        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
>> > +        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);  
>> 
>> Thanks for updating the comment with the link. I looked into this and I
>> find that what we are doing here, even though it works, does not feel
>> right at all. We should be able to do this:
>> 
>>         let metadata = core::ptr::metadata(ptr);
>>         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
>>         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
>> 
>> but the way `Pointee::Metadata` is defined will not allow this, even
>> though we know it is valid. I would suggest the following instead:
>> 
>>         let metadata = core::ptr::metadata(ptr);
>>         // Convert <T as Pointee>::Metadata to <ArcInner<T> as
>>         // Pointee>::Metadata. We know they have identical representation and thus this is OK.
>>         let metadata: <ArcInner<T> as Pointee>::Metadata = *unsafe {
>>             &*((&metadata as *const <T as Pointee>::Metadata as *const ())
>>                 as *const <ArcInner<T> as Pointee>::Metadata)
>>         };
>
> This could just be a `transmute_copy`.

Even better 👍

BR Andreas

>
>>         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
>>         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
>> 
>> Even though it is a bit more complex, it captures what we are trying to
>> do better.
>
> I agree this captures the semantics better.
>
> Best,
> Gary


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-05 14:31     ` Gary Guo
  2023-06-05 14:49       ` Andreas Hindborg (Samsung)
@ 2023-06-05 15:00       ` Boqun Feng
  2023-06-05 15:20         ` Boqun Feng
  2023-06-05 18:34         ` Andreas Hindborg (Samsung)
  1 sibling, 2 replies; 53+ messages in thread
From: Boqun Feng @ 2023-06-05 15:00 UTC (permalink / raw)
  To: Gary Guo
  Cc: Andreas Hindborg (Samsung),
	Alice Ryhl, rust-for-linux, Miguel Ojeda, Wedson Almeida Filho,
	Tejun Heo, Lai Jiangshan, Alex Gaynor, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches, Wedson Almeida Filho,
	Martin Rodriguez Reboredo

On Mon, Jun 05, 2023 at 03:31:42PM +0100, Gary Guo wrote:
> On Fri, 02 Jun 2023 12:51:08 +0200
> "Andreas Hindborg (Samsung)" <nmi@metaspace.dk> wrote:
> 
> > Alice Ryhl <aliceryhl@google.com> writes:
> > 
> > > From: Wedson Almeida Filho <walmeida@microsoft.com>
> > >
> > > 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 <walmeida@microsoft.com>
> > > Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> > > Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> > > Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
> > > ---
> > >  rust/kernel/lib.rs      |  1 +
> > >  rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
> > >  2 files changed, 42 insertions(+), 1 deletion(-)
> > >
> > > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> > > index 7ea777b731e6..ad9142928fb1 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)]
> > >  
> > > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
> > > index a89843cacaad..684be9f73aca 100644
> > > --- a/rust/kernel/sync/arc.rs
> > > +++ b/rust/kernel/sync/arc.rs
> > > @@ -24,7 +24,7 @@
> > >  };
> > >  use alloc::boxed::Box;
> > >  use core::{
> > > -    alloc::AllocError,
> > > +    alloc::{AllocError, Layout},
> > >      fmt,
> > >      marker::{PhantomData, Unsize},
> > >      mem::{ManuallyDrop, MaybeUninit},
> > > @@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
> > >          }
> > >      }
> > >  
> > > +    /// 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 = 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
> > > +    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
> > > +    ///
> > > +    /// # Safety
> > > +    ///
> > > +    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
> > > +        // SAFETY: The caller guarantees that the pointer is valid.
> > > +        let val_layout = unsafe { Layout::for_value(&*ptr) };
> > > +        // SAFETY: We're computing the layout of a real struct that existed when compiling this
> > > +        // binary, so its layout is not so large that it can trigger arithmetic overflow.
> > > +        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
> > > +
> > > +        // This preserves the metadata in the pointer, if any.
> > > +        //
> > > +        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
> > > +        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
> > > +        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);  
> > 
> > Thanks for updating the comment with the link. I looked into this and I
> > find that what we are doing here, even though it works, does not feel
> > right at all. We should be able to do this:
> > 
> >         let metadata = core::ptr::metadata(ptr);
> >         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
> >         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
> > 
> > but the way `Pointee::Metadata` is defined will not allow this, even
> > though we know it is valid. I would suggest the following instead:
> > 
> >         let metadata = core::ptr::metadata(ptr);
> >         // Convert <T as Pointee>::Metadata to <ArcInner<T> as
> >         // Pointee>::Metadata. We know they have identical representation and thus this is OK.
> >         let metadata: <ArcInner<T> as Pointee>::Metadata = *unsafe {
> >             &*((&metadata as *const <T as Pointee>::Metadata as *const ())
> >                 as *const <ArcInner<T> as Pointee>::Metadata)
> >         };
> 
> This could just be a `transmute_copy`.
> 

Or just `transmute`:

	let metadata = unsafe {
		core::mem::transmute<_, <ArcInner<T> as
		Pointee>>::Metadata>(metadata)
	};

? Since `Pointee::Metadata` is `Copy`.

Regards,
Boqun

> >         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
> >         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
> > 
> > Even though it is a bit more complex, it captures what we are trying to
> > do better.
> 
> I agree this captures the semantics better.
> 

I actually wish that we could use `wrapping_byte_offset`[1], and just

	// `*const T` and `*const ArcInner<T>` should have the same
	// metdata, so convert the pointer type first.
	let ptr = ptr as *const ArcInner<T>;

	// .. and then adjust the byte offset.
	let ptr = ptr.wrapping_byte_offset(-val_offset);

This may be the opposite direction as Andreas proposed ;-), but the
result is less code.

Regards,
Boqun

> Best,
> Gary

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-05 15:00       ` Boqun Feng
@ 2023-06-05 15:20         ` Boqun Feng
  2023-06-05 18:34         ` Andreas Hindborg (Samsung)
  1 sibling, 0 replies; 53+ messages in thread
From: Boqun Feng @ 2023-06-05 15:20 UTC (permalink / raw)
  To: Gary Guo
  Cc: Andreas Hindborg (Samsung),
	Alice Ryhl, rust-for-linux, Miguel Ojeda, Wedson Almeida Filho,
	Tejun Heo, Lai Jiangshan, Alex Gaynor, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches, Wedson Almeida Filho,
	Martin Rodriguez Reboredo

On Mon, Jun 05, 2023 at 08:00:57AM -0700, Boqun Feng wrote:
> On Mon, Jun 05, 2023 at 03:31:42PM +0100, Gary Guo wrote:
> > On Fri, 02 Jun 2023 12:51:08 +0200
> > "Andreas Hindborg (Samsung)" <nmi@metaspace.dk> wrote:
> > 
> > > Alice Ryhl <aliceryhl@google.com> writes:
> > > 
> > > > From: Wedson Almeida Filho <walmeida@microsoft.com>
> > > >
> > > > 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 <walmeida@microsoft.com>
> > > > Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> > > > Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> > > > Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
> > > > ---
> > > >  rust/kernel/lib.rs      |  1 +
> > > >  rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
> > > >  2 files changed, 42 insertions(+), 1 deletion(-)
> > > >
> > > > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> > > > index 7ea777b731e6..ad9142928fb1 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)]
> > > >  
> > > > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
> > > > index a89843cacaad..684be9f73aca 100644
> > > > --- a/rust/kernel/sync/arc.rs
> > > > +++ b/rust/kernel/sync/arc.rs
> > > > @@ -24,7 +24,7 @@
> > > >  };
> > > >  use alloc::boxed::Box;
> > > >  use core::{
> > > > -    alloc::AllocError,
> > > > +    alloc::{AllocError, Layout},
> > > >      fmt,
> > > >      marker::{PhantomData, Unsize},
> > > >      mem::{ManuallyDrop, MaybeUninit},
> > > > @@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
> > > >          }
> > > >      }
> > > >  
> > > > +    /// 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 = 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
> > > > +    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
> > > > +    ///
> > > > +    /// # Safety
> > > > +    ///
> > > > +    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
> > > > +        // SAFETY: The caller guarantees that the pointer is valid.
> > > > +        let val_layout = unsafe { Layout::for_value(&*ptr) };
> > > > +        // SAFETY: We're computing the layout of a real struct that existed when compiling this
> > > > +        // binary, so its layout is not so large that it can trigger arithmetic overflow.
> > > > +        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
> > > > +
> > > > +        // This preserves the metadata in the pointer, if any.
> > > > +        //
> > > > +        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
> > > > +        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
> > > > +        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);  
> > > 
> > > Thanks for updating the comment with the link. I looked into this and I
> > > find that what we are doing here, even though it works, does not feel
> > > right at all. We should be able to do this:
> > > 
> > >         let metadata = core::ptr::metadata(ptr);
> > >         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
> > >         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
> > > 
> > > but the way `Pointee::Metadata` is defined will not allow this, even
> > > though we know it is valid. I would suggest the following instead:
> > > 
> > >         let metadata = core::ptr::metadata(ptr);
> > >         // Convert <T as Pointee>::Metadata to <ArcInner<T> as
> > >         // Pointee>::Metadata. We know they have identical representation and thus this is OK.
> > >         let metadata: <ArcInner<T> as Pointee>::Metadata = *unsafe {
> > >             &*((&metadata as *const <T as Pointee>::Metadata as *const ())
> > >                 as *const <ArcInner<T> as Pointee>::Metadata)
> > >         };
> > 
> > This could just be a `transmute_copy`.
> > 
> 
> Or just `transmute`:
> 
> 	let metadata = unsafe {
> 		core::mem::transmute<_, <ArcInner<T> as
> 		Pointee>>::Metadata>(metadata)
> 	};
> 
> ? Since `Pointee::Metadata` is `Copy`.
> 
> Regards,
> Boqun
> 
> > >         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
> > >         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
> > > 
> > > Even though it is a bit more complex, it captures what we are trying to
> > > do better.
> > 
> > I agree this captures the semantics better.
> > 
> 
> I actually wish that we could use `wrapping_byte_offset`[1], and just
> 
> 	// `*const T` and `*const ArcInner<T>` should have the same
> 	// metdata, so convert the pointer type first.
> 	let ptr = ptr as *const ArcInner<T>;
> 
> 	// .. and then adjust the byte offset.
> 	let ptr = ptr.wrapping_byte_offset(-val_offset);
> 
> This may be the opposite direction as Andreas proposed ;-), but the
> result is less code.
> 

(Forget the link to the function)
[1]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_byte_offset

> Regards,
> Boqun
> 
> > Best,
> > Gary

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-05 15:00       ` Boqun Feng
  2023-06-05 15:20         ` Boqun Feng
@ 2023-06-05 18:34         ` Andreas Hindborg (Samsung)
  1 sibling, 0 replies; 53+ messages in thread
From: Andreas Hindborg (Samsung) @ 2023-06-05 18:34 UTC (permalink / raw)
  To: Boqun Feng
  Cc: Gary Guo, Alice Ryhl, rust-for-linux, Miguel Ojeda,
	Wedson Almeida Filho, Tejun Heo, Lai Jiangshan, Alex Gaynor,
	Björn Roy Baron, Benno Lossin, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo


Boqun Feng <boqun.feng@gmail.com> writes:

> On Mon, Jun 05, 2023 at 03:31:42PM +0100, Gary Guo wrote:
>> On Fri, 02 Jun 2023 12:51:08 +0200
>> "Andreas Hindborg (Samsung)" <nmi@metaspace.dk> wrote:
>> 
>> > Alice Ryhl <aliceryhl@google.com> writes:
>> > 
>> > > From: Wedson Almeida Filho <walmeida@microsoft.com>
>> > >
>> > > 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 <walmeida@microsoft.com>
>> > > Co-developed-by: Alice Ryhl <aliceryhl@google.com>
>> > > Signed-off-by: Alice Ryhl <aliceryhl@google.com>
>> > > Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>
>> > > ---
>> > >  rust/kernel/lib.rs      |  1 +
>> > >  rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
>> > >  2 files changed, 42 insertions(+), 1 deletion(-)
>> > >
>> > > diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
>> > > index 7ea777b731e6..ad9142928fb1 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)]
>> > >  
>> > > diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
>> > > index a89843cacaad..684be9f73aca 100644
>> > > --- a/rust/kernel/sync/arc.rs
>> > > +++ b/rust/kernel/sync/arc.rs
>> > > @@ -24,7 +24,7 @@
>> > >  };
>> > >  use alloc::boxed::Box;
>> > >  use core::{
>> > > -    alloc::AllocError,
>> > > +    alloc::{AllocError, Layout},
>> > >      fmt,
>> > >      marker::{PhantomData, Unsize},
>> > >      mem::{ManuallyDrop, MaybeUninit},
>> > > @@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
>> > >          }
>> > >      }
>> > >  
>> > > +    /// 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 = 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
>> > > +    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
>> > > +    ///
>> > > +    /// # Safety
>> > > +    ///
>> > > +    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
>> > > +        // SAFETY: The caller guarantees that the pointer is valid.
>> > > +        let val_layout = unsafe { Layout::for_value(&*ptr) };
>> > > +        // SAFETY: We're computing the layout of a real struct that existed when compiling this
>> > > +        // binary, so its layout is not so large that it can trigger arithmetic overflow.
>> > > +        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
>> > > +
>> > > +        // This preserves the metadata in the pointer, if any.
>> > > +        //
>> > > +        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
>> > > +        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
>> > > +        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);  
>> > 
>> > Thanks for updating the comment with the link. I looked into this and I
>> > find that what we are doing here, even though it works, does not feel
>> > right at all. We should be able to do this:
>> > 
>> >         let metadata = core::ptr::metadata(ptr);
>> >         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
>> >         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
>> > 
>> > but the way `Pointee::Metadata` is defined will not allow this, even
>> > though we know it is valid. I would suggest the following instead:
>> > 
>> >         let metadata = core::ptr::metadata(ptr);
>> >         // Convert <T as Pointee>::Metadata to <ArcInner<T> as
>> >         // Pointee>::Metadata. We know they have identical representation and thus this is OK.
>> >         let metadata: <ArcInner<T> as Pointee>::Metadata = *unsafe {
>> >             &*((&metadata as *const <T as Pointee>::Metadata as *const ())
>> >                 as *const <ArcInner<T> as Pointee>::Metadata)
>> >         };
>> 
>> This could just be a `transmute_copy`.
>> 
>
> Or just `transmute`:
>
> 	let metadata = unsafe {
> 		core::mem::transmute<_, <ArcInner<T> as
> 		Pointee>>::Metadata>(metadata)
> 	};
>
> ? Since `Pointee::Metadata` is `Copy`.

I like `transmute_copy()` better for being more explicit.

>
> Regards,
> Boqun
>
>> >         let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
>> >         let ptr = core::ptr::from_raw_parts_mut(ptr, metadata);
>> > 
>> > Even though it is a bit more complex, it captures what we are trying to
>> > do better.
>> 
>> I agree this captures the semantics better.
>> 
>
> I actually wish that we could use `wrapping_byte_offset`[1], and just
>
> 	// `*const T` and `*const ArcInner<T>` should have the same
> 	// metdata, so convert the pointer type first.
> 	let ptr = ptr as *const ArcInner<T>;
>
> 	// .. and then adjust the byte offset.
> 	let ptr = ptr.wrapping_byte_offset(-val_offset);
>
> This may be the opposite direction as Andreas proposed ;-), but the
> result is less code.

Idk, it is sort of similar to the original approach. I think it is a
good idea to be a bit explicit about what we are doing here.

BR Andreas

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
  2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
  2023-06-01 14:29   ` Martin Rodriguez Reboredo
  2023-06-02 14:39   ` Andreas Hindborg (Samsung)
@ 2023-06-06 23:36   ` Boqun Feng
  2023-06-07 15:18     ` Alice Ryhl
  2023-06-11 15:45   ` Benno Lossin
  3 siblings, 1 reply; 53+ messages in thread
From: Boqun Feng @ 2023-06-06 23:36 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Gary Guo, Björn Roy Baron,
	Benno Lossin, linux-kernel, patches

On Thu, Jun 01, 2023 at 01:49:39PM +0000, Alice Ryhl wrote:
[...]
> +/// A raw work item.
> +///
> +/// This is the low-level trait that is designed for being as general as possible.
> +///
> +/// The `ID` parameter to this trait exists so that a single type can provide 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 id for each field. The
> +/// actual value of the id is not important as long as you use different ids for different fields
> +/// of the same struct. (Fields of different structs need not use different ids.)
> +///
> +/// Note that the id is used only to select the right method to call during 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 documentation for `__enqueue`.

^ better to say "the #Guarantees section in the documentation for
`__enqueue`"?

Regards,
Boqun

> +pub unsafe trait RawWorkItem<const ID: u64> {
> +    /// 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. If 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 must not call the function
> +    /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
> +    ///
> +    /// If the work item type is not [`Send`], then the function pointer must be called on the same
> +    /// thread as the call to `__enqueue`.
> +    unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
> +    where
> +        F: FnOnce(*mut bindings::work_struct) -> bool;
> +}
> -- 
> 2.41.0.rc0.172.g3f132b7071-goog
> 

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 2/8] rust: add offset_of! macro
  2023-06-02 10:33   ` Andreas Hindborg (Samsung)
@ 2023-06-07 15:15     ` Alice Ryhl
  0 siblings, 0 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-07 15:15 UTC (permalink / raw)
  To: nmi
  Cc: alex.gaynor, aliceryhl, benno.lossin, bjorn3_gh, boqun.feng,
	gary, jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux,
	tj, walmeida, wedsonaf, yakoyoku

Andreas Hindborg (Samsung) <nmi@metaspace.dk> writes:
> Alice Ryhl <aliceryhl@google.com> writes:
>> +#[macro_export]
>> +macro_rules! offset_of {
>> +    ($type:path, $field:ident) => {{
> 
> Could we add a descriptive comment?
> 
>            // Prevent deref coersion to `$field` by requiring `$type`
>            // has a field named `$field`
> 
> BR Andreas

Sure. It will be in the next version of the patchset.

Alice

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
  2023-06-06 23:36   ` Boqun Feng
@ 2023-06-07 15:18     ` Alice Ryhl
  0 siblings, 0 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-07 15:18 UTC (permalink / raw)
  To: boqun.feng
  Cc: alex.gaynor, aliceryhl, benno.lossin, bjorn3_gh, gary,
	jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux, tj,
	wedsonaf

Boqun Feng <boqun.feng@gmail.com> writes:
> On Thu, Jun 01, 2023 at 01:49:39PM +0000, Alice Ryhl wrote:
> [...]
>> +/// A raw work item.
>> +///
>> +/// This is the low-level trait that is designed for being as general as possible.
>> +///
>> +/// The `ID` parameter to this trait exists so that a single type can provide 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 id for each field. The
>> +/// actual value of the id is not important as long as you use different ids for different fields
>> +/// of the same struct. (Fields of different structs need not use different ids.)
>> +///
>> +/// Note that the id is used only to select the right method to call during 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 documentation for `__enqueue`.
> 
> ^ better to say "the #Guarantees section in the documentation for
> `__enqueue`"?
> 
> Regards,
> Boqun

Sure, I will clarify that this refers to the guarantees section in the
next version of the patchset.

Alice

^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
  2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
                     ` (2 preceding siblings ...)
  2023-06-06 23:36   ` Boqun Feng
@ 2023-06-11 15:45   ` Benno Lossin
  3 siblings, 0 replies; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 15:45 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches

On 01.06.23 15:49, Alice Ryhl wrote:
> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

-- 
Cheers,
Benno

> ---
>   rust/bindings/bindings_helper.h |   1 +
>   rust/kernel/lib.rs              |   1 +
>   rust/kernel/workqueue.rs        | 107 ++++++++++++++++++++++++++++++++
>   3 files changed, 109 insertions(+)
>   create mode 100644 rust/kernel/workqueue.rs
> 
> diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
> index 50e7a76d5455..ae2e8f018268 100644
> --- a/rust/bindings/bindings_helper.h
> +++ b/rust/bindings/bindings_helper.h
> @@ -10,6 +10,7 @@
>   #include <linux/refcount.h>
>   #include <linux/wait.h>
>   #include <linux/sched.h>
> +#include <linux/workqueue.h>
> 
>   /* `bindgen` gets confused at certain things. */
>   const gfp_t BINDINGS_GFP_KERNEL = GFP_KERNEL;
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 85b261209977..eaded02ffb01 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -43,6 +43,7 @@
>   pub mod sync;
>   pub mod task;
>   pub mod types;
> +pub mod workqueue;
> 
>   #[doc(hidden)]
>   pub use bindings;
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> new file mode 100644
> index 000000000000..9c630840039b
> --- /dev/null
> +++ b/rust/kernel/workqueue.rs
> @@ -0,0 +1,107 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +//! Work queues.
> +//!
> +//! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.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 the kernel. Several are
> +/// always available, for example, `system`, `system_highpri`, `system_long`, etc.
> +#[repr(transparent)]
> +pub struct Queue(Opaque<bindings::workqueue_struct>);
> +
> +// 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 dangling, 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 pointer 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<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
> +    where
> +        W: RawWorkItem<ID> + Send + 'static,
> +    {
> +        let queue_ptr = 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` and static.
> +        //
> +        // The call to `bindings::queue_work_on` will dereference the provided 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 that the raw pointer will
> +        // stay valid until we call the function pointer in the `work_struct`, so the access is ok.
> +        unsafe {
> +            w.__enqueue(move |work_ptr| {
> +                bindings::queue_work_on(bindings::WORK_CPU_UNBOUND as _, queue_ptr, work_ptr)
> +            })
> +        }
> +    }
> +}
> +
> +/// A raw work item.
> +///
> +/// This is the low-level trait that is designed for being as general as possible.
> +///
> +/// The `ID` parameter to this trait exists so that a single type can provide 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 id for each field. The
> +/// actual value of the id is not important as long as you use different ids for different fields
> +/// of the same struct. (Fields of different structs need not use different ids.)
> +///
> +/// Note that the id is used only to select the right method to call during 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 documentation for `__enqueue`.
> +pub unsafe trait RawWorkItem<const ID: u64> {
> +    /// 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. If 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 must not call the function
> +    /// pointer after any such lifetime expires. (Never calling the function pointer is okay.)
> +    ///
> +    /// If the work item type is not [`Send`], then the function pointer must be called on the same
> +    /// thread as the call to `__enqueue`.
> +    unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
> +    where
> +        F: FnOnce(*mut bindings::work_struct) -> bool;
> +}
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 



^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 2/8] rust: add offset_of! macro
  2023-06-01 13:49 ` [PATCH v2 2/8] rust: add offset_of! macro Alice Ryhl
  2023-06-01 17:17   ` Gary Guo
  2023-06-02 10:33   ` Andreas Hindborg (Samsung)
@ 2023-06-11 15:47   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 15:47 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo

On 01.06.23 15:49, Alice Ryhl wrote:
> From: Wedson Almeida Filho <walmeida@microsoft.com>
> 
> 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<SubStruct>`, 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

-- 
Cheers,
Benno

> ---
>   rust/kernel/lib.rs     | 35 +++++++++++++++++++++++++++++++++++
>   scripts/Makefile.build |  2 +-
>   2 files changed, 36 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index eaded02ffb01..7ea777b731e6 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)]
> @@ -98,3 +99,37 @@ fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
>       // instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
>       loop {}
>   }
> +
> +/// Calculates the offset of a field from the beginning of the struct it belongs 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) => {{
> +        let $type { $field: _, .. };
> +        let tmp = ::core::mem::MaybeUninit::<$type>::uninit();
> +        let outer = 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 create an intermediate
> +        // reference.
> +        let inner = 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)
>   # ---------------------------------------------------------------------------
> 
> -rust_allowed_features := new_uninit
> +rust_allowed_features := const_refs_to_cell,new_uninit
> 
>   rust_common_cmd = \
>   	RUST_MODFILE=$(modfile) $(RUSTC_OR_CLIPPY) $(rust_flags) \
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
  2023-06-01 13:49 ` [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}` Alice Ryhl
  2023-06-01 17:26   ` Gary Guo
  2023-06-02 10:51   ` Andreas Hindborg (Samsung)
@ 2023-06-11 15:48   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 15:48 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo

On 01.06.23 15:49, Alice Ryhl wrote:
> From: Wedson Almeida Filho <walmeida@microsoft.com>
> 
> 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

-- 
Cheers,
Benno

> ---
>   rust/kernel/lib.rs      |  1 +
>   rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++-
>   2 files changed, 42 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 7ea777b731e6..ad9142928fb1 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)]
> 
> diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs
> index a89843cacaad..684be9f73aca 100644
> --- a/rust/kernel/sync/arc.rs
> +++ b/rust/kernel/sync/arc.rs
> @@ -24,7 +24,7 @@
>   };
>   use alloc::boxed::Box;
>   use core::{
> -    alloc::AllocError,
> +    alloc::{AllocError, Layout},
>       fmt,
>       marker::{PhantomData, Unsize},
>       mem::{ManuallyDrop, MaybeUninit},
> @@ -212,6 +212,46 @@ unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self {
>           }
>       }
> 
> +    /// 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 = 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
> +    /// <https://doc.rust-lang.org/reference/type-layout.html#reprc-structs>.
> +    ///
> +    /// # Safety
> +    ///
> +    /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. 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 = Layout::new::<bindings::refcount_t>();
> +        // SAFETY: The caller guarantees that the pointer is valid.
> +        let val_layout = unsafe { Layout::for_value(&*ptr) };
> +        // SAFETY: We're computing the layout of a real struct that existed when compiling this
> +        // binary, so its layout is not so large that it can trigger arithmetic overflow.
> +        let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 };
> +
> +        // This preserves the metadata in the pointer, if any.
> +        //
> +        // Note that `*const T` and `*const ArcInner<T>` have the same metadata as documented at
> +        // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>.
> +        let metadata = core::ptr::metadata(ptr as *const ArcInner<T>);
> +        let ptr = (ptr as *mut u8).wrapping_sub(val_offset) as *mut ();
> +        let ptr = 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 [`ArcBorrow`] (e.g., in a method
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
  2023-06-01 13:49 ` [PATCH v2 4/8] rust: workqueue: define built-in queues Alice Ryhl
  2023-06-01 17:30   ` Gary Guo
  2023-06-02 14:46   ` Andreas Hindborg (Samsung)
@ 2023-06-11 15:49   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 15:49 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches,
	Wedson Almeida Filho, Martin Rodriguez Reboredo

On 01.06.23 15:49, Alice Ryhl wrote:
> From: Wedson Almeida Filho <walmeida@microsoft.com>
> 
> 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 <walmeida@microsoft.com>
> Co-developed-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com>

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

-- 
Cheers,
Benno

> ---
>   rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++
>   1 file changed, 65 insertions(+)
> 
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index 9c630840039b..e37820f253f6 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -105,3 +105,68 @@ unsafe fn __enqueue<F>(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 multi-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 which 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 running 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, and 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 freezable.
> +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" variants 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_freezable_power_efficient_wq`).
> +///
> +/// It is similar to the one returned by [`system_power_efficient`] except that is freezable.
> +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) }
> +}
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
                     ` (3 preceding siblings ...)
  2023-06-02 14:41   ` Andreas Hindborg (Samsung)
@ 2023-06-11 15:59   ` Benno Lossin
  2023-06-27  8:42     ` Alice Ryhl
  4 siblings, 1 reply; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 15:59 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches

On 01.06.23 15:49, Alice Ryhl wrote:
> 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<T, ID>`. If a type
> implements this trait, then the type declares that, at the given offset,
> there is a field of type `Work<T, ID>`. 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<T>` on a type.
> The macro expands to something that only compiles if the specified field
> really has the type `Work<T>`. It is used like this:
> 
> ```
> struct MyWorkItem {
>      work_field: Work<MyWorkItem, 1>,
> }
> 
> impl_has_work! {
>      impl HasWork<MyWorkItem, 1> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

I really like this new design! It splits the relevant components in a much
more natural way and is easier to understand. I added some comments below,
they only affect documentation though.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

> ---
>   rust/helpers.c           |   8 ++
>   rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++-
>   2 files changed, 226 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/helpers.c b/rust/helpers.c
> index 81e80261d597..7f0c2fe2fbeb 100644
> --- a/rust/helpers.c
> +++ b/rust/helpers.c
> @@ -26,6 +26,7 @@
>   #include <linux/spinlock.h>
>   #include <linux/sched/signal.h>
>   #include <linux/wait.h>
> +#include <linux/workqueue.h>
> 
>   __noreturn void rust_helper_BUG(void)
>   {
> @@ -128,6 +129,13 @@ void rust_helper_put_task_struct(struct task_struct *t)
>   }
>   EXPORT_SYMBOL_GPL(rust_helper_put_task_struct);
> 
> +void rust_helper___INIT_WORK(struct work_struct *work, work_func_t func,
> +			     bool on_stack)
> +{
> +	__INIT_WORK(work, func, on_stack);
> +}
> +EXPORT_SYMBOL_GPL(rust_helper___INIT_WORK);
> +
>   /*
>    * We use `bindgen`'s `--size_t-is-usize` option to bind the C `size_t` type
>    * 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 e37820f253f6..dbf0aab29a85 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -2,9 +2,34 @@
> 
>   //! 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 struct.) Since these IDs are
> +//! generic, they are used only at compile-time, so they shouldn't exist in the final binary.
> +//!
> +//! # The raw API
> +//!
> +//! The raw API consists of the `RawWorkItem` trait, where the work item needs 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. Furthermore, it also includes
> +//! a trait called `WorkItemPointer`, which is usually not used directly by 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 enqueued to a workqueue.
> +//!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
> +//!    that implements `WorkItem`.
> +//!
>   //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
> 
> -use crate::{bindings, types::Opaque};
> +use crate::{bindings, prelude::*, types::Opaque};
> +use core::marker::{PhantomData, PhantomPinned};
> 
>   /// A kernel work queue.
>   ///
> @@ -106,6 +131,198 @@ unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput
>           F: FnOnce(*mut bindings::work_struct) -> bool;
>   }
> 
> +/// Defines the method that should be called directly when a work item is executed.
> +///
> +/// Typically you would implement [`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 the [`WorkItem`] trait.

I think it makes sense to say that `Pin<Box<T>>` and `Arc<T>` implement
this trait (adding the comment in the next commit). Just to make it less
likely that people try to implement this trait instead of WorkItem. Also,
you could mention that this trait is meant for smart pointers.

> +///
> +/// 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` initialized with the [`run`]
> +/// method of this trait as the function pointer.
> +///
> +/// [`__enqueue`]: RawWorkItem::__enqueue
> +/// [`run`]: WorkItemPointer::run
> +pub unsafe trait WorkItemPointer<const ID: u64>: RawWorkItem<ID> {
> +    /// 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 still be valid.
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct);
> +}
> +
> +/// Defines the method that should be called when this work item is executed.
> +///
> +/// This trait is used when the `work_struct` field is defined using the [`Work`] helper.
> +pub trait WorkItem<const ID: u64 = 0> {
> +    /// The pointer type that this struct is wrapped in. This will typically be `Arc<Self>` or
> +    /// `Pin<Box<Self>>`.
> +    type Pointer: WorkItemPointer<ID>;
> +
> +    /// 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 work 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 [`WorkItem`] that uses it.
> +#[repr(transparent)]
> +pub struct Work<T: ?Sized, const ID: u64 = 0> {
> +    work: Opaque<bindings::work_struct>,
> +    _pin: PhantomPinned,
> +    _inner: PhantomData<T>,
> +}
> +
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Send for Work<T, ID> {}
> +// SAFETY: Kernel work items are usable from any thread.
> +//
> +// We do not need to constrain `T` since the work item does not actually contain a `T`.
> +unsafe impl<T: ?Sized, const ID: u64> Sync for Work<T, ID> {}
> +
> +impl<T: ?Sized, const ID: u64> Work<T, ID> {
> +    /// Creates a new instance of [`Work`].
> +    #[inline]
> +    #[allow(clippy::new_ret_no_self)]
> +    pub fn new() -> impl PinInit<Self>
> +    where
> +        T: WorkItem<ID>,
> +    {
> +        // SAFETY: The `WorkItemPointer` implementation promises that `run` can be used as the work
> +        // item function.
> +        unsafe {
> +            kernel::init::pin_init_from_closure(move |slot| {
> +                bindings::__INIT_WORK(Self::raw_get(slot), Some(T::Pointer::run), false);
> +                Ok(())
> +            })
> +        }
> +    }
> +
> +    /// Get a pointer to the inner `work_struct`.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must not be dangling and must be properly aligned. (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<T, ID>`] field.
> +///

Please mention the macro here as well, maybe also copy the example
from the commit message into this section.

> +/// # Safety
> +///
> +/// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
> +/// this trait must have exactly the behavior that the definitions given below have.

I think you should just say "implementers are not allowed to implement
the functions defined by this trait." I see no reason to allow that, since
all functions are fully determined by the `OFFSET` constant.

-- 
Cheers,
Benno

> +///
> +/// [`Work<T, ID>`]: Work
> +/// [`OFFSET`]: HasWork::OFFSET
> +pub unsafe trait HasWork<T, const ID: u64 = 0> {
> +    /// The offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    const OFFSET: usize;
> +
> +    /// Returns the offset of the [`Work<T, ID>`] field.
> +    ///
> +    /// This method exists because the [`OFFSET`] constant cannot be accessed if the type is not Sized.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    /// [`OFFSET`]: HasWork::OFFSET
> +    #[inline]
> +    fn get_work_offset(&self) -> usize {
> +        Self::OFFSET
> +    }
> +
> +    /// Returns a pointer to the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The provided pointer must point at a valid struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn raw_get_work(ptr: *mut Self) -> *mut Work<T, ID> {
> +        // SAFETY: The caller promises that the pointer is valid.
> +        unsafe { (ptr as *mut u8).add(Self::OFFSET) as *mut Work<T, ID> }
> +    }
> +
> +    /// Returns a pointer to the struct containing the [`Work<T, ID>`] field.
> +    ///
> +    /// # Safety
> +    ///
> +    /// The pointer must point at a [`Work<T, ID>`] field in a struct of type `Self`.
> +    ///
> +    /// [`Work<T, ID>`]: Work
> +    #[inline]
> +    unsafe fn work_container_of(ptr: *mut Work<T, ID>) -> *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<T, ID>`] trait.
> +///
> +/// # Examples
> +///
> +/// ```
> +/// use kernel::sync::Arc;
> +///
> +/// struct MyStruct {
> +///     work_field: Work<MyStruct, 17>,
> +/// }
> +///
> +/// impl_has_work! {
> +///     impl HasWork<MyStruct, 17> for MyStruct { self.work_field }
> +/// }
> +/// ```
> +///
> +/// [`HasWork<T, ID>`]: 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 }
> +    )*) => {$(
> +        // SAFETY: The implementation of `raw_get_work` only compiles if the field has the right
> +        // type.
> +        unsafe impl$(<$($implarg),*>)? $crate::workqueue::HasWork<$work_type $(, $id)?> for $self $(<$($selfarg),*>)? {
> +            const OFFSET: usize = $crate::offset_of!(Self, $field) as usize;
> +
> +            #[inline]
> +            unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_type $(, $id)?> {
> +                // SAFETY: The caller promises that the pointer is not dangling.
> +                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 multi-threaded. There are
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types
  2023-06-01 13:49 ` [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types Alice Ryhl
  2023-06-01 14:51   ` Martin Rodriguez Reboredo
  2023-06-02 14:42   ` Andreas Hindborg (Samsung)
@ 2023-06-11 16:01   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 16:01 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches

On 01.06.23 15:49, Alice Ryhl wrote:
> 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<Box<T>>` type is for objects
> where the caller has exclusive ownership of the object.
> 
> Co-developed-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

I have a small nit below.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

> ---
>   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 dbf0aab29a85..f06a2f036d8b 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -28,8 +28,10 @@
>   //!
>   //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
> 
> -use crate::{bindings, prelude::*, types::Opaque};
> +use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
> +use alloc::boxed::Box;
>   use core::marker::{PhantomData, PhantomPinned};
> +use core::pin::Pin;
> 
>   /// A kernel work queue.
>   ///
> @@ -323,6 +325,99 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ
>       )*};
>   }
> 
> +unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
> +        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
> +        let ptr = ptr as *mut Work<T, ID>;
> +        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
> +        let ptr = unsafe { T::work_container_of(ptr) };
> +        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
> +        let arc = unsafe { Arc::from_raw(ptr) };
> +
> +        T::run(arc)
> +    }
> +}
> +
> +unsafe impl<T, const ID: u64> RawWorkItem<ID> for Arc<T>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    type EnqueueOutput = Result<(), Self>;
> +
> +    unsafe fn __enqueue<F>(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 pointer is a raw pointer.
> +        let ptr = Arc::into_raw(self) as *mut T;

I personally would prefer `cast_mut()` here.

-- 
Cheers,
Benno

> +
> +        // SAFETY: Pointers into an `Arc` point at a valid value.
> +        let work_ptr = unsafe { T::raw_get_work(ptr) };
> +        // SAFETY: `raw_get_work` returns a pointer to a valid value.
> +        let work_ptr = unsafe { Work::raw_get(work_ptr) };
> +
> +        if queue_work_on(work_ptr) {
> +            Ok(())
> +        } else {
> +            // SAFETY: The work queue has not taken ownership of the pointer.
> +            Err(unsafe { Arc::from_raw(ptr) })
> +        }
> +    }
> +}
> +
> +unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<Box<T>>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    unsafe extern "C" fn run(ptr: *mut bindings::work_struct) {
> +        // SAFETY: The `__enqueue` method always uses a `work_struct` stored in a `Work<T, ID>`.
> +        let ptr = ptr as *mut Work<T, ID>;
> +        // SAFETY: This computes the pointer that `__enqueue` got from `Arc::into_raw`.
> +        let ptr = unsafe { T::work_container_of(ptr) };
> +        // SAFETY: This pointer comes from `Arc::into_raw` and we've been given back ownership.
> +        let boxed = unsafe { Box::from_raw(ptr) };
> +        // SAFETY: The box was already pinned when it was enqueued.
> +        let pinned = unsafe { Pin::new_unchecked(boxed) };
> +
> +        T::run(pinned)
> +    }
> +}
> +
> +unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<Box<T>>
> +where
> +    T: WorkItem<ID, Pointer = Self>,
> +    T: HasWork<T, ID>,
> +{
> +    type EnqueueOutput = ();
> +
> +    unsafe fn __enqueue<F>(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 = unsafe { Pin::into_inner_unchecked(self) };
> +        let ptr = Box::into_raw(boxed);
> +
> +        // SAFETY: Pointers into a `Box` point at a valid value.
> +        let work_ptr = unsafe { T::raw_get_work(ptr) };
> +        // SAFETY: `raw_get_work` returns a pointer to a valid value.
> +        let work_ptr = 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 multi-threaded. There are
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method
  2023-06-01 13:49 ` [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method Alice Ryhl
  2023-06-01 14:53   ` Martin Rodriguez Reboredo
  2023-06-02 14:43   ` Andreas Hindborg (Samsung)
@ 2023-06-11 16:10   ` Benno Lossin
  2 siblings, 0 replies; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 16:10 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches

On 01.06.23 15:49, Alice Ryhl wrote:
> 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 <gary@garyguo.net>
> Signed-off-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

-- 
Cheers,
Benno

> ---
>   rust/kernel/workqueue.rs | 43 ++++++++++++++++++++++++++++++++++++++++
>   1 file changed, 43 insertions(+)
> 
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index f06a2f036d8b..c302e8b8624b 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -29,6 +29,7 @@
>   //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
> 
>   use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
> +use alloc::alloc::AllocError;
>   use alloc::boxed::Box;
>   use core::marker::{PhantomData, PhantomPinned};
>   use core::pin::Pin;
> @@ -87,6 +88,44 @@ pub fn enqueue<W, const ID: u64>(&self, w: W) -> W::EnqueueOutput
>               })
>           }
>       }
> +
> +    /// 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<T: 'static + Send + FnOnce()>(&self, func: T) -> Result<(), AllocError> {
> +        let init = pin_init!(ClosureWork {
> +            work <- Work::new(),
> +            func: Some(func),
> +        });
> +
> +        self.enqueue(Box::pin_init(init).map_err(|_| AllocError)?);
> +        Ok(())
> +    }
> +}
> +
> +/// A helper type used in `try_spawn`.
> +#[pin_data]
> +struct ClosureWork<T> {
> +    #[pin]
> +    work: Work<ClosureWork<T>>,
> +    func: Option<T>,
> +}
> +
> +impl<T> ClosureWork<T> {
> +    fn project(self: Pin<&mut Self>) -> &mut Option<T> {
> +        // SAFETY: The `func` field is not structurally pinned.
> +        unsafe { &mut self.get_unchecked_mut().func }
> +    }
> +}
> +
> +impl<T: FnOnce()> WorkItem for ClosureWork<T> {
> +    type Pointer = Pin<Box<Self>>;
> +
> +    fn run(mut this: Pin<Box<Self>>) {
> +        if let Some(func) = this.as_mut().project().take() {
> +            (func)()
> +        }
> +    }
>   }
> 
>   /// A raw work item.
> @@ -325,6 +364,10 @@ unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ
>       )*};
>   }
> 
> +impl_has_work! {
> +    impl<T> HasWork<Self> for ClosureWork<T> { self.work }
> +}
> +
>   unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Arc<T>
>   where
>       T: WorkItem<ID, Pointer = Self>,
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
                     ` (3 preceding siblings ...)
  2023-06-02 14:48   ` Andreas Hindborg (Samsung)
@ 2023-06-11 16:15   ` Benno Lossin
  2023-06-27  8:38     ` Alice Ryhl
  4 siblings, 1 reply; 53+ messages in thread
From: Benno Lossin @ 2023-06-11 16:15 UTC (permalink / raw)
  To: Alice Ryhl
  Cc: rust-for-linux, Miguel Ojeda, Wedson Almeida Filho, Tejun Heo,
	Lai Jiangshan, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, linux-kernel, patches

On 01.06.23 15:49, Alice Ryhl wrote:
> 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 <aliceryhl@google.com>

Reviewed-by: Benno Lossin <benno.lossin@proton.me>

I really like that you added these examples!
Is there some particular reason you decided to not use
0 as the first index in the second example? (you can keep
it this way)

-- 
Cheers,
Benno

> ---
>   rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++
>   1 file changed, 104 insertions(+)
> 
> diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs
> index c302e8b8624b..cefcf43ff40e 100644
> --- a/rust/kernel/workqueue.rs
> +++ b/rust/kernel/workqueue.rs
> @@ -26,6 +26,110 @@
>   //!  * The `WorkItemPointer` trait is implemented for the pointer type that points at a something
>   //!    that implements `WorkItem`.
>   //!
> +//! ## Example
> +//!
> +//! This example defines a struct that holds an integer and can be scheduled 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<MyStruct>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self> for MyStruct { self.work }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value,
> +//!             work <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value);
> +//!     }
> +//! }
> +//!
> +//! /// This method will enqueue the struct for execution on the system workqueue, where its value
> +//! /// will be printed.
> +//! fn print_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue(val);
> +//! }
> +//! ```
> +//!
> +//! The following example shows how multiple `work_struct` fields can be used:
> +//!
> +//! ```
> +//! 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<MyStruct, 1>,
> +//!     #[pin]
> +//!     work_2: Work<MyStruct, 2>,
> +//! }
> +//!
> +//! impl_has_work! {
> +//!     impl HasWork<Self, 1> for MyStruct { self.work_1 }
> +//!     impl HasWork<Self, 2> for MyStruct { self.work_2 }
> +//! }
> +//!
> +//! impl MyStruct {
> +//!     fn new(value_1: i32, value_2: i32) -> Result<Arc<Self>> {
> +//!         Arc::pin_init(pin_init!(MyStruct {
> +//!             value_1,
> +//!             value_2,
> +//!             work_1 <- Work::new(),
> +//!             work_2 <- Work::new(),
> +//!         }))
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<1> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The value is: {}", this.value_1);
> +//!     }
> +//! }
> +//!
> +//! impl WorkItem<2> for MyStruct {
> +//!     type Pointer = Arc<MyStruct>;
> +//!
> +//!     fn run(this: Arc<MyStruct>) {
> +//!         pr_info!("The second value is: {}", this.value_2);
> +//!     }
> +//! }
> +//!
> +//! fn print_1_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 1>(val);
> +//! }
> +//!
> +//! fn print_2_later(val: Arc<MyStruct>) {
> +//!     let _ = workqueue::system().enqueue::<Arc<MyStruct>, 2>(val);
> +//! }
> +//! ```
> +//!
>   //! C header: [`include/linux/workqueue.h`](../../../../include/linux/workqueue.h)
> 
>   use crate::{bindings, prelude::*, sync::Arc, types::Opaque};
> --
> 2.41.0.rc0.172.g3f132b7071-goog
> 


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 8/8] rust: workqueue: add examples
  2023-06-11 16:15   ` Benno Lossin
@ 2023-06-27  8:38     ` Alice Ryhl
  0 siblings, 0 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-27  8:38 UTC (permalink / raw)
  To: benno.lossin
  Cc: alex.gaynor, aliceryhl, bjorn3_gh, boqun.feng, gary,
	jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux, tj,
	wedsonaf

Benno Lossin <benno.lossin@proton.me> writes:
> On 01.06.23 15:49, Alice Ryhl wrote:
>> 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 <aliceryhl@google.com>
> 
> Reviewed-by: Benno Lossin <benno.lossin@proton.me>
> 
> I really like that you added these examples!
> Is there some particular reason you decided to not use
> 0 as the first index in the second example? (you can keep
> it this way)

In my head, it felt more natural for the first field to be called 1 and
the second field to be called 2. But it doesn't really matter which
numbers you use.

Alice


^ permalink raw reply	[flat|nested] 53+ messages in thread

* Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
  2023-06-11 15:59   ` Benno Lossin
@ 2023-06-27  8:42     ` Alice Ryhl
  0 siblings, 0 replies; 53+ messages in thread
From: Alice Ryhl @ 2023-06-27  8:42 UTC (permalink / raw)
  To: benno.lossin
  Cc: alex.gaynor, aliceryhl, bjorn3_gh, boqun.feng, gary,
	jiangshanlai, linux-kernel, ojeda, patches, rust-for-linux, tj,
	wedsonaf

Benno Lossin <benno.lossin@proton.me> writes:
> On 01.06.23 15:49, Alice Ryhl wrote:
>> +/// # Safety
>> +///
>> +/// The [`OFFSET`] constant must be the offset of a field in Self of type [`Work<T, ID>`]. The methods on
>> +/// this trait must have exactly the behavior that the definitions given below have.
> 
> I think you should just say "implementers are not allowed to implement
> the functions defined by this trait." I see no reason to allow that, since
> all functions are fully determined by the `OFFSET` constant.
 
The macro overrides one of the methods, so that wont work.
(It overrides the method to check that the field has the claimed type.)

I'll apply the rest of your suggestions.

Alice


^ permalink raw reply	[flat|nested] 53+ messages in thread

end of thread, other threads:[~2023-06-27  8:42 UTC | newest]

Thread overview: 53+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2023-06-01 13:49 [PATCH v2 0/8] rust: workqueue: add bindings for the workqueue Alice Ryhl
2023-06-01 13:49 ` [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings Alice Ryhl
2023-06-01 14:29   ` Martin Rodriguez Reboredo
2023-06-02 14:39   ` Andreas Hindborg (Samsung)
2023-06-06 23:36   ` Boqun Feng
2023-06-07 15:18     ` Alice Ryhl
2023-06-11 15:45   ` Benno Lossin
2023-06-01 13:49 ` [PATCH v2 2/8] rust: add offset_of! macro Alice Ryhl
2023-06-01 17:17   ` Gary Guo
2023-06-02 10:33   ` Andreas Hindborg (Samsung)
2023-06-07 15:15     ` Alice Ryhl
2023-06-11 15:47   ` Benno Lossin
2023-06-01 13:49 ` [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}` Alice Ryhl
2023-06-01 17:26   ` Gary Guo
2023-06-02 10:51   ` Andreas Hindborg (Samsung)
2023-06-05 14:31     ` Gary Guo
2023-06-05 14:49       ` Andreas Hindborg (Samsung)
2023-06-05 15:00       ` Boqun Feng
2023-06-05 15:20         ` Boqun Feng
2023-06-05 18:34         ` Andreas Hindborg (Samsung)
2023-06-11 15:48   ` Benno Lossin
2023-06-01 13:49 ` [PATCH v2 4/8] rust: workqueue: define built-in queues Alice Ryhl
2023-06-01 17:30   ` Gary Guo
2023-06-01 17:52     ` Martin Rodriguez Reboredo
2023-06-02  8:32     ` Alice Ryhl
2023-06-02 14:46   ` Andreas Hindborg (Samsung)
2023-06-11 15:49   ` Benno Lossin
2023-06-01 13:49 ` [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields Alice Ryhl
2023-06-01 14:50   ` Martin Rodriguez Reboredo
2023-06-01 18:44   ` Boqun Feng
2023-06-02  8:38     ` Alice Ryhl
2023-06-02 16:32       ` Boqun Feng
2023-06-01 21:09   ` Boqun Feng
2023-06-02  9:37     ` Alice Ryhl
2023-06-02 14:41   ` Andreas Hindborg (Samsung)
2023-06-11 15:59   ` Benno Lossin
2023-06-27  8:42     ` Alice Ryhl
2023-06-01 13:49 ` [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types Alice Ryhl
2023-06-01 14:51   ` Martin Rodriguez Reboredo
2023-06-02 14:42   ` Andreas Hindborg (Samsung)
2023-06-11 16:01   ` Benno Lossin
2023-06-01 13:49 ` [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method Alice Ryhl
2023-06-01 14:53   ` Martin Rodriguez Reboredo
2023-06-02 14:43   ` Andreas Hindborg (Samsung)
2023-06-11 16:10   ` Benno Lossin
2023-06-01 13:49 ` [PATCH v2 8/8] rust: workqueue: add examples Alice Ryhl
2023-06-01 14:58   ` Martin Rodriguez Reboredo
2023-06-01 17:32   ` Gary Guo
2023-06-02  9:39     ` Alice Ryhl
2023-06-02 14:44   ` Andreas Hindborg (Samsung)
2023-06-02 14:48   ` Andreas Hindborg (Samsung)
2023-06-11 16:15   ` Benno Lossin
2023-06-27  8:38     ` Alice Ryhl

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).