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 #include <linux/seq_file.h>
19
20 #define CREATE_TRACE_POINTS
21 #include <trace/events/dma_fence.h>
22
23 EXPORT_TRACEPOINT_SYMBOL(dma_fence_emit);
24 EXPORT_TRACEPOINT_SYMBOL(dma_fence_enable_signal);
25 EXPORT_TRACEPOINT_SYMBOL(dma_fence_signaled);
26
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 completion 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
dma_fence_stub_get_name(struct dma_fence * fence)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
dma_fence_init_stub(void)123 static int __init dma_fence_init_stub(void)
124 {
125 dma_fence_init(&dma_fence_stub, &dma_fence_stub_ops, NULL, 0, 0);
126 set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
127 &dma_fence_stub.flags);
128 dma_fence_signal(&dma_fence_stub);
129 return 0;
130 }
131 subsys_initcall(dma_fence_init_stub);
132
133 /**
134 * dma_fence_get_stub - return a signaled fence
135 *
136 * Return a stub fence which is already signaled. The fence's timestamp
137 * corresponds to the initialisation time of the linux kernel.
138 */
dma_fence_get_stub(void)139 struct dma_fence *dma_fence_get_stub(void)
140 {
141 return dma_fence_get(&dma_fence_stub);
142 }
143 EXPORT_SYMBOL(dma_fence_get_stub);
144
145 /**
146 * dma_fence_allocate_private_stub - return a private, signaled fence
147 * @timestamp: timestamp when the fence was signaled
148 *
149 * Return a newly allocated and signaled stub fence.
150 */
dma_fence_allocate_private_stub(ktime_t timestamp)151 struct dma_fence *dma_fence_allocate_private_stub(ktime_t timestamp)
152 {
153 struct dma_fence *fence;
154
155 fence = kzalloc_obj(*fence);
156 if (fence == NULL)
157 return NULL;
158
159 dma_fence_init(fence, &dma_fence_stub_ops, NULL, 0, 0);
160 set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
161 &fence->flags);
162
163 dma_fence_signal_timestamp(fence, timestamp);
164
165 return fence;
166 }
167 EXPORT_SYMBOL(dma_fence_allocate_private_stub);
168
169 /**
170 * dma_fence_context_alloc - allocate an array of fence contexts
171 * @num: amount of contexts to allocate
172 *
173 * This function will return the first index of the number of fence contexts
174 * allocated. The fence context is used for setting &dma_fence.context to a
175 * unique number by passing the context to dma_fence_init().
176 */
dma_fence_context_alloc(unsigned num)177 u64 dma_fence_context_alloc(unsigned num)
178 {
179 WARN_ON(!num);
180 return atomic64_fetch_add(num, &dma_fence_context_counter);
181 }
182 EXPORT_SYMBOL(dma_fence_context_alloc);
183
184 /**
185 * DOC: fence signalling annotation
186 *
187 * Proving correctness of all the kernel code around &dma_fence through code
188 * review and testing is tricky for a few reasons:
189 *
190 * * It is a cross-driver contract, and therefore all drivers must follow the
191 * same rules for lock nesting order, calling contexts for various functions
192 * and anything else significant for in-kernel interfaces. But it is also
193 * impossible to test all drivers in a single machine, hence brute-force N vs.
194 * N testing of all combinations is impossible. Even just limiting to the
195 * possible combinations is infeasible.
196 *
197 * * There is an enormous amount of driver code involved. For render drivers
198 * there's the tail of command submission, after fences are published,
199 * scheduler code, interrupt and workers to process job completion,
200 * and timeout, gpu reset and gpu hang recovery code. Plus for integration
201 * with core mm with have &mmu_notifier, respectively &mmu_interval_notifier,
202 * and &shrinker. For modesetting drivers there's the commit tail functions
203 * between when fences for an atomic modeset are published, and when the
204 * corresponding vblank completes, including any interrupt processing and
205 * related workers. Auditing all that code, across all drivers, is not
206 * feasible.
207 *
208 * * Due to how many other subsystems are involved and the locking hierarchies
209 * this pulls in there is extremely thin wiggle-room for driver-specific
210 * differences. &dma_fence interacts with almost all of the core memory
211 * handling through page fault handlers via &dma_resv, dma_resv_lock() and
212 * dma_resv_unlock(). On the other side it also interacts through all
213 * allocation sites through &mmu_notifier and &shrinker.
214 *
215 * Furthermore lockdep does not handle cross-release dependencies, which means
216 * any deadlocks between dma_fence_wait() and dma_fence_signal() can't be caught
217 * at runtime with some quick testing. The simplest example is one thread
218 * waiting on a &dma_fence while holding a lock::
219 *
220 * lock(A);
221 * dma_fence_wait(B);
222 * unlock(A);
223 *
224 * while the other thread is stuck trying to acquire the same lock, which
225 * prevents it from signalling the fence the previous thread is stuck waiting
226 * on::
227 *
228 * lock(A);
229 * unlock(A);
230 * dma_fence_signal(B);
231 *
232 * By manually annotating all code relevant to signalling a &dma_fence we can
233 * teach lockdep about these dependencies, which also helps with the validation
234 * headache since now lockdep can check all the rules for us::
235 *
236 * cookie = dma_fence_begin_signalling();
237 * lock(A);
238 * unlock(A);
239 * dma_fence_signal(B);
240 * dma_fence_end_signalling(cookie);
241 *
242 * For using dma_fence_begin_signalling() and dma_fence_end_signalling() to
243 * annotate critical sections the following rules need to be observed:
244 *
245 * * All code necessary to complete a &dma_fence must be annotated, from the
246 * point where a fence is accessible to other threads, to the point where
247 * dma_fence_signal() is called. Un-annotated code can contain deadlock issues,
248 * and due to the very strict rules and many corner cases it is infeasible to
249 * catch these just with review or normal stress testing.
250 *
251 * * &struct dma_resv deserves a special note, since the readers are only
252 * protected by rcu. This means the signalling critical section starts as soon
253 * as the new fences are installed, even before dma_resv_unlock() is called.
254 *
255 * * The only exception are fast paths and opportunistic signalling code, which
256 * calls dma_fence_signal() purely as an optimization, but is not required to
257 * guarantee completion of a &dma_fence. The usual example is a wait IOCTL
258 * which calls dma_fence_signal(), while the mandatory completion path goes
259 * through a hardware interrupt and possible job completion worker.
260 *
261 * * To aid composability of code, the annotations can be freely nested, as long
262 * as the overall locking hierarchy is consistent. The annotations also work
263 * both in interrupt and process context. Due to implementation details this
264 * requires that callers pass an opaque cookie from
265 * dma_fence_begin_signalling() to dma_fence_end_signalling().
266 *
267 * * Validation against the cross driver contract is implemented by priming
268 * lockdep with the relevant hierarchy at boot-up. This means even just
269 * testing with a single device is enough to validate a driver, at least as
270 * far as deadlocks with dma_fence_wait() against dma_fence_signal() are
271 * concerned.
272 */
273 #ifdef CONFIG_LOCKDEP
274 static struct lockdep_map dma_fence_lockdep_map = {
275 .name = "dma_fence_map"
276 };
277
278 /**
279 * dma_fence_begin_signalling - begin a critical DMA fence signalling section
280 *
281 * Drivers should use this to annotate the beginning of any code section
282 * required to eventually complete &dma_fence by calling dma_fence_signal().
283 *
284 * The end of these critical sections are annotated with
285 * dma_fence_end_signalling().
286 *
287 * Returns:
288 *
289 * Opaque cookie needed by the implementation, which needs to be passed to
290 * dma_fence_end_signalling().
291 */
dma_fence_begin_signalling(void)292 bool dma_fence_begin_signalling(void)
293 {
294 /* explicitly nesting ... */
295 if (lock_is_held_type(&dma_fence_lockdep_map, 1))
296 return true;
297
298 /* rely on might_sleep check for soft/hardirq locks */
299 if (in_atomic())
300 return true;
301
302 /* ... and non-recursive successful read_trylock */
303 lock_acquire(&dma_fence_lockdep_map, 0, 1, 1, 1, NULL, _RET_IP_);
304
305 return false;
306 }
307 EXPORT_SYMBOL(dma_fence_begin_signalling);
308
309 /**
310 * dma_fence_end_signalling - end a critical DMA fence signalling section
311 * @cookie: opaque cookie from dma_fence_begin_signalling()
312 *
313 * Closes a critical section annotation opened by dma_fence_begin_signalling().
314 */
dma_fence_end_signalling(bool cookie)315 void dma_fence_end_signalling(bool cookie)
316 {
317 if (cookie)
318 return;
319
320 lock_release(&dma_fence_lockdep_map, _RET_IP_);
321 }
322 EXPORT_SYMBOL(dma_fence_end_signalling);
323
__dma_fence_might_wait(void)324 void __dma_fence_might_wait(void)
325 {
326 bool tmp;
327
328 tmp = lock_is_held_type(&dma_fence_lockdep_map, 1);
329 if (tmp)
330 lock_release(&dma_fence_lockdep_map, _THIS_IP_);
331 lock_map_acquire(&dma_fence_lockdep_map);
332 lock_map_release(&dma_fence_lockdep_map);
333 if (tmp)
334 lock_acquire(&dma_fence_lockdep_map, 0, 1, 1, 1, NULL, _THIS_IP_);
335 }
336 #endif
337
338 /**
339 * dma_fence_signal_timestamp_locked - signal completion of a fence
340 * @fence: the fence to signal
341 * @timestamp: fence signal timestamp in kernel's CLOCK_MONOTONIC time domain
342 *
343 * Signal completion for software callbacks on a fence, this will unblock
344 * dma_fence_wait() calls and run all the callbacks added with
345 * dma_fence_add_callback(). Can be called multiple times, but since a fence
346 * can only go from the unsignaled to the signaled state and not back, it will
347 * only be effective the first time. Set the timestamp provided as the fence
348 * signal timestamp.
349 *
350 * Unlike dma_fence_signal_timestamp(), this function must be called with
351 * &dma_fence.lock held.
352 */
dma_fence_signal_timestamp_locked(struct dma_fence * fence,ktime_t timestamp)353 void dma_fence_signal_timestamp_locked(struct dma_fence *fence,
354 ktime_t timestamp)
355 {
356 const struct dma_fence_ops *ops;
357 struct dma_fence_cb *cur, *tmp;
358 struct list_head cb_list;
359
360 dma_fence_assert_held(fence);
361
362 if (unlikely(test_and_set_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
363 &fence->flags)))
364 return;
365
366 trace_dma_fence_signaled(fence);
367
368 /*
369 * When neither a release nor a wait operation is specified set the ops
370 * pointer to NULL to allow the fence structure to become independent
371 * from who originally issued it.
372 */
373 ops = rcu_dereference_protected(fence->ops, true);
374 if (!ops->release && !ops->wait)
375 RCU_INIT_POINTER(fence->ops, NULL);
376
377 /* Stash the cb_list before replacing it with the timestamp */
378 list_replace(&fence->cb_list, &cb_list);
379
380 fence->timestamp = timestamp;
381 set_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &fence->flags);
382
383 list_for_each_entry_safe(cur, tmp, &cb_list, node) {
384 INIT_LIST_HEAD(&cur->node);
385 cur->func(fence, cur);
386 }
387 }
388 EXPORT_SYMBOL(dma_fence_signal_timestamp_locked);
389
390 /**
391 * dma_fence_signal_timestamp - signal completion of a fence
392 * @fence: the fence to signal
393 * @timestamp: fence signal timestamp in kernel's CLOCK_MONOTONIC time domain
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. Set the timestamp provided as the fence
400 * signal timestamp.
401 */
dma_fence_signal_timestamp(struct dma_fence * fence,ktime_t timestamp)402 void dma_fence_signal_timestamp(struct dma_fence *fence, ktime_t timestamp)
403 {
404 unsigned long flags;
405
406 if (WARN_ON(!fence))
407 return;
408
409 dma_fence_lock_irqsave(fence, flags);
410 dma_fence_signal_timestamp_locked(fence, timestamp);
411 dma_fence_unlock_irqrestore(fence, flags);
412 }
413 EXPORT_SYMBOL(dma_fence_signal_timestamp);
414
415 /**
416 * dma_fence_signal_locked - signal completion of a fence
417 * @fence: the fence to signal
418 *
419 * Signal completion for software callbacks on a fence, this will unblock
420 * dma_fence_wait() calls and run all the callbacks added with
421 * dma_fence_add_callback(). Can be called multiple times, but since a fence
422 * can only go from the unsignaled to the signaled state and not back, it will
423 * only be effective the first time.
424 *
425 * Unlike dma_fence_signal(), this function must be called with &dma_fence.lock
426 * held.
427 */
dma_fence_signal_locked(struct dma_fence * fence)428 void dma_fence_signal_locked(struct dma_fence *fence)
429 {
430 dma_fence_signal_timestamp_locked(fence, ktime_get());
431 }
432 EXPORT_SYMBOL(dma_fence_signal_locked);
433
434 /**
435 * dma_fence_check_and_signal_locked - signal the fence if it's not yet signaled
436 * @fence: the fence to check and signal
437 *
438 * Checks whether a fence was signaled and signals it if it was not yet signaled.
439 *
440 * Unlike dma_fence_check_and_signal(), this function must be called with
441 * &struct dma_fence.lock being held.
442 *
443 * Return: true if fence has been signaled already, false otherwise.
444 */
dma_fence_check_and_signal_locked(struct dma_fence * fence)445 bool dma_fence_check_and_signal_locked(struct dma_fence *fence)
446 {
447 bool ret;
448
449 ret = dma_fence_test_signaled_flag(fence);
450 dma_fence_signal_locked(fence);
451
452 return ret;
453 }
454 EXPORT_SYMBOL(dma_fence_check_and_signal_locked);
455
456 /**
457 * dma_fence_check_and_signal - signal the fence if it's not yet signaled
458 * @fence: the fence to check and signal
459 *
460 * Checks whether a fence was signaled and signals it if it was not yet signaled.
461 * All this is done in a race-free manner.
462 *
463 * Return: true if fence has been signaled already, false otherwise.
464 */
dma_fence_check_and_signal(struct dma_fence * fence)465 bool dma_fence_check_and_signal(struct dma_fence *fence)
466 {
467 unsigned long flags;
468 bool ret;
469
470 dma_fence_lock_irqsave(fence, flags);
471 ret = dma_fence_check_and_signal_locked(fence);
472 dma_fence_unlock_irqrestore(fence, flags);
473
474 return ret;
475 }
476 EXPORT_SYMBOL(dma_fence_check_and_signal);
477
478 /**
479 * dma_fence_signal - signal completion of a fence
480 * @fence: the fence to signal
481 *
482 * Signal completion for software callbacks on a fence, this will unblock
483 * dma_fence_wait() calls and run all the callbacks added with
484 * dma_fence_add_callback(). Can be called multiple times, but since a fence
485 * can only go from the unsignaled to the signaled state and not back, it will
486 * only be effective the first time.
487 */
dma_fence_signal(struct dma_fence * fence)488 void dma_fence_signal(struct dma_fence *fence)
489 {
490 unsigned long flags;
491 bool tmp;
492
493 if (WARN_ON(!fence))
494 return;
495
496 tmp = dma_fence_begin_signalling();
497
498 dma_fence_lock_irqsave(fence, flags);
499 dma_fence_signal_timestamp_locked(fence, ktime_get());
500 dma_fence_unlock_irqrestore(fence, flags);
501
502 dma_fence_end_signalling(tmp);
503 }
504 EXPORT_SYMBOL(dma_fence_signal);
505
506 /**
507 * dma_fence_wait_timeout - sleep until the fence gets signaled
508 * or until timeout elapses
509 * @fence: the fence to wait on
510 * @intr: if true, do an interruptible wait
511 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
512 *
513 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
514 * remaining timeout in jiffies on success. Other error values may be
515 * returned on custom implementations.
516 *
517 * Performs a synchronous wait on this fence. It is assumed the caller
518 * directly or indirectly (buf-mgr between reservation and committing)
519 * holds a reference to the fence, otherwise the fence might be
520 * freed before return, resulting in undefined behavior.
521 *
522 * See also dma_fence_wait() and dma_fence_wait_any_timeout().
523 */
524 signed long
dma_fence_wait_timeout(struct dma_fence * fence,bool intr,signed long timeout)525 dma_fence_wait_timeout(struct dma_fence *fence, bool intr, signed long timeout)
526 {
527 const struct dma_fence_ops *ops;
528 signed long ret;
529
530 if (WARN_ON(timeout < 0))
531 return -EINVAL;
532
533 might_sleep();
534
535 __dma_fence_might_wait();
536
537 dma_fence_enable_signaling(fence);
538
539 rcu_read_lock();
540 ops = rcu_dereference(fence->ops);
541 trace_dma_fence_wait_start(fence);
542 if (ops && ops->wait) {
543 /*
544 * Implementing the wait ops is deprecated and not supported for
545 * issuers of fences who need their lifetime to be independent
546 * of their module after they signal, so it is ok to use the
547 * ops outside the RCU protected section.
548 */
549 rcu_read_unlock();
550 ret = ops->wait(fence, intr, timeout);
551 } else {
552 rcu_read_unlock();
553 ret = dma_fence_default_wait(fence, intr, timeout);
554 }
555 if (trace_dma_fence_wait_end_enabled()) {
556 rcu_read_lock();
557 trace_dma_fence_wait_end(fence);
558 rcu_read_unlock();
559 }
560 return ret;
561 }
562 EXPORT_SYMBOL(dma_fence_wait_timeout);
563
564 /**
565 * dma_fence_release - default release function for fences
566 * @kref: &dma_fence.recfount
567 *
568 * This is the default release functions for &dma_fence. Drivers shouldn't call
569 * this directly, but instead call dma_fence_put().
570 */
dma_fence_release(struct kref * kref)571 void dma_fence_release(struct kref *kref)
572 {
573 struct dma_fence *fence =
574 container_of(kref, struct dma_fence, refcount);
575 const struct dma_fence_ops *ops;
576
577 rcu_read_lock();
578 trace_dma_fence_destroy(fence);
579
580 if (!list_empty(&fence->cb_list) &&
581 !dma_fence_test_signaled_flag(fence)) {
582 const char __rcu *timeline;
583 const char __rcu *driver;
584 unsigned long flags;
585
586 driver = dma_fence_driver_name(fence);
587 timeline = dma_fence_timeline_name(fence);
588
589 WARN(1,
590 "Fence %s:%s:%llx:%llx released with pending signals!\n",
591 rcu_dereference(driver), rcu_dereference(timeline),
592 fence->context, fence->seqno);
593
594 /*
595 * Failed to signal before release, likely a refcounting issue.
596 *
597 * This should never happen, but if it does make sure that we
598 * don't leave chains dangling. We set the error flag first
599 * so that the callbacks know this signal is due to an error.
600 */
601 dma_fence_lock_irqsave(fence, flags);
602 fence->error = -EDEADLK;
603 dma_fence_signal_locked(fence);
604 dma_fence_unlock_irqrestore(fence, flags);
605 }
606
607 ops = rcu_dereference(fence->ops);
608 if (ops && ops->release)
609 ops->release(fence);
610 else
611 dma_fence_free(fence);
612 rcu_read_unlock();
613 }
614 EXPORT_SYMBOL(dma_fence_release);
615
616 /**
617 * dma_fence_free - default release function for &dma_fence.
618 * @fence: fence to release
619 *
620 * This is the default implementation for &dma_fence_ops.release. It calls
621 * kfree_rcu() on @fence.
622 */
dma_fence_free(struct dma_fence * fence)623 void dma_fence_free(struct dma_fence *fence)
624 {
625 kfree_rcu(fence, rcu);
626 }
627 EXPORT_SYMBOL(dma_fence_free);
628
__dma_fence_enable_signaling(struct dma_fence * fence)629 static bool __dma_fence_enable_signaling(struct dma_fence *fence)
630 {
631 const struct dma_fence_ops *ops;
632 bool was_set;
633
634 dma_fence_assert_held(fence);
635
636 was_set = test_and_set_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
637 &fence->flags);
638
639 if (dma_fence_test_signaled_flag(fence))
640 return false;
641
642 rcu_read_lock();
643 ops = rcu_dereference(fence->ops);
644 if (!was_set && ops && ops->enable_signaling) {
645 trace_dma_fence_enable_signal(fence);
646
647 if (!ops->enable_signaling(fence)) {
648 rcu_read_unlock();
649 dma_fence_signal_locked(fence);
650 return false;
651 }
652 }
653 rcu_read_unlock();
654
655 return true;
656 }
657
658 /**
659 * dma_fence_enable_signaling - enable signaling on fence
660 * @fence: the fence to enable
661 *
662 * This will request for sw signaling to be enabled, to make the fence
663 * complete as soon as possible. This calls &dma_fence_ops.enable_signaling
664 * internally.
665 */
dma_fence_enable_signaling(struct dma_fence * fence)666 void dma_fence_enable_signaling(struct dma_fence *fence)
667 {
668 unsigned long flags;
669
670 dma_fence_lock_irqsave(fence, flags);
671 __dma_fence_enable_signaling(fence);
672 dma_fence_unlock_irqrestore(fence, flags);
673 }
674 EXPORT_SYMBOL(dma_fence_enable_signaling);
675
676 /**
677 * dma_fence_add_callback - add a callback to be called when the fence
678 * is signaled
679 * @fence: the fence to wait on
680 * @cb: the callback to register
681 * @func: the function to call
682 *
683 * Add a software callback to the fence. The caller should keep a reference to
684 * the fence.
685 *
686 * @cb will be initialized by dma_fence_add_callback(), no initialization
687 * by the caller is required. Any number of callbacks can be registered
688 * to a fence, but a callback can only be registered to one fence at a time.
689 *
690 * If fence is already signaled, this function will return -ENOENT (and
691 * *not* call the callback).
692 *
693 * Note that the callback can be called from an atomic context or irq context.
694 *
695 * Returns 0 in case of success, -ENOENT if the fence is already signaled
696 * and -EINVAL in case of error.
697 */
dma_fence_add_callback(struct dma_fence * fence,struct dma_fence_cb * cb,dma_fence_func_t func)698 int dma_fence_add_callback(struct dma_fence *fence, struct dma_fence_cb *cb,
699 dma_fence_func_t func)
700 {
701 unsigned long flags;
702 int ret = 0;
703
704 if (WARN_ON(!fence || !func))
705 return -EINVAL;
706
707 if (dma_fence_test_signaled_flag(fence)) {
708 INIT_LIST_HEAD(&cb->node);
709 return -ENOENT;
710 }
711
712 dma_fence_lock_irqsave(fence, flags);
713 if (__dma_fence_enable_signaling(fence)) {
714 cb->func = func;
715 list_add_tail(&cb->node, &fence->cb_list);
716 } else {
717 INIT_LIST_HEAD(&cb->node);
718 ret = -ENOENT;
719 }
720 dma_fence_unlock_irqrestore(fence, flags);
721
722 return ret;
723 }
724 EXPORT_SYMBOL(dma_fence_add_callback);
725
726 /**
727 * dma_fence_get_status - returns the status upon completion
728 * @fence: the dma_fence to query
729 *
730 * This wraps dma_fence_get_status_locked() to return the error status
731 * condition on a signaled fence. See dma_fence_get_status_locked() for more
732 * details.
733 *
734 * Returns 0 if the fence has not yet been signaled, 1 if the fence has
735 * been signaled without an error condition, or a negative error code
736 * if the fence has been completed in err.
737 */
dma_fence_get_status(struct dma_fence * fence)738 int dma_fence_get_status(struct dma_fence *fence)
739 {
740 unsigned long flags;
741 int status;
742
743 dma_fence_lock_irqsave(fence, flags);
744 status = dma_fence_get_status_locked(fence);
745 dma_fence_unlock_irqrestore(fence, flags);
746
747 return status;
748 }
749 EXPORT_SYMBOL(dma_fence_get_status);
750
751 /**
752 * dma_fence_remove_callback - remove a callback from the signaling list
753 * @fence: the fence to wait on
754 * @cb: the callback to remove
755 *
756 * Remove a previously queued callback from the fence. This function returns
757 * true if the callback is successfully removed, or false if the fence has
758 * already been signaled.
759 *
760 * *WARNING*:
761 * Cancelling a callback should only be done if you really know what you're
762 * doing, since deadlocks and race conditions could occur all too easily. For
763 * this reason, it should only ever be done on hardware lockup recovery,
764 * with a reference held to the fence.
765 *
766 * Behaviour is undefined if @cb has not been added to @fence using
767 * dma_fence_add_callback() beforehand.
768 */
769 bool
dma_fence_remove_callback(struct dma_fence * fence,struct dma_fence_cb * cb)770 dma_fence_remove_callback(struct dma_fence *fence, struct dma_fence_cb *cb)
771 {
772 unsigned long flags;
773 bool ret;
774
775 dma_fence_lock_irqsave(fence, flags);
776 ret = !list_empty(&cb->node);
777 if (ret)
778 list_del_init(&cb->node);
779 dma_fence_unlock_irqrestore(fence, flags);
780
781 return ret;
782 }
783 EXPORT_SYMBOL(dma_fence_remove_callback);
784
785 struct default_wait_cb {
786 struct dma_fence_cb base;
787 struct task_struct *task;
788 };
789
790 static void
dma_fence_default_wait_cb(struct dma_fence * fence,struct dma_fence_cb * cb)791 dma_fence_default_wait_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
792 {
793 struct default_wait_cb *wait =
794 container_of(cb, struct default_wait_cb, base);
795
796 wake_up_state(wait->task, TASK_NORMAL);
797 }
798
799 /**
800 * dma_fence_default_wait - default sleep until the fence gets signaled
801 * or until timeout elapses
802 * @fence: the fence to wait on
803 * @intr: if true, do an interruptible wait
804 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
805 *
806 * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
807 * remaining timeout in jiffies on success. If timeout is zero the value one is
808 * returned if the fence is already signaled for consistency with other
809 * functions taking a jiffies timeout.
810 */
811 signed long
dma_fence_default_wait(struct dma_fence * fence,bool intr,signed long timeout)812 dma_fence_default_wait(struct dma_fence *fence, bool intr, signed long timeout)
813 {
814 struct default_wait_cb cb;
815 unsigned long flags;
816 signed long ret = timeout ? timeout : 1;
817
818 dma_fence_lock_irqsave(fence, flags);
819
820 if (dma_fence_test_signaled_flag(fence))
821 goto out;
822
823 if (intr && signal_pending(current)) {
824 ret = -ERESTARTSYS;
825 goto out;
826 }
827
828 if (!timeout) {
829 ret = 0;
830 goto out;
831 }
832
833 cb.base.func = dma_fence_default_wait_cb;
834 cb.task = current;
835 list_add(&cb.base.node, &fence->cb_list);
836
837 while (!dma_fence_test_signaled_flag(fence) && ret > 0) {
838 if (intr)
839 __set_current_state(TASK_INTERRUPTIBLE);
840 else
841 __set_current_state(TASK_UNINTERRUPTIBLE);
842 dma_fence_unlock_irqrestore(fence, flags);
843
844 ret = schedule_timeout(ret);
845
846 dma_fence_lock_irqsave(fence, flags);
847 if (ret > 0 && intr && signal_pending(current))
848 ret = -ERESTARTSYS;
849 }
850
851 if (!list_empty(&cb.base.node))
852 list_del(&cb.base.node);
853 __set_current_state(TASK_RUNNING);
854
855 out:
856 dma_fence_unlock_irqrestore(fence, flags);
857 return ret;
858 }
859 EXPORT_SYMBOL(dma_fence_default_wait);
860
861 static bool
dma_fence_test_signaled_any(struct dma_fence ** fences,uint32_t count,uint32_t * idx)862 dma_fence_test_signaled_any(struct dma_fence **fences, uint32_t count,
863 uint32_t *idx)
864 {
865 int i;
866
867 for (i = 0; i < count; ++i) {
868 struct dma_fence *fence = fences[i];
869 if (dma_fence_test_signaled_flag(fence)) {
870 if (idx)
871 *idx = i;
872 return true;
873 }
874 }
875 return false;
876 }
877
878 /**
879 * dma_fence_wait_any_timeout - sleep until any fence gets signaled
880 * or until timeout elapses
881 * @fences: array of fences to wait on
882 * @count: number of fences to wait on
883 * @intr: if true, do an interruptible wait
884 * @timeout: timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
885 * @idx: used to store the first signaled fence index, meaningful only on
886 * positive return
887 *
888 * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
889 * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
890 * on success.
891 *
892 * Synchronous waits for the first fence in the array to be signaled. The
893 * caller needs to hold a reference to all fences in the array, otherwise a
894 * fence might be freed before return, resulting in undefined behavior.
895 *
896 * See also dma_fence_wait() and dma_fence_wait_timeout().
897 */
898 signed long
dma_fence_wait_any_timeout(struct dma_fence ** fences,uint32_t count,bool intr,signed long timeout,uint32_t * idx)899 dma_fence_wait_any_timeout(struct dma_fence **fences, uint32_t count,
900 bool intr, signed long timeout, uint32_t *idx)
901 {
902 struct default_wait_cb *cb;
903 signed long ret = timeout;
904 unsigned i;
905
906 if (WARN_ON(!fences || !count || timeout < 0))
907 return -EINVAL;
908
909 if (timeout == 0) {
910 for (i = 0; i < count; ++i)
911 if (dma_fence_is_signaled(fences[i])) {
912 if (idx)
913 *idx = i;
914 return 1;
915 }
916
917 return 0;
918 }
919
920 cb = kzalloc_objs(struct default_wait_cb, count);
921 if (cb == NULL) {
922 ret = -ENOMEM;
923 goto err_free_cb;
924 }
925
926 for (i = 0; i < count; ++i) {
927 struct dma_fence *fence = fences[i];
928
929 cb[i].task = current;
930 if (dma_fence_add_callback(fence, &cb[i].base,
931 dma_fence_default_wait_cb)) {
932 /* This fence is already signaled */
933 if (idx)
934 *idx = i;
935 goto fence_rm_cb;
936 }
937 }
938
939 while (ret > 0) {
940 if (intr)
941 set_current_state(TASK_INTERRUPTIBLE);
942 else
943 set_current_state(TASK_UNINTERRUPTIBLE);
944
945 if (dma_fence_test_signaled_any(fences, count, idx))
946 break;
947
948 ret = schedule_timeout(ret);
949
950 if (ret > 0 && intr && signal_pending(current))
951 ret = -ERESTARTSYS;
952 }
953
954 __set_current_state(TASK_RUNNING);
955
956 fence_rm_cb:
957 while (i-- > 0)
958 dma_fence_remove_callback(fences[i], &cb[i].base);
959
960 err_free_cb:
961 kfree(cb);
962
963 return ret;
964 }
965 EXPORT_SYMBOL(dma_fence_wait_any_timeout);
966
967 /**
968 * DOC: deadline hints
969 *
970 * In an ideal world, it would be possible to pipeline a workload sufficiently
971 * that a utilization based device frequency governor could arrive at a minimum
972 * frequency that meets the requirements of the use-case, in order to minimize
973 * power consumption. But in the real world there are many workloads which
974 * defy this ideal. For example, but not limited to:
975 *
976 * * Workloads that ping-pong between device and CPU, with alternating periods
977 * of CPU waiting for device, and device waiting on CPU. This can result in
978 * devfreq and cpufreq seeing idle time in their respective domains and in
979 * result reduce frequency.
980 *
981 * * Workloads that interact with a periodic time based deadline, such as double
982 * buffered GPU rendering vs vblank sync'd page flipping. In this scenario,
983 * missing a vblank deadline results in an *increase* in idle time on the GPU
984 * (since it has to wait an additional vblank period), sending a signal to
985 * the GPU's devfreq to reduce frequency, when in fact the opposite is what is
986 * needed.
987 *
988 * To this end, deadline hint(s) can be set on a &dma_fence via &dma_fence_set_deadline
989 * (or indirectly via userspace facing ioctls like &sync_set_deadline).
990 * The deadline hint provides a way for the waiting driver, or userspace, to
991 * convey an appropriate sense of urgency to the signaling driver.
992 *
993 * A deadline hint is given in absolute ktime (CLOCK_MONOTONIC for userspace
994 * facing APIs). The time could either be some point in the future (such as
995 * the vblank based deadline for page-flipping, or the start of a compositor's
996 * composition cycle), or the current time to indicate an immediate deadline
997 * hint (Ie. forward progress cannot be made until this fence is signaled).
998 *
999 * Multiple deadlines may be set on a given fence, even in parallel. See the
1000 * documentation for &dma_fence_ops.set_deadline.
1001 *
1002 * The deadline hint is just that, a hint. The driver that created the fence
1003 * may react by increasing frequency, making different scheduling choices, etc.
1004 * Or doing nothing at all.
1005 */
1006
1007 /**
1008 * dma_fence_set_deadline - set desired fence-wait deadline hint
1009 * @fence: the fence that is to be waited on
1010 * @deadline: the time by which the waiter hopes for the fence to be
1011 * signaled
1012 *
1013 * Give the fence signaler a hint about an upcoming deadline, such as
1014 * vblank, by which point the waiter would prefer the fence to be
1015 * signaled by. This is intended to give feedback to the fence signaler
1016 * to aid in power management decisions, such as boosting GPU frequency
1017 * if a periodic vblank deadline is approaching but the fence is not
1018 * yet signaled..
1019 */
dma_fence_set_deadline(struct dma_fence * fence,ktime_t deadline)1020 void dma_fence_set_deadline(struct dma_fence *fence, ktime_t deadline)
1021 {
1022 const struct dma_fence_ops *ops;
1023
1024 rcu_read_lock();
1025 ops = rcu_dereference(fence->ops);
1026 if (ops && ops->set_deadline && !dma_fence_is_signaled(fence))
1027 ops->set_deadline(fence, deadline);
1028 rcu_read_unlock();
1029 }
1030 EXPORT_SYMBOL(dma_fence_set_deadline);
1031
1032 /**
1033 * dma_fence_describe - Dump fence description into seq_file
1034 * @fence: the fence to describe
1035 * @seq: the seq_file to put the textual description into
1036 *
1037 * Dump a textual description of the fence and it's state into the seq_file.
1038 */
dma_fence_describe(struct dma_fence * fence,struct seq_file * seq)1039 void dma_fence_describe(struct dma_fence *fence, struct seq_file *seq)
1040 {
1041 const char __rcu *timeline = (const char __rcu *)"";
1042 const char __rcu *driver = (const char __rcu *)"";
1043 const char *signaled = "";
1044
1045 rcu_read_lock();
1046
1047 if (!dma_fence_is_signaled(fence)) {
1048 timeline = dma_fence_timeline_name(fence);
1049 driver = dma_fence_driver_name(fence);
1050 signaled = "un";
1051 }
1052
1053 seq_printf(seq, "%llu:%llu %s %s %ssignalled\n",
1054 fence->context, fence->seqno, timeline, driver,
1055 signaled);
1056
1057 rcu_read_unlock();
1058 }
1059 EXPORT_SYMBOL(dma_fence_describe);
1060
1061 static void
__dma_fence_init(struct dma_fence * fence,const struct dma_fence_ops * ops,spinlock_t * lock,u64 context,u64 seqno,unsigned long flags)1062 __dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
1063 spinlock_t *lock, u64 context, u64 seqno, unsigned long flags)
1064 {
1065 BUG_ON(!ops || !ops->get_driver_name || !ops->get_timeline_name);
1066
1067 kref_init(&fence->refcount);
1068 /*
1069 * While it is counter intuitive to protect a constant function pointer
1070 * table by RCU it allows modules to wait for an RCU grace period
1071 * before they unload, to make sure that nobody is executing their
1072 * functions any more.
1073 */
1074 RCU_INIT_POINTER(fence->ops, ops);
1075 INIT_LIST_HEAD(&fence->cb_list);
1076 fence->context = context;
1077 fence->seqno = seqno;
1078 fence->flags = flags | BIT(DMA_FENCE_FLAG_INITIALIZED_BIT);
1079 if (lock) {
1080 fence->extern_lock = lock;
1081 } else {
1082 spin_lock_init(&fence->inline_lock);
1083 fence->flags |= BIT(DMA_FENCE_FLAG_INLINE_LOCK_BIT);
1084 }
1085 fence->error = 0;
1086
1087 trace_dma_fence_init(fence);
1088 }
1089
1090 /**
1091 * dma_fence_init - Initialize a custom fence.
1092 * @fence: the fence to initialize
1093 * @ops: the dma_fence_ops for operations on this fence
1094 * @lock: optional irqsafe spinlock to use for locking this fence
1095 * @context: the execution context this fence is run on
1096 * @seqno: a linear increasing sequence number for this context
1097 *
1098 * Initializes an allocated fence, the caller doesn't have to keep its
1099 * refcount after committing with this fence, but it will need to hold a
1100 * refcount again if &dma_fence_ops.enable_signaling gets called.
1101 *
1102 * context and seqno are used for easy comparison between fences, allowing
1103 * to check which fence is later by simply using dma_fence_later().
1104 *
1105 * External locks are a relic of legacy use cases that needed a shared lock
1106 * to serialize signaling when no out-of-order signaling was possible through
1107 * &dma_fence_ops.signaled. Drivers have abandoned this concept since the
1108 * introduction of the callback, but the external lock is still around. New
1109 * users MUST NOT use external locks, as they force the issuer to outlive all
1110 * fences that reference the lock.
1111 */
1112 void
dma_fence_init(struct dma_fence * fence,const struct dma_fence_ops * ops,spinlock_t * lock,u64 context,u64 seqno)1113 dma_fence_init(struct dma_fence *fence, const struct dma_fence_ops *ops,
1114 spinlock_t *lock, u64 context, u64 seqno)
1115 {
1116 __dma_fence_init(fence, ops, lock, context, seqno, 0UL);
1117 }
1118 EXPORT_SYMBOL(dma_fence_init);
1119
1120 /**
1121 * dma_fence_init64 - Initialize a custom fence with 64-bit seqno support.
1122 * @fence: the fence to initialize
1123 * @ops: the dma_fence_ops for operations on this fence
1124 * @lock: optional irqsafe spinlock to use for locking this fence
1125 * @context: the execution context this fence is run on
1126 * @seqno: a linear increasing sequence number for this context
1127 *
1128 * Initializes an allocated fence, the caller doesn't have to keep its
1129 * refcount after committing with this fence, but it will need to hold a
1130 * refcount again if &dma_fence_ops.enable_signaling gets called.
1131 *
1132 * Context and seqno are used for easy comparison between fences, allowing
1133 * to check which fence is later by simply using dma_fence_later().
1134 *
1135 * New users MUST NOT use external locks. Check the documentation in
1136 * dma_fence_init() to understand the motives behind the legacy use cases.
1137 */
1138 void
dma_fence_init64(struct dma_fence * fence,const struct dma_fence_ops * ops,spinlock_t * lock,u64 context,u64 seqno)1139 dma_fence_init64(struct dma_fence *fence, const struct dma_fence_ops *ops,
1140 spinlock_t *lock, u64 context, u64 seqno)
1141 {
1142 __dma_fence_init(fence, ops, lock, context, seqno,
1143 BIT(DMA_FENCE_FLAG_SEQNO64_BIT));
1144 }
1145 EXPORT_SYMBOL(dma_fence_init64);
1146
1147 /**
1148 * dma_fence_driver_name - Access the driver name
1149 * @fence: the fence to query
1150 *
1151 * Returns a driver name backing the dma-fence implementation.
1152 *
1153 * IMPORTANT CONSIDERATION:
1154 * Dma-fence contract stipulates that access to driver provided data (data not
1155 * directly embedded into the object itself), such as the &dma_fence.lock and
1156 * memory potentially accessed by the &dma_fence.ops functions, is forbidden
1157 * after the fence has been signalled. Drivers are allowed to free that data,
1158 * and some do.
1159 *
1160 * To allow safe access drivers are mandated to guarantee a RCU grace period
1161 * between signalling the fence and freeing said data.
1162 *
1163 * As such access to the driver name is only valid inside a RCU locked section.
1164 * The pointer MUST be both queried and USED ONLY WITHIN a SINGLE block guarded
1165 * by the &rcu_read_lock and &rcu_read_unlock pair.
1166 */
dma_fence_driver_name(struct dma_fence * fence)1167 const char __rcu *dma_fence_driver_name(struct dma_fence *fence)
1168 {
1169 const struct dma_fence_ops *ops;
1170
1171 /* RCU protection is required for safe access to returned string */
1172 ops = rcu_dereference(fence->ops);
1173 if (ops)
1174 return (const char __rcu *)ops->get_driver_name(fence);
1175 else
1176 return (const char __rcu *)"detached-driver";
1177 }
1178 EXPORT_SYMBOL(dma_fence_driver_name);
1179
1180 /**
1181 * dma_fence_timeline_name - Access the timeline name
1182 * @fence: the fence to query
1183 *
1184 * Returns a timeline name provided by the dma-fence implementation.
1185 *
1186 * IMPORTANT CONSIDERATION:
1187 * Dma-fence contract stipulates that access to driver provided data (data not
1188 * directly embedded into the object itself), such as the &dma_fence.lock and
1189 * memory potentially accessed by the &dma_fence.ops functions, is forbidden
1190 * after the fence has been signalled. Drivers are allowed to free that data,
1191 * and some do.
1192 *
1193 * To allow safe access drivers are mandated to guarantee a RCU grace period
1194 * between signalling the fence and freeing said data.
1195 *
1196 * As such access to the driver name is only valid inside a RCU locked section.
1197 * The pointer MUST be both queried and USED ONLY WITHIN a SINGLE block guarded
1198 * by the &rcu_read_lock and &rcu_read_unlock pair.
1199 */
dma_fence_timeline_name(struct dma_fence * fence)1200 const char __rcu *dma_fence_timeline_name(struct dma_fence *fence)
1201 {
1202 const struct dma_fence_ops *ops;
1203
1204 /* RCU protection is required for safe access to returned string */
1205 ops = rcu_dereference(fence->ops);
1206 if (ops)
1207 return (const char __rcu *)ops->get_timeline_name(fence);
1208 else
1209 return (const char __rcu *)"signaled-timeline";
1210 }
1211 EXPORT_SYMBOL(dma_fence_timeline_name);
1212