Skip to contentSkip to conversation

rust: workqueue: replace SAFETY TODO for `WorkItemPointer` impl on `Pin<KBox<T>>`

PATCH In review Sagar Taunk 2 participants 2 messages Apr 30 Rust

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 rust: workqueue: replace SAFETY TODO for `WorkItemPointer` impl on `Pin<KBox<T>>`

The original implementation left a SAFETY: TODO comment on the WorkItemPointer implementation for Pin<KBox<T>>. This patch documents the safety requirements that make this implementation sound.

The safety argument follows the same structure as the Arc<T> implementation and relies on three guarantees:
__enqueue strips the Pin wrapper via Pin::into_inner_unchecked
and leaks the box via KBox::into_raw, producing *mut T whose allocation remains live for the duration of the queued work; work_container_of safely reverses the raw_get_work offset arithmetic to recover the exact *mut T that __enqueue produced; and the workqueue guarantees run is called exactly once, making KBox::from_raw sound.

---
 rust/kernel/workqueue.rs | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
rust/kernel/workqueue.rs +9 -1
index 74c59f2b1c09..676ade0539e3 100644
@@ -881,7 +881,15 @@ unsafe impl<T, const ID: u64> RawDelayedWorkItem<ID> for Arc<T>
 {
 }
 
-// SAFETY: TODO.
+// SAFETY: The `__enqueue` implementation in `RawWorkItem` uses a `work_struct` initialized with
+// the `run` method of this trait as the function pointer because:
+//   - `__enqueue` gets the `work_struct` from the `Work<T, ID>` field embedded in `T`,
+//     using `T::raw_get_work` on the pointer obtained from `KBox::into_raw`.
+//   - The only safe way to create a `Work` object is through `Work::new`.
+//   - `Work::new` makes sure that `T::Pointer::run` is passed to `init_work_with_key`.
+//   - Finally, `Work` and `RawWorkItem` guarantee the correct `Work` field is used
+//     because of the `ID` const generic bound, and `Work::new` picks the correct
+//     implementation of `WorkItemPointer` for `Pin<KBox<T>>`.
 unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
Signature · 1 line
2.54.0
reviewer Reviewed-by on v2 1/1
#1 lore raw
Quoted 13 lines · Sagar Taunk

The original implementation left a SAFETY: TODO comment on the WorkItemPointer implementation for Pin<KBox<T>>. This patch documents the safety requirements that make this implementation sound.

The safety argument follows the same structure as the Arc<T> implementation and relies on three guarantees:
__enqueue strips the Pin wrapper via Pin::into_inner_unchecked
and leaks the box via KBox::into_raw, producing *mut T whose allocation remains live for the duration of the queued work; work_container_of safely reverses the raw_get_work offset arithmetic to recover the exact *mut T that __enqueue produced; and the workqueue guarantees run is called exactly once, making KBox::from_raw sound.

Quoted 1 line

Thanks