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
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);
248 * dma_fence_enable_sw_signaling - enable signaling on fence
249 * @fence: the fence to enable
251 * This will request for sw signaling to be enabled, to make the fence
252 * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
255 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
259 if (!test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
261 !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) &&
262 fence->ops->enable_signaling) {
263 trace_dma_fence_enable_signal(fence);
265 spin_lock_irqsave(fence->lock, flags);
267 if (!fence->ops->enable_signaling(fence))
268 dma_fence_signal_locked(fence);
270 spin_unlock_irqrestore(fence->lock, flags);
273 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
276 * dma_fence_add_callback - add a callback to be called when the fence
278 * @fence: the fence to wait on
279 * @cb: the callback to register
280 * @func: the function to call
282 * @cb will be initialized by dma_fence_add_callback(), no initialization
283 * by the caller is required. Any number of callbacks can be registered
284 * to a fence, but a callback can only be registered to one fence at a time.
286 * Note that the callback can be called from an atomic context. If
287 * fence is already signaled, this function will return -ENOENT (and
288 * *not* call the callback).
290 * Add a software callback to the fence. Same restrictions apply to
291 * refcount as it does to dma_fence_wait(), however the caller doesn't need to
292 * keep a refcount to fence afterward dma_fence_add_callback() has returned:
293 * when software access is enabled, the creator of the fence is required to keep
294 * the fence alive until after it signals with dma_fence_signal(). The callback
295 * itself can be called from irq context.
297 * Returns 0 in case of success, -ENOENT if the fence is already signaled
298 * and -EINVAL in case of error.
300 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
301 dma_fence_func_t func)
307 if (WARN_ON(!fence || !func))
310 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
311 INIT_LIST_HEAD(&cb->node);
315 spin_lock_irqsave(fence->lock, flags);
317 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
320 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
322 else if (!was_set && fence->ops->enable_signaling) {
323 trace_dma_fence_enable_signal(fence);
325 if (!fence->ops->enable_signaling(fence)) {
326 dma_fence_signal_locked(fence);
333 list_add_tail(&cb->node, &fence->cb_list);
335 INIT_LIST_HEAD(&cb->node);
336 spin_unlock_irqrestore(fence->lock, flags);
340 EXPORT_SYMBOL(dma_fence_add_callback);
343 * dma_fence_get_status - returns the status upon completion
344 * @fence: the dma_fence to query
346 * This wraps dma_fence_get_status_locked() to return the error status
347 * condition on a signaled fence. See dma_fence_get_status_locked() for more
350 * Returns 0 if the fence has not yet been signaled, 1 if the fence has
351 * been signaled without an error condition, or a negative error code
352 * if the fence has been completed in err.
354 int dma_fence_get_status(struct dma_fence *fence)
359 spin_lock_irqsave(fence->lock, flags);
360 status = dma_fence_get_status_locked(fence);
361 spin_unlock_irqrestore(fence->lock, flags);
365 EXPORT_SYMBOL(dma_fence_get_status);
368 * dma_fence_remove_callback - remove a callback from the signaling list
369 * @fence: the fence to wait on
370 * @cb: the callback to remove
372 * Remove a previously queued callback from the fence. This function returns
373 * true if the callback is successfully removed, or false if the fence has
374 * already been signaled.
377 * Cancelling a callback should only be done if you really know what you're
378 * doing, since deadlocks and race conditions could occur all too easily. For
379 * this reason, it should only ever be done on hardware lockup recovery,
380 * with a reference held to the fence.
382 * Behaviour is undefined if @cb has not been added to @fence using
383 * dma_fence_add_callback() beforehand.
386 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
391 spin_lock_irqsave(fence->lock, flags);
393 ret = !list_empty(&cb->node);
395 list_del_init(&cb->node);
397 spin_unlock_irqrestore(fence->lock, flags);
401 EXPORT_SYMBOL(dma_fence_remove_callback);
403 struct default_wait_cb {
404 struct dma_fence_cb base;
405 struct task_struct *task;
409 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
411 struct default_wait_cb *wait =
412 container_of(cb, struct default_wait_cb, base);
414 wake_up_state(wait->task, TASK_NORMAL);
418 * dma_fence_default_wait - default sleep until the fence gets signaled
419 * or until timeout elapses
420 * @fence: the fence to wait on
421 * @intr: if true, do an interruptible wait
422 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
424 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
425 * remaining timeout in jiffies on success. If timeout is zero the value one is
426 * returned if the fence is already signaled for consistency with other
427 * functions taking a jiffies timeout.
430 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
432 struct default_wait_cb cb;
434 signed long ret = timeout ? timeout : 1;
437 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
440 spin_lock_irqsave(fence->lock, flags);
442 if (intr && signal_pending(current)) {
447 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
450 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
453 if (!was_set && fence->ops->enable_signaling) {
454 trace_dma_fence_enable_signal(fence);
456 if (!fence->ops->enable_signaling(fence)) {
457 dma_fence_signal_locked(fence);
467 cb.base.func = dma_fence_default_wait_cb;
469 list_add(&cb.base.node, &fence->cb_list);
471 while (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
473 __set_current_state(TASK_INTERRUPTIBLE);
475 __set_current_state(TASK_UNINTERRUPTIBLE);
476 spin_unlock_irqrestore(fence->lock, flags);
478 ret = schedule_timeout(ret);
480 spin_lock_irqsave(fence->lock, flags);
481 if (ret > 0 && intr && signal_pending(current))
485 if (!list_empty(&cb.base.node))
486 list_del(&cb.base.node);
487 __set_current_state(TASK_RUNNING);
490 spin_unlock_irqrestore(fence->lock, flags);
493 EXPORT_SYMBOL(dma_fence_default_wait);
496 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
501 for (i = 0; i < count; ++i) {
502 struct dma_fence *fence = fences[i];
503 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
513 * dma_fence_wait_any_timeout - sleep until any fence gets signaled
514 * or until timeout elapses
515 * @fences: array of fences to wait on
516 * @count: number of fences to wait on
517 * @intr: if true, do an interruptible wait
518 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
519 * @idx: used to store the first signaled fence index, meaningful only on
522 * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
523 * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
526 * Synchronous waits for the first fence in the array to be signaled. The
527 * caller needs to hold a reference to all fences in the array, otherwise a
528 * fence might be freed before return, resulting in undefined behavior.
530 * See also dma_fence_wait() and dma_fence_wait_timeout().
533 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
534 bool intr, signed long timeout, uint32_t *idx)
536 struct default_wait_cb *cb;
537 signed long ret = timeout;
540 if (WARN_ON(!fences || !count || timeout < 0))
544 for (i = 0; i < count; ++i)
545 if (dma_fence_is_signaled(fences[i])) {
554 cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
560 for (i = 0; i < count; ++i) {
561 struct dma_fence *fence = fences[i];
563 cb[i].task = current;
564 if (dma_fence_add_callback(fence, &cb[i].base,
565 dma_fence_default_wait_cb)) {
566 /* This fence is already signaled */
575 set_current_state(TASK_INTERRUPTIBLE);
577 set_current_state(TASK_UNINTERRUPTIBLE);
579 if (dma_fence_test_signaled_any(fences, count, idx))
582 ret = schedule_timeout(ret);
584 if (ret > 0 && intr && signal_pending(current))
588 __set_current_state(TASK_RUNNING);
592 dma_fence_remove_callback(fences[i], &cb[i].base);
599 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
602 * dma_fence_init - Initialize a custom fence.
603 * @fence: the fence to initialize
604 * @ops: the dma_fence_ops for operations on this fence
605 * @lock: the irqsafe spinlock to use for locking this fence
606 * @context: the execution context this fence is run on
607 * @seqno: a linear increasing sequence number for this context
609 * Initializes an allocated fence, the caller doesn't have to keep its
610 * refcount after committing with this fence, but it will need to hold a
611 * refcount again if &dma_fence_ops.enable_signaling gets called.
613 * context and seqno are used for easy comparison between fences, allowing
614 * to check which fence is later by simply using dma_fence_later().
617 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
618 spinlock_t *lock, u64 context, unsigned seqno)
621 BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
623 kref_init(&fence->refcount);
625 INIT_LIST_HEAD(&fence->cb_list);
627 fence->context = context;
628 fence->seqno = seqno;
632 trace_dma_fence_init(fence);
634 EXPORT_SYMBOL(dma_fence_init);