Re: [PATCH v10 07/13] rust: hrtimer: implement `UnsafeHrTimerPointer` for `Pin<&T>`

From: Benno Lossin
Date: Fri Mar 07 2025 - 08:51:46 EST


On Fri Mar 7, 2025 at 2:37 PM CET, Andreas Hindborg wrote:
> "Benno Lossin" <benno.lossin@xxxxxxxxx> writes:
>> On Fri Mar 7, 2025 at 11:11 AM CET, Andreas Hindborg wrote:
>>> +impl<'a, T> RawHrTimerCallback for Pin<&'a T>
>>> +where
>>> + T: HasHrTimer<T>,
>>> + T: HrTimerCallback<Pointer<'a> = Self>,
>>> +{
>>> + type CallbackTarget<'b> = Self;
>>> +
>>> + unsafe extern "C" fn run(ptr: *mut bindings::hrtimer) -> bindings::hrtimer_restart {
>>> + // `HrTimer` is `repr(C)`
>>> + let timer_ptr = ptr as *mut HrTimer<T>;
>>> +
>>> + // SAFETY: By the safety requirement of this function, `timer_ptr`
>>> + // points to a `HrTimer<T>` contained in an `T`.
>>> + let receiver_ptr = unsafe { T::timer_container_of(timer_ptr) };
>>> +
>>> + // SAFETY: By the safety requirement of this function, `timer_ptr`
>>> + // points to a `HrTimer<T>` contained in an `T`.
>>
>> This justification seems wrong it talks about `HrTimer<T>`, but here we
>> have a `*const T`... Also see [1] (I am mainly interested in your
>> justification for the lifetime).
>>
>> [1]: https://doc.rust-lang.org/std/ptr/index.html#pointer-to-reference-conversion
>
> How is this:
>
> // SAFETY:
> // - By the safety requirement of this function, `timer_ptr`
> // points to a `HrTimer<T>` contained in an `T`.
> // - The `PinHrTimerHandle` associated with this timer is guaranteed to
> // be alive until this method returns. As the handle borrows from
> // `T`, `T` is also guaranteed to be alive for the duration of this
> // function.

Sounds good, if you can also explain (probably somewhere else, as every
`RawHrTimerCallback` implementer will rely on this) why the handle lives
for the duration of the callback.

---
Cheers,
Benno