2 * Fence mechanism for dma-buf and to allow for asynchronous dma access
4 * Copyright (C) 2012 Canonical Ltd
5 * Copyright (C) 2012 Texas Instruments
8 * Rob Clark <robdclark@gmail.com>
9 * Maarten Lankhorst <maarten.lankhorst@canonical.com>
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 as published by
13 * the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
21 #include <linux/slab.h>
22 #include <linux/export.h>
23 #include <linux/atomic.h>
24 #include <linux/dma-fence.h>
25 #include <linux/sched/signal.h>
27 #define CREATE_TRACE_POINTS
28 #include <trace/events/dma_fence.h>
30 EXPORT_TRACEPOINT_SYMBOL(dma_fence_emit);
31 EXPORT_TRACEPOINT_SYMBOL(dma_fence_enable_signal);
34 * fence context counter: each execution context should have its own
35 * fence context, this allows checking if fences belong to the same
36 * context or not. One device can have multiple separate contexts,
37 * and they're used if some engine can run independently of another.
39 static atomic64_t dma_fence_context_counter = ATOMIC64_INIT(0);
42 * DOC: DMA fences overview
44 * DMA fences, represented by &struct dma_fence, are the kernel internal
45 * synchronization primitive for DMA operations like GPU rendering, video
46 * encoding/decoding, or displaying buffers on a screen.
48 * A fence is initialized using dma_fence_init() and completed using
49 * dma_fence_signal(). Fences are associated with a context, allocated through
50 * dma_fence_context_alloc(), and all fences on the same context are
53 * Since the purposes of fences is to facilitate cross-device and
54 * cross-application synchronization, there's multiple ways to use one:
56 * - Individual fences can be exposed as a &sync_file, accessed as a file
57 * descriptor from userspace, created by calling sync_file_create(). This is
58 * called explicit fencing, since userspace passes around explicit
59 * synchronization points.
61 * - Some subsystems also have their own explicit fencing primitives, like
62 * &drm_syncobj. Compared to &sync_file, a &drm_syncobj allows the underlying
63 * fence to be updated.
65 * - Then there's also implicit fencing, where the synchronization points are
66 * implicitly passed around as part of shared &dma_buf instances. Such
67 * implicit fences are stored in &struct reservation_object through the
68 * &dma_buf.resv pointer.
72 * dma_fence_context_alloc - allocate an array of fence contexts
73 * @num: amount of contexts to allocate
75 * This function will return the first index of the number of fence contexts
76 * allocated. The fence context is used for setting &dma_fence.context to a
77 * unique number by passing the context to dma_fence_init().
79 u64 dma_fence_context_alloc(unsigned num)
82 return atomic64_add_return(num, &dma_fence_context_counter) - num;
84 EXPORT_SYMBOL(dma_fence_context_alloc);
87 * dma_fence_signal_locked - signal completion of a fence
88 * @fence: the fence to signal
90 * Signal completion for software callbacks on a fence, this will unblock
91 * dma_fence_wait() calls and run all the callbacks added with
92 * dma_fence_add_callback(). Can be called multiple times, but since a fence
93 * can only go from the unsignaled to the signaled state and not back, it will
94 * only be effective the first time.
96 * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
99 * Returns 0 on success and a negative error value when @fence has been
102 int dma_fence_signal_locked(struct dma_fence *fence)
104 struct dma_fence_cb *cur, *tmp;
107 lockdep_assert_held(fence->lock);
112 if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
116 * we might have raced with the unlocked dma_fence_signal,
117 * still run through all callbacks
120 fence->timestamp = ktime_get();
121 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
122 trace_dma_fence_signaled(fence);
125 list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
126 list_del_init(&cur->node);
127 cur->func(fence, cur);
131 EXPORT_SYMBOL(dma_fence_signal_locked);
134 * dma_fence_signal - signal completion of a fence
135 * @fence: the fence to signal
137 * Signal completion for software callbacks on a fence, this will unblock
138 * dma_fence_wait() calls and run all the callbacks added with
139 * dma_fence_add_callback(). Can be called multiple times, but since a fence
140 * can only go from the unsignaled to the signaled state and not back, it will
141 * only be effective the first time.
143 * Returns 0 on success and a negative error value when @fence has been
146 int dma_fence_signal(struct dma_fence *fence)
153 if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
156 fence->timestamp = ktime_get();
157 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
158 trace_dma_fence_signaled(fence);
160 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) {
161 struct dma_fence_cb *cur, *tmp;
163 spin_lock_irqsave(fence->lock, flags);
164 list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
165 list_del_init(&cur->node);
166 cur->func(fence, cur);
168 spin_unlock_irqrestore(fence->lock, flags);
172 EXPORT_SYMBOL(dma_fence_signal);
175 * dma_fence_wait_timeout - sleep until the fence gets signaled
176 * or until timeout elapses
177 * @fence: the fence to wait on
178 * @intr: if true, do an interruptible wait
179 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
181 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
182 * remaining timeout in jiffies on success. Other error values may be
183 * returned on custom implementations.
185 * Performs a synchronous wait on this fence. It is assumed the caller
186 * directly or indirectly (buf-mgr between reservation and committing)
187 * holds a reference to the fence, otherwise the fence might be
188 * freed before return, resulting in undefined behavior.
190 * See also dma_fence_wait() and dma_fence_wait_any_timeout().
193 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
197 if (WARN_ON(timeout < 0))
200 trace_dma_fence_wait_start(fence);
201 if (fence->ops->wait)
202 ret = fence->ops->wait(fence, intr, timeout);
204 ret = dma_fence_default_wait(fence, intr, timeout);
205 trace_dma_fence_wait_end(fence);
208 EXPORT_SYMBOL(dma_fence_wait_timeout);
211 * dma_fence_release - default relese function for fences
212 * @kref: &dma_fence.recfount
214 * This is the default release functions for &dma_fence. Drivers shouldn't call
215 * this directly, but instead call dma_fence_put().
217 void dma_fence_release(struct kref *kref)
219 struct dma_fence *fence =
220 container_of(kref, struct dma_fence, refcount);
222 trace_dma_fence_destroy(fence);
224 /* Failed to signal before release, could be a refcounting issue */
225 WARN_ON(!list_empty(&fence->cb_list));
227 if (fence->ops->release)
228 fence->ops->release(fence);
230 dma_fence_free(fence);
232 EXPORT_SYMBOL(dma_fence_release);
235 * dma_fence_free - default release function for &dma_fence.
236 * @fence: fence to release
238 * This is the default implementation for &dma_fence_ops.release. It calls
239 * kfree_rcu() on @fence.
241 void dma_fence_free(struct dma_fence *fence)
243 kfree_rcu(fence, rcu);
245 EXPORT_SYMBOL(dma_fence_free);
247 static bool __dma_fence_enable_signaling(struct dma_fence *fence)
251 lockdep_assert_held(fence->lock);
253 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
256 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
259 if (!was_set && fence->ops->enable_signaling) {
260 trace_dma_fence_enable_signal(fence);
262 if (!fence->ops->enable_signaling(fence)) {
263 dma_fence_signal_locked(fence);
272 * dma_fence_enable_sw_signaling - enable signaling on fence
273 * @fence: the fence to enable
275 * This will request for sw signaling to be enabled, to make the fence
276 * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
279 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
283 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
286 spin_lock_irqsave(fence->lock, flags);
287 __dma_fence_enable_signaling(fence);
288 spin_unlock_irqrestore(fence->lock, flags);
290 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
293 * dma_fence_add_callback - add a callback to be called when the fence
295 * @fence: the fence to wait on
296 * @cb: the callback to register
297 * @func: the function to call
299 * @cb will be initialized by dma_fence_add_callback(), no initialization
300 * by the caller is required. Any number of callbacks can be registered
301 * to a fence, but a callback can only be registered to one fence at a time.
303 * Note that the callback can be called from an atomic context. If
304 * fence is already signaled, this function will return -ENOENT (and
305 * *not* call the callback).
307 * Add a software callback to the fence. Same restrictions apply to
308 * refcount as it does to dma_fence_wait(), however the caller doesn't need to
309 * keep a refcount to fence afterward dma_fence_add_callback() has returned:
310 * when software access is enabled, the creator of the fence is required to keep
311 * the fence alive until after it signals with dma_fence_signal(). The callback
312 * itself can be called from irq context.
314 * Returns 0 in case of success, -ENOENT if the fence is already signaled
315 * and -EINVAL in case of error.
317 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
318 dma_fence_func_t func)
323 if (WARN_ON(!fence || !func))
326 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
327 INIT_LIST_HEAD(&cb->node);
331 spin_lock_irqsave(fence->lock, flags);
333 if (__dma_fence_enable_signaling(fence)) {
335 list_add_tail(&cb->node, &fence->cb_list);
337 INIT_LIST_HEAD(&cb->node);
341 spin_unlock_irqrestore(fence->lock, flags);
345 EXPORT_SYMBOL(dma_fence_add_callback);
348 * dma_fence_get_status - returns the status upon completion
349 * @fence: the dma_fence to query
351 * This wraps dma_fence_get_status_locked() to return the error status
352 * condition on a signaled fence. See dma_fence_get_status_locked() for more
355 * Returns 0 if the fence has not yet been signaled, 1 if the fence has
356 * been signaled without an error condition, or a negative error code
357 * if the fence has been completed in err.
359 int dma_fence_get_status(struct dma_fence *fence)
364 spin_lock_irqsave(fence->lock, flags);
365 status = dma_fence_get_status_locked(fence);
366 spin_unlock_irqrestore(fence->lock, flags);
370 EXPORT_SYMBOL(dma_fence_get_status);
373 * dma_fence_remove_callback - remove a callback from the signaling list
374 * @fence: the fence to wait on
375 * @cb: the callback to remove
377 * Remove a previously queued callback from the fence. This function returns
378 * true if the callback is successfully removed, or false if the fence has
379 * already been signaled.
382 * Cancelling a callback should only be done if you really know what you're
383 * doing, since deadlocks and race conditions could occur all too easily. For
384 * this reason, it should only ever be done on hardware lockup recovery,
385 * with a reference held to the fence.
387 * Behaviour is undefined if @cb has not been added to @fence using
388 * dma_fence_add_callback() beforehand.
391 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
396 spin_lock_irqsave(fence->lock, flags);
398 ret = !list_empty(&cb->node);
400 list_del_init(&cb->node);
402 spin_unlock_irqrestore(fence->lock, flags);
406 EXPORT_SYMBOL(dma_fence_remove_callback);
408 struct default_wait_cb {
409 struct dma_fence_cb base;
410 struct task_struct *task;
414 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
416 struct default_wait_cb *wait =
417 container_of(cb, struct default_wait_cb, base);
419 wake_up_state(wait->task, TASK_NORMAL);
423 * dma_fence_default_wait - default sleep until the fence gets signaled
424 * or until timeout elapses
425 * @fence: the fence to wait on
426 * @intr: if true, do an interruptible wait
427 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
429 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
430 * remaining timeout in jiffies on success. If timeout is zero the value one is
431 * returned if the fence is already signaled for consistency with other
432 * functions taking a jiffies timeout.
435 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
437 struct default_wait_cb cb;
439 signed long ret = timeout ? timeout : 1;
441 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
444 spin_lock_irqsave(fence->lock, flags);
446 if (intr && signal_pending(current)) {
451 if (!__dma_fence_enable_signaling(fence))
459 cb.base.func = dma_fence_default_wait_cb;
461 list_add(&cb.base.node, &fence->cb_list);
463 while (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
465 __set_current_state(TASK_INTERRUPTIBLE);
467 __set_current_state(TASK_UNINTERRUPTIBLE);
468 spin_unlock_irqrestore(fence->lock, flags);
470 ret = schedule_timeout(ret);
472 spin_lock_irqsave(fence->lock, flags);
473 if (ret > 0 && intr && signal_pending(current))
477 if (!list_empty(&cb.base.node))
478 list_del(&cb.base.node);
479 __set_current_state(TASK_RUNNING);
482 spin_unlock_irqrestore(fence->lock, flags);
485 EXPORT_SYMBOL(dma_fence_default_wait);
488 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
493 for (i = 0; i < count; ++i) {
494 struct dma_fence *fence = fences[i];
495 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
505 * dma_fence_wait_any_timeout - sleep until any fence gets signaled
506 * or until timeout elapses
507 * @fences: array of fences to wait on
508 * @count: number of fences to wait on
509 * @intr: if true, do an interruptible wait
510 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
511 * @idx: used to store the first signaled fence index, meaningful only on
514 * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
515 * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
518 * Synchronous waits for the first fence in the array to be signaled. The
519 * caller needs to hold a reference to all fences in the array, otherwise a
520 * fence might be freed before return, resulting in undefined behavior.
522 * See also dma_fence_wait() and dma_fence_wait_timeout().
525 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
526 bool intr, signed long timeout, uint32_t *idx)
528 struct default_wait_cb *cb;
529 signed long ret = timeout;
532 if (WARN_ON(!fences || !count || timeout < 0))
536 for (i = 0; i < count; ++i)
537 if (dma_fence_is_signaled(fences[i])) {
546 cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
552 for (i = 0; i < count; ++i) {
553 struct dma_fence *fence = fences[i];
555 cb[i].task = current;
556 if (dma_fence_add_callback(fence, &cb[i].base,
557 dma_fence_default_wait_cb)) {
558 /* This fence is already signaled */
567 set_current_state(TASK_INTERRUPTIBLE);
569 set_current_state(TASK_UNINTERRUPTIBLE);
571 if (dma_fence_test_signaled_any(fences, count, idx))
574 ret = schedule_timeout(ret);
576 if (ret > 0 && intr && signal_pending(current))
580 __set_current_state(TASK_RUNNING);
584 dma_fence_remove_callback(fences[i], &cb[i].base);
591 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
594 * dma_fence_init - Initialize a custom fence.
595 * @fence: the fence to initialize
596 * @ops: the dma_fence_ops for operations on this fence
597 * @lock: the irqsafe spinlock to use for locking this fence
598 * @context: the execution context this fence is run on
599 * @seqno: a linear increasing sequence number for this context
601 * Initializes an allocated fence, the caller doesn't have to keep its
602 * refcount after committing with this fence, but it will need to hold a
603 * refcount again if &dma_fence_ops.enable_signaling gets called.
605 * context and seqno are used for easy comparison between fences, allowing
606 * to check which fence is later by simply using dma_fence_later().
609 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
610 spinlock_t *lock, u64 context, unsigned seqno)
613 BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
615 kref_init(&fence->refcount);
617 INIT_LIST_HEAD(&fence->cb_list);
619 fence->context = context;
620 fence->seqno = seqno;
624 trace_dma_fence_init(fence);
626 EXPORT_SYMBOL(dma_fence_init);