xref: /linux/drivers/dma-buf/dma-fence.c (revision 96ac6d435100450f0565708d9b885ea2a7400e0a)
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 reservation_object through the
64  *   &dma_buf.resv pointer.
65  */
66 
67 static const char *dma_fence_stub_get_name(struct dma_fence *fence)
68 {
69         return "stub";
70 }
71 
72 static const struct dma_fence_ops dma_fence_stub_ops = {
73 	.get_driver_name = dma_fence_stub_get_name,
74 	.get_timeline_name = dma_fence_stub_get_name,
75 };
76 
77 /**
78  * dma_fence_get_stub - return a signaled fence
79  *
80  * Return a stub fence which is already signaled.
81  */
82 struct dma_fence *dma_fence_get_stub(void)
83 {
84 	spin_lock(&dma_fence_stub_lock);
85 	if (!dma_fence_stub.ops) {
86 		dma_fence_init(&dma_fence_stub,
87 			       &dma_fence_stub_ops,
88 			       &dma_fence_stub_lock,
89 			       0, 0);
90 		dma_fence_signal_locked(&dma_fence_stub);
91 	}
92 	spin_unlock(&dma_fence_stub_lock);
93 
94 	return dma_fence_get(&dma_fence_stub);
95 }
96 EXPORT_SYMBOL(dma_fence_get_stub);
97 
98 /**
99  * dma_fence_context_alloc - allocate an array of fence contexts
100  * @num: amount of contexts to allocate
101  *
102  * This function will return the first index of the number of fence contexts
103  * allocated.  The fence context is used for setting &dma_fence.context to a
104  * unique number by passing the context to dma_fence_init().
105  */
106 u64 dma_fence_context_alloc(unsigned num)
107 {
108 	WARN_ON(!num);
109 	return atomic64_add_return(num, &dma_fence_context_counter) - num;
110 }
111 EXPORT_SYMBOL(dma_fence_context_alloc);
112 
113 /**
114  * dma_fence_signal_locked - signal completion of a fence
115  * @fence: the fence to signal
116  *
117  * Signal completion for software callbacks on a fence, this will unblock
118  * dma_fence_wait() calls and run all the callbacks added with
119  * dma_fence_add_callback(). Can be called multiple times, but since a fence
120  * can only go from the unsignaled to the signaled state and not back, it will
121  * only be effective the first time.
122  *
123  * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
124  * held.
125  *
126  * Returns 0 on success and a negative error value when @fence has been
127  * signalled already.
128  */
129 int dma_fence_signal_locked(struct dma_fence *fence)
130 {
131 	struct dma_fence_cb *cur, *tmp;
132 	int ret = 0;
133 
134 	lockdep_assert_held(fence->lock);
135 
136 	if (WARN_ON(!fence))
137 		return -EINVAL;
138 
139 	if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
140 		ret = -EINVAL;
141 
142 		/*
143 		 * we might have raced with the unlocked dma_fence_signal,
144 		 * still run through all callbacks
145 		 */
146 	} else {
147 		fence->timestamp = ktime_get();
148 		set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
149 		trace_dma_fence_signaled(fence);
150 	}
151 
152 	list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
153 		list_del_init(&cur->node);
154 		cur->func(fence, cur);
155 	}
156 	return ret;
157 }
158 EXPORT_SYMBOL(dma_fence_signal_locked);
159 
160 /**
161  * dma_fence_signal - signal completion of a fence
162  * @fence: the fence to signal
163  *
164  * Signal completion for software callbacks on a fence, this will unblock
165  * dma_fence_wait() calls and run all the callbacks added with
166  * dma_fence_add_callback(). Can be called multiple times, but since a fence
167  * can only go from the unsignaled to the signaled state and not back, it will
168  * only be effective the first time.
169  *
170  * Returns 0 on success and a negative error value when @fence has been
171  * signalled already.
172  */
173 int dma_fence_signal(struct dma_fence *fence)
174 {
175 	unsigned long flags;
176 
177 	if (!fence)
178 		return -EINVAL;
179 
180 	if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
181 		return -EINVAL;
182 
183 	fence->timestamp = ktime_get();
184 	set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
185 	trace_dma_fence_signaled(fence);
186 
187 	if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) {
188 		struct dma_fence_cb *cur, *tmp;
189 
190 		spin_lock_irqsave(fence->lock, flags);
191 		list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
192 			list_del_init(&cur->node);
193 			cur->func(fence, cur);
194 		}
195 		spin_unlock_irqrestore(fence->lock, flags);
196 	}
197 	return 0;
198 }
199 EXPORT_SYMBOL(dma_fence_signal);
200 
201 /**
202  * dma_fence_wait_timeout - sleep until the fence gets signaled
203  * or until timeout elapses
204  * @fence: the fence to wait on
205  * @intr: if true, do an interruptible wait
206  * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
207  *
208  * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
209  * remaining timeout in jiffies on success. Other error values may be
210  * returned on custom implementations.
211  *
212  * Performs a synchronous wait on this fence. It is assumed the caller
213  * directly or indirectly (buf-mgr between reservation and committing)
214  * holds a reference to the fence, otherwise the fence might be
215  * freed before return, resulting in undefined behavior.
216  *
217  * See also dma_fence_wait() and dma_fence_wait_any_timeout().
218  */
219 signed long
220 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
221 {
222 	signed long ret;
223 
224 	if (WARN_ON(timeout < 0))
225 		return -EINVAL;
226 
227 	trace_dma_fence_wait_start(fence);
228 	if (fence->ops->wait)
229 		ret = fence->ops->wait(fence, intr, timeout);
230 	else
231 		ret = dma_fence_default_wait(fence, intr, timeout);
232 	trace_dma_fence_wait_end(fence);
233 	return ret;
234 }
235 EXPORT_SYMBOL(dma_fence_wait_timeout);
236 
237 /**
238  * dma_fence_release - default relese function for fences
239  * @kref: &dma_fence.recfount
240  *
241  * This is the default release functions for &dma_fence. Drivers shouldn't call
242  * this directly, but instead call dma_fence_put().
243  */
244 void dma_fence_release(struct kref *kref)
245 {
246 	struct dma_fence *fence =
247 		container_of(kref, struct dma_fence, refcount);
248 
249 	trace_dma_fence_destroy(fence);
250 
251 	/* Failed to signal before release, could be a refcounting issue */
252 	WARN_ON(!list_empty(&fence->cb_list));
253 
254 	if (fence->ops->release)
255 		fence->ops->release(fence);
256 	else
257 		dma_fence_free(fence);
258 }
259 EXPORT_SYMBOL(dma_fence_release);
260 
261 /**
262  * dma_fence_free - default release function for &dma_fence.
263  * @fence: fence to release
264  *
265  * This is the default implementation for &dma_fence_ops.release. It calls
266  * kfree_rcu() on @fence.
267  */
268 void dma_fence_free(struct dma_fence *fence)
269 {
270 	kfree_rcu(fence, rcu);
271 }
272 EXPORT_SYMBOL(dma_fence_free);
273 
274 /**
275  * dma_fence_enable_sw_signaling - enable signaling on fence
276  * @fence: the fence to enable
277  *
278  * This will request for sw signaling to be enabled, to make the fence
279  * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
280  * internally.
281  */
282 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
283 {
284 	unsigned long flags;
285 
286 	if (!test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
287 			      &fence->flags) &&
288 	    !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) &&
289 	    fence->ops->enable_signaling) {
290 		trace_dma_fence_enable_signal(fence);
291 
292 		spin_lock_irqsave(fence->lock, flags);
293 
294 		if (!fence->ops->enable_signaling(fence))
295 			dma_fence_signal_locked(fence);
296 
297 		spin_unlock_irqrestore(fence->lock, flags);
298 	}
299 }
300 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
301 
302 /**
303  * dma_fence_add_callback - add a callback to be called when the fence
304  * is signaled
305  * @fence: the fence to wait on
306  * @cb: the callback to register
307  * @func: the function to call
308  *
309  * @cb will be initialized by dma_fence_add_callback(), no initialization
310  * by the caller is required. Any number of callbacks can be registered
311  * to a fence, but a callback can only be registered to one fence at a time.
312  *
313  * Note that the callback can be called from an atomic context.  If
314  * fence is already signaled, this function will return -ENOENT (and
315  * *not* call the callback).
316  *
317  * Add a software callback to the fence. Same restrictions apply to
318  * refcount as it does to dma_fence_wait(), however the caller doesn't need to
319  * keep a refcount to fence afterward dma_fence_add_callback() has returned:
320  * when software access is enabled, the creator of the fence is required to keep
321  * the fence alive until after it signals with dma_fence_signal(). The callback
322  * itself can be called from irq context.
323  *
324  * Returns 0 in case of success, -ENOENT if the fence is already signaled
325  * and -EINVAL in case of error.
326  */
327 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
328 			   dma_fence_func_t func)
329 {
330 	unsigned long flags;
331 	int ret = 0;
332 	bool was_set;
333 
334 	if (WARN_ON(!fence || !func))
335 		return -EINVAL;
336 
337 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
338 		INIT_LIST_HEAD(&cb->node);
339 		return -ENOENT;
340 	}
341 
342 	spin_lock_irqsave(fence->lock, flags);
343 
344 	was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
345 				   &fence->flags);
346 
347 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
348 		ret = -ENOENT;
349 	else if (!was_set && fence->ops->enable_signaling) {
350 		trace_dma_fence_enable_signal(fence);
351 
352 		if (!fence->ops->enable_signaling(fence)) {
353 			dma_fence_signal_locked(fence);
354 			ret = -ENOENT;
355 		}
356 	}
357 
358 	if (!ret) {
359 		cb->func = func;
360 		list_add_tail(&cb->node, &fence->cb_list);
361 	} else
362 		INIT_LIST_HEAD(&cb->node);
363 	spin_unlock_irqrestore(fence->lock, flags);
364 
365 	return ret;
366 }
367 EXPORT_SYMBOL(dma_fence_add_callback);
368 
369 /**
370  * dma_fence_get_status - returns the status upon completion
371  * @fence: the dma_fence to query
372  *
373  * This wraps dma_fence_get_status_locked() to return the error status
374  * condition on a signaled fence. See dma_fence_get_status_locked() for more
375  * details.
376  *
377  * Returns 0 if the fence has not yet been signaled, 1 if the fence has
378  * been signaled without an error condition, or a negative error code
379  * if the fence has been completed in err.
380  */
381 int dma_fence_get_status(struct dma_fence *fence)
382 {
383 	unsigned long flags;
384 	int status;
385 
386 	spin_lock_irqsave(fence->lock, flags);
387 	status = dma_fence_get_status_locked(fence);
388 	spin_unlock_irqrestore(fence->lock, flags);
389 
390 	return status;
391 }
392 EXPORT_SYMBOL(dma_fence_get_status);
393 
394 /**
395  * dma_fence_remove_callback - remove a callback from the signaling list
396  * @fence: the fence to wait on
397  * @cb: the callback to remove
398  *
399  * Remove a previously queued callback from the fence. This function returns
400  * true if the callback is successfully removed, or false if the fence has
401  * already been signaled.
402  *
403  * *WARNING*:
404  * Cancelling a callback should only be done if you really know what you're
405  * doing, since deadlocks and race conditions could occur all too easily. For
406  * this reason, it should only ever be done on hardware lockup recovery,
407  * with a reference held to the fence.
408  *
409  * Behaviour is undefined if @cb has not been added to @fence using
410  * dma_fence_add_callback() beforehand.
411  */
412 bool
413 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
414 {
415 	unsigned long flags;
416 	bool ret;
417 
418 	spin_lock_irqsave(fence->lock, flags);
419 
420 	ret = !list_empty(&cb->node);
421 	if (ret)
422 		list_del_init(&cb->node);
423 
424 	spin_unlock_irqrestore(fence->lock, flags);
425 
426 	return ret;
427 }
428 EXPORT_SYMBOL(dma_fence_remove_callback);
429 
430 struct default_wait_cb {
431 	struct dma_fence_cb base;
432 	struct task_struct *task;
433 };
434 
435 static void
436 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
437 {
438 	struct default_wait_cb *wait =
439 		container_of(cb, struct default_wait_cb, base);
440 
441 	wake_up_state(wait->task, TASK_NORMAL);
442 }
443 
444 /**
445  * dma_fence_default_wait - default sleep until the fence gets signaled
446  * or until timeout elapses
447  * @fence: the fence to wait on
448  * @intr: if true, do an interruptible wait
449  * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
450  *
451  * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
452  * remaining timeout in jiffies on success. If timeout is zero the value one is
453  * returned if the fence is already signaled for consistency with other
454  * functions taking a jiffies timeout.
455  */
456 signed long
457 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
458 {
459 	struct default_wait_cb cb;
460 	unsigned long flags;
461 	signed long ret = timeout ? timeout : 1;
462 	bool was_set;
463 
464 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
465 		return ret;
466 
467 	spin_lock_irqsave(fence->lock, flags);
468 
469 	if (intr && signal_pending(current)) {
470 		ret = -ERESTARTSYS;
471 		goto out;
472 	}
473 
474 	was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
475 				   &fence->flags);
476 
477 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
478 		goto out;
479 
480 	if (!was_set && fence->ops->enable_signaling) {
481 		trace_dma_fence_enable_signal(fence);
482 
483 		if (!fence->ops->enable_signaling(fence)) {
484 			dma_fence_signal_locked(fence);
485 			goto out;
486 		}
487 	}
488 
489 	if (!timeout) {
490 		ret = 0;
491 		goto out;
492 	}
493 
494 	cb.base.func = dma_fence_default_wait_cb;
495 	cb.task = current;
496 	list_add(&cb.base.node, &fence->cb_list);
497 
498 	while (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
499 		if (intr)
500 			__set_current_state(TASK_INTERRUPTIBLE);
501 		else
502 			__set_current_state(TASK_UNINTERRUPTIBLE);
503 		spin_unlock_irqrestore(fence->lock, flags);
504 
505 		ret = schedule_timeout(ret);
506 
507 		spin_lock_irqsave(fence->lock, flags);
508 		if (ret > 0 && intr && signal_pending(current))
509 			ret = -ERESTARTSYS;
510 	}
511 
512 	if (!list_empty(&cb.base.node))
513 		list_del(&cb.base.node);
514 	__set_current_state(TASK_RUNNING);
515 
516 out:
517 	spin_unlock_irqrestore(fence->lock, flags);
518 	return ret;
519 }
520 EXPORT_SYMBOL(dma_fence_default_wait);
521 
522 static bool
523 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
524 			    uint32_t *idx)
525 {
526 	int i;
527 
528 	for (i = 0; i < count; ++i) {
529 		struct dma_fence *fence = fences[i];
530 		if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
531 			if (idx)
532 				*idx = i;
533 			return true;
534 		}
535 	}
536 	return false;
537 }
538 
539 /**
540  * dma_fence_wait_any_timeout - sleep until any fence gets signaled
541  * or until timeout elapses
542  * @fences: array of fences to wait on
543  * @count: number of fences to wait on
544  * @intr: if true, do an interruptible wait
545  * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
546  * @idx: used to store the first signaled fence index, meaningful only on
547  *	positive return
548  *
549  * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
550  * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
551  * on success.
552  *
553  * Synchronous waits for the first fence in the array to be signaled. The
554  * caller needs to hold a reference to all fences in the array, otherwise a
555  * fence might be freed before return, resulting in undefined behavior.
556  *
557  * See also dma_fence_wait() and dma_fence_wait_timeout().
558  */
559 signed long
560 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
561 			   bool intr, signed long timeout, uint32_t *idx)
562 {
563 	struct default_wait_cb *cb;
564 	signed long ret = timeout;
565 	unsigned i;
566 
567 	if (WARN_ON(!fences || !count || timeout < 0))
568 		return -EINVAL;
569 
570 	if (timeout == 0) {
571 		for (i = 0; i < count; ++i)
572 			if (dma_fence_is_signaled(fences[i])) {
573 				if (idx)
574 					*idx = i;
575 				return 1;
576 			}
577 
578 		return 0;
579 	}
580 
581 	cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
582 	if (cb == NULL) {
583 		ret = -ENOMEM;
584 		goto err_free_cb;
585 	}
586 
587 	for (i = 0; i < count; ++i) {
588 		struct dma_fence *fence = fences[i];
589 
590 		cb[i].task = current;
591 		if (dma_fence_add_callback(fence, &cb[i].base,
592 					   dma_fence_default_wait_cb)) {
593 			/* This fence is already signaled */
594 			if (idx)
595 				*idx = i;
596 			goto fence_rm_cb;
597 		}
598 	}
599 
600 	while (ret > 0) {
601 		if (intr)
602 			set_current_state(TASK_INTERRUPTIBLE);
603 		else
604 			set_current_state(TASK_UNINTERRUPTIBLE);
605 
606 		if (dma_fence_test_signaled_any(fences, count, idx))
607 			break;
608 
609 		ret = schedule_timeout(ret);
610 
611 		if (ret > 0 && intr && signal_pending(current))
612 			ret = -ERESTARTSYS;
613 	}
614 
615 	__set_current_state(TASK_RUNNING);
616 
617 fence_rm_cb:
618 	while (i-- > 0)
619 		dma_fence_remove_callback(fences[i], &cb[i].base);
620 
621 err_free_cb:
622 	kfree(cb);
623 
624 	return ret;
625 }
626 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
627 
628 /**
629  * dma_fence_init - Initialize a custom fence.
630  * @fence: the fence to initialize
631  * @ops: the dma_fence_ops for operations on this fence
632  * @lock: the irqsafe spinlock to use for locking this fence
633  * @context: the execution context this fence is run on
634  * @seqno: a linear increasing sequence number for this context
635  *
636  * Initializes an allocated fence, the caller doesn't have to keep its
637  * refcount after committing with this fence, but it will need to hold a
638  * refcount again if &dma_fence_ops.enable_signaling gets called.
639  *
640  * context and seqno are used for easy comparison between fences, allowing
641  * to check which fence is later by simply using dma_fence_later().
642  */
643 void
644 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
645 	       spinlock_t *lock, u64 context, u64 seqno)
646 {
647 	BUG_ON(!lock);
648 	BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
649 
650 	kref_init(&fence->refcount);
651 	fence->ops = ops;
652 	INIT_LIST_HEAD(&fence->cb_list);
653 	fence->lock = lock;
654 	fence->context = context;
655 	fence->seqno = seqno;
656 	fence->flags = 0UL;
657 	fence->error = 0;
658 
659 	trace_dma_fence_init(fence);
660 }
661 EXPORT_SYMBOL(dma_fence_init);
662