Skip to contentSkip to conversation

rust: aref: document safety of ARef doctest example

PATCH Superseded Cian McGuire 1 participant 4 messages Jul 24

Subsystems (2)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/4 rust: aref: document safety of ARef doctest example

The into_raw doctest contains two unsafe items whose SAFETY comments were left as "TODO.": the AlwaysRefCounted impl for the example's Empty type, and the subsequent ARef::from_raw call.

Both are sound for the same reason: Empty's inc_ref/dec_ref are no-ops. AlwaysRefCounted's safety contract only constrains dec_ref, requiring that it not free the object while a live increment remains; since this dec_ref never frees anything, that requirement holds vacuously.

The same fact justifies the from_raw call. Elsewhere in this file, Clone and From<&T> justify their own calls to from_raw by pointing at a preceding inc_ref() call, but no such call happens in this example. That is fine here specifically because Empty does not track a real reference count at all, so there is no accounting for from_raw to violate, regardless of whether an increment "really" occurred.

---
 rust/kernel/sync/aref.rs | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
rust/kernel/sync/aref.rs +4 -2
index b721b2e00b98..a27b9b8f2eda 100644
@@ -124,7 +124,8 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
     ///
     /// struct Empty {}
     ///
-    /// # // SAFETY: TODO.
+    /// # // SAFETY: `inc_ref` and `dec_ref` are no-ops, so the requirement that `dec_ref`
+    /// # // must not free the object while a live increment remains is trivially satisfied.
     /// unsafe impl AlwaysRefCounted for Empty {
     ///     fn inc_ref(&self) {}
     ///     unsafe fn dec_ref(_obj: NonNull<Self>) {}
