1 /*
2 * Fence mechanism for dma-buf and to allow for asynchronous dma access
3 *
4 * Copyright (C) 2012 Canonical Ltd
5 * Copyright (C) 2012 Texas Instruments
6 *
7 * Authors:
8 * Rob Clark <robdclark@gmail.com>
9 * Maarten Lankhorst <maarten.lankhorst@canonical.com>
10 *
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License version 2 as published by
13 * the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
18 * more details.
19 */
20
21 #include <linux/slab.h>
22 #include <linux/export.h>
23 #include <linux/atomic.h>
24 #include <linux/dma-fence.h>
25 #include <linux/sched/signal.h>
26
27 #define CREATE_TRACE_POINTS
28 #include <trace/events/dma_fence.h>
29
30 EXPORT_TRACEPOINT_SYMBOL(dma_fence_emit);
31 EXPORT_TRACEPOINT_SYMBOL(dma_fence_enable_signal);
32
33 /*
34 * fence context counter: each execution context should have its own
35 * fence context, this allows checking if fences belong to the same
36 * context or not. One device can have multiple separate contexts,
37 * and they're used if some engine can run independently of another.
38 */
39 static atomic64_t dma_fence_context_counter = ATOMIC64_INIT(0);
40
41 /**
42 * DOC: DMA fences overview
43 *
44 * DMA fences, represented by &struct dma_fence, are the kernel internal
45 * synchronization primitive for DMA operations like GPU rendering, video
46 * encoding/decoding, or displaying buffers on a screen.
47 *
48 * A fence is initialized using dma_fence_init() and completed using
49 * dma_fence_signal(). Fences are associated with a context, allocated through
50 * dma_fence_context_alloc(), and all fences on the same context are
51 * fully ordered.
52 *
53 * Since the purposes of fences is to facilitate cross-device and
54 * cross-application synchronization, there's multiple ways to use one:
55 *
56 * - Individual fences can be exposed as a &sync_file, accessed as a file
57 * descriptor from userspace, created by calling sync_file_create(). This is
58 * called explicit fencing, since userspace passes around explicit
59 * synchronization points.
60 *
61 * - Some subsystems also have their own explicit fencing primitives, like
62 * &drm_syncobj. Compared to &sync_file, a &drm_syncobj allows the underlying
63 * fence to be updated.
64 *
65 * - Then there's also implicit fencing, where the synchronization points are
66 * implicitly passed around as part of shared &dma_buf instances. Such
67 * implicit fences are stored in &struct reservation_object through the
68 * &dma_buf.resv pointer.
69 */
70
71 /**
72 * dma_fence_context_alloc - allocate an array of fence contexts
73 * @num: amount of contexts to allocate
74 *
75 * This function will return the first index of the number of fence contexts
76 * allocated. The fence context is used for setting &dma_fence.context to a
77 * unique number by passing the context to dma_fence_init().
78 */
dma_fence_context_alloc(unsigned num)79 u64 dma_fence_context_alloc(unsigned num)
80 {
81 WARN_ON(!num);
82 return atomic64_add_return(num, &dma_fence_context_counter) - num;
83 }
84 EXPORT_SYMBOL(dma_fence_context_alloc);
85
86 /**
87 * dma_fence_signal_locked - signal completion of a fence
88 * @fence: the fence to signal
89 *
90 * Signal completion for software callbacks on a fence, this will unblock
91 * dma_fence_wait() calls and run all the callbacks added with
92 * dma_fence_add_callback(). Can be called multiple times, but since a fence
93 * can only go from the unsignaled to the signaled state and not back, it will
94 * only be effective the first time.
95 *
96 * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
97 * held.
98 *
99 * Returns 0 on success and a negative error value when @fence has been
100 * signalled already.
101 */
dma_fence_signal_locked(struct dma_fence * fence)102 int dma_fence_signal_locked(struct dma_fence *fence)
103 {
104 struct dma_fence_cb *cur, *tmp;
105 int ret = 0;
106
107 lockdep_assert_held(fence->lock);
108
109 if (WARN_ON(!fence))
110 return -EINVAL;
111
112 if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
113 ret = -EINVAL;
114
115 /*
116 * we might have raced with the unlocked dma_fence_signal,
117 * still run through all callbacks
118 */
119 } else {
120 fence->timestamp = ktime_get();
121 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
122 trace_dma_fence_signaled(fence);
123 }
124
125 list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
126 list_del_init(&cur->node);
127 cur->func(fence, cur);
128 }
129 return ret;
130 }
131 EXPORT_SYMBOL(dma_fence_signal_locked);
132
133 /**
134 * dma_fence_signal - signal completion of a fence
135 * @fence: the fence to signal
136 *
137 * Signal completion for software callbacks on a fence, this will unblock
138 * dma_fence_wait() calls and run all the callbacks added with
139 * dma_fence_add_callback(). Can be called multiple times, but since a fence
140 * can only go from the unsignaled to the signaled state and not back, it will
141 * only be effective the first time.
142 *
143 * Returns 0 on success and a negative error value when @fence has been
144 * signalled already.
145 */
dma_fence_signal(struct dma_fence * fence)146 int dma_fence_signal(struct dma_fence *fence)
147 {
148 unsigned long flags;
149
150 if (!fence)
151 return -EINVAL;
152
153 if (test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
154 return -EINVAL;
155
156 fence->timestamp = ktime_get();
157 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
158 trace_dma_fence_signaled(fence);
159
160 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) {
161 struct dma_fence_cb *cur, *tmp;
162
163 spin_lock_irqsave(fence->lock, flags);
164 list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
165 list_del_init(&cur->node);
166 cur->func(fence, cur);
167 }
168 spin_unlock_irqrestore(fence->lock, flags);
169 }
170 return 0;
171 }
172 EXPORT_SYMBOL(dma_fence_signal);
173
174 /**
175 * dma_fence_wait_timeout - sleep until the fence gets signaled
176 * or until timeout elapses
177 * @fence: the fence to wait on
178 * @intr: if true, do an interruptible wait
179 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
180 *
181 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
182 * remaining timeout in jiffies on success. Other error values may be
183 * returned on custom implementations.
184 *
185 * Performs a synchronous wait on this fence. It is assumed the caller
186 * directly or indirectly (buf-mgr between reservation and committing)
187 * holds a reference to the fence, otherwise the fence might be
188 * freed before return, resulting in undefined behavior.
189 *
190 * See also dma_fence_wait() and dma_fence_wait_any_timeout().
191 */
192 signed long
dma_fence_wait_timeout(struct dma_fence * fence,bool intr,signed long timeout)193 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
194 {
195 signed long ret;
196
197 if (WARN_ON(timeout < 0))
198 return -EINVAL;
199
200 trace_dma_fence_wait_start(fence);
201 if (fence->ops->wait)
202 ret = fence->ops->wait(fence, intr, timeout);
203 else
204 ret = dma_fence_default_wait(fence, intr, timeout);
205 trace_dma_fence_wait_end(fence);
206 return ret;
207 }
208 EXPORT_SYMBOL(dma_fence_wait_timeout);
209
210 /**
211 * dma_fence_release - default relese function for fences
212 * @kref: &dma_fence.recfount
213 *
214 * This is the default release functions for &dma_fence. Drivers shouldn't call
215 * this directly, but instead call dma_fence_put().
216 */
dma_fence_release(struct kref * kref)217 void dma_fence_release(struct kref *kref)
218 {
219 struct dma_fence *fence =
220 container_of(kref, struct dma_fence, refcount);
221
222 trace_dma_fence_destroy(fence);
223
224 /* Failed to signal before release, could be a refcounting issue */
225 WARN_ON(!list_empty(&fence->cb_list));
226
227 if (fence->ops->release)
228 fence->ops->release(fence);
229 else
230 dma_fence_free(fence);
231 }
232 EXPORT_SYMBOL(dma_fence_release);
233
234 /**
235 * dma_fence_free - default release function for &dma_fence.
236 * @fence: fence to release
237 *
238 * This is the default implementation for &dma_fence_ops.release. It calls
239 * kfree_rcu() on @fence.
240 */
dma_fence_free(struct dma_fence * fence)241 void dma_fence_free(struct dma_fence *fence)
242 {
243 kfree_rcu(fence, rcu);
244 }
245 EXPORT_SYMBOL(dma_fence_free);
246
__dma_fence_enable_signaling(struct dma_fence * fence)247 static bool __dma_fence_enable_signaling(struct dma_fence *fence)
248 {
249 bool was_set;
250
251 lockdep_assert_held(fence->lock);
252
253 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
254 &fence->flags);
255
256 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
257 return false;
258
259 if (!was_set && fence->ops->enable_signaling) {
260 trace_dma_fence_enable_signal(fence);
261
262 if (!fence->ops->enable_signaling(fence)) {
263 dma_fence_signal_locked(fence);
264 return false;
265 }
266 }
267
268 return true;
269 }
270
271 /**
272 * dma_fence_enable_sw_signaling - enable signaling on fence
273 * @fence: the fence to enable
274 *
275 * This will request for sw signaling to be enabled, to make the fence
276 * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
277 * internally.
278 */
dma_fence_enable_sw_signaling(struct dma_fence * fence)279 void dma_fence_enable_sw_signaling(struct dma_fence *fence)
280 {
281 unsigned long flags;
282
283 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
284 return;
285
286 spin_lock_irqsave(fence->lock, flags);
287 __dma_fence_enable_signaling(fence);
288 spin_unlock_irqrestore(fence->lock, flags);
289 }
290 EXPORT_SYMBOL(dma_fence_enable_sw_signaling);
291
292 /**
293 * dma_fence_add_callback - add a callback to be called when the fence
294 * is signaled
295 * @fence: the fence to wait on
296 * @cb: the callback to register
297 * @func: the function to call
298 *
299 * @cb will be initialized by dma_fence_add_callback(), no initialization
300 * by the caller is required. Any number of callbacks can be registered
301 * to a fence, but a callback can only be registered to one fence at a time.
302 *
303 * Note that the callback can be called from an atomic context. If
304 * fence is already signaled, this function will return -ENOENT (and
305 * *not* call the callback).
306 *
307 * Add a software callback to the fence. Same restrictions apply to
308 * refcount as it does to dma_fence_wait(), however the caller doesn't need to
309 * keep a refcount to fence afterward dma_fence_add_callback() has returned:
310 * when software access is enabled, the creator of the fence is required to keep
311 * the fence alive until after it signals with dma_fence_signal(). The callback
312 * itself can be called from irq context.
313 *
314 * Returns 0 in case of success, -ENOENT if the fence is already signaled
315 * and -EINVAL in case of error.
316 */
dma_fence_add_callback(struct dma_fence * fence,struct dma_fence_cb * cb,dma_fence_func_t func)317 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
318 dma_fence_func_t func)
319 {
320 unsigned long flags;
321 int ret = 0;
322
323 if (WARN_ON(!fence || !func))
324 return -EINVAL;
325
326 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
327 INIT_LIST_HEAD(&cb->node);
328 return -ENOENT;
329 }
330
331 spin_lock_irqsave(fence->lock, flags);
332
333 if (__dma_fence_enable_signaling(fence)) {
334 cb->func = func;
335 list_add_tail(&cb->node, &fence->cb_list);
336 } else {
337 INIT_LIST_HEAD(&cb->node);
338 ret = -ENOENT;
339 }
340
341 spin_unlock_irqrestore(fence->lock, flags);
342
343 return ret;
344 }
345 EXPORT_SYMBOL(dma_fence_add_callback);
346
347 /**
348 * dma_fence_get_status - returns the status upon completion
349 * @fence: the dma_fence to query
350 *
351 * This wraps dma_fence_get_status_locked() to return the error status
352 * condition on a signaled fence. See dma_fence_get_status_locked() for more
353 * details.
354 *
355 * Returns 0 if the fence has not yet been signaled, 1 if the fence has
356 * been signaled without an error condition, or a negative error code
357 * if the fence has been completed in err.
358 */
dma_fence_get_status(struct dma_fence * fence)359 int dma_fence_get_status(struct dma_fence *fence)
360 {
361 unsigned long flags;
362 int status;
363
364 spin_lock_irqsave(fence->lock, flags);
365 status = dma_fence_get_status_locked(fence);
366 spin_unlock_irqrestore(fence->lock, flags);
367
368 return status;
369 }
370 EXPORT_SYMBOL(dma_fence_get_status);
371
372 /**
373 * dma_fence_remove_callback - remove a callback from the signaling list
374 * @fence: the fence to wait on
375 * @cb: the callback to remove
376 *
377 * Remove a previously queued callback from the fence. This function returns
378 * true if the callback is successfully removed, or false if the fence has
379 * already been signaled.
380 *
381 * *WARNING*:
382 * Cancelling a callback should only be done if you really know what you're
383 * doing, since deadlocks and race conditions could occur all too easily. For
384 * this reason, it should only ever be done on hardware lockup recovery,
385 * with a reference held to the fence.
386 *
387 * Behaviour is undefined if @cb has not been added to @fence using
388 * dma_fence_add_callback() beforehand.
389 */
390 bool
dma_fence_remove_callback(struct dma_fence * fence,struct dma_fence_cb * cb)391 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
392 {
393 unsigned long flags;
394 bool ret;
395
396 spin_lock_irqsave(fence->lock, flags);
397
398 ret = !list_empty(&cb->node);
399 if (ret)
400 list_del_init(&cb->node);
401
402 spin_unlock_irqrestore(fence->lock, flags);
403
404 return ret;
405 }
406 EXPORT_SYMBOL(dma_fence_remove_callback);
407
408 struct default_wait_cb {
409 struct dma_fence_cb base;
410 struct task_struct *task;
411 };
412
413 static void
dma_fence_default_wait_cb(struct dma_fence * fence,struct dma_fence_cb * cb)414 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
415 {
416 struct default_wait_cb *wait =
417 container_of(cb, struct default_wait_cb, base);
418
419 wake_up_state(wait->task, TASK_NORMAL);
420 }
421
422 /**
423 * dma_fence_default_wait - default sleep until the fence gets signaled
424 * or until timeout elapses
425 * @fence: the fence to wait on
426 * @intr: if true, do an interruptible wait
427 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
428 *
429 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
430 * remaining timeout in jiffies on success. If timeout is zero the value one is
431 * returned if the fence is already signaled for consistency with other
432 * functions taking a jiffies timeout.
433 */
434 signed long
dma_fence_default_wait(struct dma_fence * fence,bool intr,signed long timeout)435 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
436 {
437 struct default_wait_cb cb;
438 unsigned long flags;
439 signed long ret = timeout ? timeout : 1;
440
441 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
442 return ret;
443
444 spin_lock_irqsave(fence->lock, flags);
445
446 if (intr && signal_pending(current)) {
447 ret = -ERESTARTSYS;
448 goto out;
449 }
450
451 if (!__dma_fence_enable_signaling(fence))
452 goto out;
453
454 if (!timeout) {
455 ret = 0;
456 goto out;
457 }
458
459 cb.base.func = dma_fence_default_wait_cb;
460 cb.task = current;
461 list_add(&cb.base.node, &fence->cb_list);
462
463 while (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
464 if (intr)
465 __set_current_state(TASK_INTERRUPTIBLE);
466 else
467 __set_current_state(TASK_UNINTERRUPTIBLE);
468 spin_unlock_irqrestore(fence->lock, flags);
469
470 ret = schedule_timeout(ret);
471
472 spin_lock_irqsave(fence->lock, flags);
473 if (ret > 0 && intr && signal_pending(current))
474 ret = -ERESTARTSYS;
475 }
476
477 if (!list_empty(&cb.base.node))
478 list_del(&cb.base.node);
479 __set_current_state(TASK_RUNNING);
480
481 out:
482 spin_unlock_irqrestore(fence->lock, flags);
483 return ret;
484 }
485 EXPORT_SYMBOL(dma_fence_default_wait);
486
487 static bool
dma_fence_test_signaled_any(struct dma_fence ** fences,uint32_t count,uint32_t * idx)488 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
489 uint32_t *idx)
490 {
491 int i;
492
493 for (i = 0; i < count; ++i) {
494 struct dma_fence *fence = fences[i];
495 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
496 if (idx)
497 *idx = i;
498 return true;
499 }
500 }
501 return false;
502 }
503
504 /**
505 * dma_fence_wait_any_timeout - sleep until any fence gets signaled
506 * or until timeout elapses
507 * @fences: array of fences to wait on
508 * @count: number of fences to wait on
509 * @intr: if true, do an interruptible wait
510 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
511 * @idx: used to store the first signaled fence index, meaningful only on
512 * positive return
513 *
514 * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
515 * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
516 * on success.
517 *
518 * Synchronous waits for the first fence in the array to be signaled. The
519 * caller needs to hold a reference to all fences in the array, otherwise a
520 * fence might be freed before return, resulting in undefined behavior.
521 *
522 * See also dma_fence_wait() and dma_fence_wait_timeout().
523 */
524 signed long
dma_fence_wait_any_timeout(struct dma_fence ** fences,uint32_t count,bool intr,signed long timeout,uint32_t * idx)525 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
526 bool intr, signed long timeout, uint32_t *idx)
527 {
528 struct default_wait_cb *cb;
529 signed long ret = timeout;
530 unsigned i;
531
532 if (WARN_ON(!fences || !count || timeout < 0))
533 return -EINVAL;
534
535 if (timeout == 0) {
536 for (i = 0; i < count; ++i)
537 if (dma_fence_is_signaled(fences[i])) {
538 if (idx)
539 *idx = i;
540 return 1;
541 }
542
543 return 0;
544 }
545
546 cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
547 if (cb == NULL) {
548 ret = -ENOMEM;
549 goto err_free_cb;
550 }
551
552 for (i = 0; i < count; ++i) {
553 struct dma_fence *fence = fences[i];
554
555 cb[i].task = current;
556 if (dma_fence_add_callback(fence, &cb[i].base,
557 dma_fence_default_wait_cb)) {
558 /* This fence is already signaled */
559 if (idx)
560 *idx = i;
561 goto fence_rm_cb;
562 }
563 }
564
565 while (ret > 0) {
566 if (intr)
567 set_current_state(TASK_INTERRUPTIBLE);
568 else
569 set_current_state(TASK_UNINTERRUPTIBLE);
570
571 if (dma_fence_test_signaled_any(fences, count, idx))
572 break;
573
574 ret = schedule_timeout(ret);
575
576 if (ret > 0 && intr && signal_pending(current))
577 ret = -ERESTARTSYS;
578 }
579
580 __set_current_state(TASK_RUNNING);
581
582 fence_rm_cb:
583 while (i-- > 0)
584 dma_fence_remove_callback(fences[i], &cb[i].base);
585
586 err_free_cb:
587 kfree(cb);
588
589 return ret;
590 }
591 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
592
593 /**
594 * dma_fence_init - Initialize a custom fence.
595 * @fence: the fence to initialize
596 * @ops: the dma_fence_ops for operations on this fence
597 * @lock: the irqsafe spinlock to use for locking this fence
598 * @context: the execution context this fence is run on
599 * @seqno: a linear increasing sequence number for this context
600 *
601 * Initializes an allocated fence, the caller doesn't have to keep its
602 * refcount after committing with this fence, but it will need to hold a
603 * refcount again if &dma_fence_ops.enable_signaling gets called.
604 *
605 * context and seqno are used for easy comparison between fences, allowing
606 * to check which fence is later by simply using dma_fence_later().
607 */
608 void
dma_fence_init(struct dma_fence * fence,const struct dma_fence_ops * ops,spinlock_t * lock,u64 context,unsigned seqno)609 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
610 spinlock_t *lock, u64 context, unsigned seqno)
611 {
612 BUG_ON(!lock);
613 BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
614
615 kref_init(&fence->refcount);
616 fence->ops = ops;
617 INIT_LIST_HEAD(&fence->cb_list);
618 fence->lock = lock;
619 fence->context = context;
620 fence->seqno = seqno;
621 fence->flags = 0UL;
622 fence->error = 0;
623
624 trace_dma_fence_init(fence);
625 }
626 EXPORT_SYMBOL(dma_fence_init);
627