On Tue, 2026-08-04 at 14:54 -0300, Daniel Almeida wrote:
Hi Phillip :)
Tested-by: Daniel Almeida daniel.almeida@collabora.com
Hi, thx for the test
I address your major feedback below; minor points like renaming I will address in the next revision.
On 31 Jul 2026, at 05:04, Philipp Stanner phasta@kernel.org wrote:
[…]
An additional issue discovered during the review process of this code is that there is (currently) no mechanism in Rust to prevent someone from circumventing the DriverFence's FenceContext-reference's lifetime by "forgetting" the fence, e.g. with core::mem::forget(). Since this apparently can also happen with recfounting cycles, it's quite likely that it would enable UAF bugs on the FenceContext. Print warnings if this or other misuse of the fence API happens.
I think cycles are fine, if anything they make things live longer than intended (possibly leaking them forever), but at no point they lead to UAFs. And for the mem::forget() point, there seems to be precedent in other patches pointing to unsafe constructors, where the safety requirement is basically "don't mem::forget() this".
In fact, if you mem::forget() in the previous Arc approach, it seems like you leak the context, while mem::forget() on the current solution does seem to allow UAF by ending the borrow as you said yourself:
let ctx = .... // FenceContext in some driver queue structure let fence = ctx.fence_alloc(...).new_fence() // DriverFence<'_, T> // borrows ctx mem::forget(fence); // ends the borrow drop(ctx); // DriverFenceData contains a dangling &FenceContext, and that allocation is managed by C
versus:
let ctx: Arc<FenceCtx<...>> = ...; // same as above, assume refcount==1 let fence = ctx.new_fence_allocation(..).new_fence(); // ctx refcount==2 mem::forget(fence); // ctx refcount==2 drop(ctx) //ctx refcount==1
I noticed that you added a counter to catch the first case, but that assumes that signaled fences won’t reach into the context anymore, IIUC? More on that below.
Answering on that further down below
[…]
SPDX is being used here,
+/*
- Copyright (C) 2025, 2026 Red Hat Inc.:
- * Author: Philipp Stanner pstanner@redhat.com
- */
So perhaps SPDX-CopyrightText should be used here?
What does that look like? I think I never saw it anywhere.
[…]
+ // happening. + // + // However, we cannot fully guarantee in Rust that `DriverFence`s will not + // be forgotten, e.g., through refcounting. This could circumvent the + // lifetime which intends to enforce that all fences disappear before their + // context. + nr_of_unsignaled_fences: Atomic<u64>,
Why are we tracking the number of unsignaled fences, specifically? Is it not possible for the C side (which controls the actual allocation) to reach back into the Rust side via the callbacks even after the context drops, regardless of their signaled status?
Tracking the number was agreed on as a compromise to move the abstraction forward. It only exists for a warning-print.
The signaled status is absolutely decisive for preventing that both the DriverFence::data and FenceContext cannot be reached anymore by both C *and* Rust code consuming a Fence.
The reason is that the fence backend ops can reach the DriverFence and the FenceContext. Only signalling the fence decouples them, and then you still have to wait for an RCU grace period to be sure that all accessors are gone. This is what the C backend forces on us, but it also applies for someone doing (future implementations of) Fence::get_driver_name() or Fence::is_signaled().
And in any case, even side stepping this signaled vs unsignaled dilemma that this counter is trying to check, the end result seems to be "sorry, you misused the API and now a UAF is possible". In this specific sense, it doesn't sound that much better than what we are trying to move away from in C.
The more I think about this borrow design, the more I believe a simple refcount would be way safer. I mean, this field would go away to begin with, IIUC, and that’s not even considering the point above.
Refcounting does not solve the fundamental issue. A dma_fence must always correctly represent the state of the associated job on the GPU. If you forget a fence, you might deadlock. If you signal a fence for a job that is still running on the GPU, you might get unnoticed memory corruptions.
Refcounting the fctx was also my solution, but was objected to by various parties (IIRC at least Boris and Danilo) who argue that the life time is the proper solution. If I understood correctly the major objection is that the refcount enables the device resources in FenceContext::data to arbitrarily outlive its device, which is something Danilo is very concerned about.
Anyways, as we discussed in the call, and as also my code comment in FenceContext::drop() highlights, this atomic is only there for printing a warning, because the proper solution we actually want is to have the FenceContext signal all forgotten fences when it drops. *Then* you are really completely safe, because then the forgotten fences get decoupled from the fence context. So no UAF, although a driver that forgets fences would still be broken.
The reason why (IIRC) Alice proposed doing the counter + warning and a TODO entry is to move forward faster with the fence implementation, which I understood is also in Tyr's interest (regarding this unlikely bug).
The reason why it is not solved right now is that you need a data structure in FenceContext that keeps track of unsignaled fences. Entries in that data structure then have to be pre-allocated. And you have to remove entries from the data structure *whenever a fence signals*.
The only good data structure we have in Rust currently is XArray, which we cannot use because: * it uses `usize` as an index, but dma_fence seqno is u64, so this could become a problem for Tyr, supporting 32-bit architectures. * We'd need to wait for Andreas' reservation mechanism for XArray. * XArray is not a good data structure for ever-increasing seqnos like the u64 of dma_fence. It quickly performance-degrades because it preserves index order, resulting in like a dozen pointer indirections for large indices.
So I had investigated using a List, but the list would force you then to shove another refcounting mechanism (ListArc) on top of the stored fences, and Rust's list implementation is really not trivial to be used. At least not for me. Getting this right would take time.
Note that with the JobQueue design we're aiming at right now, DriverFence and FenceContext would all be owned by JobQueue, so the driver couldn't ever forget a DriverFence whithout also forgetting the FenceContext. Hence, for the forseeable future, no one will encounter that bug.
So, long story short, this is a solvable TODO, but we need a good data structure for it. Preferably a hash table? Or the list implementation needs to be improved so that it can take an ARef<Fence> instead of a ListArc<Fence>. But someone needs to do that work.
Please tell me whether you agree with proceeding like this and make FenceContext::drop() completely waterproof later, or whether you want to suggest to do that now – but then I'd need help with the data structures.
[…]
+ /// The `data` you pass here must not perform any operations that are illegal + /// in atomic context in its [`Drop`] implementation. + pub fn fence_alloc(&self, data: T::FenceDataType) -> Result<DriverFenceAllocation<'_, T>> {
^ In the same spirit as the last iteration, can we please rename this?
We don’t need to shorten methods and types IMHO. We can just say “new_allocation” or a some other variation without “alloc”.
Well, the name IMO needs to reflect that this method creates some fency object. So just "new_allocation" is not good I think because you want to see *what* is being allocated.
new_fence_allocation() maybe?
[…]
+/// The receiving counterpart of a [`DriverFence`]. +/// +/// The Rust DMA fence implementation has a dualistic design: [`DriverFence`]s +/// are the producer-side, intended to be always owned by only one party. That +/// party has the monopoly on signalling the fence. +/// +/// A [`Fence`] is the counterpart for consumers. Thus, [`Fence`]s are always +/// refcounted and can shared with an arbitrary number of parties, including +/// userspace. Hereby, a [`Fence`] can only be used for actions such as checking +/// the fence's status or for registering callbacks on it. +/// +/// Once the associated [`DriverFence`] signals, all +/// [`FenceCallbackRegistration`]s registered on the [`Fence`] will be executed. +/// +/// A [`Fence`] can arbitrarily outlive its [`DriverFence`] and the +/// [`FenceContext`]. Signalling a [`DriverFence`] decouples it from its +/// [`Fence`]s. +#[repr(transparent)] +pub struct Fence { + /// The actual dma_fence passed to C. + inner: Opaquebindings::dma_fence, +}
+/// Guard helper for locking within this module.
Is this new? Needs a bit more documentation.
It is new, yes. Changelog mentions it.
OTOH I think we shouldn’t come up with a new guard type. IIRC from Lyude’s et al previous work, there’s already a way to build a Rust lock from a C lock (Lock::from_raw()). In fact, I think this whole implementation can boil down to:
pub fn lock(&self) -> SpinLockIrqGuard<‘_, ()> { let ptr = unsafe {bindings::dma_fence_spinlock(…)}; unsafe { SpinLockIrq::<()>::from_raw(ptr)}.lock() }
This has a few advantages:
a) doesn’t introduce its own guard type, instead reusing something that was previously tested,
b) you get the right behavior with the included NotThreadSafe token.
c) the guard is now borrowed. Your guard is owned, which can easily lead to UB because the lifetime is detached from the &self that originated it.
This little helper is only used internally, and where it is used other code bits have to operate on the rawpointer with other unsafe blocks. At other places we use the fence rawpointer without taking the lock. So I'm not sure whether this will ever be clean.
The only reason I added it was that I by now had 3 places where I do unsafe { } lock and unlock.
Lyude's code is not yet merged.
[…]
+/// +/// let mut fctx = KBox::pin_init(FenceContext::new(0, driver_name, timeline_name, fctx_data), GFP_KERNEL)?;
Missing rustfmt?
I do run rustfmt. It doesn't do anything about this line.
P.
linaro-mm-sig@lists.linaro.org