xref: /linux/drivers/dma-buf/dma-fence.c (revision ca853314e78b0a65c20b6a889a23c31f918d4aa2)
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_locked - signal completion of a fence
316  * @fence: the fence to signal
317  *
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.
323  *
324  * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
325  * held.
326  *
327  * Returns 0 on success and a negative error value when @fence has been
328  * signalled already.
329  */
330 int dma_fence_signal_locked(struct dma_fence *fence)
331 {
332 	struct dma_fence_cb *cur, *tmp;
333 	struct list_head cb_list;
334 
335 	lockdep_assert_held(fence->lock);
336 
337 	if (unlikely(test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
338 				      &fence->flags)))
339 		return -EINVAL;
340 
341 	/* Stash the cb_list before replacing it with the timestamp */
342 	list_replace(&fence->cb_list, &cb_list);
343 
344 	fence->timestamp = ktime_get();
345 	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
346 	trace_dma_fence_signaled(fence);
347 
348 	list_for_each_entry_safe(cur, tmp, &cb_list, node) {
349 		INIT_LIST_HEAD(&cur->node);
350 		cur->func(fence, cur);
351 	}
352 
353 	return 0;
354 }
355 EXPORT_SYMBOL(dma_fence_signal_locked);
356 
357 /**
358  * dma_fence_signal - signal completion of a fence
359  * @fence: the fence to signal
360  *
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.
366  *
367  * Returns 0 on success and a negative error value when @fence has been
368  * signalled already.
369  */
370 int dma_fence_signal(struct dma_fence *fence)
371 {
372 	unsigned long flags;
373 	int ret;
374 	bool tmp;
375 
376 	if (!fence)
377 		return -EINVAL;
378 
379 	tmp = dma_fence_begin_signalling();
380 
381 	spin_lock_irqsave(fence->lock, flags);
382 	ret = dma_fence_signal_locked(fence);
383 	spin_unlock_irqrestore(fence->lock, flags);
384 
385 	dma_fence_end_signalling(tmp);
386 
387 	return ret;
388 }
389 EXPORT_SYMBOL(dma_fence_signal);
390 
391 /**
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
397  *
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.
401  *
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.
406  *
407  * See also dma_fence_wait() and dma_fence_wait_any_timeout().
408  */
409 signed long
410 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
411 {
412 	signed long ret;
413 
414 	if (WARN_ON(timeout < 0))
415 		return -EINVAL;
416 
417 	might_sleep();
418 
419 	__dma_fence_might_wait();
420 
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;
428 }
429 EXPORT_SYMBOL(dma_fence_wait_timeout);
430 
431 /**
432  * dma_fence_release - default relese function for fences
433  * @kref: &dma_fence.recfount
434  *
435  * This is the default release functions for &dma_fence. Drivers shouldn't call
436  * this directly, but instead call dma_fence_put().
437  */
438 void dma_fence_release(struct kref *kref)
439 {
440 	struct dma_fence *fence =
441 		container_of(kref, struct dma_fence, refcount);
442 
443 	trace_dma_fence_destroy(fence);
444 
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;
452 
453 		/*
454 		 * Failed to signal before release, likely a refcounting issue.
455 		 *
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.
459 		 */
460 		spin_lock_irqsave(fence->lock, flags);
461 		fence->error = -EDEADLK;
462 		dma_fence_signal_locked(fence);
463 		spin_unlock_irqrestore(fence->lock, flags);
464 	}
465 
466 	if (fence->ops->release)
467 		fence->ops->release(fence);
468 	else
469 		dma_fence_free(fence);
470 }
471 EXPORT_SYMBOL(dma_fence_release);
472 
473 /**
474  * dma_fence_free - default release function for &dma_fence.
475  * @fence: fence to release
476  *
477  * This is the default implementation for &dma_fence_ops.release. It calls
478  * kfree_rcu() on @fence.
479  */
480 void dma_fence_free(struct dma_fence *fence)
481 {
482 	kfree_rcu(fence, rcu);
483 }
484 EXPORT_SYMBOL(dma_fence_free);
485 
486 static bool __dma_fence_enable_signaling(struct dma_fence *fence)
487 {
488 	bool was_set;
489 
490 	lockdep_assert_held(fence->lock);
491 
492 	was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
493 				   &fence->flags);
494 
495 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
496 		return false;
497 
498 	if (!was_set && fence->ops->enable_signaling) {
499 		trace_dma_fence_enable_signal(fence);
500 
501 		if (!fence->ops->enable_signaling(fence)) {
502 			dma_fence_signal_locked(fence);
503 			return false;
504 		}
505 	}
506 
507 	return true;
508 }
509 
510 /**
511  * dma_fence_enable_sw_signaling - enable signaling on fence
512  * @fence: the fence to enable
513  *
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.
517  */
518 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
519 {
520 	unsigned long flags;
521 
522 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
523 		return;
524 
525 	spin_lock_irqsave(fence->lock, flags);
526 	__dma_fence_enable_signaling(fence);
527 	spin_unlock_irqrestore(fence->lock, flags);
528 }
529 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
530 
531 /**
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
537  *
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.
541  *
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).
545  *
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.
552  *
553  * Returns 0 in case of success, -ENOENT if the fence is already signaled
554  * and -EINVAL in case of error.
555  */
556 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
557 			   dma_fence_func_t func)
558 {
559 	unsigned long flags;
560 	int ret = 0;
561 
562 	if (WARN_ON(!fence || !func))
563 		return -EINVAL;
564 
565 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
566 		INIT_LIST_HEAD(&cb->node);
567 		return -ENOENT;
568 	}
569 
570 	spin_lock_irqsave(fence->lock, flags);
571 
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;
578 	}
579 
580 	spin_unlock_irqrestore(fence->lock, flags);
581 
582 	return ret;
583 }
584 EXPORT_SYMBOL(dma_fence_add_callback);
585 
586 /**
587  * dma_fence_get_status - returns the status upon completion
588  * @fence: the dma_fence to query
589  *
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.
593  *
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.
597  */
598 int dma_fence_get_status(struct dma_fence *fence)
599 {
600 	unsigned long flags;
601 	int status;
602 
603 	spin_lock_irqsave(fence->lock, flags);
604 	status = dma_fence_get_status_locked(fence);
605 	spin_unlock_irqrestore(fence->lock, flags);
606 
607 	return status;
608 }
609 EXPORT_SYMBOL(dma_fence_get_status);
610 
611 /**
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
615  *
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.
619  *
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.
625  *
626  * Behaviour is undefined if @cb has not been added to @fence using
627  * dma_fence_add_callback() beforehand.
628  */
629 bool
630 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
631 {
632 	unsigned long flags;
633 	bool ret;
634 
635 	spin_lock_irqsave(fence->lock, flags);
636 
637 	ret = !list_empty(&cb->node);
638 	if (ret)
639 		list_del_init(&cb->node);
640 
641 	spin_unlock_irqrestore(fence->lock, flags);
642 
643 	return ret;
644 }
645 EXPORT_SYMBOL(dma_fence_remove_callback);
646 
647 struct default_wait_cb {
648 	struct dma_fence_cb base;
649 	struct task_struct *task;
650 };
651 
652 static void
653 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
654 {
655 	struct default_wait_cb *wait =
656 		container_of(cb, struct default_wait_cb, base);
657 
658 	wake_up_state(wait->task, TASK_NORMAL);
659 }
660 
661 /**
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
667  *
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.
672  */
673 signed long
674 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
675 {
676 	struct default_wait_cb cb;
677 	unsigned long flags;
678 	signed long ret = timeout ? timeout : 1;
679 
680 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
681 		return ret;
682 
683 	spin_lock_irqsave(fence->lock, flags);
684 
685 	if (intr && signal_pending(current)) {
686 		ret = -ERESTARTSYS;
687 		goto out;
688 	}
689 
690 	if (!__dma_fence_enable_signaling(fence))
691 		goto out;
692 
693 	if (!timeout) {
694 		ret = 0;
695 		goto out;
696 	}
697 
698 	cb.base.func = dma_fence_default_wait_cb;
699 	cb.task = current;
700 	list_add(&cb.base.node, &fence->cb_list);
701 
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);
708 
709 		ret = schedule_timeout(ret);
710 
711 		spin_lock_irqsave(fence->lock, flags);
712 		if (ret > 0 && intr && signal_pending(current))
713 			ret = -ERESTARTSYS;
714 	}
715 
716 	if (!list_empty(&cb.base.node))
717 		list_del(&cb.base.node);
718 	__set_current_state(TASK_RUNNING);
719 
720 out:
721 	spin_unlock_irqrestore(fence->lock, flags);
722 	return ret;
723 }
724 EXPORT_SYMBOL(dma_fence_default_wait);
725 
726 static bool
727 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
728 			    uint32_t *idx)
729 {
730 	int i;
731 
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;
738 		}
739 	}
740 	return false;
741 }
742 
743 /**
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
752  *
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.
756  *
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.
760  *
761  * See also dma_fence_wait() and dma_fence_wait_timeout().
762  */
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)
766 {
767 	struct default_wait_cb *cb;
768 	signed long ret = timeout;
769 	unsigned i;
770 
771 	if (WARN_ON(!fences || !count || timeout < 0))
772 		return -EINVAL;
773 
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;
780 			}
781 
782 		return 0;
783 	}
784 
785 	cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
786 	if (cb == NULL) {
787 		ret = -ENOMEM;
788 		goto err_free_cb;
789 	}
790 
791 	for (i = 0; i < count; ++i) {
792 		struct dma_fence *fence = fences[i];
793 
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;
801 		}
802 	}
803 
804 	while (ret > 0) {
805 		if (intr)
806 			set_current_state(TASK_INTERRUPTIBLE);
807 		else
808 			set_current_state(TASK_UNINTERRUPTIBLE);
809 
810 		if (dma_fence_test_signaled_any(fences, count, idx))
811 			break;
812 
813 		ret = schedule_timeout(ret);
814 
815 		if (ret > 0 && intr && signal_pending(current))
816 			ret = -ERESTARTSYS;
817 	}
818 
819 	__set_current_state(TASK_RUNNING);
820 
821 fence_rm_cb:
822 	while (i-- > 0)
823 		dma_fence_remove_callback(fences[i], &cb[i].base);
824 
825 err_free_cb:
826 	kfree(cb);
827 
828 	return ret;
829 }
830 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
831 
832 /**
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
839  *
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.
843  *
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().
846  */
847 void
848 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
849 	       spinlock_t *lock, u64 context, u64 seqno)
850 {
851 	BUG_ON(!lock);
852 	BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
853 
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;
862 
863 	trace_dma_fence_init(fence);
864 }
865 EXPORT_SYMBOL(dma_fence_init);
866