rust: aref: document safety of ARef doctest example
PATCH v2 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 dec_ref is a no-op and never deallocates anything. AlwaysRefCounted's "keep alive until matching decrement" guarantee therefore holds vacuously here -- no decrement in this impl ever frees the object, so it cannot be freed while a live increment remains. The object's actual lifetime is governed entirely by ordinary Rust scoping instead: data is a stack value that outlives every use of ptr/data_ref/raw_ptr, none of which is ever dereferenced in the example.
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.
---
v2:
- Reworked the AlwaysRefCounted for Empty comment: v1 only argued the dec_ref half of the trait's contract; now it also explains why the no-op dec_ref means nothing is ever freed through this impl, so the "keep alive until matching decrement" guarantee cannot be violated, and notes neither pointer is dereferenced in the example.
- Reworded the from_raw comment to state concretely which invariant is vacuous, instead of just asserting "vacuously satisfied".
rust/kernel/sync/aref.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
rust/kernel/sync/aref.rs +8 -2
@@ -124,7 +124,11 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// /// struct Empty {} /// -/// # // SAFETY: TODO. +/// # // SAFETY: `dec_ref` is a no-op and never deallocates `data`, so the object's +/// # // lifetime is governed entirely by ordinary Rust scoping, not by this impl; the +/// # // trait's "keep alive until matching decrement" guarantee holds vacuously because +/// # // no decrement here ever frees anything, and neither `ptr` nor `raw_ptr` is ever +/// # // dereferenced in this example. /// unsafe impl AlwaysRefCounted for Empty { /// fn inc_ref(&self) {} /// unsafe fn dec_ref(_obj: NonNull<Self>) {}
@@ -132,7 +136,9 @@ pub unsafe fn from_raw(ptr: NonNull<T>) -> Self {/// /// let mut data = Empty {}; /// let ptr = NonNull::<Empty>::new(&mut data).unwrap(); -/// # // SAFETY: TODO. +/// # // SAFETY: `from_raw`'s contract concerns a reference count that `Empty` doesn't +/// # // actually have; since `inc_ref`/`dec_ref` never touch any state, there is no +/// # // invariant here for `from_raw` to violate. /// 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
PATCH v2 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.
rust_fmt_argument is only reachable through the %pA format specifier. Every in-tree Rust caller that uses %pA -- call_printk, device::printk, kunit::printk, and seq_file::call_printf -- invokes it synchronously with a pointer derived from its own live fmt::Arguments, as one call in a switch dispatch in lib/vsprintf.c's pointer formatter that returns its result immediately; there is no deferred use or storage of the pointer on the C side. So the fmt::Arguments value stays alive on the caller'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).
---
v2:
- The rust_fmt_argument comment named only call_printk as the caller supplying ptr; it now names all four in-tree %pA callers (call_printk, device::printk, kunit::printk, seq_file::call_printf), since the argument applies to any of them.
rust/kernel/print.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
rust/kernel/print.rs +9 -2
@@ -29,7 +29,10 @@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; using `%pA` from +// Rust requires the caller to invoke it synchronously with a `ptr` 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 +112,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
PATCH v2 3/4 rust: list: document safety of List::remove
In reply to Cian McGuireThe 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
@@ -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
PATCH v2 4/4 rust: workqueue: document safety of Pin<KBox<T>> work item impls
In reply to Cian McGuireThe 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:
the only safe ways to produce that work_struct are Work::new and DelayedWork::new (reached via HasDelayedWork's raw_as_work), and both are generic over any T: WorkItem<ID> and always bake in T::Pointer::run, so for a T bound by WorkItem<ID, Pointer = Self> either one 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.
---
v2:
- The WorkItemPointer comment claimed Work::new was the only safe way to construct the backing work_struct; it now also credits DelayedWork::new (via HasDelayedWork's raw_as_work) as a second valid path, and updates the closing sentence to match.
rust/kernel/workqueue.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-)
rust/kernel/workqueue.rs +18 -2
@@ -881,7 +881,16 @@ 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 ways to produce that `work_struct` are `Work::new` and `DelayedWork::new` +// (via `HasDelayedWork`'s `raw_as_work`), and both pass `T::Pointer::run` 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 the matching constructor 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 +910,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