xref: /openbmc/linux/drivers/dma-buf/dma-fence.c (revision 7f9321ff)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Fence mechanism for dma-buf and to allow for asynchronous dma access
4  *
5  * Copyright (C) 2012 Canonical Ltd
6  * Copyright (C) 2012 Texas Instruments
7  *
8  * Authors:
9  * Rob Clark <robdclark@gmail.com>
10  * Maarten Lankhorst <maarten.lankhorst@canonical.com>
11  */
12 
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>
18 
19 #define CREATE_TRACE_POINTS
20 #include <trace/events/dma_fence.h>
21 
22 EXPORT_TRACEPOINT_SYMBOL(dma_fence_emit);
23 EXPORT_TRACEPOINT_SYMBOL(dma_fence_enable_signal);
24 EXPORT_TRACEPOINT_SYMBOL(dma_fence_signaled);
25 
26 static DEFINE_SPINLOCK(dma_fence_stub_lock);
27 static struct dma_fence dma_fence_stub;
28 
29 /*
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.
34  */
35 static atomic64_t dma_fence_context_counter = ATOMIC64_INIT(1);
36 
37 /**
38  * DOC: DMA fences overview
39  *
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.
43  *
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.
48  *
49  * Since the purposes of fences is to facilitate cross-device and
50  * cross-application synchronization, there's multiple ways to use one:
51  *
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.
56  *
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.
60  *
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.
65  */
66 
67 /**
68  * DOC: fence cross-driver contract
69  *
70  * Since &dma_fence provide a cross driver contract, all drivers must follow the
71  * same rules:
72  *
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.
81  *
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.
87  *
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().
92  *
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().
97  *
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.
101  *
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.
106  *
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.
111  */
112 
113 static const char *dma_fence_stub_get_name(struct dma_fence *fence)
114 {
115         return "stub";
116 }
117 
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,
121 };
122 
123 /**
124  * dma_fence_get_stub - return a signaled fence
125  *
126  * Return a stub fence which is already signaled.
127  */
128 struct dma_fence *dma_fence_get_stub(void)
129 {
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);
137 	}
138 	spin_unlock(&dma_fence_stub_lock);
139 
140 	return dma_fence_get(&dma_fence_stub);
141 }
142 EXPORT_SYMBOL(dma_fence_get_stub);
143 
144 /**
145  * dma_fence_context_alloc - allocate an array of fence contexts
146  * @num: amount of contexts to allocate
147  *
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().
151  */
152 u64 dma_fence_context_alloc(unsigned num)
153 {
154 	WARN_ON(!num);
155 	return atomic64_fetch_add(num, &dma_fence_context_counter);
156 }
157 EXPORT_SYMBOL(dma_fence_context_alloc);
158 
159 /**
160  * DOC: fence signalling annotation
161  *
162  * Proving correctness of all the kernel code around &dma_fence through code
163  * review and testing is tricky for a few reasons:
164  *
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.
171  *
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.
182  *
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.
189  *
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::
194  *
195  *     lock(A);
196  *     dma_fence_wait(B);
197  *     unlock(A);
198  *
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::
202  *
203  *     lock(A);
204  *     unlock(A);
205  *     dma_fence_signal(B);
206  *
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::
210  *
211  *    cookie = dma_fence_begin_signalling();
212  *    lock(A);
213  *    unlock(A);
214  *    dma_fence_signal(B);
215  *    dma_fence_end_signalling(cookie);
216  *
217  * For using dma_fence_begin_signalling() and dma_fence_end_signalling() to
218  * annotate critical sections the following rules need to be observed:
219  *
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.
225  *
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.
229  *
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.
235  *
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().
241  *
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.
247  */
248 #ifdef CONFIG_LOCKDEP
249 static struct lockdep_map dma_fence_lockdep_map = {
250 	.name = "dma_fence_map"
251 };
252 
253 /**
254  * dma_fence_begin_signalling - begin a critical DMA fence signalling section
255  *
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().
258  *
259  * The end of these critical sections are annotated with
260  * dma_fence_end_signalling().
261  *
262  * Returns:
263  *
264  * Opaque cookie needed by the implementation, which needs to be passed to
265  * dma_fence_end_signalling().
266  */
267 bool dma_fence_begin_signalling(void)
268 {
269 	/* explicitly nesting ... */
270 	if (lock_is_held_type(&dma_fence_lockdep_map, 1))
271 		return true;
272 
273 	/* rely on might_sleep check for soft/hardirq locks */
274 	if (in_atomic())
275 		return true;
276 
277 	/* ... and non-recursive readlock */
278 	lock_acquire(&dma_fence_lockdep_map, 0, 0, 1, 1, NULL, _RET_IP_);
279 
280 	return false;
281 }
282 EXPORT_SYMBOL(dma_fence_begin_signalling);
283 
284 /**
285  * dma_fence_end_signalling - end a critical DMA fence signalling section
286  * @cookie: opaque cookie from dma_fence_begin_signalling()
287  *
288  * Closes a critical section annotation opened by dma_fence_begin_signalling().
289  */
290 void dma_fence_end_signalling(bool cookie)
291 {
292 	if (cookie)
293 		return;
294 
295 	lock_release(&dma_fence_lockdep_map, _RET_IP_);
296 }
297 EXPORT_SYMBOL(dma_fence_end_signalling);
298 
299 void __dma_fence_might_wait(void)
300 {
301 	bool tmp;
302 
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_);
310 }
311 #endif
312 
313 
314 /**
315  * dma_fence_signal_timestamp_locked - signal completion of a fence
316  * @fence: the fence to signal
317  * @timestamp: fence signal timestamp in kernel's CLOCK_MONOTONIC time domain
318  *
319  * Signal completion for software callbacks on a fence, this will unblock
320  * dma_fence_wait() calls and run all the callbacks added with
321  * dma_fence_add_callback(). Can be called multiple times, but since a fence
322  * can only go from the unsignaled to the signaled state and not back, it will
323  * only be effective the first time. Set the timestamp provided as the fence
324  * signal timestamp.
325  *
326  * Unlike dma_fence_signal_timestamp(), this function must be called with
327  * &dma_fence.lock held.
328  *
329  * Returns 0 on success and a negative error value when @fence has been
330  * signalled already.
331  */
332 int dma_fence_signal_timestamp_locked(struct dma_fence *fence,
333 				      ktime_t timestamp)
334 {
335 	struct dma_fence_cb *cur, *tmp;
336 	struct list_head cb_list;
337 
338 	lockdep_assert_held(fence->lock);
339 
340 	if (unlikely(test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
341 				      &fence->flags)))
342 		return -EINVAL;
343 
344 	/* Stash the cb_list before replacing it with the timestamp */
345 	list_replace(&fence->cb_list, &cb_list);
346 
347 	fence->timestamp = timestamp;
348 	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
349 	trace_dma_fence_signaled(fence);
350 
351 	list_for_each_entry_safe(cur, tmp, &cb_list, node) {
352 		INIT_LIST_HEAD(&cur->node);
353 		cur->func(fence, cur);
354 	}
355 
356 	return 0;
357 }
358 EXPORT_SYMBOL(dma_fence_signal_timestamp_locked);
359 
360 /**
361  * dma_fence_signal_timestamp - signal completion of a fence
362  * @fence: the fence to signal
363  * @timestamp: fence signal timestamp in kernel's CLOCK_MONOTONIC time domain
364  *
365  * Signal completion for software callbacks on a fence, this will unblock
366  * dma_fence_wait() calls and run all the callbacks added with
367  * dma_fence_add_callback(). Can be called multiple times, but since a fence
368  * can only go from the unsignaled to the signaled state and not back, it will
369  * only be effective the first time. Set the timestamp provided as the fence
370  * signal timestamp.
371  *
372  * Returns 0 on success and a negative error value when @fence has been
373  * signalled already.
374  */
375 int dma_fence_signal_timestamp(struct dma_fence *fence, ktime_t timestamp)
376 {
377 	unsigned long flags;
378 	int ret;
379 
380 	if (!fence)
381 		return -EINVAL;
382 
383 	spin_lock_irqsave(fence->lock, flags);
384 	ret = dma_fence_signal_timestamp_locked(fence, timestamp);
385 	spin_unlock_irqrestore(fence->lock, flags);
386 
387 	return ret;
388 }
389 EXPORT_SYMBOL(dma_fence_signal_timestamp);
390 
391 /**
392  * dma_fence_signal_locked - signal completion of a fence
393  * @fence: the fence to signal
394  *
395  * Signal completion for software callbacks on a fence, this will unblock
396  * dma_fence_wait() calls and run all the callbacks added with
397  * dma_fence_add_callback(). Can be called multiple times, but since a fence
398  * can only go from the unsignaled to the signaled state and not back, it will
399  * only be effective the first time.
400  *
401  * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
402  * held.
403  *
404  * Returns 0 on success and a negative error value when @fence has been
405  * signalled already.
406  */
407 int dma_fence_signal_locked(struct dma_fence *fence)
408 {
409 	return dma_fence_signal_timestamp_locked(fence, ktime_get());
410 }
411 EXPORT_SYMBOL(dma_fence_signal_locked);
412 
413 /**
414  * dma_fence_signal - signal completion of a fence
415  * @fence: the fence to signal
416  *
417  * Signal completion for software callbacks on a fence, this will unblock
418  * dma_fence_wait() calls and run all the callbacks added with
419  * dma_fence_add_callback(). Can be called multiple times, but since a fence
420  * can only go from the unsignaled to the signaled state and not back, it will
421  * only be effective the first time.
422  *
423  * Returns 0 on success and a negative error value when @fence has been
424  * signalled already.
425  */
426 int dma_fence_signal(struct dma_fence *fence)
427 {
428 	unsigned long flags;
429 	int ret;
430 	bool tmp;
431 
432 	if (!fence)
433 		return -EINVAL;
434 
435 	tmp = dma_fence_begin_signalling();
436 
437 	spin_lock_irqsave(fence->lock, flags);
438 	ret = dma_fence_signal_timestamp_locked(fence, ktime_get());
439 	spin_unlock_irqrestore(fence->lock, flags);
440 
441 	dma_fence_end_signalling(tmp);
442 
443 	return ret;
444 }
445 EXPORT_SYMBOL(dma_fence_signal);
446 
447 /**
448  * dma_fence_wait_timeout - sleep until the fence gets signaled
449  * or until timeout elapses
450  * @fence: the fence to wait on
451  * @intr: if true, do an interruptible wait
452  * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
453  *
454  * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
455  * remaining timeout in jiffies on success. Other error values may be
456  * returned on custom implementations.
457  *
458  * Performs a synchronous wait on this fence. It is assumed the caller
459  * directly or indirectly (buf-mgr between reservation and committing)
460  * holds a reference to the fence, otherwise the fence might be
461  * freed before return, resulting in undefined behavior.
462  *
463  * See also dma_fence_wait() and dma_fence_wait_any_timeout().
464  */
465 signed long
466 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
467 {
468 	signed long ret;
469 
470 	if (WARN_ON(timeout < 0))
471 		return -EINVAL;
472 
473 	might_sleep();
474 
475 	__dma_fence_might_wait();
476 
477 	trace_dma_fence_wait_start(fence);
478 	if (fence->ops->wait)
479 		ret = fence->ops->wait(fence, intr, timeout);
480 	else
481 		ret = dma_fence_default_wait(fence, intr, timeout);
482 	trace_dma_fence_wait_end(fence);
483 	return ret;
484 }
485 EXPORT_SYMBOL(dma_fence_wait_timeout);
486 
487 /**
488  * dma_fence_release - default relese function for fences
489  * @kref: &dma_fence.recfount
490  *
491  * This is the default release functions for &dma_fence. Drivers shouldn't call
492  * this directly, but instead call dma_fence_put().
493  */
494 void dma_fence_release(struct kref *kref)
495 {
496 	struct dma_fence *fence =
497 		container_of(kref, struct dma_fence, refcount);
498 
499 	trace_dma_fence_destroy(fence);
500 
501 	if (WARN(!list_empty(&fence->cb_list) &&
502 		 !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags),
503 		 "Fence %s:%s:%llx:%llx released with pending signals!\n",
504 		 fence->ops->get_driver_name(fence),
505 		 fence->ops->get_timeline_name(fence),
506 		 fence->context, fence->seqno)) {
507 		unsigned long flags;
508 
509 		/*
510 		 * Failed to signal before release, likely a refcounting issue.
511 		 *
512 		 * This should never happen, but if it does make sure that we
513 		 * don't leave chains dangling. We set the error flag first
514 		 * so that the callbacks know this signal is due to an error.
515 		 */
516 		spin_lock_irqsave(fence->lock, flags);
517 		fence->error = -EDEADLK;
518 		dma_fence_signal_locked(fence);
519 		spin_unlock_irqrestore(fence->lock, flags);
520 	}
521 
522 	if (fence->ops->release)
523 		fence->ops->release(fence);
524 	else
525 		dma_fence_free(fence);
526 }
527 EXPORT_SYMBOL(dma_fence_release);
528 
529 /**
530  * dma_fence_free - default release function for &dma_fence.
531  * @fence: fence to release
532  *
533  * This is the default implementation for &dma_fence_ops.release. It calls
534  * kfree_rcu() on @fence.
535  */
536 void dma_fence_free(struct dma_fence *fence)
537 {
538 	kfree_rcu(fence, rcu);
539 }
540 EXPORT_SYMBOL(dma_fence_free);
541 
542 static bool __dma_fence_enable_signaling(struct dma_fence *fence)
543 {
544 	bool was_set;
545 
546 	lockdep_assert_held(fence->lock);
547 
548 	was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
549 				   &fence->flags);
550 
551 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
552 		return false;
553 
554 	if (!was_set && fence->ops->enable_signaling) {
555 		trace_dma_fence_enable_signal(fence);
556 
557 		if (!fence->ops->enable_signaling(fence)) {
558 			dma_fence_signal_locked(fence);
559 			return false;
560 		}
561 	}
562 
563 	return true;
564 }
565 
566 /**
567  * dma_fence_enable_sw_signaling - enable signaling on fence
568  * @fence: the fence to enable
569  *
570  * This will request for sw signaling to be enabled, to make the fence
571  * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
572  * internally.
573  */
574 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
575 {
576 	unsigned long flags;
577 
578 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
579 		return;
580 
581 	spin_lock_irqsave(fence->lock, flags);
582 	__dma_fence_enable_signaling(fence);
583 	spin_unlock_irqrestore(fence->lock, flags);
584 }
585 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
586 
587 /**
588  * dma_fence_add_callback - add a callback to be called when the fence
589  * is signaled
590  * @fence: the fence to wait on
591  * @cb: the callback to register
592  * @func: the function to call
593  *
594  * @cb will be initialized by dma_fence_add_callback(), no initialization
595  * by the caller is required. Any number of callbacks can be registered
596  * to a fence, but a callback can only be registered to one fence at a time.
597  *
598  * Note that the callback can be called from an atomic context.  If
599  * fence is already signaled, this function will return -ENOENT (and
600  * *not* call the callback).
601  *
602  * Add a software callback to the fence. Same restrictions apply to
603  * refcount as it does to dma_fence_wait(), however the caller doesn't need to
604  * keep a refcount to fence afterward dma_fence_add_callback() has returned:
605  * when software access is enabled, the creator of the fence is required to keep
606  * the fence alive until after it signals with dma_fence_signal(). The callback
607  * itself can be called from irq context.
608  *
609  * Returns 0 in case of success, -ENOENT if the fence is already signaled
610  * and -EINVAL in case of error.
611  */
612 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
613 			   dma_fence_func_t func)
614 {
615 	unsigned long flags;
616 	int ret = 0;
617 
618 	if (WARN_ON(!fence || !func))
619 		return -EINVAL;
620 
621 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
622 		INIT_LIST_HEAD(&cb->node);
623 		return -ENOENT;
624 	}
625 
626 	spin_lock_irqsave(fence->lock, flags);
627 
628 	if (__dma_fence_enable_signaling(fence)) {
629 		cb->func = func;
630 		list_add_tail(&cb->node, &fence->cb_list);
631 	} else {
632 		INIT_LIST_HEAD(&cb->node);
633 		ret = -ENOENT;
634 	}
635 
636 	spin_unlock_irqrestore(fence->lock, flags);
637 
638 	return ret;
639 }
640 EXPORT_SYMBOL(dma_fence_add_callback);
641 
642 /**
643  * dma_fence_get_status - returns the status upon completion
644  * @fence: the dma_fence to query
645  *
646  * This wraps dma_fence_get_status_locked() to return the error status
647  * condition on a signaled fence. See dma_fence_get_status_locked() for more
648  * details.
649  *
650  * Returns 0 if the fence has not yet been signaled, 1 if the fence has
651  * been signaled without an error condition, or a negative error code
652  * if the fence has been completed in err.
653  */
654 int dma_fence_get_status(struct dma_fence *fence)
655 {
656 	unsigned long flags;
657 	int status;
658 
659 	spin_lock_irqsave(fence->lock, flags);
660 	status = dma_fence_get_status_locked(fence);
661 	spin_unlock_irqrestore(fence->lock, flags);
662 
663 	return status;
664 }
665 EXPORT_SYMBOL(dma_fence_get_status);
666 
667 /**
668  * dma_fence_remove_callback - remove a callback from the signaling list
669  * @fence: the fence to wait on
670  * @cb: the callback to remove
671  *
672  * Remove a previously queued callback from the fence. This function returns
673  * true if the callback is successfully removed, or false if the fence has
674  * already been signaled.
675  *
676  * *WARNING*:
677  * Cancelling a callback should only be done if you really know what you're
678  * doing, since deadlocks and race conditions could occur all too easily. For
679  * this reason, it should only ever be done on hardware lockup recovery,
680  * with a reference held to the fence.
681  *
682  * Behaviour is undefined if @cb has not been added to @fence using
683  * dma_fence_add_callback() beforehand.
684  */
685 bool
686 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
687 {
688 	unsigned long flags;
689 	bool ret;
690 
691 	spin_lock_irqsave(fence->lock, flags);
692 
693 	ret = !list_empty(&cb->node);
694 	if (ret)
695 		list_del_init(&cb->node);
696 
697 	spin_unlock_irqrestore(fence->lock, flags);
698 
699 	return ret;
700 }
701 EXPORT_SYMBOL(dma_fence_remove_callback);
702 
703 struct default_wait_cb {
704 	struct dma_fence_cb base;
705 	struct task_struct *task;
706 };
707 
708 static void
709 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
710 {
711 	struct default_wait_cb *wait =
712 		container_of(cb, struct default_wait_cb, base);
713 
714 	wake_up_state(wait->task, TASK_NORMAL);
715 }
716 
717 /**
718  * dma_fence_default_wait - default sleep until the fence gets signaled
719  * or until timeout elapses
720  * @fence: the fence to wait on
721  * @intr: if true, do an interruptible wait
722  * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
723  *
724  * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
725  * remaining timeout in jiffies on success. If timeout is zero the value one is
726  * returned if the fence is already signaled for consistency with other
727  * functions taking a jiffies timeout.
728  */
729 signed long
730 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
731 {
732 	struct default_wait_cb cb;
733 	unsigned long flags;
734 	signed long ret = timeout ? timeout : 1;
735 
736 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
737 		return ret;
738 
739 	spin_lock_irqsave(fence->lock, flags);
740 
741 	if (intr && signal_pending(current)) {
742 		ret = -ERESTARTSYS;
743 		goto out;
744 	}
745 
746 	if (!__dma_fence_enable_signaling(fence))
747 		goto out;
748 
749 	if (!timeout) {
750 		ret = 0;
751 		goto out;
752 	}
753 
754 	cb.base.func = dma_fence_default_wait_cb;
755 	cb.task = current;
756 	list_add(&cb.base.node, &fence->cb_list);
757 
758 	while (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
759 		if (intr)
760 			__set_current_state(TASK_INTERRUPTIBLE);
761 		else
762 			__set_current_state(TASK_UNINTERRUPTIBLE);
763 		spin_unlock_irqrestore(fence->lock, flags);
764 
765 		ret = schedule_timeout(ret);
766 
767 		spin_lock_irqsave(fence->lock, flags);
768 		if (ret > 0 && intr && signal_pending(current))
769 			ret = -ERESTARTSYS;
770 	}
771 
772 	if (!list_empty(&cb.base.node))
773 		list_del(&cb.base.node);
774 	__set_current_state(TASK_RUNNING);
775 
776 out:
777 	spin_unlock_irqrestore(fence->lock, flags);
778 	return ret;
779 }
780 EXPORT_SYMBOL(dma_fence_default_wait);
781 
782 static bool
783 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
784 			    uint32_t *idx)
785 {
786 	int i;
787 
788 	for (i = 0; i < count; ++i) {
789 		struct dma_fence *fence = fences[i];
790 		if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
791 			if (idx)
792 				*idx = i;
793 			return true;
794 		}
795 	}
796 	return false;
797 }
798 
799 /**
800  * dma_fence_wait_any_timeout - sleep until any fence gets signaled
801  * or until timeout elapses
802  * @fences: array of fences to wait on
803  * @count: number of fences to wait on
804  * @intr: if true, do an interruptible wait
805  * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
806  * @idx: used to store the first signaled fence index, meaningful only on
807  *	positive return
808  *
809  * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
810  * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
811  * on success.
812  *
813  * Synchronous waits for the first fence in the array to be signaled. The
814  * caller needs to hold a reference to all fences in the array, otherwise a
815  * fence might be freed before return, resulting in undefined behavior.
816  *
817  * See also dma_fence_wait() and dma_fence_wait_timeout().
818  */
819 signed long
820 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
821 			   bool intr, signed long timeout, uint32_t *idx)
822 {
823 	struct default_wait_cb *cb;
824 	signed long ret = timeout;
825 	unsigned i;
826 
827 	if (WARN_ON(!fences || !count || timeout < 0))
828 		return -EINVAL;
829 
830 	if (timeout == 0) {
831 		for (i = 0; i < count; ++i)
832 			if (dma_fence_is_signaled(fences[i])) {
833 				if (idx)
834 					*idx = i;
835 				return 1;
836 			}
837 
838 		return 0;
839 	}
840 
841 	cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
842 	if (cb == NULL) {
843 		ret = -ENOMEM;
844 		goto err_free_cb;
845 	}
846 
847 	for (i = 0; i < count; ++i) {
848 		struct dma_fence *fence = fences[i];
849 
850 		cb[i].task = current;
851 		if (dma_fence_add_callback(fence, &cb[i].base,
852 					   dma_fence_default_wait_cb)) {
853 			/* This fence is already signaled */
854 			if (idx)
855 				*idx = i;
856 			goto fence_rm_cb;
857 		}
858 	}
859 
860 	while (ret > 0) {
861 		if (intr)
862 			set_current_state(TASK_INTERRUPTIBLE);
863 		else
864 			set_current_state(TASK_UNINTERRUPTIBLE);
865 
866 		if (dma_fence_test_signaled_any(fences, count, idx))
867 			break;
868 
869 		ret = schedule_timeout(ret);
870 
871 		if (ret > 0 && intr && signal_pending(current))
872 			ret = -ERESTARTSYS;
873 	}
874 
875 	__set_current_state(TASK_RUNNING);
876 
877 fence_rm_cb:
878 	while (i-- > 0)
879 		dma_fence_remove_callback(fences[i], &cb[i].base);
880 
881 err_free_cb:
882 	kfree(cb);
883 
884 	return ret;
885 }
886 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
887 
888 /**
889  * dma_fence_init - Initialize a custom fence.
890  * @fence: the fence to initialize
891  * @ops: the dma_fence_ops for operations on this fence
892  * @lock: the irqsafe spinlock to use for locking this fence
893  * @context: the execution context this fence is run on
894  * @seqno: a linear increasing sequence number for this context
895  *
896  * Initializes an allocated fence, the caller doesn't have to keep its
897  * refcount after committing with this fence, but it will need to hold a
898  * refcount again if &dma_fence_ops.enable_signaling gets called.
899  *
900  * context and seqno are used for easy comparison between fences, allowing
901  * to check which fence is later by simply using dma_fence_later().
902  */
903 void
904 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
905 	       spinlock_t *lock, u64 context, u64 seqno)
906 {
907 	BUG_ON(!lock);
908 	BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
909 
910 	kref_init(&fence->refcount);
911 	fence->ops = ops;
912 	INIT_LIST_HEAD(&fence->cb_list);
913 	fence->lock = lock;
914 	fence->context = context;
915 	fence->seqno = seqno;
916 	fence->flags = 0UL;
917 	fence->error = 0;
918 
919 	trace_dma_fence_init(fence);
920 }
921 EXPORT_SYMBOL(dma_fence_init);
922