@@ -132,7 +133,8 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {
     ///
     /// let mut data = Empty {};
     /// let ptr = NonNull::<Empty>::new(&mut data).unwrap();
-    /// # // SAFETY: TODO.
+    /// # // SAFETY: `Empty`'s `inc_ref`/`dec_ref` do not track a real count, so `dec_ref` can
+    /// # // never free `data`; the safety contract of `from_raw` is vacuously satisfied here.
     /// let data_ref: ARef<Empty> = unsafe { ARef::from_raw(ptr) };
     /// let raw_ptr: NonNull<Empty> = ARef::into_raw(data_ref);
     ///
Signature · 1 line
2.55.0
#1 lore raw

PATCH 2/4 rust: print: document safety of _printk FFI calls

Two calls in this file had their SAFETY comments left as "TODO.": the cast back to fmt::Arguments in rust_fmt_argument, and the call to bindings::_printk in call_printk.

Both are two ends of the same round trip. call_printk passes a raw pointer to its args: fmt::Arguments<'_> parameter into _printk, whose format string always contains a %pA specifier for it. The %pA case in lib/vsprintf.c's pointer formatter calls back into rust_fmt_argument with that same pointer, synchronously, as one call in a switch dispatch that returns its result immediately -- there is no deferred use or storage of the pointer on the C side. So args remains alive on call_printk's stack for the whole time rust_fmt_argument is running with ptr pointing at it.

The _printk call itself is also justified by this function's own # Safety section: format_string is guaranteed to be one of the fixed format_strings statics (traced through every pr_*! macro, each of which hardcodes a specific one), so its %s/%pA specifiers always match the two extra arguments supplied, and module_name is guaranteed null-terminated by both of its possible origins (kernel::__LOG_PREFIX and the one generated by the module! proc macro).

---
 rust/kernel/print.rs | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
rust/kernel/print.rs +10 -2
index 6fd84389a858..0e341262f83e 100644
@@ -29,7 +29,11 @@
     use fmt::Write;
     // SAFETY: The C contract guarantees that `buf` is valid if it's less than `end`.
     let mut w = unsafe { RawFormatter::from_ptrs(buf.cast(), end.cast()) };
-    // SAFETY: TODO.
+    // SAFETY: This function is only reachable via the `%pA` format specifier handled in
+    // `lib/vsprintf.c`, which calls it synchronously with the `ptr` that `call_printk`
+    // derived from a live `&fmt::Arguments`, before that reference's scope can end. `ptr`
+    // is therefore valid and properly aligned for a `fmt::Arguments<'_>` for the duration
+    // of this call.
     let _ = w.write_fmt(unsafe { *ptr.cast::<fmt::Arguments<'_>>() });
     w.pos().cast()
 }
@@ -109,7 +113,11 @@ pub unsafe fn call_printk(
 ) {
     // `_printk` does not seem to fail in any path.
     #[cfg(CONFIG_PRINTK)]
-    // SAFETY: TODO.
+    // SAFETY: By this function's safety requirements, `format_string` is one of the fixed
+    // `format_strings` statics, so its `%s`/`%pA` specifiers match the two arguments
+    // supplied below, and `module_name` is null-terminated as `%s` requires. The third
+    // argument points at `args`, which remains valid for the duration of this call and is
+    // only read back synchronously, through `%pA`, by `rust_fmt_argument`.
     unsafe {
         bindings::_printk(
             format_string.as_ptr(),
Signature · 1 line
2.55.0
#2 lore raw

PATCH 3/4 rust: list: document safety of List::remove

In reply to Cian McGuire

The call to ListLinks::fields(T::view_links(item)) in List::remove had its SAFETY comment left as "TODO.". This call chains two separate safety requirements that need to be discharged together.

view_links requires its pointer argument to point at a valid value. item is a &T, and Rust's reference guarantees mean it is always a valid, non-dangling pointer to a live value of type T, so this is satisfied without needing anything beyond ordinary reference validity (view_links's own doc comment notes it "need not be in an Arc", to head off the assumption that anything more is required here).

fields requires its pointer argument to be dereferenceable. The pointer returned by view_links is guaranteed dereferenceable by its own documented guarantees: it is either the pointer from a preceding prepare_to_insert call, which itself must point at a valid value, or it points at a read-only ListLinks with null fields. Either way, fields's requirement is satisfied.

---
 rust/kernel/list.rs | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
rust/kernel/list.rs +6 -1
index 406e3a028c55..22b497eb10c0 100644
@@ -599,7 +599,12 @@ pub fn pop_front(&mut self) -> Option<ListArc<T, ID>> {
     ///
     /// `item` must not be in a different linked list (with the same id).
     pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {
-        // SAFETY: TODO.
+        // SAFETY: `item` is a `&T`, and Rust's reference guarantees mean it is always a valid,
+        // non-dangling pointer to a live value of type `T`, satisfying `view_links`'s safety
+        // requirement. The pointer `view_links` returns is guaranteed dereferenceable by its own
+        // documented guarantees: it's either the pointer from a preceding `prepare_to_insert`
+        // call, which itself must point at a valid value, or it points at a read-only
+        // `ListLinks` with null fields. Either way, `fields`'s safety requirement is satisfied.
         let mut item = unsafe { ListLinks::fields(T::view_links(item)) };
         // SAFETY: The user provided a reference, and reference are never dangling.
         //
Signature · 1 line
2.55.0
#3 lore raw

PATCH 4/4 rust: workqueue: document safety of Pin<KBox<T>> work item impls

In reply to Cian McGuire

The WorkItemPointer and RawWorkItem impls for Pin<KBox<T>> had their SAFETY comments left as "TODO.". Both traits are already implemented for Arc<T> earlier in this file with real justifications; these two impls follow the same shape, adapted for KBox.

WorkItemPointer's contract requires that __enqueue use a work_struct initialized with this impl's run as the function pointer. This holds regardless of which smart pointer type is involved:
Work::new is generic over any T: WorkItem<ID> and always bakes in T::Pointer::run, so for a T bound by WorkItem<ID, Pointer = Self> it bakes in exactly this impl's run. The argument is identical to the existing Arc<T> comment and does not depend on anything Arc-specific.

RawWorkItem's contract requires that pointers passed to the queue_work_on closure remain valid for the duration __enqueue guarantees. This one is not a direct copy of the Arc<T> case, because the two __enqueue implementations differ: __enqueue here leaks the box via KBox::into_raw before calling the closure, so the pointer is valid for the call. If the closure returns true, the pointer remains valid until reclaimed in WorkItemPointer::run via a matching KBox::from_raw. If the closure returns false, __enqueue's own safety requirement only permits that when the work_struct is already enqueued elsewhere -- but self is an exclusively-owned Pin<KBox<T>>, and ownership is only ever given up by enqueuing it, so it cannot already be enqueued while this call still holds it. That branch is therefore genuinely unreachable, matching the unreachable_unchecked call.

---
 rust/kernel/workqueue.rs | 19 +++++++++++++++++--
 1 file changed, 17 insertions(+), 2 deletions(-)
rust/kernel/workqueue.rs +17 -2
index 7e253b6f299c..0a525746028b 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` field, using `T::raw_get_work`.
+//   - 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 that the correct `Work` field will be used
+//     because of the ID const generic bound. This makes sure that `T::raw_get_work` uses the
+//     correct offset for the `Work` field, 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>,
@@ -901,7 +909,14 @@ unsafe impl<T, const ID: u64> WorkItemPointer<ID> for Pin<KBox<T>>
     }
 }
 
-// SAFETY: TODO.
+// SAFETY: `__enqueue` leaks the box via `KBox::into_raw` before calling `queue_work_on`, so
+// the pointer is valid for the duration of that call. If the closure returns true, the
+// pointer remains valid until reclaimed in `WorkItemPointer::run`, which reconstructs the box
+// with a matching `KBox::from_raw`. If the closure returns false, `__enqueue`'s own safety
+// requirement only permits that when the `work_struct` is already in a workqueue -- but
+// `self` is an exclusively-owned `Pin<KBox<T>>`, and ownership is only ever given up by
+// enqueuing it, so it cannot already be enqueued elsewhere while we still hold it here. That
+// branch is therefore unreachable, matching the `unreachable_unchecked` call.
 unsafe impl<T, const ID: u64> RawWorkItem<ID> for Pin<KBox<T>>
 where
     T: WorkItem<ID, Pointer = Self>,
Signature · 1 line
2.55.0