GNU Linux-libre 4.9.331-gnu1
[releases.git] / drivers / dma-buf / fence.c
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/fence.h>
25
26 #define CREATE_TRACE_POINTS
27 #include <trace/events/fence.h>
28
29 EXPORT_TRACEPOINT_SYMBOL(fence_annotate_wait_on);
30 EXPORT_TRACEPOINT_SYMBOL(fence_emit);
31
32 /*
33  * fence context counter: each execution context should have its own
34  * fence context, this allows checking if fences belong to the same
35  * context or not. One device can have multiple separate contexts,
36  * and they're used if some engine can run independently of another.
37  */
38 static atomic64_t fence_context_counter = ATOMIC64_INIT(0);
39
40 /**
41  * fence_context_alloc - allocate an array of fence contexts
42  * @num:        [in]    amount of contexts to allocate
43  *
44  * This function will return the first index of the number of fences allocated.
45  * The fence context is used for setting fence->context to a unique number.
46  */
47 u64 fence_context_alloc(unsigned num)
48 {
49         BUG_ON(!num);
50         return atomic64_add_return(num, &fence_context_counter) - num;
51 }
52 EXPORT_SYMBOL(fence_context_alloc);
53
54 /**
55  * fence_signal_locked - signal completion of a fence
56  * @fence: the fence to signal
57  *
58  * Signal completion for software callbacks on a fence, this will unblock
59  * fence_wait() calls and run all the callbacks added with
60  * fence_add_callback(). Can be called multiple times, but since a fence
61  * can only go from unsignaled to signaled state, it will only be effective
62  * the first time.
63  *
64  * Unlike fence_signal, this function must be called with fence->lock held.
65  */
66 int fence_signal_locked(struct fence *fence)
67 {
68         struct fence_cb *cur, *tmp;
69         int ret = 0;
70
71         if (WARN_ON(!fence))
72                 return -EINVAL;
73
74         if (!ktime_to_ns(fence->timestamp)) {
75                 fence->timestamp = ktime_get();
76                 smp_mb__before_atomic();
77         }
78
79         if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
80                 ret = -EINVAL;
81
82                 /*
83                  * we might have raced with the unlocked fence_signal,
84                  * still run through all callbacks
85                  */
86         } else
87                 trace_fence_signaled(fence);
88
89         list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
90                 list_del_init(&cur->node);
91                 cur->func(fence, cur);
92         }
93         return ret;
94 }
95 EXPORT_SYMBOL(fence_signal_locked);
96
97 /**
98  * fence_signal - signal completion of a fence
99  * @fence: the fence to signal
100  *
101  * Signal completion for software callbacks on a fence, this will unblock
102  * fence_wait() calls and run all the callbacks added with
103  * fence_add_callback(). Can be called multiple times, but since a fence
104  * can only go from unsignaled to signaled state, it will only be effective
105  * the first time.
106  */
107 int fence_signal(struct fence *fence)
108 {
109         unsigned long flags;
110
111         if (!fence)
112                 return -EINVAL;
113
114         if (!ktime_to_ns(fence->timestamp)) {
115                 fence->timestamp = ktime_get();
116                 smp_mb__before_atomic();
117         }
118
119         if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
120                 return -EINVAL;
121
122         trace_fence_signaled(fence);
123
124         if (test_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) {
125                 struct fence_cb *cur, *tmp;
126
127                 spin_lock_irqsave(fence->lock, flags);
128                 list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
129                         list_del_init(&cur->node);
130                         cur->func(fence, cur);
131                 }
132                 spin_unlock_irqrestore(fence->lock, flags);
133         }
134         return 0;
135 }
136 EXPORT_SYMBOL(fence_signal);
137
138 /**
139  * fence_wait_timeout - sleep until the fence gets signaled
140  * or until timeout elapses
141  * @fence:      [in]    the fence to wait on
142  * @intr:       [in]    if true, do an interruptible wait
143  * @timeout:    [in]    timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
144  *
145  * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
146  * remaining timeout in jiffies on success. Other error values may be
147  * returned on custom implementations.
148  *
149  * Performs a synchronous wait on this fence. It is assumed the caller
150  * directly or indirectly (buf-mgr between reservation and committing)
151  * holds a reference to the fence, otherwise the fence might be
152  * freed before return, resulting in undefined behavior.
153  */
154 signed long
155 fence_wait_timeout(struct fence *fence, bool intr, signed long timeout)
156 {
157         signed long ret;
158
159         if (WARN_ON(timeout < 0))
160                 return -EINVAL;
161
162         if (timeout == 0)
163                 return fence_is_signaled(fence);
164
165         trace_fence_wait_start(fence);
166         ret = fence->ops->wait(fence, intr, timeout);
167         trace_fence_wait_end(fence);
168         return ret;
169 }
170 EXPORT_SYMBOL(fence_wait_timeout);
171
172 void fence_release(struct kref *kref)
173 {
174         struct fence *fence =
175                         container_of(kref, struct fence, refcount);
176
177         trace_fence_destroy(fence);
178
179         BUG_ON(!list_empty(&fence->cb_list));
180
181         if (fence->ops->release)
182                 fence->ops->release(fence);
183         else
184                 fence_free(fence);
185 }
186 EXPORT_SYMBOL(fence_release);
187
188 void fence_free(struct fence *fence)
189 {
190         kfree_rcu(fence, rcu);
191 }
192 EXPORT_SYMBOL(fence_free);
193
194 /**
195  * fence_enable_sw_signaling - enable signaling on fence
196  * @fence:      [in]    the fence to enable
197  *
198  * this will request for sw signaling to be enabled, to make the fence
199  * complete as soon as possible
200  */
201 void fence_enable_sw_signaling(struct fence *fence)
202 {
203         unsigned long flags;
204
205         if (!test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags) &&
206             !test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
207                 trace_fence_enable_signal(fence);
208
209                 spin_lock_irqsave(fence->lock, flags);
210
211                 if (!fence->ops->enable_signaling(fence))
212                         fence_signal_locked(fence);
213
214                 spin_unlock_irqrestore(fence->lock, flags);
215         }
216 }
217 EXPORT_SYMBOL(fence_enable_sw_signaling);
218
219 /**
220  * fence_add_callback - add a callback to be called when the fence
221  * is signaled
222  * @fence:      [in]    the fence to wait on
223  * @cb:         [in]    the callback to register
224  * @func:       [in]    the function to call
225  *
226  * cb will be initialized by fence_add_callback, no initialization
227  * by the caller is required. Any number of callbacks can be registered
228  * to a fence, but a callback can only be registered to one fence at a time.
229  *
230  * Note that the callback can be called from an atomic context.  If
231  * fence is already signaled, this function will return -ENOENT (and
232  * *not* call the callback)
233  *
234  * Add a software callback to the fence. Same restrictions apply to
235  * refcount as it does to fence_wait, however the caller doesn't need to
236  * keep a refcount to fence afterwards: when software access is enabled,
237  * the creator of the fence is required to keep the fence alive until
238  * after it signals with fence_signal. The callback itself can be called
239  * from irq context.
240  *
241  */
242 int fence_add_callback(struct fence *fence, struct fence_cb *cb,
243                        fence_func_t func)
244 {
245         unsigned long flags;
246         int ret = 0;
247         bool was_set;
248
249         if (WARN_ON(!fence || !func))
250                 return -EINVAL;
251
252         if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
253                 INIT_LIST_HEAD(&cb->node);
254                 return -ENOENT;
255         }
256
257         spin_lock_irqsave(fence->lock, flags);
258
259         was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags);
260
261         if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
262                 ret = -ENOENT;
263         else if (!was_set) {
264                 trace_fence_enable_signal(fence);
265
266                 if (!fence->ops->enable_signaling(fence)) {
267                         fence_signal_locked(fence);
268                         ret = -ENOENT;
269                 }
270         }
271
272         if (!ret) {
273                 cb->func = func;
274                 list_add_tail(&cb->node, &fence->cb_list);
275         } else
276                 INIT_LIST_HEAD(&cb->node);
277         spin_unlock_irqrestore(fence->lock, flags);
278
279         return ret;
280 }
281 EXPORT_SYMBOL(fence_add_callback);
282
283 /**
284  * fence_get_status - returns the status upon completion
285  * @fence: [in] the fence to query
286  *
287  * This wraps fence_get_status_locked() to return the error status
288  * condition on a signaled fence. See fence_get_status_locked() for more
289  * details.
290  *
291  * Returns 0 if the fence has not yet been signaled, 1 if the fence has
292  * been signaled without an error condition, or a negative error code
293  * if the fence has been completed in err.
294  */
295 int fence_get_status(struct fence *fence)
296 {
297         unsigned long flags;
298         int status;
299
300         spin_lock_irqsave(fence->lock, flags);
301         status = fence_get_status_locked(fence);
302         spin_unlock_irqrestore(fence->lock, flags);
303
304         return status;
305 }
306 EXPORT_SYMBOL(fence_get_status);
307
308 /**
309  * fence_remove_callback - remove a callback from the signaling list
310  * @fence:      [in]    the fence to wait on
311  * @cb:         [in]    the callback to remove
312  *
313  * Remove a previously queued callback from the fence. This function returns
314  * true if the callback is successfully removed, or false if the fence has
315  * already been signaled.
316  *
317  * *WARNING*:
318  * Cancelling a callback should only be done if you really know what you're
319  * doing, since deadlocks and race conditions could occur all too easily. For
320  * this reason, it should only ever be done on hardware lockup recovery,
321  * with a reference held to the fence.
322  */
323 bool
324 fence_remove_callback(struct fence *fence, struct fence_cb *cb)
325 {
326         unsigned long flags;
327         bool ret;
328
329         spin_lock_irqsave(fence->lock, flags);
330
331         ret = !list_empty(&cb->node);
332         if (ret)
333                 list_del_init(&cb->node);
334
335         spin_unlock_irqrestore(fence->lock, flags);
336
337         return ret;
338 }
339 EXPORT_SYMBOL(fence_remove_callback);
340
341 struct default_wait_cb {
342         struct fence_cb base;
343         struct task_struct *task;
344 };
345
346 static void
347 fence_default_wait_cb(struct fence *fence, struct fence_cb *cb)
348 {
349         struct default_wait_cb *wait =
350                 container_of(cb, struct default_wait_cb, base);
351
352         wake_up_state(wait->task, TASK_NORMAL);
353 }
354
355 /**
356  * fence_default_wait - default sleep until the fence gets signaled
357  * or until timeout elapses
358  * @fence:      [in]    the fence to wait on
359  * @intr:       [in]    if true, do an interruptible wait
360  * @timeout:    [in]    timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
361  *
362  * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
363  * remaining timeout in jiffies on success.
364  */
365 signed long
366 fence_default_wait(struct fence *fence, bool intr, signed long timeout)
367 {
368         struct default_wait_cb cb;
369         unsigned long flags;
370         signed long ret = timeout;
371         bool was_set;
372
373         if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
374                 return timeout;
375
376         spin_lock_irqsave(fence->lock, flags);
377
378         if (intr && signal_pending(current)) {
379                 ret = -ERESTARTSYS;
380                 goto out;
381         }
382
383         was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags);
384
385         if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
386                 goto out;
387
388         if (!was_set) {
389                 trace_fence_enable_signal(fence);
390
391                 if (!fence->ops->enable_signaling(fence)) {
392                         fence_signal_locked(fence);
393                         goto out;
394                 }
395         }
396
397         cb.base.func = fence_default_wait_cb;
398         cb.task = current;
399         list_add(&cb.base.node, &fence->cb_list);
400
401         while (!test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
402                 if (intr)
403                         __set_current_state(TASK_INTERRUPTIBLE);
404                 else
405                         __set_current_state(TASK_UNINTERRUPTIBLE);
406                 spin_unlock_irqrestore(fence->lock, flags);
407
408                 ret = schedule_timeout(ret);
409
410                 spin_lock_irqsave(fence->lock, flags);
411                 if (ret > 0 && intr && signal_pending(current))
412                         ret = -ERESTARTSYS;
413         }
414
415         if (!list_empty(&cb.base.node))
416                 list_del(&cb.base.node);
417         __set_current_state(TASK_RUNNING);
418
419 out:
420         spin_unlock_irqrestore(fence->lock, flags);
421         return ret;
422 }
423 EXPORT_SYMBOL(fence_default_wait);
424
425 static bool
426 fence_test_signaled_any(struct fence **fences, uint32_t count)
427 {
428         int i;
429
430         for (i = 0; i < count; ++i) {
431                 struct fence *fence = fences[i];
432                 if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
433                         return true;
434         }
435         return false;
436 }
437
438 /**
439  * fence_wait_any_timeout - sleep until any fence gets signaled
440  * or until timeout elapses
441  * @fences:     [in]    array of fences to wait on
442  * @count:      [in]    number of fences to wait on
443  * @intr:       [in]    if true, do an interruptible wait
444  * @timeout:    [in]    timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
445  *
446  * Returns -EINVAL on custom fence wait implementation, -ERESTARTSYS if
447  * interrupted, 0 if the wait timed out, or the remaining timeout in jiffies
448  * on success.
449  *
450  * Synchronous waits for the first fence in the array to be signaled. The
451  * caller needs to hold a reference to all fences in the array, otherwise a
452  * fence might be freed before return, resulting in undefined behavior.
453  */
454 signed long
455 fence_wait_any_timeout(struct fence **fences, uint32_t count,
456                        bool intr, signed long timeout)
457 {
458         struct default_wait_cb *cb;
459         signed long ret = timeout;
460         unsigned i;
461
462         if (WARN_ON(!fences || !count || timeout < 0))
463                 return -EINVAL;
464
465         if (timeout == 0) {
466                 for (i = 0; i < count; ++i)
467                         if (fence_is_signaled(fences[i]))
468                                 return 1;
469
470                 return 0;
471         }
472
473         cb = kcalloc(count, sizeof(struct default_wait_cb), GFP_KERNEL);
474         if (cb == NULL) {
475                 ret = -ENOMEM;
476                 goto err_free_cb;
477         }
478
479         for (i = 0; i < count; ++i) {
480                 struct fence *fence = fences[i];
481
482                 if (fence->ops->wait != fence_default_wait) {
483                         ret = -EINVAL;
484                         goto fence_rm_cb;
485                 }
486
487                 cb[i].task = current;
488                 if (fence_add_callback(fence, &cb[i].base,
489                                        fence_default_wait_cb)) {
490                         /* This fence is already signaled */
491                         goto fence_rm_cb;
492                 }
493         }
494
495         while (ret > 0) {
496                 if (intr)
497                         set_current_state(TASK_INTERRUPTIBLE);
498                 else
499                         set_current_state(TASK_UNINTERRUPTIBLE);
500
501                 if (fence_test_signaled_any(fences, count))
502                         break;
503
504                 ret = schedule_timeout(ret);
505
506                 if (ret > 0 && intr && signal_pending(current))
507                         ret = -ERESTARTSYS;
508         }
509
510         __set_current_state(TASK_RUNNING);
511
512 fence_rm_cb:
513         while (i-- > 0)
514                 fence_remove_callback(fences[i], &cb[i].base);
515
516 err_free_cb:
517         kfree(cb);
518
519         return ret;
520 }
521 EXPORT_SYMBOL(fence_wait_any_timeout);
522
523 /**
524  * fence_init - Initialize a custom fence.
525  * @fence:      [in]    the fence to initialize
526  * @ops:        [in]    the fence_ops for operations on this fence
527  * @lock:       [in]    the irqsafe spinlock to use for locking this fence
528  * @context:    [in]    the execution context this fence is run on
529  * @seqno:      [in]    a linear increasing sequence number for this context
530  *
531  * Initializes an allocated fence, the caller doesn't have to keep its
532  * refcount after committing with this fence, but it will need to hold a
533  * refcount again if fence_ops.enable_signaling gets called. This can
534  * be used for other implementing other types of fence.
535  *
536  * context and seqno are used for easy comparison between fences, allowing
537  * to check which fence is later by simply using fence_later.
538  */
539 void
540 fence_init(struct fence *fence, const struct fence_ops *ops,
541              spinlock_t *lock, u64 context, unsigned seqno)
542 {
543         BUG_ON(!lock);
544         BUG_ON(!ops || !ops->wait || !ops->enable_signaling ||
545                !ops->get_driver_name || !ops->get_timeline_name);
546
547         kref_init(&fence->refcount);
548         fence->ops = ops;
549         INIT_LIST_HEAD(&fence->cb_list);
550         fence->lock = lock;
551         fence->context = context;
552         fence->seqno = seqno;
553         fence->flags = 0UL;
554         fence->error = 0;
555
556         trace_fence_init(fence);
557 }
558 EXPORT_SYMBOL(fence_init);