Merge tag 'trace-v5.11-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt...
[linux/fpc-iii.git] / drivers / dma-buf / dma-fence.c
blob7475e09b0680835e0606b5acbb3a16133d71e658
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Fence mechanism for dma-buf and to allow for asynchronous dma access
5 * Copyright (C) 2012 Canonical Ltd
6 * Copyright (C) 2012 Texas Instruments
8 * Authors:
9 * Rob Clark <robdclark@gmail.com>
10 * Maarten Lankhorst <maarten.lankhorst@canonical.com>
13 #include <linux/slab.h>
14 #include <linux/export.h>
15 #include <linux/atomic.h>
16 #include <linux/dma-fence.h>
17 #include <linux/sched/signal.h>
19 #define CREATE_TRACE_POINTS
20 #include <trace/events/dma_fence.h>
22 EXPORT_TRACEPOINT_SYMBOL(dma_fence_emit);
23 EXPORT_TRACEPOINT_SYMBOL(dma_fence_enable_signal);
24 EXPORT_TRACEPOINT_SYMBOL(dma_fence_signaled);
26 static DEFINE_SPINLOCK(dma_fence_stub_lock);
27 static struct dma_fence dma_fence_stub;
30 * fence context counter: each execution context should have its own
31 * fence context, this allows checking if fences belong to the same
32 * context or not. One device can have multiple separate contexts,
33 * and they're used if some engine can run independently of another.
35 static atomic64_t dma_fence_context_counter = ATOMIC64_INIT(1);
37 /**
38 * DOC: DMA fences overview
40 * DMA fences, represented by &struct dma_fence, are the kernel internal
41 * synchronization primitive for DMA operations like GPU rendering, video
42 * encoding/decoding, or displaying buffers on a screen.
44 * A fence is initialized using dma_fence_init() and completed using
45 * dma_fence_signal(). Fences are associated with a context, allocated through
46 * dma_fence_context_alloc(), and all fences on the same context are
47 * fully ordered.
49 * Since the purposes of fences is to facilitate cross-device and
50 * cross-application synchronization, there's multiple ways to use one:
52 * - Individual fences can be exposed as a &sync_file, accessed as a file
53 * descriptor from userspace, created by calling sync_file_create(). This is
54 * called explicit fencing, since userspace passes around explicit
55 * synchronization points.
57 * - Some subsystems also have their own explicit fencing primitives, like
58 * &drm_syncobj. Compared to &sync_file, a &drm_syncobj allows the underlying
59 * fence to be updated.
61 * - Then there's also implicit fencing, where the synchronization points are
62 * implicitly passed around as part of shared &dma_buf instances. Such
63 * implicit fences are stored in &struct dma_resv through the
64 * &dma_buf.resv pointer.
67 /**
68 * DOC: fence cross-driver contract
70 * Since &dma_fence provide a cross driver contract, all drivers must follow the
71 * same rules:
73 * * Fences must complete in a reasonable time. Fences which represent kernels
74 * and shaders submitted by userspace, which could run forever, must be backed
75 * up by timeout and gpu hang recovery code. Minimally that code must prevent
76 * further command submission and force complete all in-flight fences, e.g.
77 * when the driver or hardware do not support gpu reset, or if the gpu reset
78 * failed for some reason. Ideally the driver supports gpu recovery which only
79 * affects the offending userspace context, and no other userspace
80 * submissions.
82 * * Drivers may have different ideas of what completion within a reasonable
83 * time means. Some hang recovery code uses a fixed timeout, others a mix
84 * between observing forward progress and increasingly strict timeouts.
85 * Drivers should not try to second guess timeout handling of fences from
86 * other drivers.
88 * * To ensure there's no deadlocks of dma_fence_wait() against other locks
89 * drivers should annotate all code required to reach dma_fence_signal(),
90 * which completes the fences, with dma_fence_begin_signalling() and
91 * dma_fence_end_signalling().
93 * * Drivers are allowed to call dma_fence_wait() while holding dma_resv_lock().
94 * This means any code required for fence completion cannot acquire a
95 * &dma_resv lock. Note that this also pulls in the entire established
96 * locking hierarchy around dma_resv_lock() and dma_resv_unlock().
98 * * Drivers are allowed to call dma_fence_wait() from their &shrinker
99 * callbacks. This means any code required for fence completion cannot
100 * allocate memory with GFP_KERNEL.
102 * * Drivers are allowed to call dma_fence_wait() from their &mmu_notifier
103 * respectively &mmu_interval_notifier callbacks. This means any code required
104 * for fence completeion cannot allocate memory with GFP_NOFS or GFP_NOIO.
105 * Only GFP_ATOMIC is permissible, which might fail.
107 * Note that only GPU drivers have a reasonable excuse for both requiring
108 * &mmu_interval_notifier and &shrinker callbacks at the same time as having to
109 * track asynchronous compute work using &dma_fence. No driver outside of
110 * drivers/gpu should ever call dma_fence_wait() in such contexts.
113 static const char *dma_fence_stub_get_name(struct dma_fence *fence)
115 return "stub";
118 static const struct dma_fence_ops dma_fence_stub_ops = {
119 .get_driver_name = dma_fence_stub_get_name,
120 .get_timeline_name = dma_fence_stub_get_name,
124 * dma_fence_get_stub - return a signaled fence
126 * Return a stub fence which is already signaled.
128 struct dma_fence *dma_fence_get_stub(void)
130 spin_lock(&dma_fence_stub_lock);
131 if (!dma_fence_stub.ops) {
132 dma_fence_init(&dma_fence_stub,
133 &dma_fence_stub_ops,
134 &dma_fence_stub_lock,
135 0, 0);
136 dma_fence_signal_locked(&dma_fence_stub);
138 spin_unlock(&dma_fence_stub_lock);
140 return dma_fence_get(&dma_fence_stub);
142 EXPORT_SYMBOL(dma_fence_get_stub);
145 * dma_fence_context_alloc - allocate an array of fence contexts
146 * @num: amount of contexts to allocate
148 * This function will return the first index of the number of fence contexts
149 * allocated. The fence context is used for setting &dma_fence.context to a
150 * unique number by passing the context to dma_fence_init().
152 u64 dma_fence_context_alloc(unsigned num)
154 WARN_ON(!num);
155 return atomic64_fetch_add(num, &dma_fence_context_counter);
157 EXPORT_SYMBOL(dma_fence_context_alloc);
160 * DOC: fence signalling annotation
162 * Proving correctness of all the kernel code around &dma_fence through code
163 * review and testing is tricky for a few reasons:
165 * * It is a cross-driver contract, and therefore all drivers must follow the
166 * same rules for lock nesting order, calling contexts for various functions
167 * and anything else significant for in-kernel interfaces. But it is also
168 * impossible to test all drivers in a single machine, hence brute-force N vs.
169 * N testing of all combinations is impossible. Even just limiting to the
170 * possible combinations is infeasible.
172 * * There is an enormous amount of driver code involved. For render drivers
173 * there's the tail of command submission, after fences are published,
174 * scheduler code, interrupt and workers to process job completion,
175 * and timeout, gpu reset and gpu hang recovery code. Plus for integration
176 * with core mm with have &mmu_notifier, respectively &mmu_interval_notifier,
177 * and &shrinker. For modesetting drivers there's the commit tail functions
178 * between when fences for an atomic modeset are published, and when the
179 * corresponding vblank completes, including any interrupt processing and
180 * related workers. Auditing all that code, across all drivers, is not
181 * feasible.
183 * * Due to how many other subsystems are involved and the locking hierarchies
184 * this pulls in there is extremely thin wiggle-room for driver-specific
185 * differences. &dma_fence interacts with almost all of the core memory
186 * handling through page fault handlers via &dma_resv, dma_resv_lock() and
187 * dma_resv_unlock(). On the other side it also interacts through all
188 * allocation sites through &mmu_notifier and &shrinker.
190 * Furthermore lockdep does not handle cross-release dependencies, which means
191 * any deadlocks between dma_fence_wait() and dma_fence_signal() can't be caught
192 * at runtime with some quick testing. The simplest example is one thread
193 * waiting on a &dma_fence while holding a lock::
195 * lock(A);
196 * dma_fence_wait(B);
197 * unlock(A);
199 * while the other thread is stuck trying to acquire the same lock, which
200 * prevents it from signalling the fence the previous thread is stuck waiting
201 * on::
203 * lock(A);
204 * unlock(A);
205 * dma_fence_signal(B);
207 * By manually annotating all code relevant to signalling a &dma_fence we can
208 * teach lockdep about these dependencies, which also helps with the validation
209 * headache since now lockdep can check all the rules for us::
211 * cookie = dma_fence_begin_signalling();
212 * lock(A);
213 * unlock(A);
214 * dma_fence_signal(B);
215 * dma_fence_end_signalling(cookie);
217 * For using dma_fence_begin_signalling() and dma_fence_end_signalling() to
218 * annotate critical sections the following rules need to be observed:
220 * * All code necessary to complete a &dma_fence must be annotated, from the
221 * point where a fence is accessible to other threads, to the point where
222 * dma_fence_signal() is called. Un-annotated code can contain deadlock issues,
223 * and due to the very strict rules and many corner cases it is infeasible to
224 * catch these just with review or normal stress testing.
226 * * &struct dma_resv deserves a special note, since the readers are only
227 * protected by rcu. This means the signalling critical section starts as soon
228 * as the new fences are installed, even before dma_resv_unlock() is called.
230 * * The only exception are fast paths and opportunistic signalling code, which
231 * calls dma_fence_signal() purely as an optimization, but is not required to
232 * guarantee completion of a &dma_fence. The usual example is a wait IOCTL
233 * which calls dma_fence_signal(), while the mandatory completion path goes
234 * through a hardware interrupt and possible job completion worker.
236 * * To aid composability of code, the annotations can be freely nested, as long
237 * as the overall locking hierarchy is consistent. The annotations also work
238 * both in interrupt and process context. Due to implementation details this
239 * requires that callers pass an opaque cookie from
240 * dma_fence_begin_signalling() to dma_fence_end_signalling().
242 * * Validation against the cross driver contract is implemented by priming
243 * lockdep with the relevant hierarchy at boot-up. This means even just
244 * testing with a single device is enough to validate a driver, at least as
245 * far as deadlocks with dma_fence_wait() against dma_fence_signal() are
246 * concerned.
248 #ifdef CONFIG_LOCKDEP
249 static struct lockdep_map dma_fence_lockdep_map = {
250 .name = "dma_fence_map"
254 * dma_fence_begin_signalling - begin a critical DMA fence signalling section
256 * Drivers should use this to annotate the beginning of any code section
257 * required to eventually complete &dma_fence by calling dma_fence_signal().
259 * The end of these critical sections are annotated with
260 * dma_fence_end_signalling().
262 * Returns:
264 * Opaque cookie needed by the implementation, which needs to be passed to
265 * dma_fence_end_signalling().
267 bool dma_fence_begin_signalling(void)
269 /* explicitly nesting ... */
270 if (lock_is_held_type(&dma_fence_lockdep_map, 1))
271 return true;
273 /* rely on might_sleep check for soft/hardirq locks */
274 if (in_atomic())
275 return true;
277 /* ... and non-recursive readlock */
278 lock_acquire(&dma_fence_lockdep_map, 0, 0, 1, 1, NULL, _RET_IP_);
280 return false;
282 EXPORT_SYMBOL(dma_fence_begin_signalling);
285 * dma_fence_end_signalling - end a critical DMA fence signalling section
286 * @cookie: opaque cookie from dma_fence_begin_signalling()
288 * Closes a critical section annotation opened by dma_fence_begin_signalling().
290 void dma_fence_end_signalling(bool cookie)
292 if (cookie)
293 return;
295 lock_release(&dma_fence_lockdep_map, _RET_IP_);
297 EXPORT_SYMBOL(dma_fence_end_signalling);
299 void __dma_fence_might_wait(void)
301 bool tmp;
303 tmp = lock_is_held_type(&dma_fence_lockdep_map, 1);
304 if (tmp)
305 lock_release(&dma_fence_lockdep_map, _THIS_IP_);
306 lock_map_acquire(&dma_fence_lockdep_map);
307 lock_map_release(&dma_fence_lockdep_map);
308 if (tmp)
309 lock_acquire(&dma_fence_lockdep_map, 0, 0, 1, 1, NULL, _THIS_IP_);
311 #endif
315 * dma_fence_signal_locked - signal completion of a fence
316 * @fence: the fence to signal
318 * Signal completion for software callbacks on a fence, this will unblock
319 * dma_fence_wait() calls and run all the callbacks added with
320 * dma_fence_add_callback(). Can be called multiple times, but since a fence
321 * can only go from the unsignaled to the signaled state and not back, it will
322 * only be effective the first time.
324 * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
325 * held.
327 * Returns 0 on success and a negative error value when @fence has been
328 * signalled already.
330 int dma_fence_signal_locked(struct dma_fence *fence)
332 struct dma_fence_cb *cur, *tmp;
333 struct list_head cb_list;
335 lockdep_assert_held(fence->lock);
337 if (unlikely(test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
338 &fence->flags)))
339 return -EINVAL;
341 /* Stash the cb_list before replacing it with the timestamp */
342 list_replace(&fence->cb_list, &cb_list);
344 fence->timestamp = ktime_get();
345 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
346 trace_dma_fence_signaled(fence);
348 list_for_each_entry_safe(cur, tmp, &cb_list, node) {
349 INIT_LIST_HEAD(&cur->node);
350 cur->func(fence, cur);
353 return 0;
355 EXPORT_SYMBOL(dma_fence_signal_locked);
358 * dma_fence_signal - signal completion of a fence
359 * @fence: the fence to signal
361 * Signal completion for software callbacks on a fence, this will unblock
362 * dma_fence_wait() calls and run all the callbacks added with
363 * dma_fence_add_callback(). Can be called multiple times, but since a fence
364 * can only go from the unsignaled to the signaled state and not back, it will
365 * only be effective the first time.
367 * Returns 0 on success and a negative error value when @fence has been
368 * signalled already.
370 int dma_fence_signal(struct dma_fence *fence)
372 unsigned long flags;
373 int ret;
374 bool tmp;
376 if (!fence)
377 return -EINVAL;
379 tmp = dma_fence_begin_signalling();
381 spin_lock_irqsave(fence->lock, flags);
382 ret = dma_fence_signal_locked(fence);
383 spin_unlock_irqrestore(fence->lock, flags);
385 dma_fence_end_signalling(tmp);
387 return ret;
389 EXPORT_SYMBOL(dma_fence_signal);
392 * dma_fence_wait_timeout - sleep until the fence gets signaled
393 * or until timeout elapses
394 * @fence: the fence to wait on
395 * @intr: if true, do an interruptible wait
396 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
398 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
399 * remaining timeout in jiffies on success. Other error values may be
400 * returned on custom implementations.
402 * Performs a synchronous wait on this fence. It is assumed the caller
403 * directly or indirectly (buf-mgr between reservation and committing)
404 * holds a reference to the fence, otherwise the fence might be
405 * freed before return, resulting in undefined behavior.
407 * See also dma_fence_wait() and dma_fence_wait_any_timeout().
409 signed long
410 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
412 signed long ret;
414 if (WARN_ON(timeout < 0))
415 return -EINVAL;
417 might_sleep();
419 __dma_fence_might_wait();
421 trace_dma_fence_wait_start(fence);
422 if (fence->ops->wait)
423 ret = fence->ops->wait(fence, intr, timeout);
424 else
425 ret = dma_fence_default_wait(fence, intr, timeout);
426 trace_dma_fence_wait_end(fence);
427 return ret;
429 EXPORT_SYMBOL(dma_fence_wait_timeout);
432 * dma_fence_release - default relese function for fences
433 * @kref: &dma_fence.recfount
435 * This is the default release functions for &dma_fence. Drivers shouldn't call
436 * this directly, but instead call dma_fence_put().
438 void dma_fence_release(struct kref *kref)
440 struct dma_fence *fence =
441 container_of(kref, struct dma_fence, refcount);
443 trace_dma_fence_destroy(fence);
445 if (WARN(!list_empty(&fence->cb_list) &&
446 !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags),
447 "Fence %s:%s:%llx:%llx released with pending signals!\n",
448 fence->ops->get_driver_name(fence),
449 fence->ops->get_timeline_name(fence),
450 fence->context, fence->seqno)) {
451 unsigned long flags;
454 * Failed to signal before release, likely a refcounting issue.
456 * This should never happen, but if it does make sure that we
457 * don't leave chains dangling. We set the error flag first
458 * so that the callbacks know this signal is due to an error.
460 spin_lock_irqsave(fence->lock, flags);
461 fence->error = -EDEADLK;
462 dma_fence_signal_locked(fence);
463 spin_unlock_irqrestore(fence->lock, flags);
466 if (fence->ops->release)
467 fence->ops->release(fence);
468 else
469 dma_fence_free(fence);
471 EXPORT_SYMBOL(dma_fence_release);
474 * dma_fence_free - default release function for &dma_fence.
475 * @fence: fence to release
477 * This is the default implementation for &dma_fence_ops.release. It calls
478 * kfree_rcu() on @fence.
480 void dma_fence_free(struct dma_fence *fence)
482 kfree_rcu(fence, rcu);
484 EXPORT_SYMBOL(dma_fence_free);
486 static bool __dma_fence_enable_signaling(struct dma_fence *fence)
488 bool was_set;
490 lockdep_assert_held(fence->lock);
492 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
493 &fence->flags);
495 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
496 return false;
498 if (!was_set && fence->ops->enable_signaling) {
499 trace_dma_fence_enable_signal(fence);
501 if (!fence->ops->enable_signaling(fence)) {
502 dma_fence_signal_locked(fence);
503 return false;
507 return true;
511 * dma_fence_enable_sw_signaling - enable signaling on fence
512 * @fence: the fence to enable
514 * This will request for sw signaling to be enabled, to make the fence
515 * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
516 * internally.
518 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
520 unsigned long flags;
522 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
523 return;
525 spin_lock_irqsave(fence->lock, flags);
526 __dma_fence_enable_signaling(fence);
527 spin_unlock_irqrestore(fence->lock, flags);
529 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
532 * dma_fence_add_callback - add a callback to be called when the fence
533 * is signaled
534 * @fence: the fence to wait on
535 * @cb: the callback to register
536 * @func: the function to call
538 * @cb will be initialized by dma_fence_add_callback(), no initialization
539 * by the caller is required. Any number of callbacks can be registered
540 * to a fence, but a callback can only be registered to one fence at a time.
542 * Note that the callback can be called from an atomic context. If
543 * fence is already signaled, this function will return -ENOENT (and
544 * *not* call the callback).
546 * Add a software callback to the fence. Same restrictions apply to
547 * refcount as it does to dma_fence_wait(), however the caller doesn't need to
548 * keep a refcount to fence afterward dma_fence_add_callback() has returned:
549 * when software access is enabled, the creator of the fence is required to keep
550 * the fence alive until after it signals with dma_fence_signal(). The callback
551 * itself can be called from irq context.
553 * Returns 0 in case of success, -ENOENT if the fence is already signaled
554 * and -EINVAL in case of error.
556 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
557 dma_fence_func_t func)
559 unsigned long flags;
560 int ret = 0;
562 if (WARN_ON(!fence || !func))
563 return -EINVAL;
565 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
566 INIT_LIST_HEAD(&cb->node);
567 return -ENOENT;
570 spin_lock_irqsave(fence->lock, flags);
572 if (__dma_fence_enable_signaling(fence)) {
573 cb->func = func;
574 list_add_tail(&cb->node, &fence->cb_list);
575 } else {
576 INIT_LIST_HEAD(&cb->node);
577 ret = -ENOENT;
580 spin_unlock_irqrestore(fence->lock, flags);
582 return ret;
584 EXPORT_SYMBOL(dma_fence_add_callback);
587 * dma_fence_get_status - returns the status upon completion
588 * @fence: the dma_fence to query
590 * This wraps dma_fence_get_status_locked() to return the error status
591 * condition on a signaled fence. See dma_fence_get_status_locked() for more
592 * details.
594 * Returns 0 if the fence has not yet been signaled, 1 if the fence has
595 * been signaled without an error condition, or a negative error code
596 * if the fence has been completed in err.
598 int dma_fence_get_status(struct dma_fence *fence)
600 unsigned long flags;
601 int status;
603 spin_lock_irqsave(fence->lock, flags);
604 status = dma_fence_get_status_locked(fence);
605 spin_unlock_irqrestore(fence->lock, flags);
607 return status;
609 EXPORT_SYMBOL(dma_fence_get_status);
612 * dma_fence_remove_callback - remove a callback from the signaling list
613 * @fence: the fence to wait on
614 * @cb: the callback to remove
616 * Remove a previously queued callback from the fence. This function returns
617 * true if the callback is successfully removed, or false if the fence has
618 * already been signaled.
620 * *WARNING*:
621 * Cancelling a callback should only be done if you really know what you're
622 * doing, since deadlocks and race conditions could occur all too easily. For
623 * this reason, it should only ever be done on hardware lockup recovery,
624 * with a reference held to the fence.
626 * Behaviour is undefined if @cb has not been added to @fence using
627 * dma_fence_add_callback() beforehand.
629 bool
630 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
632 unsigned long flags;
633 bool ret;
635 spin_lock_irqsave(fence->lock, flags);
637 ret = !list_empty(&cb->node);
638 if (ret)
639 list_del_init(&cb->node);
641 spin_unlock_irqrestore(fence->lock, flags);
643 return ret;
645 EXPORT_SYMBOL(dma_fence_remove_callback);
647 struct default_wait_cb {
648 struct dma_fence_cb base;
649 struct task_struct *task;
652 static void
653 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
655 struct default_wait_cb *wait =
656 container_of(cb, struct default_wait_cb, base);
658 wake_up_state(wait->task, TASK_NORMAL);
662 * dma_fence_default_wait - default sleep until the fence gets signaled
663 * or until timeout elapses
664 * @fence: the fence to wait on
665 * @intr: if true, do an interruptible wait
666 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
668 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
669 * remaining timeout in jiffies on success. If timeout is zero the value one is
670 * returned if the fence is already signaled for consistency with other
671 * functions taking a jiffies timeout.
673 signed long
674 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
676 struct default_wait_cb cb;
677 unsigned long flags;
678 signed long ret = timeout ? timeout : 1;
680 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
681 return ret;
683 spin_lock_irqsave(fence->lock, flags);
685 if (intr && signal_pending(current)) {
686 ret = -ERESTARTSYS;
687 goto out;
690 if (!__dma_fence_enable_signaling(fence))
691 goto out;
693 if (!timeout) {
694 ret = 0;
695 goto out;
698 cb.base.func = dma_fence_default_wait_cb;
699 cb.task = current;
700 list_add(&cb.base.node, &fence->cb_list);
702 while (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
703 if (intr)
704 __set_current_state(TASK_INTERRUPTIBLE);
705 else
706 __set_current_state(TASK_UNINTERRUPTIBLE);
707 spin_unlock_irqrestore(fence->lock, flags);
709 ret = schedule_timeout(ret);
711 spin_lock_irqsave(fence->lock, flags);
712 if (ret > 0 && intr && signal_pending(current))
713 ret = -ERESTARTSYS;
716 if (!list_empty(&cb.base.node))
717 list_del(&cb.base.node);
718 __set_current_state(TASK_RUNNING);
720 out:
721 spin_unlock_irqrestore(fence->lock, flags);
722 return ret;
724 EXPORT_SYMBOL(dma_fence_default_wait);
726 static bool
727 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
728 uint32_t *idx)
730 int i;
732 for (i = 0; i < count; ++i) {
733 struct dma_fence *fence = fences[i];
734 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
735 if (idx)
736 *idx = i;
737 return true;
740 return false;
744 * dma_fence_wait_any_timeout - sleep until any fence gets signaled
745 * or until timeout elapses
746 * @fences: array of fences to wait on
747 * @count: number of fences to wait on
748 * @intr: if true, do an interruptible wait
749 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
750 * @idx: used to store the first signaled fence index, meaningful only on
751 * positive return
753 * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
754 * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
755 * on success.
757 * Synchronous waits for the first fence in the array to be signaled. The
758 * caller needs to hold a reference to all fences in the array, otherwise a
759 * fence might be freed before return, resulting in undefined behavior.
761 * See also dma_fence_wait() and dma_fence_wait_timeout().
763 signed long
764 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
765 bool intr, signed long timeout, uint32_t *idx)
767 struct default_wait_cb *cb;
768 signed long ret = timeout;
769 unsigned i;
771 if (WARN_ON(!fences || !count || timeout < 0))
772 return -EINVAL;
774 if (timeout == 0) {
775 for (i = 0; i < count; ++i)
776 if (dma_fence_is_signaled(fences[i])) {
777 if (idx)
778 *idx = i;
779 return 1;
782 return 0;
785 cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
786 if (cb == NULL) {
787 ret = -ENOMEM;
788 goto err_free_cb;
791 for (i = 0; i < count; ++i) {
792 struct dma_fence *fence = fences[i];
794 cb[i].task = current;
795 if (dma_fence_add_callback(fence, &cb[i].base,
796 dma_fence_default_wait_cb)) {
797 /* This fence is already signaled */
798 if (idx)
799 *idx = i;
800 goto fence_rm_cb;
804 while (ret > 0) {
805 if (intr)
806 set_current_state(TASK_INTERRUPTIBLE);
807 else
808 set_current_state(TASK_UNINTERRUPTIBLE);
810 if (dma_fence_test_signaled_any(fences, count, idx))
811 break;
813 ret = schedule_timeout(ret);
815 if (ret > 0 && intr && signal_pending(current))
816 ret = -ERESTARTSYS;
819 __set_current_state(TASK_RUNNING);
821 fence_rm_cb:
822 while (i-- > 0)
823 dma_fence_remove_callback(fences[i], &cb[i].base);
825 err_free_cb:
826 kfree(cb);
828 return ret;
830 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
833 * dma_fence_init - Initialize a custom fence.
834 * @fence: the fence to initialize
835 * @ops: the dma_fence_ops for operations on this fence
836 * @lock: the irqsafe spinlock to use for locking this fence
837 * @context: the execution context this fence is run on
838 * @seqno: a linear increasing sequence number for this context
840 * Initializes an allocated fence, the caller doesn't have to keep its
841 * refcount after committing with this fence, but it will need to hold a
842 * refcount again if &dma_fence_ops.enable_signaling gets called.
844 * context and seqno are used for easy comparison between fences, allowing
845 * to check which fence is later by simply using dma_fence_later().
847 void
848 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
849 spinlock_t *lock, u64 context, u64 seqno)
851 BUG_ON(!lock);
852 BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
854 kref_init(&fence->refcount);
855 fence->ops = ops;
856 INIT_LIST_HEAD(&fence->cb_list);
857 fence->lock = lock;
858 fence->context = context;
859 fence->seqno = seqno;
860 fence->flags = 0UL;
861 fence->error = 0;
863 trace_dma_fence_init(fence);
865 EXPORT_SYMBOL(dma_fence_init);