On 12/1/26 10:17, Philipp Stanner wrote: > fence timestamps can be written and read without any memory ordering > since, presumably, forever. This can cause real bugs for parties whose > algorithms depend on valid timestamp values. > > The current misordering allows for the bit DMA_FENCE_FLAG_TIMESTAMP_BIT > to be read as true before the union containing the timestamp actually > gets the timestamp set. Thus, a reader could interpret the list-head in > the union as a timestamp value by accident. > > So currently, both direct users of dma_fence_timestamp() and parties > that check the flag DMA_FENCE_FLAG_TIMESTAMP_BIT manually rely on UB, > which is especially likely to produce bugs on weakly ordered > architectures. > > Fix the problem for now by adding appropriate memory barriers to ensure > ordering. > > Cc: [email protected] > Fixes: 76250f2b743b ("dma-buf/fence: Avoid use of uninitialised timestamp") > Signed-off-by: Philipp Stanner <[email protected]>
Reviewed-by: Christian König <[email protected]> > --- > drivers/dma-buf/dma-fence.c | 9 +++++++++ > include/linux/dma-fence.h | 6 +++++- > 2 files changed, 14 insertions(+), 1 deletion(-) > > diff --git a/drivers/dma-buf/dma-fence.c b/drivers/dma-buf/dma-fence.c > index bd58688b81a7..ccb8258690f7 100644 > --- a/drivers/dma-buf/dma-fence.c > +++ b/drivers/dma-buf/dma-fence.c > @@ -378,6 +378,15 @@ void dma_fence_signal_timestamp_locked(struct dma_fence > *fence, > list_replace(&fence->cb_list, &cb_list); > > fence->timestamp = timestamp; > + /* > + * TODO: > + * This is a (temporary?) fix to prevent misordering until we can > + * completely remove the TIMESTAMP bit. > + * > + * The counterpart of this barrier is the test_bit_acquire() in > + * dma_fence_timestamp(). > + */ > + smp_mb__before_atomic(); > set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags); > > list_for_each_entry_safe(cur, tmp, &cb_list, node) { > diff --git a/include/linux/dma-fence.h b/include/linux/dma-fence.h > index 64330bf52561..fcfdf302f1d9 100644 > --- a/include/linux/dma-fence.h > +++ b/include/linux/dma-fence.h > @@ -718,7 +718,11 @@ static inline ktime_t dma_fence_timestamp(struct > dma_fence *fence) > if (WARN_ON(!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))) > return ktime_get(); > > - while (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags)) > + /* > + * The test_bit_acquire() calls order against the > + * smp_mb__before_atomic() in dma_fence_signal_timestamp_locked(). > + */ > + while (!test_bit_acquire(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags)) > cpu_relax(); > > return fence->timestamp;
