rust: workqueue: add bindings for the workqueue
Alice Ryhl
maintainerv2 cover rust: workqueue: add bindings for the workqueue
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/[email protected]/
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
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Alice Ryhl
maintainerPATCH v2 1/8 rust: workqueue: add low-level workqueue bindings
Define basic low-level bindings to a kernel workqueue. The API defined here can only be used unsafely. Later commits will provide safe wrappers.
--- 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
rust/bindings/bindings_helper.h +1 -0
@@ -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 ;
rust/kernel/lib.rs +1 -0
@@ -43,6 +43,7 @@pub mod sync;pub mod task;pub mod types; +pub mod workqueue;#[doc(hidden)] pub use bindings;
rust/kernel/workqueue.rs new file +107 -0
107 lines not on this page · raw message
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
Quoted 9 lines · Alice Ryhl
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 <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>---
[...]
My Reviewed-by is missing.
Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
In reply to Alice RyhlQuoted 7 lines · Alice Ryhl
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 <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
Quoted 144 lines
--- 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.rsrust/bindings/bindings_helper.h +1
-0@@ -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 ;rust/kernel/lib.rs +1
-0@@ -43,6 +43,7 @@pub mod sync;pub mod task;pub mod types; +pub mod workqueue;#[doc(hidden)] pub use bindings;rust/kernel/workqueue.rs new file +107
-0@@ -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 ) -> &'aQueue { +// SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The +// caller promises that the pointer is not dangling. +unsafe { &*(ptras *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 ; +}
Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
In reply to Alice RyhlOn Thu, Jun 01, 2023 at 01:49:39PM +0000, Alice Ryhl wrote:
[...]
Quoted 7 lines
rust/kernel/workqueue.rs new file +7
-0+/// 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
rust/kernel/workqueue.rs line 81
Quoted 10 lines
rust/kernel/workqueue.rs new file +10
-0+/// 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
Quoted 29 lines
rust/kernel/workqueue.rs new file +26
-0+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 ; +}Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Alice Ryhl
maintainerRe: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
Quoted 23 lines · Boqun Feng
On Thu, Jun 01, 2023 at 01:49:39PM +0000, Alice Ryhl wrote:
[...]Quoted 7 lines
rust/kernel/workqueue.rs new file +7
-0+/// 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 rust/kernel/workqueue.rs line 81
Quoted 10 lines
rust/kernel/workqueue.rs new file +10
-0+/// 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"?
Quoted 2 lines
Regards,
Boqun
Sure, I will clarify that this refers to the guarantees section in the next version of the patchset.
Alice
Re: [PATCH v2 1/8] rust: workqueue: add low-level workqueue bindings
In reply to Alice RyhlQuoted 7 lines · Alice Ryhl
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 <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
Signature · 2 lines
Cheers, Benno
Quoted 147 lines
--- 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.rsrust/bindings/bindings_helper.h +1
-0@@ -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 ;rust/kernel/lib.rs +1
-0@@ -43,6 +43,7 @@pub mod sync;pub mod task;pub mod types; +pub mod workqueue;#[doc(hidden)] pub use bindings;rust/kernel/workqueue.rs new file +107
-1@@ -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 ) -> &'aQueue { +// SAFETY: The `Queue` type is `#[repr(transparent)]`, so the pointer cast is valid. The +// caller promises that the pointer is not dangling. +unsafe { &*(ptras *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
Alice Ryhl
maintainerPATCH v2 2/8 rust: add offset_of! macro
In reply to Alice RyhlFrom: Wedson Almeida Filho <[email protected]>
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.
--- rust/kernel/lib.rs | 35 +++++++++++++++++++++++++++++++++++ scripts/Makefile.build | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-)
rust/kernel/lib.rs +35 -0
@@ -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 (outeras *const u8 )as usize + } + }}; +}
scripts/Makefile.build +1 -1
@@ -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) \
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 2/8] rust: add offset_of! macro
Quoted 19 lines · On Thu, 1 Jun 2023 13:49:40 +0000 Alice Ryhl <[email protected]> wrote:
From: Wedson Almeida Filho <[email protected]>
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 ofsub_fieldwithfield's type being a struct with a field calledsub_field. This is becausefieldmight be aBox<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.
Quoted 5 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>
Quoted 68 lines
--- rust/kernel/lib.rs | 35 +++++++++++++++++++++++++++++++++++ scripts/Makefile.build | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-)rust/kernel/lib.rs +35
-0@@ -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 (outeras *const u8 )as usize + } + }}; +}scripts/Makefile.build +1
-1@@ -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) \
Re: [PATCH v2 2/8] rust: add offset_of! macro
In reply to Alice RyhlQuoted 52 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
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 ofsub_fieldwithfield's type being a struct with a field calledsub_field. This is becausefieldmight be aBox<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.Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>--- rust/kernel/lib.rs | 35 +++++++++++++++++++++++++++++++++++ scripts/Makefile.build | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-)rust/kernel/lib.rs +8
-0@@ -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)]
rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 118
Quoted 10 lines
rust/kernel/lib.rs +10
-0+/// 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
Quoted 30 lines
rust/kernel/lib.rs +17
-0+ 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 (outeras *const u8 )as usize + } + }}; +}scripts/Makefile.build +1
-1@@ -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) \
Alice Ryhl
maintainerRe: [PATCH v2 2/8] rust: add offset_of! macro
Quoted 11 lines · Andreas Hindborg (Samsung)
rust/kernel/lib.rs fn panic(info: &core::panic::PanicInfo<'_>) -> ! { · line 118
Quoted 3 lines · Alice Ryhl
rust/kernel/lib.rs +3
-0+#[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
Re: [PATCH v2 2/8] rust: add offset_of! macro
In reply to Alice RyhlQuoted 19 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
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 ofsub_fieldwithfield's type being a struct with a field calledsub_field. This is becausefieldmight be aBox<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.
Quoted 5 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>
Signature · 2 lines
Cheers, Benno
Quoted 71 lines
--- rust/kernel/lib.rs | 35 +++++++++++++++++++++++++++++++++++ scripts/Makefile.build | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-)rust/kernel/lib.rs +35
-0@@ -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 (outeras *const u8 )as usize + } + }}; +}scripts/Makefile.build +1
-2@@ -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
Alice Ryhl
maintainerPATCH v2 3/8 rust: sync: add `Arc::{from_raw, into_raw}`
In reply to Alice RyhlFrom: Wedson Almeida Filho <[email protected]>
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.
--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)
rust/kernel/lib.rs +1 -0
@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)]
rust/kernel/sync/arc.rs +41 -1
54 lines not on this page · raw message
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
Quoted 10 lines · On Thu, 1 Jun 2023 13:49:41 +0000 Alice Ryhl <[email protected]> wrote:
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.
Quoted 6 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>
Quoted 4 lines
--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)
Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
In reply to Alice RyhlQuoted 72 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)rust/kernel/lib.rs +1
-0@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] rust/kernel/sync/arc.rs +23
-1@@ -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.
rust/kernel/sync/arc.rs unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { · line 246
Quoted 10 lines
rust/kernel/sync/arc.rs +10
-0+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 (ptras *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
Quoted 11 lines
rust/kernel/sync/arc.rs +8
-0+let ptr = (ptras *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
Gary Guo
maintainerRe: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
Quoted 96 lines · On Fri, 02 Jun 2023 12:51:08 +0200 "Andreas Hindborg (Samsung)"…
Quoted 72 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)rust/kernel/lib.rs +1
-0@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] rust/kernel/sync/arc.rs +23
-1@@ -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. rust/kernel/sync/arc.rs unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { · line 246
Quoted 10 lines
rust/kernel/sync/arc.rs +10
-0+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 (ptras *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::Metadatais defined will not allow this, even though we know it is valid. I would suggest the following instead:
Quoted 7 lines
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.
Quoted 5 lines
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
Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
Quoted 107 lines · Gary Guo
Quoted 96 lines · On Fri, 02 Jun 2023 12:51:08 +0200 "Andreas Hindborg (Samsung)"…
Quoted 72 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)rust/kernel/lib.rs +1
-0@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] rust/kernel/sync/arc.rs +23
-1@@ -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. rust/kernel/sync/arc.rs unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { · line 246
Quoted 10 lines
rust/kernel/sync/arc.rs +10
-0+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 (ptras *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::Metadatais defined will not allow this, even though we know it is valid. I would suggest the following instead:Quoted 7 lines
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) };
Quoted 1 line
This could just be a
transmute_copy.
Even better 👍
BR Andreas
Quoted 11 lines
Quoted 6 lines
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
Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
In reply to Gary GuoQuoted 107 lines · Gary Guo
Quoted 96 lines · On Fri, 02 Jun 2023 12:51:08 +0200 "Andreas Hindborg (Samsung)"…
Quoted 72 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)rust/kernel/lib.rs +1
-0@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] rust/kernel/sync/arc.rs +23
-1@@ -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. rust/kernel/sync/arc.rs unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { · line 246
Quoted 10 lines
rust/kernel/sync/arc.rs +10
-0+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 (ptras *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::Metadatais defined will not allow this, even though we know it is valid. I would suggest the following instead:Quoted 7 lines
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) };
Quoted 2 lines
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
Quoted 8 lines
Quoted 5 lines
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
Quoted 2 lines
Best,
Gary
Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
Quoted 141 lines · Boqun Feng
Quoted 107 lines · Gary Guo
Quoted 96 lines · On Fri, 02 Jun 2023 12:51:08 +0200 "Andreas Hindborg (Samsung)"…
Quoted 72 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)rust/kernel/lib.rs +1
-0@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] rust/kernel/sync/arc.rs +23
-1@@ -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. rust/kernel/sync/arc.rs unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { · line 246
Quoted 10 lines
rust/kernel/sync/arc.rs +10
-0+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 (ptras *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::Metadatais defined will not allow this, even though we know it is valid. I would suggest the following instead:Quoted 7 lines
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) };Quoted 2 lines
This could just be a
transmute_copy.Or just
transmute:let metadata = unsafe { core::mem::transmute<_, <ArcInner<T> as Pointee>>::Metadata>(metadata) };? Since
Pointee::MetadataisCopy.Regards,
BoqunQuoted 8 lines
Quoted 5 lines
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);
Quoted 3 lines
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
Quoted 5 lines
Regards,
BoqunQuoted 2 lines
Best,
Gary
Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
In reply to Boqun FengQuoted 111 lines · Boqun Feng
Quoted 107 lines · Gary Guo
Quoted 96 lines · On Fri, 02 Jun 2023 12:51:08 +0200 "Andreas Hindborg (Samsung)"…
Quoted 72 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)rust/kernel/lib.rs +1
-0@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] rust/kernel/sync/arc.rs +23
-1@@ -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. rust/kernel/sync/arc.rs unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { · line 246
Quoted 10 lines
rust/kernel/sync/arc.rs +10
-0+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 (ptras *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::Metadatais defined will not allow this, even though we know it is valid. I would suggest the following instead:Quoted 7 lines
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) };Quoted 2 lines
This could just be a
transmute_copy.
Quoted 8 lines
Or just
transmute:let metadata = unsafe { core::mem::transmute<_, <ArcInner<T> as Pointee>>::Metadata>(metadata) };? Since
Pointee::MetadataisCopy.
I like transmute_copy() better for being more explicit.
Quoted 22 lines
Regards,
BoqunQuoted 8 lines
Quoted 5 lines
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);
Quoted 2 lines
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
Re: [PATCH v2 3/8] rust: sync: add `Arc::{from_raw, into_raw}`
In reply to Alice RyhlQuoted 10 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
These methods can be used to turn an
Arcinto a raw pointer and back, in a way that preserves the metadata for fat pointers.This is done using the unstable
ptr_metadatafeature [1]. However, it could also be done using the unstablepointer_byte_offsetsfeature [2], which is likely to have a shorter path to stabilization thanptr_metadata.
Quoted 6 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>
Signature · 2 lines
Cheers, Benno
Quoted 80 lines
--- rust/kernel/lib.rs | 1 + rust/kernel/sync/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-)rust/kernel/lib.rs +1
-0@@ -17,6 +17,7 @@#![feature(const_refs_to_cell)] #![feature(dispatch_from_dyn)] #![feature(new_uninit)] +#![feature(ptr_metadata)] #![feature(receiver_trait)] #![feature(unsize)] rust/kernel/sync/arc.rs +41
-2@@ -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 (ptras *const ArcInner <T >); +let ptr = (ptras *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
Alice Ryhl
maintainerPATCH v2 4/8 rust: workqueue: define built-in queues
In reply to Alice RyhlFrom: Wedson Almeida Filho <[email protected]>
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.
--- rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+)
rust/kernel/workqueue.rs +65 -0
@@ -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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// SAFETY: `system_freezable_power_efficient_wq` is a C global, always available. +unsafe {Queue ::from_raw (bindings::system_freezable_power_efficient_wq) } +}
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
Quoted 10 lines · On Thu, 1 Jun 2023 13:49:42 +0000 Alice Ryhl <[email protected]> wrote:
From: Wedson Almeida Filho <[email protected]>
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.
Quoted 4 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>
This looks fine to me, so:
Just one question about style: would people prefer:
kernel::workqueue::system().enqueue(...)
or
use kernel::workqueue::Queue; Queue::system().enqueue(...)
?
Quoted 77 lines
--- rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+)rust/kernel/workqueue.rs +65
-0@@ -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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// SAFETY: `system_freezable_power_efficient_wq` is a C global, always available. +unsafe {Queue ::from_raw (bindings::system_freezable_power_efficient_wq) } +}
Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
Quoted 24 lines · Gary Guo
Quoted 10 lines · On Thu, 1 Jun 2023 13:49:42 +0000 Alice Ryhl <[email protected]> wrote:
From: Wedson Almeida Filho <[email protected]>
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.Quoted 4 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>This looks fine to me, so:
Reviewed-by Gary Guo <[email protected]>Just one question about style: would people prefer:
Quoted 8 lines
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.
Quoted 1 line
[...]
Alice Ryhl
maintainerRe: [PATCH v2 4/8] rust: workqueue: define built-in queues
In reply to Gary GuoQuoted 23 lines · Gary Guo
Quoted 10 lines · On Thu, 1 Jun 2023 13:49:42 +0000 Alice Ryhl <[email protected]> wrote:
From: Wedson Almeida Filho <[email protected]>
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.Quoted 4 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>This looks fine to me, so:
Reviewed-by Gary Guo <[email protected]>Just one question about style: would people prefer:
Quoted 8 lines
kernel::workqueue::system().enqueue(...)or
use kernel::workqueue::Queue; Queue::system().enqueue(...)?
I prefer the first version.
Alice
Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
In reply to Alice RyhlQuoted 10 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
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.
Quoted 4 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>
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 👍
Quoted 77 lines
--- rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+)rust/kernel/workqueue.rs +65
-0@@ -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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// SAFETY: `system_freezable_power_efficient_wq` is a C global, always available. +unsafe {Queue ::from_raw (bindings::system_freezable_power_efficient_wq) } +}
Re: [PATCH v2 4/8] rust: workqueue: define built-in queues
In reply to Alice RyhlQuoted 10 lines · Alice Ryhl
From: Wedson Almeida Filho <[email protected]>
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.
Quoted 4 lines
Signed-off-by Wedson Almeida Filho <[email protected]>Co-developed-by Alice Ryhl <[email protected]>Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Martin Rodriguez Reboredo <[email protected]>
Signature · 2 lines
Cheers, Benno
Quoted 80 lines
--- rust/kernel/workqueue.rs | 65 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+)rust/kernel/workqueue.rs +65
-1@@ -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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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 () -> &'staticQueue { +// 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
Alice Ryhl
maintainerPATCH v2 5/8 rust: workqueue: add helper for defining work_struct fields
In reply to Alice RyhlThe 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.
--- rust/helpers.c | 8 ++ rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 226 insertions(+), 1 deletion(-)
rust/helpers.c +8 -0
@@ -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
rust/kernel/workqueue.rs +218 -1
233 lines not on this page · raw message
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
Quoted 46 lines · Alice Ryhl
The main challenge with defining
work_structfields is making sure that the function pointer stored in thework_structis appropriate for the work item type it is embedded in. It needs to know the offset of thework_structfield being used (even if there are several!) so that it can do acontainer_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.
* Thework_structfield. This is a field of the work item struct.This patch introduces a separate trait for each piece. The pointer type is given a
WorkItemPointertrait, which pointer types need to implement to be usable with the workqueue. This trait will be implemented forArcandBoxin a later patch in this patchset. Implementing this trait is unsafe because this is where thecontainer_ofoperation happens, but user-code will not need to implement it themselves.The work item struct should then implement the
WorkItemtrait. 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_structfield, we use a trait calledHasWork<T, ID>. If a type implements this trait, then the type declares that, at the given offset, there is a field of typeWork<T, ID>. The trait is marked unsafe because the OFFSET constant must be correct, but we provide animpl_has_work!macro that can safely implementHasWork<T>on a type. The macro expands to something that only compiles if the specified field really has the typeWork<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 } } ```
Quoted 8 lines
Note that since the
Worktype is annotated with an id, you can have severalwork_structfields by using a different id for each one.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>---
[...]
Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
In reply to Alice RyhlQuoted 70 lines · Alice Ryhl
The main challenge with defining
work_structfields is making sure that the function pointer stored in thework_structis appropriate for the work item type it is embedded in. It needs to know the offset of thework_structfield being used (even if there are several!) so that it can do acontainer_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.
* Thework_structfield. This is a field of the work item struct.This patch introduces a separate trait for each piece. The pointer type is given a
WorkItemPointertrait, which pointer types need to implement to be usable with the workqueue. This trait will be implemented forArcandBoxin a later patch in this patchset. Implementing this trait is unsafe because this is where thecontainer_ofoperation happens, but user-code will not need to implement it themselves.The work item struct should then implement the
WorkItemtrait. 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_structfield, we use a trait calledHasWork<T, ID>. If a type implements this trait, then the type declares that, at the given offset, there is a field of typeWork<T, ID>. The trait is marked unsafe because the OFFSET constant must be correct, but we provide animpl_has_work!macro that can safely implementHasWork<T>on a type. The macro expands to something that only compiles if the specified field really has the typeWork<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
Worktype is annotated with an id, you can have severalwork_structfields by using a different id for each one.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>--- rust/helpers.c | 8 ++ rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 226 insertions(+), 1 deletion(-)rust/helpers.c +1
-0@@ -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 ) {
rust/helpers.c void rust_helper_put_task_struct(struct task_struct *t) · line 135
Quoted 7 lines
rust/helpers.c +4
-0@@ -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/[email protected]/
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
Quoted 248 lines
rust/helpers.c +3
-0+} +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 rust/kernel/workqueue.rs +218
-1@@ -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 { (ptras *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 { (ptras *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 Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Alice Ryhl
maintainerRe: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
Quoted 51 lines · Boqun Feng
Quoted 13 lines · Alice Ryhl
rust/helpers.c +1
-0@@ -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 ) {rust/helpers.c void rust_helper_put_task_struct(struct task_struct *t) · line 135
Quoted 7 lines
rust/helpers.c +4
-0@@ -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.
Quoted 8 lines
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/[email protected]/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
Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
Quoted 55 lines · Alice Ryhl
Quoted 54 lines · Boqun Feng
Quoted 13 lines · Alice Ryhl
rust/helpers.c +1
-0@@ -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 ) {rust/helpers.c void rust_helper_put_task_struct(struct task_struct *t) · line 135
Quoted 7 lines
rust/helpers.c +4
-0@@ -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:
Quoted 9 lines
Quoted 5 lines
https://lore.kernel.org/rust-for-linux/[email protected]/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
Quoted 1 line
Alice
Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
In reply to Alice RyhlQuoted 149 lines · Alice Ryhl
The main challenge with defining
work_structfields is making sure that the function pointer stored in thework_structis appropriate for the work item type it is embedded in. It needs to know the offset of thework_structfield being used (even if there are several!) so that it can do acontainer_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.
* Thework_structfield. This is a field of the work item struct.This patch introduces a separate trait for each piece. The pointer type is given a
WorkItemPointertrait, which pointer types need to implement to be usable with the workqueue. This trait will be implemented forArcandBoxin a later patch in this patchset. Implementing this trait is unsafe because this is where thecontainer_ofoperation happens, but user-code will not need to implement it themselves.The work item struct should then implement the
WorkItemtrait. 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_structfield, we use a trait calledHasWork<T, ID>. If a type implements this trait, then the type declares that, at the given offset, there is a field of typeWork<T, ID>. The trait is marked unsafe because the OFFSET constant must be correct, but we provide animpl_has_work!macro that can safely implementHasWork<T>on a type. The macro expands to something that only compiles if the specified field really has the typeWork<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
Worktype is annotated with an id, you can have severalwork_structfields by using a different id for each one.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>--- rust/helpers.c | 8 ++ rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 226 insertions(+), 1 deletion(-)rust/helpers.c +8
-0@@ -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 rust/kernel/workqueue.rs +48
-1@@ -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.
rust/kernel/workqueue.rs unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput · line 165
Quoted 10 lines
rust/kernel/workqueue.rs +10
-0+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
Quoted 166 lines
rust/kernel/workqueue.rs +160
-0+ +/// 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 { (ptras *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 { (ptras *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 Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Alice Ryhl
maintainerRe: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
Quoted 69 lines · Boqun Feng
Quoted 22 lines · Alice Ryhl
rust/kernel/workqueue.rs +22
-0+/// 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. rust/kernel/workqueue.rs unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput · line 165
Quoted 10 lines
rust/kernel/workqueue.rs +10
-0+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(); } }
Quoted 4 lines
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
Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
In reply to Alice RyhlQuoted 46 lines · Alice Ryhl
The main challenge with defining
work_structfields is making sure that the function pointer stored in thework_structis appropriate for the work item type it is embedded in. It needs to know the offset of thework_structfield being used (even if there are several!) so that it can do acontainer_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.
* Thework_structfield. This is a field of the work item struct.This patch introduces a separate trait for each piece. The pointer type is given a
WorkItemPointertrait, which pointer types need to implement to be usable with the workqueue. This trait will be implemented forArcandBoxin a later patch in this patchset. Implementing this trait is unsafe because this is where thecontainer_ofoperation happens, but user-code will not need to implement it themselves.The work item struct should then implement the
WorkItemtrait. 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_structfield, we use a trait calledHasWork<T, ID>. If a type implements this trait, then the type declares that, at the given offset, there is a field of typeWork<T, ID>. The trait is marked unsafe because the OFFSET constant must be correct, but we provide animpl_has_work!macro that can safely implementHasWork<T>on a type. The macro expands to something that only compiles if the specified field really has the typeWork<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 } } ```
Quoted 6 lines
Note that since the
Worktype is annotated with an id, you can have severalwork_structfields by using a different id for each one.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
Quoted 270 lines
--- rust/helpers.c | 8 ++ rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 226 insertions(+), 1 deletion(-)rust/helpers.c +8
-0@@ -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 rust/kernel/workqueue.rs +218
-1@@ -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 { (ptras *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 { (ptras *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
Re: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
In reply to Alice RyhlQuoted 46 lines · Alice Ryhl
The main challenge with defining
work_structfields is making sure that the function pointer stored in thework_structis appropriate for the work item type it is embedded in. It needs to know the offset of thework_structfield being used (even if there are several!) so that it can do acontainer_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.
* Thework_structfield. This is a field of the work item struct.This patch introduces a separate trait for each piece. The pointer type is given a
WorkItemPointertrait, which pointer types need to implement to be usable with the workqueue. This trait will be implemented forArcandBoxin a later patch in this patchset. Implementing this trait is unsafe because this is where thecontainer_ofoperation happens, but user-code will not need to implement it themselves.The work item struct should then implement the
WorkItemtrait. 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_structfield, we use a trait calledHasWork<T, ID>. If a type implements this trait, then the type declares that, at the given offset, there is a field of typeWork<T, ID>. The trait is marked unsafe because the OFFSET constant must be correct, but we provide animpl_has_work!macro that can safely implementHasWork<T>on a type. The macro expands to something that only compiles if the specified field really has the typeWork<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 } } ```
Quoted 6 lines
Note that since the
Worktype is annotated with an id, you can have severalwork_structfields by using a different id for each one.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
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.
Quoted 72 lines
--- rust/helpers.c | 8 ++ rust/kernel/workqueue.rs | 219 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 226 insertions(+), 1 deletion(-)rust/helpers.c +8
-0@@ -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 rust/kernel/workqueue.rs +26
-1@@ -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. ///
rust/kernel/workqueue.rs unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput · line 138
Quoted 8 lines
rust/kernel/workqueue.rs +5
-0@@ -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.
Quoted 82 lines
rust/kernel/workqueue.rs +82
-0+/// +/// 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 {
rust/kernel/workqueue.rs unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput · line 230
Quoted 10 lines
rust/kernel/workqueue.rs +10
-0+// 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.
rust/kernel/workqueue.rs unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput · line 234
Quoted 4 lines
rust/kernel/workqueue.rs +4
-0+/// # 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.
Signature · 2 lines
Cheers, Benno
Quoted 97 lines
rust/kernel/workqueue.rs +91
-1+/// +/// [`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 { (ptras *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 { (ptras *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
Alice Ryhl
maintainerRe: [PATCH v2 5/8] rust: workqueue: add helper for defining work_struct fields
Quoted 9 lines · Benno Lossin
rust/kernel/workqueue.rs unsafe fn __enqueue<F>(self, queue_work_on: F) -> Self::EnqueueOutput · line 234
Quoted 4 lines · Alice Ryhl
rust/kernel/workqueue.rs +4
-0+/// # 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
OFFSETconstant.
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
Alice Ryhl
maintainerPATCH v2 6/8 rust: workqueue: implement `WorkItemPointer` for pointer types
In reply to Alice RyhlThis 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.
--- rust/kernel/workqueue.rs | 97 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-)
rust/kernel/workqueue.rs +96 -1
@@ -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 = ptras *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 = ptras *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
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types
Quoted 10 lines · Alice Ryhl
This implements the
WorkItemPointertrait for the pointer types that you are likely to use the workqueue with. TheArctype is for reference counted objects, and thePin<Box<T>>type is for objects where the caller has exclusive ownership of the object.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>---
[...]
Re: [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types
In reply to Alice RyhlQuoted 8 lines · Alice Ryhl
This implements the
WorkItemPointertrait for the pointer types that you are likely to use the workqueue with. TheArctype is for reference counted objects, and thePin<Box<T>>type is for objects where the caller has exclusive ownership of the object.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
Quoted 120 lines
--- rust/kernel/workqueue.rs | 97 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-)rust/kernel/workqueue.rs +96
-1@@ -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 = ptras *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 = ptras *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
Re: [PATCH v2 6/8] rust: workqueue: implement `WorkItemPointer` for pointer types
In reply to Alice RyhlQuoted 8 lines · Alice Ryhl
This implements the
WorkItemPointertrait for the pointer types that you are likely to use the workqueue with. TheArctype is for reference counted objects, and thePin<Box<T>>type is for objects where the caller has exclusive ownership of the object.Co-developed-by Gary Guo <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
I have a small nit below.
Quoted 44 lines
--- rust/kernel/workqueue.rs | 97 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-)rust/kernel/workqueue.rs +23
-1@@ -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 = ptras *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 >,
rust/kernel/workqueue.rs unsafe fn raw_get_work(ptr: *mut Self) -> *mut $crate::workqueue::Work<$work_typ · line 357
Quoted 10 lines
rust/kernel/workqueue.rs +10
-0+ 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.
Signature · 2 lines
Cheers, Benno
Quoted 69 lines
rust/kernel/workqueue.rs +63
-1+ +// 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 = ptras *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
Alice Ryhl
maintainerPATCH v2 7/8 rust: workqueue: add `try_spawn` helper method
In reply to Alice RyhlThis 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.
--- rust/kernel/workqueue.rs | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+)
rust/kernel/workqueue.rs +43 -0
@@ -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 >,
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method
Quoted 9 lines · Alice Ryhl
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 <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>---
[...]
Re: [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method
In reply to Alice RyhlQuoted 7 lines · Alice Ryhl
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 <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
Quoted 72 lines
--- rust/kernel/workqueue.rs | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+)rust/kernel/workqueue.rs +43
-0@@ -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 >,
Re: [PATCH v2 7/8] rust: workqueue: add `try_spawn` helper method
In reply to Alice RyhlQuoted 7 lines · Alice Ryhl
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 <[email protected]>Signed-off-by Gary Guo <[email protected]>Signed-off-by Alice Ryhl <[email protected]>
Signature · 2 lines
Cheers, Benno
Quoted 75 lines
--- rust/kernel/workqueue.rs | 43 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+)rust/kernel/workqueue.rs +43
-1@@ -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
Alice Ryhl
maintainerPATCH v2 8/8 rust: workqueue: add examples
In reply to Alice RyhlThis 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.
--- rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+)
rust/kernel/workqueue.rs +104 -0
@@ -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 };
Signature · 1 line
2.41.0.rc0.172.g3f132b7071-goog
Re: [PATCH v2 8/8] rust: workqueue: add examples
Quoted 8 lines · Alice Ryhl
This adds two examples of how to use the workqueue. The first example shows how to use it when you only have one
work_structfield, and the second example shows how to use it when you have multiplework_structfields.Signed-off-by Alice Ryhl <[email protected]>---
[...]
Re: [PATCH v2 8/8] rust: workqueue: add examples
In reply to Alice RyhlQuoted 105 lines · On Thu, 1 Jun 2023 13:49:46 +0000 Alice Ryhl <[email protected]> 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_structfield, and the second example shows how to use it when you have multiplework_structfields.Signed-off-by Alice Ryhl <[email protected]>--- rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+)rust/kernel/workqueue.rs +87
-0@@ -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); +//! } +//! } +//!
rust/kernel/workqueue.rs line 125
Quoted 10 lines
rust/kernel/workqueue.rs +10
-0+//! 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?
Quoted 10 lines
rust/kernel/workqueue.rs +7
-0+//! } +//! +//! 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 };
Alice Ryhl
maintainerRe: [PATCH v2 8/8] rust: workqueue: add examples
Quoted 121 lines · Gary Guo
Quoted 105 lines · On Thu, 1 Jun 2023 13:49:46 +0000 Alice Ryhl <[email protected]> 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_structfield, and the second example shows how to use it when you have multiplework_structfields.Signed-off-by Alice Ryhl <[email protected]>--- rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+)rust/kernel/workqueue.rs +87
-0@@ -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); +//! } +//! } +//! rust/kernel/workqueue.rs line 125
Quoted 10 lines
rust/kernel/workqueue.rs +10
-0+//! 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
Quoted 3 lines
let _ = workqueue::system().enqueue::<_, 1>(val);here, right?
Yes, you can also do that.
Re: [PATCH v2 8/8] rust: workqueue: add examples
In reply to Alice RyhlQuoted 6 lines · Alice Ryhl
This adds two examples of how to use the workqueue. The first example shows how to use it when you only have one
work_structfield, and the second example shows how to use it when you have multiplework_structfields.Signed-off-by Alice Ryhl <[email protected]>
Quoted 119 lines
--- rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+)rust/kernel/workqueue.rs +104
-0@@ -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 };
Re: [PATCH v2 8/8] rust: workqueue: add examples
In reply to Alice RyhlQuoted 6 lines · Alice Ryhl
This adds two examples of how to use the workqueue. The first example shows how to use it when you only have one
work_structfield, and the second example shows how to use it when you have multiplework_structfields.Signed-off-by Alice Ryhl <[email protected]>
Quoted 119 lines
--- rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+)rust/kernel/workqueue.rs +104
-0@@ -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 };
Re: [PATCH v2 8/8] rust: workqueue: add examples
In reply to Alice RyhlQuoted 6 lines · Alice Ryhl
This adds two examples of how to use the workqueue. The first example shows how to use it when you only have one
work_structfield, and the second example shows how to use it when you have multiplework_structfields.Signed-off-by Alice Ryhl <[email protected]>
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)
Signature · 2 lines
Cheers, Benno
Quoted 122 lines
--- rust/kernel/workqueue.rs | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+)rust/kernel/workqueue.rs +104
-1@@ -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
Alice Ryhl
maintainerRe: [PATCH v2 8/8] rust: workqueue: add examples
Quoted 6 lines · Benno Lossin
Quoted 5 lines · Alice Ryhl
This adds two examples of how to use the workqueue. The first example shows how to use it when you only have one
work_structfield, and the second example shows how to use it when you have multiplework_structfields.
Quoted 8 lines
Quoted 1 line
Signed-off-by Alice Ryhl <[email protected]>Reviewed-by Benno Lossin <[email protected]>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