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);
32 EXPORT_TRACEPOINT_SYMBOL(dma_fence_signaled);
34 static DEFINE_SPINLOCK(dma_fence_stub_lock);
35 static struct dma_fence dma_fence_stub;
38 * fence context counter: each execution context should have its own
39 * fence context, this allows checking if fences belong to the same
40 * context or not. One device can have multiple separate contexts,
41 * and they're used if some engine can run independently of another.
43 static atomic64_t dma_fence_context_counter = ATOMIC64_INIT(1);
46 * DOC: DMA fences overview
48 * DMA fences, represented by &struct dma_fence, are the kernel internal
49 * synchronization primitive for DMA operations like GPU rendering, video
50 * encoding/decoding, or displaying buffers on a screen.
52 * A fence is initialized using dma_fence_init() and completed using
53 * dma_fence_signal(). Fences are associated with a context, allocated through
54 * dma_fence_context_alloc(), and all fences on the same context are
57 * Since the purposes of fences is to facilitate cross-device and
58 * cross-application synchronization, there's multiple ways to use one:
60 * - Individual fences can be exposed as a &sync_file, accessed as a file
61 * descriptor from userspace, created by calling sync_file_create(). This is
62 * called explicit fencing, since userspace passes around explicit
63 * synchronization points.
65 * - Some subsystems also have their own explicit fencing primitives, like
66 * &drm_syncobj. Compared to &sync_file, a &drm_syncobj allows the underlying
67 * fence to be updated.
69 * - Then there's also implicit fencing, where the synchronization points are
70 * implicitly passed around as part of shared &dma_buf instances. Such
71 * implicit fences are stored in &struct reservation_object through the
72 * &dma_buf.resv pointer.
75 static const char *dma_fence_stub_get_name(struct dma_fence *fence)
80 static const struct dma_fence_ops dma_fence_stub_ops = {
81 .get_driver_name = dma_fence_stub_get_name,
82 .get_timeline_name = dma_fence_stub_get_name,
86 * dma_fence_get_stub - return a signaled fence
88 * Return a stub fence which is already signaled.
90 struct dma_fence *dma_fence_get_stub(void)
92 spin_lock(&dma_fence_stub_lock);
93 if (!dma_fence_stub.ops) {
94 dma_fence_init(&dma_fence_stub,
98 dma_fence_signal_locked(&dma_fence_stub);
100 spin_unlock(&dma_fence_stub_lock);
102 return dma_fence_get(&dma_fence_stub);
104 EXPORT_SYMBOL(dma_fence_get_stub);
107 * dma_fence_context_alloc - allocate an array of fence contexts
108 * @num: amount of contexts to allocate
110 * This function will return the first index of the number of fence contexts
111 * allocated. The fence context is used for setting &dma_fence.context to a
112 * unique number by passing the context to dma_fence_init().
114 u64 dma_fence_context_alloc(unsigned num)
117 return atomic64_add_return(num, &dma_fence_context_counter) - num;
119 EXPORT_SYMBOL(dma_fence_context_alloc);
122 * dma_fence_signal_locked - signal completion of a fence
123 * @fence: the fence to signal
125 * Signal completion for software callbacks on a fence, this will unblock
126 * dma_fence_wait() calls and run all the callbacks added with
127 * dma_fence_add_callback(). Can be called multiple times, but since a fence
128 * can only go from the unsignaled to the signaled state and not back, it will
129 * only be effective the first time.
131 * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
134 * Returns 0 on success and a negative error value when @fence has been
137 int dma_fence_signal_locked(struct dma_fence *fence)
139 struct dma_fence_cb *cur, *tmp;
142 lockdep_assert_held(fence->lock);
147 if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
151 * we might have raced with the unlocked dma_fence_signal,
152 * still run through all callbacks
155 fence->timestamp = ktime_get();
156 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
157 trace_dma_fence_signaled(fence);
160 list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
161 list_del_init(&cur->node);
162 cur->func(fence, cur);
166 EXPORT_SYMBOL(dma_fence_signal_locked);
169 * dma_fence_signal - signal completion of a fence
170 * @fence: the fence to signal
172 * Signal completion for software callbacks on a fence, this will unblock
173 * dma_fence_wait() calls and run all the callbacks added with
174 * dma_fence_add_callback(). Can be called multiple times, but since a fence
175 * can only go from the unsignaled to the signaled state and not back, it will
176 * only be effective the first time.
178 * Returns 0 on success and a negative error value when @fence has been
181 int dma_fence_signal(struct dma_fence *fence)
188 if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
191 fence->timestamp = ktime_get();
192 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
193 trace_dma_fence_signaled(fence);
195 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) {
196 struct dma_fence_cb *cur, *tmp;
198 spin_lock_irqsave(fence->lock, flags);
199 list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
200 list_del_init(&cur->node);
201 cur->func(fence, cur);
203 spin_unlock_irqrestore(fence->lock, flags);
207 EXPORT_SYMBOL(dma_fence_signal);
210 * dma_fence_wait_timeout - sleep until the fence gets signaled
211 * or until timeout elapses
212 * @fence: the fence to wait on
213 * @intr: if true, do an interruptible wait
214 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
216 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
217 * remaining timeout in jiffies on success. Other error values may be
218 * returned on custom implementations.
220 * Performs a synchronous wait on this fence. It is assumed the caller
221 * directly or indirectly (buf-mgr between reservation and committing)
222 * holds a reference to the fence, otherwise the fence might be
223 * freed before return, resulting in undefined behavior.
225 * See also dma_fence_wait() and dma_fence_wait_any_timeout().
228 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
232 if (WARN_ON(timeout < 0))
235 trace_dma_fence_wait_start(fence);
236 if (fence->ops->wait)
237 ret = fence->ops->wait(fence, intr, timeout);
239 ret = dma_fence_default_wait(fence, intr, timeout);
240 trace_dma_fence_wait_end(fence);
243 EXPORT_SYMBOL(dma_fence_wait_timeout);
246 * dma_fence_release - default relese function for fences
247 * @kref: &dma_fence.recfount
249 * This is the default release functions for &dma_fence. Drivers shouldn't call
250 * this directly, but instead call dma_fence_put().
252 void dma_fence_release(struct kref *kref)
254 struct dma_fence *fence =
255 container_of(kref, struct dma_fence, refcount);
257 trace_dma_fence_destroy(fence);
259 /* Failed to signal before release, could be a refcounting issue */
260 WARN_ON(!list_empty(&fence->cb_list));
262 if (fence->ops->release)
263 fence->ops->release(fence);
265 dma_fence_free(fence);
267 EXPORT_SYMBOL(dma_fence_release);
270 * dma_fence_free - default release function for &dma_fence.
271 * @fence: fence to release
273 * This is the default implementation for &dma_fence_ops.release. It calls
274 * kfree_rcu() on @fence.
276 void dma_fence_free(struct dma_fence *fence)
278 kfree_rcu(fence, rcu);
280 EXPORT_SYMBOL(dma_fence_free);
283 * dma_fence_enable_sw_signaling - enable signaling on fence
284 * @fence: the fence to enable
286 * This will request for sw signaling to be enabled, to make the fence
287 * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
290 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
294 if (!test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
296 !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) &&
297 fence->ops->enable_signaling) {
298 trace_dma_fence_enable_signal(fence);
300 spin_lock_irqsave(fence->lock, flags);
302 if (!fence->ops->enable_signaling(fence))
303 dma_fence_signal_locked(fence);
305 spin_unlock_irqrestore(fence->lock, flags);
308 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
311 * dma_fence_add_callback - add a callback to be called when the fence
313 * @fence: the fence to wait on
314 * @cb: the callback to register
315 * @func: the function to call
317 * @cb will be initialized by dma_fence_add_callback(), no initialization
318 * by the caller is required. Any number of callbacks can be registered
319 * to a fence, but a callback can only be registered to one fence at a time.
321 * Note that the callback can be called from an atomic context. If
322 * fence is already signaled, this function will return -ENOENT (and
323 * *not* call the callback).
325 * Add a software callback to the fence. Same restrictions apply to
326 * refcount as it does to dma_fence_wait(), however the caller doesn't need to
327 * keep a refcount to fence afterward dma_fence_add_callback() has returned:
328 * when software access is enabled, the creator of the fence is required to keep
329 * the fence alive until after it signals with dma_fence_signal(). The callback
330 * itself can be called from irq context.
332 * Returns 0 in case of success, -ENOENT if the fence is already signaled
333 * and -EINVAL in case of error.
335 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
336 dma_fence_func_t func)
342 if (WARN_ON(!fence || !func))
345 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
346 INIT_LIST_HEAD(&cb->node);
350 spin_lock_irqsave(fence->lock, flags);
352 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
355 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
357 else if (!was_set && fence->ops->enable_signaling) {
358 trace_dma_fence_enable_signal(fence);
360 if (!fence->ops->enable_signaling(fence)) {
361 dma_fence_signal_locked(fence);
368 list_add_tail(&cb->node, &fence->cb_list);
370 INIT_LIST_HEAD(&cb->node);
371 spin_unlock_irqrestore(fence->lock, flags);
375 EXPORT_SYMBOL(dma_fence_add_callback);
378 * dma_fence_get_status - returns the status upon completion
379 * @fence: the dma_fence to query
381 * This wraps dma_fence_get_status_locked() to return the error status
382 * condition on a signaled fence. See dma_fence_get_status_locked() for more
385 * Returns 0 if the fence has not yet been signaled, 1 if the fence has
386 * been signaled without an error condition, or a negative error code
387 * if the fence has been completed in err.
389 int dma_fence_get_status(struct dma_fence *fence)
394 spin_lock_irqsave(fence->lock, flags);
395 status = dma_fence_get_status_locked(fence);
396 spin_unlock_irqrestore(fence->lock, flags);
400 EXPORT_SYMBOL(dma_fence_get_status);
403 * dma_fence_remove_callback - remove a callback from the signaling list
404 * @fence: the fence to wait on
405 * @cb: the callback to remove
407 * Remove a previously queued callback from the fence. This function returns
408 * true if the callback is successfully removed, or false if the fence has
409 * already been signaled.
412 * Cancelling a callback should only be done if you really know what you're
413 * doing, since deadlocks and race conditions could occur all too easily. For
414 * this reason, it should only ever be done on hardware lockup recovery,
415 * with a reference held to the fence.
417 * Behaviour is undefined if @cb has not been added to @fence using
418 * dma_fence_add_callback() beforehand.
421 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
426 spin_lock_irqsave(fence->lock, flags);
428 ret = !list_empty(&cb->node);
430 list_del_init(&cb->node);
432 spin_unlock_irqrestore(fence->lock, flags);
436 EXPORT_SYMBOL(dma_fence_remove_callback);
438 struct default_wait_cb {
439 struct dma_fence_cb base;
440 struct task_struct *task;
444 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
446 struct default_wait_cb *wait =
447 container_of(cb, struct default_wait_cb, base);
449 wake_up_state(wait->task, TASK_NORMAL);
453 * dma_fence_default_wait - default sleep until the fence gets signaled
454 * or until timeout elapses
455 * @fence: the fence to wait on
456 * @intr: if true, do an interruptible wait
457 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
459 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
460 * remaining timeout in jiffies on success. If timeout is zero the value one is
461 * returned if the fence is already signaled for consistency with other
462 * functions taking a jiffies timeout.
465 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
467 struct default_wait_cb cb;
469 signed long ret = timeout ? timeout : 1;
472 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
475 spin_lock_irqsave(fence->lock, flags);
477 if (intr && signal_pending(current)) {
482 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
485 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
488 if (!was_set && fence->ops->enable_signaling) {
489 trace_dma_fence_enable_signal(fence);
491 if (!fence->ops->enable_signaling(fence)) {
492 dma_fence_signal_locked(fence);
502 cb.base.func = dma_fence_default_wait_cb;
504 list_add(&cb.base.node, &fence->cb_list);
506 while (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
508 __set_current_state(TASK_INTERRUPTIBLE);
510 __set_current_state(TASK_UNINTERRUPTIBLE);
511 spin_unlock_irqrestore(fence->lock, flags);
513 ret = schedule_timeout(ret);
515 spin_lock_irqsave(fence->lock, flags);
516 if (ret > 0 && intr && signal_pending(current))
520 if (!list_empty(&cb.base.node))
521 list_del(&cb.base.node);
522 __set_current_state(TASK_RUNNING);
525 spin_unlock_irqrestore(fence->lock, flags);
528 EXPORT_SYMBOL(dma_fence_default_wait);
531 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
536 for (i = 0; i < count; ++i) {
537 struct dma_fence *fence = fences[i];
538 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
548 * dma_fence_wait_any_timeout - sleep until any fence gets signaled
549 * or until timeout elapses
550 * @fences: array of fences to wait on
551 * @count: number of fences to wait on
552 * @intr: if true, do an interruptible wait
553 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
554 * @idx: used to store the first signaled fence index, meaningful only on
557 * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
558 * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
561 * Synchronous waits for the first fence in the array to be signaled. The
562 * caller needs to hold a reference to all fences in the array, otherwise a
563 * fence might be freed before return, resulting in undefined behavior.
565 * See also dma_fence_wait() and dma_fence_wait_timeout().
568 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
569 bool intr, signed long timeout, uint32_t *idx)
571 struct default_wait_cb *cb;
572 signed long ret = timeout;
575 if (WARN_ON(!fences || !count || timeout < 0))
579 for (i = 0; i < count; ++i)
580 if (dma_fence_is_signaled(fences[i])) {
589 cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
595 for (i = 0; i < count; ++i) {
596 struct dma_fence *fence = fences[i];
598 cb[i].task = current;
599 if (dma_fence_add_callback(fence, &cb[i].base,
600 dma_fence_default_wait_cb)) {
601 /* This fence is already signaled */
610 set_current_state(TASK_INTERRUPTIBLE);
612 set_current_state(TASK_UNINTERRUPTIBLE);
614 if (dma_fence_test_signaled_any(fences, count, idx))
617 ret = schedule_timeout(ret);
619 if (ret > 0 && intr && signal_pending(current))
623 __set_current_state(TASK_RUNNING);
627 dma_fence_remove_callback(fences[i], &cb[i].base);
634 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
637 * dma_fence_init - Initialize a custom fence.
638 * @fence: the fence to initialize
639 * @ops: the dma_fence_ops for operations on this fence
640 * @lock: the irqsafe spinlock to use for locking this fence
641 * @context: the execution context this fence is run on
642 * @seqno: a linear increasing sequence number for this context
644 * Initializes an allocated fence, the caller doesn't have to keep its
645 * refcount after committing with this fence, but it will need to hold a
646 * refcount again if &dma_fence_ops.enable_signaling gets called.
648 * context and seqno are used for easy comparison between fences, allowing
649 * to check which fence is later by simply using dma_fence_later().
652 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
653 spinlock_t *lock, u64 context, u64 seqno)
656 BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
658 kref_init(&fence->refcount);
660 INIT_LIST_HEAD(&fence->cb_list);
662 fence->context = context;
663 fence->seqno = seqno;
667 trace_dma_fence_init(fence);
669 EXPORT_SYMBOL(dma_fence_init);