xref: /linux/drivers/gpu/drm/drm_syncobj.c (revision ce29b8f9fb606f87014c2d05483a3fef05a11f38)
1 /*
2  * Copyright 2017 Red Hat
3  * Parts ported from amdgpu (fence wait code).
4  * Copyright 2016 Advanced Micro Devices, Inc.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the next
14  * paragraph) shall be included in all copies or substantial portions of the
15  * Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23  * IN THE SOFTWARE.
24  *
25  * Authors:
26  *
27  */
28 
29 /**
30  * DOC: Overview
31  *
32  * DRM synchronisation objects (syncobj, see struct &drm_syncobj) provide a
33  * container for a synchronization primitive which can be used by userspace
34  * to explicitly synchronize GPU commands, can be shared between userspace
35  * processes, and can be shared between different DRM drivers.
36  * Their primary use-case is to implement Vulkan fences and semaphores.
37  * The syncobj userspace API provides ioctls for several operations:
38  *
39  *  - Creation and destruction of syncobjs
40  *  - Import and export of syncobjs to/from a syncobj file descriptor
41  *  - Import and export a syncobj's underlying fence to/from a sync file
42  *  - Reset a syncobj (set its fence to NULL)
43  *  - Signal a syncobj (set a trivially signaled fence)
44  *  - Wait for a syncobj's fence to appear and be signaled
45  *
46  * The syncobj userspace API also provides operations to manipulate a syncobj
47  * in terms of a timeline of struct &dma_fence_chain rather than a single
48  * struct &dma_fence, through the following operations:
49  *
50  *   - Signal a given point on the timeline
51  *   - Wait for a given point to appear and/or be signaled
52  *   - Import and export from/to a given point of a timeline
53  *
54  * At it's core, a syncobj is simply a wrapper around a pointer to a struct
55  * &dma_fence which may be NULL.
56  * When a syncobj is first created, its pointer is either NULL or a pointer
57  * to an already signaled fence depending on whether the
58  * &DRM_SYNCOBJ_CREATE_SIGNALED flag is passed to
59  * &DRM_IOCTL_SYNCOBJ_CREATE.
60  *
61  * If the syncobj is considered as a binary (its state is either signaled or
62  * unsignaled) primitive, when GPU work is enqueued in a DRM driver to signal
63  * the syncobj, the syncobj's fence is replaced with a fence which will be
64  * signaled by the completion of that work.
65  * If the syncobj is considered as a timeline primitive, when GPU work is
66  * enqueued in a DRM driver to signal the a given point of the syncobj, a new
67  * struct &dma_fence_chain pointing to the DRM driver's fence and also
68  * pointing to the previous fence that was in the syncobj. The new struct
69  * &dma_fence_chain fence replace the syncobj's fence and will be signaled by
70  * completion of the DRM driver's work and also any work associated with the
71  * fence previously in the syncobj.
72  *
73  * When GPU work which waits on a syncobj is enqueued in a DRM driver, at the
74  * time the work is enqueued, it waits on the syncobj's fence before
75  * submitting the work to hardware. That fence is either :
76  *
77  *    - The syncobj's current fence if the syncobj is considered as a binary
78  *      primitive.
79  *    - The struct &dma_fence associated with a given point if the syncobj is
80  *      considered as a timeline primitive.
81  *
82  * If the syncobj's fence is NULL or not present in the syncobj's timeline,
83  * the enqueue operation is expected to fail.
84  *
85  * With binary syncobj, all manipulation of the syncobjs's fence happens in
86  * terms of the current fence at the time the ioctl is called by userspace
87  * regardless of whether that operation is an immediate host-side operation
88  * (signal or reset) or or an operation which is enqueued in some driver
89  * queue. &DRM_IOCTL_SYNCOBJ_RESET and &DRM_IOCTL_SYNCOBJ_SIGNAL can be used
90  * to manipulate a syncobj from the host by resetting its pointer to NULL or
91  * setting its pointer to a fence which is already signaled.
92  *
93  * With a timeline syncobj, all manipulation of the synobj's fence happens in
94  * terms of a u64 value referring to point in the timeline. See
95  * dma_fence_chain_find_seqno() to see how a given point is found in the
96  * timeline.
97  *
98  * Note that applications should be careful to always use timeline set of
99  * ioctl() when dealing with syncobj considered as timeline. Using a binary
100  * set of ioctl() with a syncobj considered as timeline could result incorrect
101  * synchronization. The use of binary syncobj is supported through the
102  * timeline set of ioctl() by using a point value of 0, this will reproduce
103  * the behavior of the binary set of ioctl() (for example replace the
104  * syncobj's fence when signaling).
105  *
106  *
107  * Host-side wait on syncobjs
108  * --------------------------
109  *
110  * &DRM_IOCTL_SYNCOBJ_WAIT takes an array of syncobj handles and does a
111  * host-side wait on all of the syncobj fences simultaneously.
112  * If &DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL is set, the wait ioctl will wait on
113  * all of the syncobj fences to be signaled before it returns.
114  * Otherwise, it returns once at least one syncobj fence has been signaled
115  * and the index of a signaled fence is written back to the client.
116  *
117  * Unlike the enqueued GPU work dependencies which fail if they see a NULL
118  * fence in a syncobj, if &DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT is set,
119  * the host-side wait will first wait for the syncobj to receive a non-NULL
120  * fence and then wait on that fence.
121  * If &DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT is not set and any one of the
122  * syncobjs in the array has a NULL fence, -EINVAL will be returned.
123  * Assuming the syncobj starts off with a NULL fence, this allows a client
124  * to do a host wait in one thread (or process) which waits on GPU work
125  * submitted in another thread (or process) without having to manually
126  * synchronize between the two.
127  * This requirement is inherited from the Vulkan fence API.
128  *
129  * If &DRM_SYNCOBJ_WAIT_FLAGS_WAIT_DEADLINE is set, the ioctl will also set
130  * a fence deadline hint on the backing fences before waiting, to provide the
131  * fence signaler with an appropriate sense of urgency.  The deadline is
132  * specified as an absolute &CLOCK_MONOTONIC value in units of ns.
133  *
134  * Similarly, &DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT takes an array of syncobj
135  * handles as well as an array of u64 points and does a host-side wait on all
136  * of syncobj fences at the given points simultaneously.
137  *
138  * &DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT also adds the ability to wait for a given
139  * fence to materialize on the timeline without waiting for the fence to be
140  * signaled by using the &DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE flag. This
141  * requirement is inherited from the wait-before-signal behavior required by
142  * the Vulkan timeline semaphore API.
143  *
144  * Alternatively, &DRM_IOCTL_SYNCOBJ_EVENTFD can be used to wait without
145  * blocking: an eventfd will be signaled when the syncobj is. This is useful to
146  * integrate the wait in an event loop.
147  *
148  *
149  * Import/export of syncobjs
150  * -------------------------
151  *
152  * &DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE and &DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD
153  * provide two mechanisms for import/export of syncobjs.
154  *
155  * The first lets the client import or export an entire syncobj to a file
156  * descriptor.
157  * These fd's are opaque and have no other use case, except passing the
158  * syncobj between processes.
159  * All exported file descriptors and any syncobj handles created as a
160  * result of importing those file descriptors own a reference to the
161  * same underlying struct &drm_syncobj and the syncobj can be used
162  * persistently across all the processes with which it is shared.
163  * The syncobj is freed only once the last reference is dropped.
164  * Unlike dma-buf, importing a syncobj creates a new handle (with its own
165  * reference) for every import instead of de-duplicating.
166  * The primary use-case of this persistent import/export is for shared
167  * Vulkan fences and semaphores.
168  *
169  * The second import/export mechanism, which is indicated by
170  * &DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE or
171  * &DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE lets the client
172  * import/export the syncobj's current fence from/to a &sync_file.
173  * When a syncobj is exported to a sync file, that sync file wraps the
174  * sycnobj's fence at the time of export and any later signal or reset
175  * operations on the syncobj will not affect the exported sync file.
176  * When a sync file is imported into a syncobj, the syncobj's fence is set
177  * to the fence wrapped by that sync file.
178  * Because sync files are immutable, resetting or signaling the syncobj
179  * will not affect any sync files whose fences have been imported into the
180  * syncobj.
181  *
182  *
183  * Import/export of timeline points in timeline syncobjs
184  * -----------------------------------------------------
185  *
186  * &DRM_IOCTL_SYNCOBJ_TRANSFER provides a mechanism to transfer a struct
187  * &dma_fence_chain of a syncobj at a given u64 point to another u64 point
188  * into another syncobj.
189  *
190  * Note that if you want to transfer a struct &dma_fence_chain from a given
191  * point on a timeline syncobj from/into a binary syncobj, you can use the
192  * point 0 to mean take/replace the fence in the syncobj.
193  */
194 
195 #include <linux/anon_inodes.h>
196 #include <linux/dma-fence-unwrap.h>
197 #include <linux/eventfd.h>
198 #include <linux/export.h>
199 #include <linux/file.h>
200 #include <linux/fs.h>
201 #include <linux/sched/signal.h>
202 #include <linux/sizes.h>
203 #include <linux/sync_file.h>
204 #include <linux/uaccess.h>
205 
206 #include <drm/drm.h>
207 #include <drm/drm_drv.h>
208 #include <drm/drm_file.h>
209 #include <drm/drm_gem.h>
210 #include <drm/drm_print.h>
211 #include <drm/drm_syncobj.h>
212 #include <drm/drm_timeout.h>
213 
214 #include "drm_internal.h"
215 
216 struct syncobj_wait_entry {
217 	struct list_head node;
218 	struct task_struct *task;
219 	struct dma_fence *fence;
220 	struct dma_fence_cb fence_cb;
221 	u64    point;
222 };
223 
224 /*
225  * Upper limit for the number of handles passed to a single ioctl. This is a
226  * fixed number so that the limit is the same on all architectures. The
227  * largest per-handle allocation is the wait entry array, which must stay
228  * below the INT_MAX size limit of kvmalloc().
229  */
230 #define DRM_SYNCOBJ_MAX_HANDLES	SZ_1M
231 static_assert(DRM_SYNCOBJ_MAX_HANDLES <=
232 	      INT_MAX / sizeof(struct syncobj_wait_entry));
233 
234 static void syncobj_wait_syncobj_func(struct drm_syncobj *syncobj,
235 				      struct syncobj_wait_entry *wait);
236 
237 struct syncobj_eventfd_entry {
238 	struct list_head node;
239 	struct dma_fence *fence;
240 	struct dma_fence_cb fence_cb;
241 	struct drm_syncobj *syncobj;
242 	struct eventfd_ctx *ev_fd_ctx;
243 	u64 point;
244 	u32 flags;
245 };
246 
247 static void
248 syncobj_eventfd_entry_func(struct drm_syncobj *syncobj,
249 			   struct syncobj_eventfd_entry *entry);
250 
251 /**
252  * drm_syncobj_find - lookup and reference a sync object.
253  * @file_private: drm file private pointer
254  * @handle: sync object handle to lookup.
255  *
256  * Returns a reference to the syncobj pointed to by handle or NULL. The
257  * reference must be released by calling drm_syncobj_put().
258  */
259 struct drm_syncobj *drm_syncobj_find(struct drm_file *file_private,
260 				     u32 handle)
261 {
262 	struct drm_syncobj *syncobj;
263 
264 	xa_lock(&file_private->syncobj_xa);
265 
266 	/* Check if we currently have a reference on the object */
267 	syncobj = xa_load(&file_private->syncobj_xa, handle);
268 	if (syncobj)
269 		drm_syncobj_get(syncobj);
270 
271 	xa_unlock(&file_private->syncobj_xa);
272 
273 	return syncobj;
274 }
275 EXPORT_SYMBOL(drm_syncobj_find);
276 
277 static void drm_syncobj_fence_add_wait(struct drm_syncobj *syncobj,
278 				       struct syncobj_wait_entry *wait)
279 {
280 	struct dma_fence *fence;
281 
282 	if (wait->fence)
283 		return;
284 
285 	spin_lock(&syncobj->lock);
286 	/* We've already tried once to get a fence and failed.  Now that we
287 	 * have the lock, try one more time just to be sure we don't add a
288 	 * callback when a fence has already been set.
289 	 */
290 	fence = dma_fence_get(rcu_dereference_protected(syncobj->fence, 1));
291 	if (!fence || dma_fence_chain_find_seqno(&fence, wait->point)) {
292 		dma_fence_put(fence);
293 		list_add_tail(&wait->node, &syncobj->cb_list);
294 	} else if (!fence) {
295 		wait->fence = dma_fence_get_stub();
296 	} else {
297 		wait->fence = fence;
298 	}
299 	spin_unlock(&syncobj->lock);
300 }
301 
302 static void drm_syncobj_remove_wait(struct drm_syncobj *syncobj,
303 				    struct syncobj_wait_entry *wait)
304 {
305 	if (!wait->node.next)
306 		return;
307 
308 	spin_lock(&syncobj->lock);
309 	list_del_init(&wait->node);
310 	spin_unlock(&syncobj->lock);
311 }
312 
313 static void
314 syncobj_eventfd_entry_free(struct syncobj_eventfd_entry *entry)
315 {
316 	eventfd_ctx_put(entry->ev_fd_ctx);
317 	dma_fence_put(entry->fence);
318 	/* This happens either inside the syncobj lock, or after the node has
319 	 * already been removed from the list.
320 	 */
321 	list_del(&entry->node);
322 	kfree(entry);
323 }
324 
325 static void
326 drm_syncobj_add_eventfd(struct drm_syncobj *syncobj,
327 			struct syncobj_eventfd_entry *entry)
328 {
329 	spin_lock(&syncobj->lock);
330 	list_add_tail(&entry->node, &syncobj->ev_fd_list);
331 	syncobj_eventfd_entry_func(syncobj, entry);
332 	spin_unlock(&syncobj->lock);
333 }
334 
335 /**
336  * drm_syncobj_add_point - add new timeline point to the syncobj
337  * @syncobj: sync object to add timeline point do
338  * @chain: chain node to use to add the point
339  * @fence: fence to encapsulate in the chain node
340  * @point: sequence number to use for the point
341  *
342  * Add the chain node as new timeline point to the syncobj.
343  */
344 void drm_syncobj_add_point(struct drm_syncobj *syncobj,
345 			   struct dma_fence_chain *chain,
346 			   struct dma_fence *fence,
347 			   uint64_t point)
348 {
349 	struct syncobj_wait_entry *wait_cur, *wait_tmp;
350 	struct syncobj_eventfd_entry *ev_fd_cur, *ev_fd_tmp;
351 	struct dma_fence *prev;
352 
353 	dma_fence_get(fence);
354 
355 	spin_lock(&syncobj->lock);
356 
357 	prev = drm_syncobj_fence_get(syncobj);
358 	/* You are adding an unorder point to timeline, which could cause payload returned from query_ioctl is 0! */
359 	if (prev && prev->seqno >= point)
360 		DRM_DEBUG("You are adding an unorder point to timeline!\n");
361 	dma_fence_chain_init(chain, prev, fence, point);
362 	rcu_assign_pointer(syncobj->fence, &chain->base);
363 
364 	list_for_each_entry_safe(wait_cur, wait_tmp, &syncobj->cb_list, node)
365 		syncobj_wait_syncobj_func(syncobj, wait_cur);
366 	list_for_each_entry_safe(ev_fd_cur, ev_fd_tmp, &syncobj->ev_fd_list, node)
367 		syncobj_eventfd_entry_func(syncobj, ev_fd_cur);
368 	spin_unlock(&syncobj->lock);
369 
370 	/* Walk the chain once to trigger garbage collection */
371 	dma_fence_chain_for_each(fence, prev);
372 	dma_fence_put(prev);
373 }
374 EXPORT_SYMBOL(drm_syncobj_add_point);
375 
376 /**
377  * drm_syncobj_replace_fence - replace fence in a sync object.
378  * @syncobj: Sync object to replace fence in
379  * @fence: fence to install in sync file.
380  *
381  * This replaces the fence on a sync object.
382  */
383 void drm_syncobj_replace_fence(struct drm_syncobj *syncobj,
384 			       struct dma_fence *fence)
385 {
386 	struct dma_fence *old_fence;
387 	struct syncobj_wait_entry *wait_cur, *wait_tmp;
388 	struct syncobj_eventfd_entry *ev_fd_cur, *ev_fd_tmp;
389 
390 	if (fence)
391 		dma_fence_get(fence);
392 
393 	spin_lock(&syncobj->lock);
394 
395 	old_fence = rcu_dereference_protected(syncobj->fence,
396 					      lockdep_is_held(&syncobj->lock));
397 	rcu_assign_pointer(syncobj->fence, fence);
398 
399 	if (fence != old_fence) {
400 		list_for_each_entry_safe(wait_cur, wait_tmp, &syncobj->cb_list, node)
401 			syncobj_wait_syncobj_func(syncobj, wait_cur);
402 		list_for_each_entry_safe(ev_fd_cur, ev_fd_tmp, &syncobj->ev_fd_list, node)
403 			syncobj_eventfd_entry_func(syncobj, ev_fd_cur);
404 	}
405 
406 	spin_unlock(&syncobj->lock);
407 
408 	dma_fence_put(old_fence);
409 }
410 EXPORT_SYMBOL(drm_syncobj_replace_fence);
411 
412 /**
413  * drm_syncobj_assign_null_handle - assign a stub fence to the sync object
414  * @syncobj: sync object to assign the fence on
415  *
416  * Assign a already signaled stub fence to the sync object.
417  */
418 static int drm_syncobj_assign_null_handle(struct drm_syncobj *syncobj)
419 {
420 	struct dma_fence *fence = dma_fence_allocate_private_stub(ktime_get());
421 
422 	if (!fence)
423 		return -ENOMEM;
424 
425 	drm_syncobj_replace_fence(syncobj, fence);
426 	dma_fence_put(fence);
427 	return 0;
428 }
429 
430 /* 5s default for wait submission */
431 #define DRM_SYNCOBJ_WAIT_FOR_SUBMIT_TIMEOUT 5000000000ULL
432 /**
433  * drm_syncobj_find_fence - lookup and reference the fence in a sync object
434  * @file_private: drm file private pointer
435  * @handle: sync object handle to lookup.
436  * @point: timeline point
437  * @flags: DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT or not
438  * @fence: out parameter for the fence
439  *
440  * This is just a convenience function that combines drm_syncobj_find() and
441  * drm_syncobj_fence_get().
442  *
443  * Returns 0 on success or a negative error value on failure. On success @fence
444  * contains a reference to the fence, which must be released by calling
445  * dma_fence_put().
446  */
447 int drm_syncobj_find_fence(struct drm_file *file_private,
448 			   u32 handle, u64 point, u64 flags,
449 			   struct dma_fence **fence)
450 {
451 	struct drm_syncobj *syncobj = drm_syncobj_find(file_private, handle);
452 	struct syncobj_wait_entry wait;
453 	u64 timeout = nsecs_to_jiffies64(DRM_SYNCOBJ_WAIT_FOR_SUBMIT_TIMEOUT);
454 	int ret;
455 
456 	if (!syncobj)
457 		return -ENOENT;
458 
459 	if (flags & ~DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT) {
460 		ret = -EINVAL;
461 		goto out;
462 	}
463 
464 	/* Waiting for userspace with locks held is illegal cause that can
465 	 * trivial deadlock with page faults for example. Make lockdep complain
466 	 * about it early on.
467 	 */
468 	if (flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT) {
469 		might_sleep();
470 		lockdep_assert_none_held_once();
471 	}
472 
473 	*fence = drm_syncobj_fence_get(syncobj);
474 
475 	if (*fence) {
476 		ret = dma_fence_chain_find_seqno(fence, point);
477 		if (!ret) {
478 			/* If the requested seqno is already signaled
479 			 * drm_syncobj_find_fence may return a NULL
480 			 * fence. To make sure the recipient gets
481 			 * signalled, use a new fence instead.
482 			 */
483 			if (!*fence)
484 				*fence = dma_fence_get_stub();
485 
486 			goto out;
487 		}
488 		dma_fence_put(*fence);
489 	} else {
490 		ret = -EINVAL;
491 	}
492 
493 	if (!(flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT))
494 		goto out;
495 
496 	memset(&wait, 0, sizeof(wait));
497 	wait.task = current;
498 	wait.point = point;
499 	drm_syncobj_fence_add_wait(syncobj, &wait);
500 
501 	do {
502 		set_current_state(TASK_INTERRUPTIBLE);
503 		if (wait.fence) {
504 			ret = 0;
505 			break;
506 		}
507                 if (timeout == 0) {
508                         ret = -ETIME;
509                         break;
510                 }
511 
512 		if (signal_pending(current)) {
513 			ret = -ERESTARTSYS;
514 			break;
515 		}
516 
517                 timeout = schedule_timeout(timeout);
518 	} while (1);
519 
520 	__set_current_state(TASK_RUNNING);
521 	*fence = wait.fence;
522 
523 	if (wait.node.next)
524 		drm_syncobj_remove_wait(syncobj, &wait);
525 
526 out:
527 	drm_syncobj_put(syncobj);
528 
529 	return ret;
530 }
531 EXPORT_SYMBOL(drm_syncobj_find_fence);
532 
533 /**
534  * drm_syncobj_free - free a sync object.
535  * @kref: kref to free.
536  *
537  * Only to be called from kref_put in drm_syncobj_put.
538  */
539 void drm_syncobj_free(struct kref *kref)
540 {
541 	struct drm_syncobj *syncobj = container_of(kref,
542 						   struct drm_syncobj,
543 						   refcount);
544 	struct syncobj_eventfd_entry *ev_fd_cur, *ev_fd_tmp;
545 
546 	drm_syncobj_replace_fence(syncobj, NULL);
547 
548 	list_for_each_entry_safe(ev_fd_cur, ev_fd_tmp, &syncobj->ev_fd_list, node)
549 		syncobj_eventfd_entry_free(ev_fd_cur);
550 
551 	kfree(syncobj);
552 }
553 EXPORT_SYMBOL(drm_syncobj_free);
554 
555 /**
556  * drm_syncobj_create - create a new syncobj
557  * @out_syncobj: returned syncobj
558  * @flags: DRM_SYNCOBJ_* flags
559  * @fence: if non-NULL, the syncobj will represent this fence
560  *
561  * This is the first function to create a sync object. After creating, drivers
562  * probably want to make it available to userspace, either through
563  * drm_syncobj_get_handle() or drm_syncobj_get_fd().
564  *
565  * Returns 0 on success or a negative error value on failure.
566  */
567 int drm_syncobj_create(struct drm_syncobj **out_syncobj, uint32_t flags,
568 		       struct dma_fence *fence)
569 {
570 	int ret;
571 	struct drm_syncobj *syncobj;
572 
573 	syncobj = kzalloc_obj(struct drm_syncobj);
574 	if (!syncobj)
575 		return -ENOMEM;
576 
577 	kref_init(&syncobj->refcount);
578 	INIT_LIST_HEAD(&syncobj->cb_list);
579 	INIT_LIST_HEAD(&syncobj->ev_fd_list);
580 	spin_lock_init(&syncobj->lock);
581 
582 	if (flags & DRM_SYNCOBJ_CREATE_SIGNALED) {
583 		ret = drm_syncobj_assign_null_handle(syncobj);
584 		if (ret < 0) {
585 			drm_syncobj_put(syncobj);
586 			return ret;
587 		}
588 	}
589 
590 	if (fence)
591 		drm_syncobj_replace_fence(syncobj, fence);
592 
593 	*out_syncobj = syncobj;
594 	return 0;
595 }
596 EXPORT_SYMBOL(drm_syncobj_create);
597 
598 /**
599  * drm_syncobj_get_handle - get a handle from a syncobj
600  * @file_private: drm file private pointer
601  * @syncobj: Sync object to export
602  * @handle: out parameter with the new handle
603  *
604  * Exports a sync object created with drm_syncobj_create() as a handle on
605  * @file_private to userspace.
606  *
607  * Returns 0 on success or a negative error value on failure.
608  */
609 int drm_syncobj_get_handle(struct drm_file *file_private,
610 			   struct drm_syncobj *syncobj, u32 *handle)
611 {
612 	int ret;
613 
614 	/* take a reference to put in the xarray */
615 	drm_syncobj_get(syncobj);
616 
617 	ret = xa_alloc(&file_private->syncobj_xa, handle, syncobj, xa_limit_32b,
618 		       GFP_KERNEL);
619 	if (ret)
620 		drm_syncobj_put(syncobj);
621 
622 	return ret;
623 }
624 EXPORT_SYMBOL(drm_syncobj_get_handle);
625 
626 static int drm_syncobj_create_as_handle(struct drm_file *file_private,
627 					u32 *handle, uint32_t flags)
628 {
629 	int ret;
630 	struct drm_syncobj *syncobj;
631 
632 	ret = drm_syncobj_create(&syncobj, flags, NULL);
633 	if (ret)
634 		return ret;
635 
636 	ret = drm_syncobj_get_handle(file_private, syncobj, handle);
637 	drm_syncobj_put(syncobj);
638 	return ret;
639 }
640 
641 static int drm_syncobj_destroy(struct drm_file *file_private,
642 			       u32 handle)
643 {
644 	struct drm_syncobj *syncobj;
645 
646 	syncobj = xa_erase(&file_private->syncobj_xa, handle);
647 	if (!syncobj)
648 		return -EINVAL;
649 
650 	drm_syncobj_put(syncobj);
651 	return 0;
652 }
653 
654 static int drm_syncobj_file_release(struct inode *inode, struct file *file)
655 {
656 	struct drm_syncobj *syncobj = file->private_data;
657 
658 	drm_syncobj_put(syncobj);
659 	return 0;
660 }
661 
662 static const struct file_operations drm_syncobj_file_fops = {
663 	.release = drm_syncobj_file_release,
664 };
665 
666 /**
667  * drm_syncobj_get_fd - get a file descriptor from a syncobj
668  * @syncobj: Sync object to export
669  * @p_fd: out parameter with the new file descriptor
670  *
671  * Exports a sync object created with drm_syncobj_create() as a file descriptor.
672  *
673  * Returns 0 on success or a negative error value on failure.
674  */
675 int drm_syncobj_get_fd(struct drm_syncobj *syncobj, int *p_fd)
676 {
677 	struct file *file;
678 	int fd;
679 
680 	fd = get_unused_fd_flags(O_CLOEXEC);
681 	if (fd < 0)
682 		return fd;
683 
684 	file = anon_inode_getfile("syncobj_file",
685 				  &drm_syncobj_file_fops,
686 				  syncobj, 0);
687 	if (IS_ERR(file)) {
688 		put_unused_fd(fd);
689 		return PTR_ERR(file);
690 	}
691 
692 	drm_syncobj_get(syncobj);
693 	fd_install(fd, file);
694 
695 	*p_fd = fd;
696 	return 0;
697 }
698 EXPORT_SYMBOL(drm_syncobj_get_fd);
699 
700 static int drm_syncobj_handle_to_fd(struct drm_file *file_private,
701 				    u32 handle, int *p_fd)
702 {
703 	struct drm_syncobj *syncobj = drm_syncobj_find(file_private, handle);
704 	int ret;
705 
706 	if (!syncobj)
707 		return -EINVAL;
708 
709 	ret = drm_syncobj_get_fd(syncobj, p_fd);
710 	drm_syncobj_put(syncobj);
711 	return ret;
712 }
713 
714 static int drm_syncobj_fd_to_handle(struct drm_file *file_private,
715 				    int fd, u32 *handle)
716 {
717 	struct drm_syncobj *syncobj;
718 	CLASS(fd, f)(fd);
719 	int ret;
720 
721 	if (fd_empty(f))
722 		return -EINVAL;
723 
724 	if (fd_file(f)->f_op != &drm_syncobj_file_fops)
725 		return -EINVAL;
726 
727 	/* take a reference to put in the xarray */
728 	syncobj = fd_file(f)->private_data;
729 	drm_syncobj_get(syncobj);
730 
731 	ret = xa_alloc(&file_private->syncobj_xa, handle, syncobj, xa_limit_32b,
732 		       GFP_KERNEL);
733 	if (ret)
734 		drm_syncobj_put(syncobj);
735 
736 	return ret;
737 }
738 
739 static int drm_syncobj_import_sync_file_fence(struct drm_file *file_private,
740 					      int fd, int handle, u64 point)
741 {
742 	struct dma_fence *fence = sync_file_get_fence(fd);
743 	struct drm_syncobj *syncobj;
744 
745 	if (!fence)
746 		return -EINVAL;
747 
748 	syncobj = drm_syncobj_find(file_private, handle);
749 	if (!syncobj) {
750 		dma_fence_put(fence);
751 		return -ENOENT;
752 	}
753 
754 	if (point) {
755 		struct dma_fence_chain *chain = dma_fence_chain_alloc();
756 
757 		if (!chain)
758 			return -ENOMEM;
759 
760 		drm_syncobj_add_point(syncobj, chain, fence, point);
761 	} else {
762 		drm_syncobj_replace_fence(syncobj, fence);
763 	}
764 
765 	dma_fence_put(fence);
766 	drm_syncobj_put(syncobj);
767 	return 0;
768 }
769 
770 static int drm_syncobj_export_sync_file(struct drm_file *file_private,
771 					int handle, u64 point, int *p_fd)
772 {
773 	int ret;
774 	struct dma_fence *fence;
775 	struct sync_file *sync_file;
776 	int fd = get_unused_fd_flags(O_CLOEXEC);
777 
778 	if (fd < 0)
779 		return fd;
780 
781 	ret = drm_syncobj_find_fence(file_private, handle, point, 0, &fence);
782 	if (ret)
783 		goto err_put_fd;
784 
785 	sync_file = sync_file_create(fence);
786 
787 	dma_fence_put(fence);
788 
789 	if (!sync_file) {
790 		ret = -EINVAL;
791 		goto err_put_fd;
792 	}
793 
794 	fd_install(fd, sync_file->file);
795 
796 	*p_fd = fd;
797 	return 0;
798 err_put_fd:
799 	put_unused_fd(fd);
800 	return ret;
801 }
802 /**
803  * drm_syncobj_open - initializes syncobj file-private structures at devnode open time
804  * @file_private: drm file-private structure to set up
805  *
806  * Called at device open time, sets up the structure for handling refcounting
807  * of sync objects.
808  */
809 void
810 drm_syncobj_open(struct drm_file *file_private)
811 {
812 	xa_init_flags(&file_private->syncobj_xa, XA_FLAGS_ALLOC1);
813 }
814 
815 /**
816  * drm_syncobj_release - release file-private sync object resources
817  * @file_private: drm file-private structure to clean up
818  *
819  * Called at close time when the filp is going away.
820  *
821  * Releases any remaining references on objects by this filp.
822  */
823 void
824 drm_syncobj_release(struct drm_file *file_private)
825 {
826 	struct drm_syncobj *syncobj;
827 	unsigned long handle;
828 
829 	xa_for_each(&file_private->syncobj_xa, handle, syncobj)
830 		drm_syncobj_put(syncobj);
831 	xa_destroy(&file_private->syncobj_xa);
832 }
833 
834 int
835 drm_syncobj_create_ioctl(struct drm_device *dev, void *data,
836 			 struct drm_file *file_private)
837 {
838 	struct drm_syncobj_create *args = data;
839 
840 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ))
841 		return -EOPNOTSUPP;
842 
843 	/* no valid flags yet */
844 	if (args->flags & ~DRM_SYNCOBJ_CREATE_SIGNALED)
845 		return -EINVAL;
846 
847 	return drm_syncobj_create_as_handle(file_private,
848 					    &args->handle, args->flags);
849 }
850 
851 int
852 drm_syncobj_destroy_ioctl(struct drm_device *dev, void *data,
853 			  struct drm_file *file_private)
854 {
855 	struct drm_syncobj_destroy *args = data;
856 
857 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ))
858 		return -EOPNOTSUPP;
859 
860 	/* make sure padding is empty */
861 	if (args->pad)
862 		return -EINVAL;
863 	return drm_syncobj_destroy(file_private, args->handle);
864 }
865 
866 int
867 drm_syncobj_handle_to_fd_ioctl(struct drm_device *dev, void *data,
868 				   struct drm_file *file_private)
869 {
870 	struct drm_syncobj_handle *args = data;
871 	unsigned int valid_flags = DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_TIMELINE |
872 				   DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE;
873 	u64 point = 0;
874 
875 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ))
876 		return -EOPNOTSUPP;
877 
878 	if (args->pad)
879 		return -EINVAL;
880 
881 	if (args->flags & ~valid_flags)
882 		return -EINVAL;
883 
884 	if (args->flags & DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_TIMELINE)
885 		point = args->point;
886 
887 	if (args->flags & DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE)
888 		return drm_syncobj_export_sync_file(file_private, args->handle,
889 						    point, &args->fd);
890 
891 	if (args->point)
892 		return -EINVAL;
893 
894 	return drm_syncobj_handle_to_fd(file_private, args->handle,
895 					&args->fd);
896 }
897 
898 int
899 drm_syncobj_fd_to_handle_ioctl(struct drm_device *dev, void *data,
900 				   struct drm_file *file_private)
901 {
902 	struct drm_syncobj_handle *args = data;
903 	unsigned int valid_flags = DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_TIMELINE |
904 				   DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE;
905 	u64 point = 0;
906 
907 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ))
908 		return -EOPNOTSUPP;
909 
910 	if (args->pad)
911 		return -EINVAL;
912 
913 	if (args->flags & ~valid_flags)
914 		return -EINVAL;
915 
916 	if (args->flags & DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_TIMELINE)
917 		point = args->point;
918 
919 	if (args->flags & DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE)
920 		return drm_syncobj_import_sync_file_fence(file_private,
921 							  args->fd,
922 							  args->handle,
923 							  point);
924 
925 	if (args->point)
926 		return -EINVAL;
927 
928 	return drm_syncobj_fd_to_handle(file_private, args->fd,
929 					&args->handle);
930 }
931 
932 static int drm_syncobj_transfer_to_timeline(struct drm_file *file_private,
933 					    struct drm_syncobj_transfer *args)
934 {
935 	struct drm_syncobj *timeline_syncobj = NULL;
936 	struct dma_fence *fence, *tmp;
937 	struct dma_fence_chain *chain;
938 	int ret;
939 
940 	timeline_syncobj = drm_syncobj_find(file_private, args->dst_handle);
941 	if (!timeline_syncobj) {
942 		return -ENOENT;
943 	}
944 	ret = drm_syncobj_find_fence(file_private, args->src_handle,
945 				     args->src_point, args->flags,
946 				     &tmp);
947 	if (ret)
948 		goto err_put_timeline;
949 
950 	fence = dma_fence_unwrap_merge(tmp);
951 	dma_fence_put(tmp);
952 	if (!fence) {
953 		ret = -ENOMEM;
954 		goto err_put_timeline;
955 	}
956 
957 	chain = dma_fence_chain_alloc();
958 	if (!chain) {
959 		ret = -ENOMEM;
960 		goto err_free_fence;
961 	}
962 
963 	drm_syncobj_add_point(timeline_syncobj, chain, fence, args->dst_point);
964 err_free_fence:
965 	dma_fence_put(fence);
966 err_put_timeline:
967 	drm_syncobj_put(timeline_syncobj);
968 
969 	return ret;
970 }
971 
972 static int
973 drm_syncobj_transfer_to_binary(struct drm_file *file_private,
974 			       struct drm_syncobj_transfer *args)
975 {
976 	struct drm_syncobj *binary_syncobj = NULL;
977 	struct dma_fence *fence;
978 	int ret;
979 
980 	binary_syncobj = drm_syncobj_find(file_private, args->dst_handle);
981 	if (!binary_syncobj)
982 		return -ENOENT;
983 	ret = drm_syncobj_find_fence(file_private, args->src_handle,
984 				     args->src_point, args->flags, &fence);
985 	if (ret)
986 		goto err;
987 	drm_syncobj_replace_fence(binary_syncobj, fence);
988 	dma_fence_put(fence);
989 err:
990 	drm_syncobj_put(binary_syncobj);
991 
992 	return ret;
993 }
994 int
995 drm_syncobj_transfer_ioctl(struct drm_device *dev, void *data,
996 			   struct drm_file *file_private)
997 {
998 	struct drm_syncobj_transfer *args = data;
999 	int ret;
1000 
1001 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ_TIMELINE))
1002 		return -EOPNOTSUPP;
1003 
1004 	if (args->pad)
1005 		return -EINVAL;
1006 
1007 	if (args->dst_point)
1008 		ret = drm_syncobj_transfer_to_timeline(file_private, args);
1009 	else
1010 		ret = drm_syncobj_transfer_to_binary(file_private, args);
1011 
1012 	return ret;
1013 }
1014 
1015 static void syncobj_wait_fence_func(struct dma_fence *fence,
1016 				    struct dma_fence_cb *cb)
1017 {
1018 	struct syncobj_wait_entry *wait =
1019 		container_of(cb, struct syncobj_wait_entry, fence_cb);
1020 
1021 	wake_up_process(wait->task);
1022 }
1023 
1024 static void syncobj_wait_syncobj_func(struct drm_syncobj *syncobj,
1025 				      struct syncobj_wait_entry *wait)
1026 {
1027 	struct dma_fence *fence;
1028 
1029 	/* This happens inside the syncobj lock */
1030 	fence = rcu_dereference_protected(syncobj->fence,
1031 					  lockdep_is_held(&syncobj->lock));
1032 	dma_fence_get(fence);
1033 	if (!fence || dma_fence_chain_find_seqno(&fence, wait->point)) {
1034 		dma_fence_put(fence);
1035 		return;
1036 	} else if (!fence) {
1037 		wait->fence = dma_fence_get_stub();
1038 	} else {
1039 		wait->fence = fence;
1040 	}
1041 
1042 	wake_up_process(wait->task);
1043 	list_del_init(&wait->node);
1044 }
1045 
1046 static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs,
1047 						  void __user *user_points,
1048 						  uint32_t count,
1049 						  uint32_t flags,
1050 						  signed long timeout,
1051 						  uint32_t *idx,
1052 						  ktime_t *deadline)
1053 {
1054 	struct syncobj_wait_entry *entries;
1055 	struct dma_fence *fence;
1056 	uint64_t *points;
1057 	uint32_t signaled_count, i;
1058 
1059 	if (flags & (DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT |
1060 		     DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE)) {
1061 		might_sleep();
1062 		lockdep_assert_none_held_once();
1063 	}
1064 
1065 	points = kvmalloc_objs(*points, count);
1066 	if (points == NULL)
1067 		return -ENOMEM;
1068 
1069 	if (!user_points) {
1070 		memset(points, 0, count * sizeof(uint64_t));
1071 
1072 	} else if (copy_from_user(points, user_points,
1073 				  sizeof(uint64_t) * count)) {
1074 		timeout = -EFAULT;
1075 		goto err_free_points;
1076 	}
1077 
1078 	entries = kvzalloc_objs(*entries, count);
1079 	if (!entries) {
1080 		timeout = -ENOMEM;
1081 		goto err_free_points;
1082 	}
1083 	/* Walk the list of sync objects and initialize entries.  We do
1084 	 * this up-front so that we can properly return -EINVAL if there is
1085 	 * a syncobj with a missing fence and then never have the chance of
1086 	 * returning -EINVAL again.
1087 	 */
1088 	signaled_count = 0;
1089 	for (i = 0; i < count; ++i) {
1090 		struct dma_fence *fence;
1091 
1092 		entries[i].task = current;
1093 		entries[i].point = points[i];
1094 		fence = drm_syncobj_fence_get(syncobjs[i]);
1095 		if (!fence || dma_fence_chain_find_seqno(&fence, points[i])) {
1096 			dma_fence_put(fence);
1097 			if (flags & (DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT |
1098 				     DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE)) {
1099 				continue;
1100 			} else {
1101 				timeout = -EINVAL;
1102 				goto cleanup_entries;
1103 			}
1104 		}
1105 
1106 		if (fence)
1107 			entries[i].fence = fence;
1108 		else
1109 			entries[i].fence = dma_fence_get_stub();
1110 
1111 		if ((flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE) ||
1112 		    dma_fence_is_signaled(entries[i].fence)) {
1113 			if (signaled_count == 0 && idx)
1114 				*idx = i;
1115 			signaled_count++;
1116 		}
1117 	}
1118 
1119 	if (signaled_count == count ||
1120 	    (signaled_count > 0 &&
1121 	     !(flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL)))
1122 		goto cleanup_entries;
1123 
1124 	/* There's a very annoying laxness in the dma_fence API here, in
1125 	 * that backends are not required to automatically report when a
1126 	 * fence is signaled prior to fence->ops->enable_signaling() being
1127 	 * called.  So here if we fail to match signaled_count, we need to
1128 	 * fallthough and try a 0 timeout wait!
1129 	 */
1130 
1131 	if (flags & (DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT |
1132 		     DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE)) {
1133 		for (i = 0; i < count; ++i)
1134 			drm_syncobj_fence_add_wait(syncobjs[i], &entries[i]);
1135 	}
1136 
1137 	if (deadline) {
1138 		for (i = 0; i < count; ++i) {
1139 			fence = entries[i].fence;
1140 			if (!fence)
1141 				continue;
1142 			dma_fence_set_deadline(fence, *deadline);
1143 		}
1144 	}
1145 
1146 	do {
1147 		set_current_state(TASK_INTERRUPTIBLE);
1148 
1149 		signaled_count = 0;
1150 		for (i = 0; i < count; ++i) {
1151 			fence = entries[i].fence;
1152 			if (!fence)
1153 				continue;
1154 
1155 			if ((flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE) ||
1156 			    dma_fence_is_signaled(fence) ||
1157 			    (!entries[i].fence_cb.func &&
1158 			     dma_fence_add_callback(fence,
1159 						    &entries[i].fence_cb,
1160 						    syncobj_wait_fence_func))) {
1161 				/* The fence has been signaled */
1162 				if (flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL) {
1163 					signaled_count++;
1164 				} else {
1165 					if (idx)
1166 						*idx = i;
1167 					goto done_waiting;
1168 				}
1169 			}
1170 		}
1171 
1172 		if (signaled_count == count)
1173 			goto done_waiting;
1174 
1175 		if (timeout == 0) {
1176 			timeout = -ETIME;
1177 			goto done_waiting;
1178 		}
1179 
1180 		if (signal_pending(current)) {
1181 			timeout = -ERESTARTSYS;
1182 			goto done_waiting;
1183 		}
1184 
1185 		timeout = schedule_timeout(timeout);
1186 	} while (1);
1187 
1188 done_waiting:
1189 	__set_current_state(TASK_RUNNING);
1190 
1191 cleanup_entries:
1192 	for (i = 0; i < count; ++i) {
1193 		drm_syncobj_remove_wait(syncobjs[i], &entries[i]);
1194 		if (entries[i].fence_cb.func)
1195 			dma_fence_remove_callback(entries[i].fence,
1196 						  &entries[i].fence_cb);
1197 		dma_fence_put(entries[i].fence);
1198 	}
1199 	kvfree(entries);
1200 
1201 err_free_points:
1202 	kvfree(points);
1203 
1204 	return timeout;
1205 }
1206 
1207 static int drm_syncobj_array_wait(struct drm_device *dev,
1208 				  struct drm_file *file_private,
1209 				  struct drm_syncobj_wait *wait,
1210 				  struct drm_syncobj_timeline_wait *timeline_wait,
1211 				  struct drm_syncobj **syncobjs, bool timeline,
1212 				  ktime_t *deadline)
1213 {
1214 	signed long timeout = 0;
1215 	uint32_t first = ~0;
1216 
1217 	if (!timeline) {
1218 		timeout = drm_timeout_abs_to_jiffies(wait->timeout_nsec);
1219 		timeout = drm_syncobj_array_wait_timeout(syncobjs,
1220 							 NULL,
1221 							 wait->count_handles,
1222 							 wait->flags,
1223 							 timeout, &first,
1224 							 deadline);
1225 		if (timeout < 0)
1226 			return timeout;
1227 		wait->first_signaled = first;
1228 	} else {
1229 		timeout = drm_timeout_abs_to_jiffies(timeline_wait->timeout_nsec);
1230 		timeout = drm_syncobj_array_wait_timeout(syncobjs,
1231 							 u64_to_user_ptr(timeline_wait->points),
1232 							 timeline_wait->count_handles,
1233 							 timeline_wait->flags,
1234 							 timeout, &first,
1235 							 deadline);
1236 		if (timeout < 0)
1237 			return timeout;
1238 		timeline_wait->first_signaled = first;
1239 	}
1240 	return 0;
1241 }
1242 
1243 static int drm_syncobj_array_find(struct drm_file *file_private,
1244 				  void __user *user_handles,
1245 				  uint32_t count_handles,
1246 				  struct drm_syncobj ***syncobjs_out)
1247 {
1248 	uint32_t i, *handles;
1249 	struct drm_syncobj **syncobjs;
1250 	int ret;
1251 
1252 	if (count_handles > DRM_SYNCOBJ_MAX_HANDLES)
1253 		return -EINVAL;
1254 
1255 	handles = kvmalloc_objs(*handles, count_handles);
1256 	if (handles == NULL)
1257 		return -ENOMEM;
1258 
1259 	if (copy_from_user(handles, user_handles,
1260 			   sizeof(uint32_t) * count_handles)) {
1261 		ret = -EFAULT;
1262 		goto err_free_handles;
1263 	}
1264 
1265 	syncobjs = kvmalloc_objs(*syncobjs, count_handles);
1266 	if (syncobjs == NULL) {
1267 		ret = -ENOMEM;
1268 		goto err_free_handles;
1269 	}
1270 
1271 	for (i = 0; i < count_handles; i++) {
1272 		syncobjs[i] = drm_syncobj_find(file_private, handles[i]);
1273 		if (!syncobjs[i]) {
1274 			ret = -ENOENT;
1275 			goto err_put_syncobjs;
1276 		}
1277 	}
1278 
1279 	kvfree(handles);
1280 	*syncobjs_out = syncobjs;
1281 	return 0;
1282 
1283 err_put_syncobjs:
1284 	while (i-- > 0)
1285 		drm_syncobj_put(syncobjs[i]);
1286 	kvfree(syncobjs);
1287 err_free_handles:
1288 	kvfree(handles);
1289 
1290 	return ret;
1291 }
1292 
1293 static void drm_syncobj_array_free(struct drm_syncobj **syncobjs,
1294 				   uint32_t count)
1295 {
1296 	uint32_t i;
1297 
1298 	for (i = 0; i < count; i++)
1299 		drm_syncobj_put(syncobjs[i]);
1300 	kvfree(syncobjs);
1301 }
1302 
1303 int
1304 drm_syncobj_wait_ioctl(struct drm_device *dev, void *data,
1305 		       struct drm_file *file_private)
1306 {
1307 	struct drm_syncobj_wait *args = data;
1308 	struct drm_syncobj **syncobjs;
1309 	unsigned int possible_flags;
1310 	ktime_t t, *tp = NULL;
1311 	int ret = 0;
1312 
1313 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ))
1314 		return -EOPNOTSUPP;
1315 
1316 	possible_flags = DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL |
1317 			 DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT |
1318 			 DRM_SYNCOBJ_WAIT_FLAGS_WAIT_DEADLINE;
1319 
1320 	if (args->flags & ~possible_flags)
1321 		return -EINVAL;
1322 
1323 	if (args->count_handles == 0)
1324 		return 0;
1325 
1326 	ret = drm_syncobj_array_find(file_private,
1327 				     u64_to_user_ptr(args->handles),
1328 				     args->count_handles,
1329 				     &syncobjs);
1330 	if (ret < 0)
1331 		return ret;
1332 
1333 	if (args->flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_DEADLINE) {
1334 		t = ns_to_ktime(args->deadline_nsec);
1335 		tp = &t;
1336 	}
1337 
1338 	ret = drm_syncobj_array_wait(dev, file_private,
1339 				     args, NULL, syncobjs, false, tp);
1340 
1341 	drm_syncobj_array_free(syncobjs, args->count_handles);
1342 
1343 	return ret;
1344 }
1345 
1346 int
1347 drm_syncobj_timeline_wait_ioctl(struct drm_device *dev, void *data,
1348 				struct drm_file *file_private)
1349 {
1350 	struct drm_syncobj_timeline_wait *args = data;
1351 	struct drm_syncobj **syncobjs;
1352 	unsigned int possible_flags;
1353 	ktime_t t, *tp = NULL;
1354 	int ret = 0;
1355 
1356 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ_TIMELINE))
1357 		return -EOPNOTSUPP;
1358 
1359 	possible_flags = DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL |
1360 			 DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT |
1361 			 DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE |
1362 			 DRM_SYNCOBJ_WAIT_FLAGS_WAIT_DEADLINE;
1363 
1364 	if (args->flags & ~possible_flags)
1365 		return -EINVAL;
1366 
1367 	if (args->count_handles == 0)
1368 		return 0;
1369 
1370 	ret = drm_syncobj_array_find(file_private,
1371 				     u64_to_user_ptr(args->handles),
1372 				     args->count_handles,
1373 				     &syncobjs);
1374 	if (ret < 0)
1375 		return ret;
1376 
1377 	if (args->flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_DEADLINE) {
1378 		t = ns_to_ktime(args->deadline_nsec);
1379 		tp = &t;
1380 	}
1381 
1382 	ret = drm_syncobj_array_wait(dev, file_private,
1383 				     NULL, args, syncobjs, true, tp);
1384 
1385 	drm_syncobj_array_free(syncobjs, args->count_handles);
1386 
1387 	return ret;
1388 }
1389 
1390 static void syncobj_eventfd_entry_fence_func(struct dma_fence *fence,
1391 					     struct dma_fence_cb *cb)
1392 {
1393 	struct syncobj_eventfd_entry *entry =
1394 		container_of(cb, struct syncobj_eventfd_entry, fence_cb);
1395 
1396 	eventfd_signal(entry->ev_fd_ctx);
1397 	syncobj_eventfd_entry_free(entry);
1398 }
1399 
1400 static void
1401 syncobj_eventfd_entry_func(struct drm_syncobj *syncobj,
1402 			   struct syncobj_eventfd_entry *entry)
1403 {
1404 	int ret;
1405 	struct dma_fence *fence;
1406 
1407 	/* This happens inside the syncobj lock */
1408 	fence = dma_fence_get(rcu_dereference_protected(syncobj->fence, 1));
1409 	if (!fence)
1410 		return;
1411 
1412 	ret = dma_fence_chain_find_seqno(&fence, entry->point);
1413 	if (ret != 0) {
1414 		/* The given seqno has not been submitted yet. */
1415 		dma_fence_put(fence);
1416 		return;
1417 	} else if (!fence) {
1418 		/* If dma_fence_chain_find_seqno returns 0 but sets the fence
1419 		 * to NULL, it implies that the given seqno is signaled and a
1420 		 * later seqno has already been submitted. Assign a stub fence
1421 		 * so that the eventfd still gets signaled below.
1422 		 */
1423 		fence = dma_fence_get_stub();
1424 	}
1425 
1426 	list_del_init(&entry->node);
1427 	entry->fence = fence;
1428 
1429 	if (entry->flags & DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE) {
1430 		eventfd_signal(entry->ev_fd_ctx);
1431 		syncobj_eventfd_entry_free(entry);
1432 	} else {
1433 		ret = dma_fence_add_callback(fence, &entry->fence_cb,
1434 					     syncobj_eventfd_entry_fence_func);
1435 		if (ret == -ENOENT) {
1436 			eventfd_signal(entry->ev_fd_ctx);
1437 			syncobj_eventfd_entry_free(entry);
1438 		}
1439 	}
1440 }
1441 
1442 int
1443 drm_syncobj_eventfd_ioctl(struct drm_device *dev, void *data,
1444 			  struct drm_file *file_private)
1445 {
1446 	struct drm_syncobj_eventfd *args = data;
1447 	struct drm_syncobj *syncobj;
1448 	struct eventfd_ctx *ev_fd_ctx;
1449 	struct syncobj_eventfd_entry *entry;
1450 	int ret;
1451 
1452 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ_TIMELINE))
1453 		return -EOPNOTSUPP;
1454 
1455 	if (args->flags & ~DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE)
1456 		return -EINVAL;
1457 
1458 	if (args->pad)
1459 		return -EINVAL;
1460 
1461 	syncobj = drm_syncobj_find(file_private, args->handle);
1462 	if (!syncobj)
1463 		return -ENOENT;
1464 
1465 	ev_fd_ctx = eventfd_ctx_fdget(args->fd);
1466 	if (IS_ERR(ev_fd_ctx)) {
1467 		ret = PTR_ERR(ev_fd_ctx);
1468 		goto err_fdget;
1469 	}
1470 
1471 	entry = kzalloc_obj(*entry);
1472 	if (!entry) {
1473 		ret = -ENOMEM;
1474 		goto err_kzalloc;
1475 	}
1476 	entry->syncobj = syncobj;
1477 	entry->ev_fd_ctx = ev_fd_ctx;
1478 	entry->point = args->point;
1479 	entry->flags = args->flags;
1480 
1481 	drm_syncobj_add_eventfd(syncobj, entry);
1482 	drm_syncobj_put(syncobj);
1483 
1484 	return 0;
1485 
1486 err_kzalloc:
1487 	eventfd_ctx_put(ev_fd_ctx);
1488 err_fdget:
1489 	drm_syncobj_put(syncobj);
1490 	return ret;
1491 }
1492 
1493 int
1494 drm_syncobj_reset_ioctl(struct drm_device *dev, void *data,
1495 			struct drm_file *file_private)
1496 {
1497 	struct drm_syncobj_array *args = data;
1498 	struct drm_syncobj **syncobjs;
1499 	uint32_t i;
1500 	int ret;
1501 
1502 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ))
1503 		return -EOPNOTSUPP;
1504 
1505 	if (args->pad != 0)
1506 		return -EINVAL;
1507 
1508 	if (args->count_handles == 0)
1509 		return -EINVAL;
1510 
1511 	ret = drm_syncobj_array_find(file_private,
1512 				     u64_to_user_ptr(args->handles),
1513 				     args->count_handles,
1514 				     &syncobjs);
1515 	if (ret < 0)
1516 		return ret;
1517 
1518 	for (i = 0; i < args->count_handles; i++)
1519 		drm_syncobj_replace_fence(syncobjs[i], NULL);
1520 
1521 	drm_syncobj_array_free(syncobjs, args->count_handles);
1522 
1523 	return 0;
1524 }
1525 
1526 int
1527 drm_syncobj_signal_ioctl(struct drm_device *dev, void *data,
1528 			 struct drm_file *file_private)
1529 {
1530 	struct drm_syncobj_array *args = data;
1531 	struct drm_syncobj **syncobjs;
1532 	uint32_t i;
1533 	int ret;
1534 
1535 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ))
1536 		return -EOPNOTSUPP;
1537 
1538 	if (args->pad != 0)
1539 		return -EINVAL;
1540 
1541 	if (args->count_handles == 0)
1542 		return -EINVAL;
1543 
1544 	ret = drm_syncobj_array_find(file_private,
1545 				     u64_to_user_ptr(args->handles),
1546 				     args->count_handles,
1547 				     &syncobjs);
1548 	if (ret < 0)
1549 		return ret;
1550 
1551 	for (i = 0; i < args->count_handles; i++) {
1552 		ret = drm_syncobj_assign_null_handle(syncobjs[i]);
1553 		if (ret < 0)
1554 			break;
1555 	}
1556 
1557 	drm_syncobj_array_free(syncobjs, args->count_handles);
1558 
1559 	return ret;
1560 }
1561 
1562 int
1563 drm_syncobj_timeline_signal_ioctl(struct drm_device *dev, void *data,
1564 				  struct drm_file *file_private)
1565 {
1566 	struct drm_syncobj_timeline_array *args = data;
1567 	struct drm_syncobj **syncobjs;
1568 	struct dma_fence_chain **chains;
1569 	uint64_t *points;
1570 	uint32_t i, j;
1571 	int ret;
1572 
1573 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ_TIMELINE))
1574 		return -EOPNOTSUPP;
1575 
1576 	if (args->flags != 0)
1577 		return -EINVAL;
1578 
1579 	if (args->count_handles == 0)
1580 		return -EINVAL;
1581 
1582 	ret = drm_syncobj_array_find(file_private,
1583 				     u64_to_user_ptr(args->handles),
1584 				     args->count_handles,
1585 				     &syncobjs);
1586 	if (ret < 0)
1587 		return ret;
1588 
1589 	points = kvmalloc_objs(*points, args->count_handles);
1590 	if (!points) {
1591 		ret = -ENOMEM;
1592 		goto out;
1593 	}
1594 	if (!u64_to_user_ptr(args->points)) {
1595 		memset(points, 0, args->count_handles * sizeof(uint64_t));
1596 	} else if (copy_from_user(points, u64_to_user_ptr(args->points),
1597 				  sizeof(uint64_t) * args->count_handles)) {
1598 		ret = -EFAULT;
1599 		goto err_points;
1600 	}
1601 
1602 	chains = kvmalloc_objs(*chains, args->count_handles);
1603 	if (!chains) {
1604 		ret = -ENOMEM;
1605 		goto err_points;
1606 	}
1607 	for (i = 0; i < args->count_handles; i++) {
1608 		chains[i] = dma_fence_chain_alloc();
1609 		if (!chains[i]) {
1610 			for (j = 0; j < i; j++)
1611 				dma_fence_chain_free(chains[j]);
1612 			ret = -ENOMEM;
1613 			goto err_chains;
1614 		}
1615 	}
1616 
1617 	for (i = 0; i < args->count_handles; i++) {
1618 		struct dma_fence *fence = dma_fence_get_stub();
1619 
1620 		drm_syncobj_add_point(syncobjs[i], chains[i],
1621 				      fence, points[i]);
1622 		dma_fence_put(fence);
1623 	}
1624 err_chains:
1625 	kvfree(chains);
1626 err_points:
1627 	kvfree(points);
1628 out:
1629 	drm_syncobj_array_free(syncobjs, args->count_handles);
1630 
1631 	return ret;
1632 }
1633 
1634 int drm_syncobj_query_ioctl(struct drm_device *dev, void *data,
1635 			    struct drm_file *file_private)
1636 {
1637 	struct drm_syncobj_timeline_array *args = data;
1638 	struct drm_syncobj **syncobjs;
1639 	uint64_t __user *points = u64_to_user_ptr(args->points);
1640 	uint32_t i;
1641 	int ret;
1642 
1643 	if (!drm_core_check_feature(dev, DRIVER_SYNCOBJ_TIMELINE))
1644 		return -EOPNOTSUPP;
1645 
1646 	if (args->flags & ~DRM_SYNCOBJ_QUERY_FLAGS_LAST_SUBMITTED)
1647 		return -EINVAL;
1648 
1649 	if (args->count_handles == 0)
1650 		return -EINVAL;
1651 
1652 	ret = drm_syncobj_array_find(file_private,
1653 				     u64_to_user_ptr(args->handles),
1654 				     args->count_handles,
1655 				     &syncobjs);
1656 	if (ret < 0)
1657 		return ret;
1658 
1659 	for (i = 0; i < args->count_handles; i++) {
1660 		struct dma_fence_chain *chain;
1661 		struct dma_fence *fence;
1662 		uint64_t point;
1663 
1664 		fence = drm_syncobj_fence_get(syncobjs[i]);
1665 		chain = to_dma_fence_chain(fence);
1666 		if (chain) {
1667 			struct dma_fence *iter, *last_signaled =
1668 				dma_fence_get(fence);
1669 
1670 			if (args->flags &
1671 			    DRM_SYNCOBJ_QUERY_FLAGS_LAST_SUBMITTED) {
1672 				point = fence->seqno;
1673 			} else {
1674 				dma_fence_chain_for_each(iter, fence) {
1675 					if (iter->context != fence->context) {
1676 						dma_fence_put(iter);
1677 						/* It is most likely that timeline has
1678 						* unorder points. */
1679 						break;
1680 					}
1681 					dma_fence_put(last_signaled);
1682 					last_signaled = dma_fence_get(iter);
1683 				}
1684 				point = dma_fence_is_signaled(last_signaled) ?
1685 					last_signaled->seqno :
1686 					to_dma_fence_chain(last_signaled)->prev_seqno;
1687 			}
1688 			dma_fence_put(last_signaled);
1689 		} else {
1690 			point = 0;
1691 		}
1692 		dma_fence_put(fence);
1693 		ret = copy_to_user(&points[i], &point, sizeof(uint64_t));
1694 		ret = ret ? -EFAULT : 0;
1695 		if (ret)
1696 			break;
1697 	}
1698 	drm_syncobj_array_free(syncobjs, args->count_handles);
1699 
1700 	return ret;
1701 }
1702