xref: /openbmc/linux/drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c (revision e5f586c763a079349398e2b0c7c271386193ac34)
1 /*
2  * Copyright 2008 Jerome Glisse.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *    Jerome Glisse <glisse@freedesktop.org>
26  */
27 #include <linux/pagemap.h>
28 #include <drm/drmP.h>
29 #include <drm/amdgpu_drm.h>
30 #include "amdgpu.h"
31 #include "amdgpu_trace.h"
32 
33 int amdgpu_cs_get_ring(struct amdgpu_device *adev, u32 ip_type,
34 		       u32 ip_instance, u32 ring,
35 		       struct amdgpu_ring **out_ring)
36 {
37 	/* Right now all IPs have only one instance - multiple rings. */
38 	if (ip_instance != 0) {
39 		DRM_ERROR("invalid ip instance: %d\n", ip_instance);
40 		return -EINVAL;
41 	}
42 
43 	switch (ip_type) {
44 	default:
45 		DRM_ERROR("unknown ip type: %d\n", ip_type);
46 		return -EINVAL;
47 	case AMDGPU_HW_IP_GFX:
48 		if (ring < adev->gfx.num_gfx_rings) {
49 			*out_ring = &adev->gfx.gfx_ring[ring];
50 		} else {
51 			DRM_ERROR("only %d gfx rings are supported now\n",
52 				  adev->gfx.num_gfx_rings);
53 			return -EINVAL;
54 		}
55 		break;
56 	case AMDGPU_HW_IP_COMPUTE:
57 		if (ring < adev->gfx.num_compute_rings) {
58 			*out_ring = &adev->gfx.compute_ring[ring];
59 		} else {
60 			DRM_ERROR("only %d compute rings are supported now\n",
61 				  adev->gfx.num_compute_rings);
62 			return -EINVAL;
63 		}
64 		break;
65 	case AMDGPU_HW_IP_DMA:
66 		if (ring < adev->sdma.num_instances) {
67 			*out_ring = &adev->sdma.instance[ring].ring;
68 		} else {
69 			DRM_ERROR("only %d SDMA rings are supported\n",
70 				  adev->sdma.num_instances);
71 			return -EINVAL;
72 		}
73 		break;
74 	case AMDGPU_HW_IP_UVD:
75 		*out_ring = &adev->uvd.ring;
76 		break;
77 	case AMDGPU_HW_IP_VCE:
78 		if (ring < adev->vce.num_rings){
79 			*out_ring = &adev->vce.ring[ring];
80 		} else {
81 			DRM_ERROR("only %d VCE rings are supported\n", adev->vce.num_rings);
82 			return -EINVAL;
83 		}
84 		break;
85 	case AMDGPU_HW_IP_UVD_ENC:
86 		if (ring < adev->uvd.num_enc_rings){
87 			*out_ring = &adev->uvd.ring_enc[ring];
88 		} else {
89 			DRM_ERROR("only %d UVD ENC rings are supported\n",
90 				adev->uvd.num_enc_rings);
91 			return -EINVAL;
92 		}
93 		break;
94 	}
95 
96 	if (!(*out_ring && (*out_ring)->adev)) {
97 		DRM_ERROR("Ring %d is not initialized on IP %d\n",
98 			  ring, ip_type);
99 		return -EINVAL;
100 	}
101 
102 	return 0;
103 }
104 
105 static int amdgpu_cs_user_fence_chunk(struct amdgpu_cs_parser *p,
106 				      struct drm_amdgpu_cs_chunk_fence *data,
107 				      uint32_t *offset)
108 {
109 	struct drm_gem_object *gobj;
110 	unsigned long size;
111 
112 	gobj = drm_gem_object_lookup(p->filp, data->handle);
113 	if (gobj == NULL)
114 		return -EINVAL;
115 
116 	p->uf_entry.robj = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj));
117 	p->uf_entry.priority = 0;
118 	p->uf_entry.tv.bo = &p->uf_entry.robj->tbo;
119 	p->uf_entry.tv.shared = true;
120 	p->uf_entry.user_pages = NULL;
121 
122 	size = amdgpu_bo_size(p->uf_entry.robj);
123 	if (size != PAGE_SIZE || (data->offset + 8) > size)
124 		return -EINVAL;
125 
126 	*offset = data->offset;
127 
128 	drm_gem_object_unreference_unlocked(gobj);
129 
130 	if (amdgpu_ttm_tt_get_usermm(p->uf_entry.robj->tbo.ttm)) {
131 		amdgpu_bo_unref(&p->uf_entry.robj);
132 		return -EINVAL;
133 	}
134 
135 	return 0;
136 }
137 
138 int amdgpu_cs_parser_init(struct amdgpu_cs_parser *p, void *data)
139 {
140 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
141 	struct amdgpu_vm *vm = &fpriv->vm;
142 	union drm_amdgpu_cs *cs = data;
143 	uint64_t *chunk_array_user;
144 	uint64_t *chunk_array;
145 	unsigned size, num_ibs = 0;
146 	uint32_t uf_offset = 0;
147 	int i;
148 	int ret;
149 
150 	if (cs->in.num_chunks == 0)
151 		return 0;
152 
153 	chunk_array = kmalloc_array(cs->in.num_chunks, sizeof(uint64_t), GFP_KERNEL);
154 	if (!chunk_array)
155 		return -ENOMEM;
156 
157 	p->ctx = amdgpu_ctx_get(fpriv, cs->in.ctx_id);
158 	if (!p->ctx) {
159 		ret = -EINVAL;
160 		goto free_chunk;
161 	}
162 
163 	/* get chunks */
164 	chunk_array_user = (uint64_t __user *)(unsigned long)(cs->in.chunks);
165 	if (copy_from_user(chunk_array, chunk_array_user,
166 			   sizeof(uint64_t)*cs->in.num_chunks)) {
167 		ret = -EFAULT;
168 		goto put_ctx;
169 	}
170 
171 	p->nchunks = cs->in.num_chunks;
172 	p->chunks = kmalloc_array(p->nchunks, sizeof(struct amdgpu_cs_chunk),
173 			    GFP_KERNEL);
174 	if (!p->chunks) {
175 		ret = -ENOMEM;
176 		goto put_ctx;
177 	}
178 
179 	for (i = 0; i < p->nchunks; i++) {
180 		struct drm_amdgpu_cs_chunk __user **chunk_ptr = NULL;
181 		struct drm_amdgpu_cs_chunk user_chunk;
182 		uint32_t __user *cdata;
183 
184 		chunk_ptr = (void __user *)(unsigned long)chunk_array[i];
185 		if (copy_from_user(&user_chunk, chunk_ptr,
186 				       sizeof(struct drm_amdgpu_cs_chunk))) {
187 			ret = -EFAULT;
188 			i--;
189 			goto free_partial_kdata;
190 		}
191 		p->chunks[i].chunk_id = user_chunk.chunk_id;
192 		p->chunks[i].length_dw = user_chunk.length_dw;
193 
194 		size = p->chunks[i].length_dw;
195 		cdata = (void __user *)(unsigned long)user_chunk.chunk_data;
196 
197 		p->chunks[i].kdata = drm_malloc_ab(size, sizeof(uint32_t));
198 		if (p->chunks[i].kdata == NULL) {
199 			ret = -ENOMEM;
200 			i--;
201 			goto free_partial_kdata;
202 		}
203 		size *= sizeof(uint32_t);
204 		if (copy_from_user(p->chunks[i].kdata, cdata, size)) {
205 			ret = -EFAULT;
206 			goto free_partial_kdata;
207 		}
208 
209 		switch (p->chunks[i].chunk_id) {
210 		case AMDGPU_CHUNK_ID_IB:
211 			++num_ibs;
212 			break;
213 
214 		case AMDGPU_CHUNK_ID_FENCE:
215 			size = sizeof(struct drm_amdgpu_cs_chunk_fence);
216 			if (p->chunks[i].length_dw * sizeof(uint32_t) < size) {
217 				ret = -EINVAL;
218 				goto free_partial_kdata;
219 			}
220 
221 			ret = amdgpu_cs_user_fence_chunk(p, p->chunks[i].kdata,
222 							 &uf_offset);
223 			if (ret)
224 				goto free_partial_kdata;
225 
226 			break;
227 
228 		case AMDGPU_CHUNK_ID_DEPENDENCIES:
229 			break;
230 
231 		default:
232 			ret = -EINVAL;
233 			goto free_partial_kdata;
234 		}
235 	}
236 
237 	ret = amdgpu_job_alloc(p->adev, num_ibs, &p->job, vm);
238 	if (ret)
239 		goto free_all_kdata;
240 
241 	if (p->uf_entry.robj)
242 		p->job->uf_addr = uf_offset;
243 	kfree(chunk_array);
244 	return 0;
245 
246 free_all_kdata:
247 	i = p->nchunks - 1;
248 free_partial_kdata:
249 	for (; i >= 0; i--)
250 		drm_free_large(p->chunks[i].kdata);
251 	kfree(p->chunks);
252 	p->chunks = NULL;
253 	p->nchunks = 0;
254 put_ctx:
255 	amdgpu_ctx_put(p->ctx);
256 free_chunk:
257 	kfree(chunk_array);
258 
259 	return ret;
260 }
261 
262 /* Convert microseconds to bytes. */
263 static u64 us_to_bytes(struct amdgpu_device *adev, s64 us)
264 {
265 	if (us <= 0 || !adev->mm_stats.log2_max_MBps)
266 		return 0;
267 
268 	/* Since accum_us is incremented by a million per second, just
269 	 * multiply it by the number of MB/s to get the number of bytes.
270 	 */
271 	return us << adev->mm_stats.log2_max_MBps;
272 }
273 
274 static s64 bytes_to_us(struct amdgpu_device *adev, u64 bytes)
275 {
276 	if (!adev->mm_stats.log2_max_MBps)
277 		return 0;
278 
279 	return bytes >> adev->mm_stats.log2_max_MBps;
280 }
281 
282 /* Returns how many bytes TTM can move right now. If no bytes can be moved,
283  * it returns 0. If it returns non-zero, it's OK to move at least one buffer,
284  * which means it can go over the threshold once. If that happens, the driver
285  * will be in debt and no other buffer migrations can be done until that debt
286  * is repaid.
287  *
288  * This approach allows moving a buffer of any size (it's important to allow
289  * that).
290  *
291  * The currency is simply time in microseconds and it increases as the clock
292  * ticks. The accumulated microseconds (us) are converted to bytes and
293  * returned.
294  */
295 static u64 amdgpu_cs_get_threshold_for_moves(struct amdgpu_device *adev)
296 {
297 	s64 time_us, increment_us;
298 	u64 max_bytes;
299 	u64 free_vram, total_vram, used_vram;
300 
301 	/* Allow a maximum of 200 accumulated ms. This is basically per-IB
302 	 * throttling.
303 	 *
304 	 * It means that in order to get full max MBps, at least 5 IBs per
305 	 * second must be submitted and not more than 200ms apart from each
306 	 * other.
307 	 */
308 	const s64 us_upper_bound = 200000;
309 
310 	if (!adev->mm_stats.log2_max_MBps)
311 		return 0;
312 
313 	total_vram = adev->mc.real_vram_size - adev->vram_pin_size;
314 	used_vram = atomic64_read(&adev->vram_usage);
315 	free_vram = used_vram >= total_vram ? 0 : total_vram - used_vram;
316 
317 	spin_lock(&adev->mm_stats.lock);
318 
319 	/* Increase the amount of accumulated us. */
320 	time_us = ktime_to_us(ktime_get());
321 	increment_us = time_us - adev->mm_stats.last_update_us;
322 	adev->mm_stats.last_update_us = time_us;
323 	adev->mm_stats.accum_us = min(adev->mm_stats.accum_us + increment_us,
324                                       us_upper_bound);
325 
326 	/* This prevents the short period of low performance when the VRAM
327 	 * usage is low and the driver is in debt or doesn't have enough
328 	 * accumulated us to fill VRAM quickly.
329 	 *
330 	 * The situation can occur in these cases:
331 	 * - a lot of VRAM is freed by userspace
332 	 * - the presence of a big buffer causes a lot of evictions
333 	 *   (solution: split buffers into smaller ones)
334 	 *
335 	 * If 128 MB or 1/8th of VRAM is free, start filling it now by setting
336 	 * accum_us to a positive number.
337 	 */
338 	if (free_vram >= 128 * 1024 * 1024 || free_vram >= total_vram / 8) {
339 		s64 min_us;
340 
341 		/* Be more aggresive on dGPUs. Try to fill a portion of free
342 		 * VRAM now.
343 		 */
344 		if (!(adev->flags & AMD_IS_APU))
345 			min_us = bytes_to_us(adev, free_vram / 4);
346 		else
347 			min_us = 0; /* Reset accum_us on APUs. */
348 
349 		adev->mm_stats.accum_us = max(min_us, adev->mm_stats.accum_us);
350 	}
351 
352 	/* This returns 0 if the driver is in debt to disallow (optional)
353 	 * buffer moves.
354 	 */
355 	max_bytes = us_to_bytes(adev, adev->mm_stats.accum_us);
356 
357 	spin_unlock(&adev->mm_stats.lock);
358 	return max_bytes;
359 }
360 
361 /* Report how many bytes have really been moved for the last command
362  * submission. This can result in a debt that can stop buffer migrations
363  * temporarily.
364  */
365 void amdgpu_cs_report_moved_bytes(struct amdgpu_device *adev, u64 num_bytes)
366 {
367 	spin_lock(&adev->mm_stats.lock);
368 	adev->mm_stats.accum_us -= bytes_to_us(adev, num_bytes);
369 	spin_unlock(&adev->mm_stats.lock);
370 }
371 
372 static int amdgpu_cs_bo_validate(struct amdgpu_cs_parser *p,
373 				 struct amdgpu_bo *bo)
374 {
375 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
376 	u64 initial_bytes_moved;
377 	uint32_t domain;
378 	int r;
379 
380 	if (bo->pin_count)
381 		return 0;
382 
383 	/* Don't move this buffer if we have depleted our allowance
384 	 * to move it. Don't move anything if the threshold is zero.
385 	 */
386 	if (p->bytes_moved < p->bytes_moved_threshold)
387 		domain = bo->prefered_domains;
388 	else
389 		domain = bo->allowed_domains;
390 
391 retry:
392 	amdgpu_ttm_placement_from_domain(bo, domain);
393 	initial_bytes_moved = atomic64_read(&adev->num_bytes_moved);
394 	r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
395 	p->bytes_moved += atomic64_read(&adev->num_bytes_moved) -
396 		initial_bytes_moved;
397 
398 	if (unlikely(r == -ENOMEM) && domain != bo->allowed_domains) {
399 		domain = bo->allowed_domains;
400 		goto retry;
401 	}
402 
403 	return r;
404 }
405 
406 /* Last resort, try to evict something from the current working set */
407 static bool amdgpu_cs_try_evict(struct amdgpu_cs_parser *p,
408 				struct amdgpu_bo *validated)
409 {
410 	uint32_t domain = validated->allowed_domains;
411 	int r;
412 
413 	if (!p->evictable)
414 		return false;
415 
416 	for (;&p->evictable->tv.head != &p->validated;
417 	     p->evictable = list_prev_entry(p->evictable, tv.head)) {
418 
419 		struct amdgpu_bo_list_entry *candidate = p->evictable;
420 		struct amdgpu_bo *bo = candidate->robj;
421 		struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
422 		u64 initial_bytes_moved;
423 		uint32_t other;
424 
425 		/* If we reached our current BO we can forget it */
426 		if (candidate->robj == validated)
427 			break;
428 
429 		other = amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type);
430 
431 		/* Check if this BO is in one of the domains we need space for */
432 		if (!(other & domain))
433 			continue;
434 
435 		/* Check if we can move this BO somewhere else */
436 		other = bo->allowed_domains & ~domain;
437 		if (!other)
438 			continue;
439 
440 		/* Good we can try to move this BO somewhere else */
441 		amdgpu_ttm_placement_from_domain(bo, other);
442 		initial_bytes_moved = atomic64_read(&adev->num_bytes_moved);
443 		r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
444 		p->bytes_moved += atomic64_read(&adev->num_bytes_moved) -
445 			initial_bytes_moved;
446 
447 		if (unlikely(r))
448 			break;
449 
450 		p->evictable = list_prev_entry(p->evictable, tv.head);
451 		list_move(&candidate->tv.head, &p->validated);
452 
453 		return true;
454 	}
455 
456 	return false;
457 }
458 
459 static int amdgpu_cs_validate(void *param, struct amdgpu_bo *bo)
460 {
461 	struct amdgpu_cs_parser *p = param;
462 	int r;
463 
464 	do {
465 		r = amdgpu_cs_bo_validate(p, bo);
466 	} while (r == -ENOMEM && amdgpu_cs_try_evict(p, bo));
467 	if (r)
468 		return r;
469 
470 	if (bo->shadow)
471 		r = amdgpu_cs_bo_validate(p, bo->shadow);
472 
473 	return r;
474 }
475 
476 static int amdgpu_cs_list_validate(struct amdgpu_cs_parser *p,
477 			    struct list_head *validated)
478 {
479 	struct amdgpu_bo_list_entry *lobj;
480 	int r;
481 
482 	list_for_each_entry(lobj, validated, tv.head) {
483 		struct amdgpu_bo *bo = lobj->robj;
484 		bool binding_userptr = false;
485 		struct mm_struct *usermm;
486 
487 		usermm = amdgpu_ttm_tt_get_usermm(bo->tbo.ttm);
488 		if (usermm && usermm != current->mm)
489 			return -EPERM;
490 
491 		/* Check if we have user pages and nobody bound the BO already */
492 		if (lobj->user_pages && bo->tbo.ttm->state != tt_bound) {
493 			size_t size = sizeof(struct page *);
494 
495 			size *= bo->tbo.ttm->num_pages;
496 			memcpy(bo->tbo.ttm->pages, lobj->user_pages, size);
497 			binding_userptr = true;
498 		}
499 
500 		if (p->evictable == lobj)
501 			p->evictable = NULL;
502 
503 		r = amdgpu_cs_validate(p, bo);
504 		if (r)
505 			return r;
506 
507 		if (binding_userptr) {
508 			drm_free_large(lobj->user_pages);
509 			lobj->user_pages = NULL;
510 		}
511 	}
512 	return 0;
513 }
514 
515 static int amdgpu_cs_parser_bos(struct amdgpu_cs_parser *p,
516 				union drm_amdgpu_cs *cs)
517 {
518 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
519 	struct amdgpu_bo_list_entry *e;
520 	struct list_head duplicates;
521 	bool need_mmap_lock = false;
522 	unsigned i, tries = 10;
523 	int r;
524 
525 	INIT_LIST_HEAD(&p->validated);
526 
527 	p->bo_list = amdgpu_bo_list_get(fpriv, cs->in.bo_list_handle);
528 	if (p->bo_list) {
529 		need_mmap_lock = p->bo_list->first_userptr !=
530 			p->bo_list->num_entries;
531 		amdgpu_bo_list_get_list(p->bo_list, &p->validated);
532 	}
533 
534 	INIT_LIST_HEAD(&duplicates);
535 	amdgpu_vm_get_pd_bo(&fpriv->vm, &p->validated, &p->vm_pd);
536 
537 	if (p->uf_entry.robj)
538 		list_add(&p->uf_entry.tv.head, &p->validated);
539 
540 	if (need_mmap_lock)
541 		down_read(&current->mm->mmap_sem);
542 
543 	while (1) {
544 		struct list_head need_pages;
545 		unsigned i;
546 
547 		r = ttm_eu_reserve_buffers(&p->ticket, &p->validated, true,
548 					   &duplicates);
549 		if (unlikely(r != 0)) {
550 			if (r != -ERESTARTSYS)
551 				DRM_ERROR("ttm_eu_reserve_buffers failed.\n");
552 			goto error_free_pages;
553 		}
554 
555 		/* Without a BO list we don't have userptr BOs */
556 		if (!p->bo_list)
557 			break;
558 
559 		INIT_LIST_HEAD(&need_pages);
560 		for (i = p->bo_list->first_userptr;
561 		     i < p->bo_list->num_entries; ++i) {
562 
563 			e = &p->bo_list->array[i];
564 
565 			if (amdgpu_ttm_tt_userptr_invalidated(e->robj->tbo.ttm,
566 				 &e->user_invalidated) && e->user_pages) {
567 
568 				/* We acquired a page array, but somebody
569 				 * invalidated it. Free it an try again
570 				 */
571 				release_pages(e->user_pages,
572 					      e->robj->tbo.ttm->num_pages,
573 					      false);
574 				drm_free_large(e->user_pages);
575 				e->user_pages = NULL;
576 			}
577 
578 			if (e->robj->tbo.ttm->state != tt_bound &&
579 			    !e->user_pages) {
580 				list_del(&e->tv.head);
581 				list_add(&e->tv.head, &need_pages);
582 
583 				amdgpu_bo_unreserve(e->robj);
584 			}
585 		}
586 
587 		if (list_empty(&need_pages))
588 			break;
589 
590 		/* Unreserve everything again. */
591 		ttm_eu_backoff_reservation(&p->ticket, &p->validated);
592 
593 		/* We tried too many times, just abort */
594 		if (!--tries) {
595 			r = -EDEADLK;
596 			DRM_ERROR("deadlock in %s\n", __func__);
597 			goto error_free_pages;
598 		}
599 
600 		/* Fill the page arrays for all useptrs. */
601 		list_for_each_entry(e, &need_pages, tv.head) {
602 			struct ttm_tt *ttm = e->robj->tbo.ttm;
603 
604 			e->user_pages = drm_calloc_large(ttm->num_pages,
605 							 sizeof(struct page*));
606 			if (!e->user_pages) {
607 				r = -ENOMEM;
608 				DRM_ERROR("calloc failure in %s\n", __func__);
609 				goto error_free_pages;
610 			}
611 
612 			r = amdgpu_ttm_tt_get_user_pages(ttm, e->user_pages);
613 			if (r) {
614 				DRM_ERROR("amdgpu_ttm_tt_get_user_pages failed.\n");
615 				drm_free_large(e->user_pages);
616 				e->user_pages = NULL;
617 				goto error_free_pages;
618 			}
619 		}
620 
621 		/* And try again. */
622 		list_splice(&need_pages, &p->validated);
623 	}
624 
625 	p->bytes_moved_threshold = amdgpu_cs_get_threshold_for_moves(p->adev);
626 	p->bytes_moved = 0;
627 	p->evictable = list_last_entry(&p->validated,
628 				       struct amdgpu_bo_list_entry,
629 				       tv.head);
630 
631 	r = amdgpu_vm_validate_pt_bos(p->adev, &fpriv->vm,
632 				      amdgpu_cs_validate, p);
633 	if (r) {
634 		DRM_ERROR("amdgpu_vm_validate_pt_bos() failed.\n");
635 		goto error_validate;
636 	}
637 
638 	r = amdgpu_cs_list_validate(p, &duplicates);
639 	if (r) {
640 		DRM_ERROR("amdgpu_cs_list_validate(duplicates) failed.\n");
641 		goto error_validate;
642 	}
643 
644 	r = amdgpu_cs_list_validate(p, &p->validated);
645 	if (r) {
646 		DRM_ERROR("amdgpu_cs_list_validate(validated) failed.\n");
647 		goto error_validate;
648 	}
649 
650 	amdgpu_cs_report_moved_bytes(p->adev, p->bytes_moved);
651 
652 	fpriv->vm.last_eviction_counter =
653 		atomic64_read(&p->adev->num_evictions);
654 
655 	if (p->bo_list) {
656 		struct amdgpu_bo *gds = p->bo_list->gds_obj;
657 		struct amdgpu_bo *gws = p->bo_list->gws_obj;
658 		struct amdgpu_bo *oa = p->bo_list->oa_obj;
659 		struct amdgpu_vm *vm = &fpriv->vm;
660 		unsigned i;
661 
662 		for (i = 0; i < p->bo_list->num_entries; i++) {
663 			struct amdgpu_bo *bo = p->bo_list->array[i].robj;
664 
665 			p->bo_list->array[i].bo_va = amdgpu_vm_bo_find(vm, bo);
666 		}
667 
668 		if (gds) {
669 			p->job->gds_base = amdgpu_bo_gpu_offset(gds);
670 			p->job->gds_size = amdgpu_bo_size(gds);
671 		}
672 		if (gws) {
673 			p->job->gws_base = amdgpu_bo_gpu_offset(gws);
674 			p->job->gws_size = amdgpu_bo_size(gws);
675 		}
676 		if (oa) {
677 			p->job->oa_base = amdgpu_bo_gpu_offset(oa);
678 			p->job->oa_size = amdgpu_bo_size(oa);
679 		}
680 	}
681 
682 	if (!r && p->uf_entry.robj) {
683 		struct amdgpu_bo *uf = p->uf_entry.robj;
684 
685 		r = amdgpu_ttm_bind(&uf->tbo, &uf->tbo.mem);
686 		p->job->uf_addr += amdgpu_bo_gpu_offset(uf);
687 	}
688 
689 error_validate:
690 	if (r) {
691 		amdgpu_vm_move_pt_bos_in_lru(p->adev, &fpriv->vm);
692 		ttm_eu_backoff_reservation(&p->ticket, &p->validated);
693 	}
694 
695 error_free_pages:
696 
697 	if (need_mmap_lock)
698 		up_read(&current->mm->mmap_sem);
699 
700 	if (p->bo_list) {
701 		for (i = p->bo_list->first_userptr;
702 		     i < p->bo_list->num_entries; ++i) {
703 			e = &p->bo_list->array[i];
704 
705 			if (!e->user_pages)
706 				continue;
707 
708 			release_pages(e->user_pages,
709 				      e->robj->tbo.ttm->num_pages,
710 				      false);
711 			drm_free_large(e->user_pages);
712 		}
713 	}
714 
715 	return r;
716 }
717 
718 static int amdgpu_cs_sync_rings(struct amdgpu_cs_parser *p)
719 {
720 	struct amdgpu_bo_list_entry *e;
721 	int r;
722 
723 	list_for_each_entry(e, &p->validated, tv.head) {
724 		struct reservation_object *resv = e->robj->tbo.resv;
725 		r = amdgpu_sync_resv(p->adev, &p->job->sync, resv, p->filp);
726 
727 		if (r)
728 			return r;
729 	}
730 	return 0;
731 }
732 
733 /**
734  * cs_parser_fini() - clean parser states
735  * @parser:	parser structure holding parsing context.
736  * @error:	error number
737  *
738  * If error is set than unvalidate buffer, otherwise just free memory
739  * used by parsing context.
740  **/
741 static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser, int error, bool backoff)
742 {
743 	struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
744 	unsigned i;
745 
746 	if (!error) {
747 		amdgpu_vm_move_pt_bos_in_lru(parser->adev, &fpriv->vm);
748 
749 		ttm_eu_fence_buffer_objects(&parser->ticket,
750 					    &parser->validated,
751 					    parser->fence);
752 	} else if (backoff) {
753 		ttm_eu_backoff_reservation(&parser->ticket,
754 					   &parser->validated);
755 	}
756 	dma_fence_put(parser->fence);
757 
758 	if (parser->ctx)
759 		amdgpu_ctx_put(parser->ctx);
760 	if (parser->bo_list)
761 		amdgpu_bo_list_put(parser->bo_list);
762 
763 	for (i = 0; i < parser->nchunks; i++)
764 		drm_free_large(parser->chunks[i].kdata);
765 	kfree(parser->chunks);
766 	if (parser->job)
767 		amdgpu_job_free(parser->job);
768 	amdgpu_bo_unref(&parser->uf_entry.robj);
769 }
770 
771 static int amdgpu_bo_vm_update_pte(struct amdgpu_cs_parser *p)
772 {
773 	struct amdgpu_device *adev = p->adev;
774 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
775 	struct amdgpu_vm *vm = &fpriv->vm;
776 	struct amdgpu_bo_va *bo_va;
777 	struct amdgpu_bo *bo;
778 	int i, r;
779 
780 	r = amdgpu_vm_update_directories(adev, vm);
781 	if (r)
782 		return r;
783 
784 	r = amdgpu_sync_fence(adev, &p->job->sync, vm->last_dir_update);
785 	if (r)
786 		return r;
787 
788 	r = amdgpu_vm_clear_freed(adev, vm, NULL);
789 	if (r)
790 		return r;
791 
792 	r = amdgpu_vm_bo_update(adev, fpriv->prt_va, false);
793 	if (r)
794 		return r;
795 
796 	r = amdgpu_sync_fence(adev, &p->job->sync,
797 			      fpriv->prt_va->last_pt_update);
798 	if (r)
799 		return r;
800 
801 	if (amdgpu_sriov_vf(adev)) {
802 		struct dma_fence *f;
803 		bo_va = vm->csa_bo_va;
804 		BUG_ON(!bo_va);
805 		r = amdgpu_vm_bo_update(adev, bo_va, false);
806 		if (r)
807 			return r;
808 
809 		f = bo_va->last_pt_update;
810 		r = amdgpu_sync_fence(adev, &p->job->sync, f);
811 		if (r)
812 			return r;
813 	}
814 
815 	if (p->bo_list) {
816 		for (i = 0; i < p->bo_list->num_entries; i++) {
817 			struct dma_fence *f;
818 
819 			/* ignore duplicates */
820 			bo = p->bo_list->array[i].robj;
821 			if (!bo)
822 				continue;
823 
824 			bo_va = p->bo_list->array[i].bo_va;
825 			if (bo_va == NULL)
826 				continue;
827 
828 			r = amdgpu_vm_bo_update(adev, bo_va, false);
829 			if (r)
830 				return r;
831 
832 			f = bo_va->last_pt_update;
833 			r = amdgpu_sync_fence(adev, &p->job->sync, f);
834 			if (r)
835 				return r;
836 		}
837 
838 	}
839 
840 	r = amdgpu_vm_clear_invalids(adev, vm, &p->job->sync);
841 
842 	if (amdgpu_vm_debug && p->bo_list) {
843 		/* Invalidate all BOs to test for userspace bugs */
844 		for (i = 0; i < p->bo_list->num_entries; i++) {
845 			/* ignore duplicates */
846 			bo = p->bo_list->array[i].robj;
847 			if (!bo)
848 				continue;
849 
850 			amdgpu_vm_bo_invalidate(adev, bo);
851 		}
852 	}
853 
854 	return r;
855 }
856 
857 static int amdgpu_cs_ib_vm_chunk(struct amdgpu_device *adev,
858 				 struct amdgpu_cs_parser *p)
859 {
860 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
861 	struct amdgpu_vm *vm = &fpriv->vm;
862 	struct amdgpu_ring *ring = p->job->ring;
863 	int i, r;
864 
865 	/* Only for UVD/VCE VM emulation */
866 	if (ring->funcs->parse_cs) {
867 		for (i = 0; i < p->job->num_ibs; i++) {
868 			r = amdgpu_ring_parse_cs(ring, p, i);
869 			if (r)
870 				return r;
871 		}
872 	}
873 
874 	if (p->job->vm) {
875 		p->job->vm_pd_addr = amdgpu_bo_gpu_offset(vm->root.bo);
876 
877 		r = amdgpu_bo_vm_update_pte(p);
878 		if (r)
879 			return r;
880 	}
881 
882 	return amdgpu_cs_sync_rings(p);
883 }
884 
885 static int amdgpu_cs_ib_fill(struct amdgpu_device *adev,
886 			     struct amdgpu_cs_parser *parser)
887 {
888 	struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
889 	struct amdgpu_vm *vm = &fpriv->vm;
890 	int i, j;
891 	int r, ce_preempt = 0, de_preempt = 0;
892 
893 	for (i = 0, j = 0; i < parser->nchunks && j < parser->job->num_ibs; i++) {
894 		struct amdgpu_cs_chunk *chunk;
895 		struct amdgpu_ib *ib;
896 		struct drm_amdgpu_cs_chunk_ib *chunk_ib;
897 		struct amdgpu_ring *ring;
898 
899 		chunk = &parser->chunks[i];
900 		ib = &parser->job->ibs[j];
901 		chunk_ib = (struct drm_amdgpu_cs_chunk_ib *)chunk->kdata;
902 
903 		if (chunk->chunk_id != AMDGPU_CHUNK_ID_IB)
904 			continue;
905 
906 		if (chunk_ib->ip_type == AMDGPU_HW_IP_GFX && amdgpu_sriov_vf(adev)) {
907 			if (chunk_ib->flags & AMDGPU_IB_FLAG_PREEMPT)
908 				if (chunk_ib->flags & AMDGPU_IB_FLAG_CE)
909 					ce_preempt++;
910 				else
911 					de_preempt++;
912 
913 			/* each GFX command submit allows 0 or 1 IB preemptible for CE & DE */
914 			if (ce_preempt > 1 || de_preempt > 1)
915 				return -EINVAL;
916 		}
917 
918 		r = amdgpu_cs_get_ring(adev, chunk_ib->ip_type,
919 				       chunk_ib->ip_instance, chunk_ib->ring,
920 				       &ring);
921 		if (r)
922 			return r;
923 
924 		if (chunk_ib->flags & AMDGPU_IB_FLAG_PREAMBLE) {
925 			parser->job->preamble_status |= AMDGPU_PREAMBLE_IB_PRESENT;
926 			if (!parser->ctx->preamble_presented) {
927 				parser->job->preamble_status |= AMDGPU_PREAMBLE_IB_PRESENT_FIRST;
928 				parser->ctx->preamble_presented = true;
929 			}
930 		}
931 
932 		if (parser->job->ring && parser->job->ring != ring)
933 			return -EINVAL;
934 
935 		parser->job->ring = ring;
936 
937 		if (ring->funcs->parse_cs) {
938 			struct amdgpu_bo_va_mapping *m;
939 			struct amdgpu_bo *aobj = NULL;
940 			uint64_t offset;
941 			uint8_t *kptr;
942 
943 			m = amdgpu_cs_find_mapping(parser, chunk_ib->va_start,
944 						   &aobj);
945 			if (!aobj) {
946 				DRM_ERROR("IB va_start is invalid\n");
947 				return -EINVAL;
948 			}
949 
950 			if ((chunk_ib->va_start + chunk_ib->ib_bytes) >
951 			    (m->it.last + 1) * AMDGPU_GPU_PAGE_SIZE) {
952 				DRM_ERROR("IB va_start+ib_bytes is invalid\n");
953 				return -EINVAL;
954 			}
955 
956 			/* the IB should be reserved at this point */
957 			r = amdgpu_bo_kmap(aobj, (void **)&kptr);
958 			if (r) {
959 				return r;
960 			}
961 
962 			offset = ((uint64_t)m->it.start) * AMDGPU_GPU_PAGE_SIZE;
963 			kptr += chunk_ib->va_start - offset;
964 
965 			r =  amdgpu_ib_get(adev, vm, chunk_ib->ib_bytes, ib);
966 			if (r) {
967 				DRM_ERROR("Failed to get ib !\n");
968 				return r;
969 			}
970 
971 			memcpy(ib->ptr, kptr, chunk_ib->ib_bytes);
972 			amdgpu_bo_kunmap(aobj);
973 		} else {
974 			r =  amdgpu_ib_get(adev, vm, 0, ib);
975 			if (r) {
976 				DRM_ERROR("Failed to get ib !\n");
977 				return r;
978 			}
979 
980 		}
981 
982 		ib->gpu_addr = chunk_ib->va_start;
983 		ib->length_dw = chunk_ib->ib_bytes / 4;
984 		ib->flags = chunk_ib->flags;
985 		j++;
986 	}
987 
988 	/* UVD & VCE fw doesn't support user fences */
989 	if (parser->job->uf_addr && (
990 	    parser->job->ring->funcs->type == AMDGPU_RING_TYPE_UVD ||
991 	    parser->job->ring->funcs->type == AMDGPU_RING_TYPE_VCE))
992 		return -EINVAL;
993 
994 	return 0;
995 }
996 
997 static int amdgpu_cs_dependencies(struct amdgpu_device *adev,
998 				  struct amdgpu_cs_parser *p)
999 {
1000 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
1001 	int i, j, r;
1002 
1003 	for (i = 0; i < p->nchunks; ++i) {
1004 		struct drm_amdgpu_cs_chunk_dep *deps;
1005 		struct amdgpu_cs_chunk *chunk;
1006 		unsigned num_deps;
1007 
1008 		chunk = &p->chunks[i];
1009 
1010 		if (chunk->chunk_id != AMDGPU_CHUNK_ID_DEPENDENCIES)
1011 			continue;
1012 
1013 		deps = (struct drm_amdgpu_cs_chunk_dep *)chunk->kdata;
1014 		num_deps = chunk->length_dw * 4 /
1015 			sizeof(struct drm_amdgpu_cs_chunk_dep);
1016 
1017 		for (j = 0; j < num_deps; ++j) {
1018 			struct amdgpu_ring *ring;
1019 			struct amdgpu_ctx *ctx;
1020 			struct dma_fence *fence;
1021 
1022 			r = amdgpu_cs_get_ring(adev, deps[j].ip_type,
1023 					       deps[j].ip_instance,
1024 					       deps[j].ring, &ring);
1025 			if (r)
1026 				return r;
1027 
1028 			ctx = amdgpu_ctx_get(fpriv, deps[j].ctx_id);
1029 			if (ctx == NULL)
1030 				return -EINVAL;
1031 
1032 			fence = amdgpu_ctx_get_fence(ctx, ring,
1033 						     deps[j].handle);
1034 			if (IS_ERR(fence)) {
1035 				r = PTR_ERR(fence);
1036 				amdgpu_ctx_put(ctx);
1037 				return r;
1038 
1039 			} else if (fence) {
1040 				r = amdgpu_sync_fence(adev, &p->job->sync,
1041 						      fence);
1042 				dma_fence_put(fence);
1043 				amdgpu_ctx_put(ctx);
1044 				if (r)
1045 					return r;
1046 			}
1047 		}
1048 	}
1049 
1050 	return 0;
1051 }
1052 
1053 static int amdgpu_cs_submit(struct amdgpu_cs_parser *p,
1054 			    union drm_amdgpu_cs *cs)
1055 {
1056 	struct amdgpu_ring *ring = p->job->ring;
1057 	struct amd_sched_entity *entity = &p->ctx->rings[ring->idx].entity;
1058 	struct amdgpu_job *job;
1059 	int r;
1060 
1061 	job = p->job;
1062 	p->job = NULL;
1063 
1064 	r = amd_sched_job_init(&job->base, &ring->sched, entity, p->filp);
1065 	if (r) {
1066 		amdgpu_job_free(job);
1067 		return r;
1068 	}
1069 
1070 	job->owner = p->filp;
1071 	job->fence_ctx = entity->fence_context;
1072 	p->fence = dma_fence_get(&job->base.s_fence->finished);
1073 	cs->out.handle = amdgpu_ctx_add_fence(p->ctx, ring, p->fence);
1074 	job->uf_sequence = cs->out.handle;
1075 	amdgpu_job_free_resources(job);
1076 
1077 	trace_amdgpu_cs_ioctl(job);
1078 	amd_sched_entity_push_job(&job->base);
1079 
1080 	return 0;
1081 }
1082 
1083 int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
1084 {
1085 	struct amdgpu_device *adev = dev->dev_private;
1086 	union drm_amdgpu_cs *cs = data;
1087 	struct amdgpu_cs_parser parser = {};
1088 	bool reserved_buffers = false;
1089 	int i, r;
1090 
1091 	if (!adev->accel_working)
1092 		return -EBUSY;
1093 
1094 	parser.adev = adev;
1095 	parser.filp = filp;
1096 
1097 	r = amdgpu_cs_parser_init(&parser, data);
1098 	if (r) {
1099 		DRM_ERROR("Failed to initialize parser !\n");
1100 		goto out;
1101 	}
1102 
1103 	r = amdgpu_cs_parser_bos(&parser, data);
1104 	if (r) {
1105 		if (r == -ENOMEM)
1106 			DRM_ERROR("Not enough memory for command submission!\n");
1107 		else if (r != -ERESTARTSYS)
1108 			DRM_ERROR("Failed to process the buffer list %d!\n", r);
1109 		goto out;
1110 	}
1111 
1112 	reserved_buffers = true;
1113 	r = amdgpu_cs_ib_fill(adev, &parser);
1114 	if (r)
1115 		goto out;
1116 
1117 	r = amdgpu_cs_dependencies(adev, &parser);
1118 	if (r) {
1119 		DRM_ERROR("Failed in the dependencies handling %d!\n", r);
1120 		goto out;
1121 	}
1122 
1123 	for (i = 0; i < parser.job->num_ibs; i++)
1124 		trace_amdgpu_cs(&parser, i);
1125 
1126 	r = amdgpu_cs_ib_vm_chunk(adev, &parser);
1127 	if (r)
1128 		goto out;
1129 
1130 	r = amdgpu_cs_submit(&parser, cs);
1131 
1132 out:
1133 	amdgpu_cs_parser_fini(&parser, r, reserved_buffers);
1134 	return r;
1135 }
1136 
1137 /**
1138  * amdgpu_cs_wait_ioctl - wait for a command submission to finish
1139  *
1140  * @dev: drm device
1141  * @data: data from userspace
1142  * @filp: file private
1143  *
1144  * Wait for the command submission identified by handle to finish.
1145  */
1146 int amdgpu_cs_wait_ioctl(struct drm_device *dev, void *data,
1147 			 struct drm_file *filp)
1148 {
1149 	union drm_amdgpu_wait_cs *wait = data;
1150 	struct amdgpu_device *adev = dev->dev_private;
1151 	unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout);
1152 	struct amdgpu_ring *ring = NULL;
1153 	struct amdgpu_ctx *ctx;
1154 	struct dma_fence *fence;
1155 	long r;
1156 
1157 	r = amdgpu_cs_get_ring(adev, wait->in.ip_type, wait->in.ip_instance,
1158 			       wait->in.ring, &ring);
1159 	if (r)
1160 		return r;
1161 
1162 	ctx = amdgpu_ctx_get(filp->driver_priv, wait->in.ctx_id);
1163 	if (ctx == NULL)
1164 		return -EINVAL;
1165 
1166 	fence = amdgpu_ctx_get_fence(ctx, ring, wait->in.handle);
1167 	if (IS_ERR(fence))
1168 		r = PTR_ERR(fence);
1169 	else if (fence) {
1170 		r = dma_fence_wait_timeout(fence, true, timeout);
1171 		dma_fence_put(fence);
1172 	} else
1173 		r = 1;
1174 
1175 	amdgpu_ctx_put(ctx);
1176 	if (r < 0)
1177 		return r;
1178 
1179 	memset(wait, 0, sizeof(*wait));
1180 	wait->out.status = (r == 0);
1181 
1182 	return 0;
1183 }
1184 
1185 /**
1186  * amdgpu_cs_get_fence - helper to get fence from drm_amdgpu_fence
1187  *
1188  * @adev: amdgpu device
1189  * @filp: file private
1190  * @user: drm_amdgpu_fence copied from user space
1191  */
1192 static struct dma_fence *amdgpu_cs_get_fence(struct amdgpu_device *adev,
1193 					     struct drm_file *filp,
1194 					     struct drm_amdgpu_fence *user)
1195 {
1196 	struct amdgpu_ring *ring;
1197 	struct amdgpu_ctx *ctx;
1198 	struct dma_fence *fence;
1199 	int r;
1200 
1201 	r = amdgpu_cs_get_ring(adev, user->ip_type, user->ip_instance,
1202 			       user->ring, &ring);
1203 	if (r)
1204 		return ERR_PTR(r);
1205 
1206 	ctx = amdgpu_ctx_get(filp->driver_priv, user->ctx_id);
1207 	if (ctx == NULL)
1208 		return ERR_PTR(-EINVAL);
1209 
1210 	fence = amdgpu_ctx_get_fence(ctx, ring, user->seq_no);
1211 	amdgpu_ctx_put(ctx);
1212 
1213 	return fence;
1214 }
1215 
1216 /**
1217  * amdgpu_cs_wait_all_fence - wait on all fences to signal
1218  *
1219  * @adev: amdgpu device
1220  * @filp: file private
1221  * @wait: wait parameters
1222  * @fences: array of drm_amdgpu_fence
1223  */
1224 static int amdgpu_cs_wait_all_fences(struct amdgpu_device *adev,
1225 				     struct drm_file *filp,
1226 				     union drm_amdgpu_wait_fences *wait,
1227 				     struct drm_amdgpu_fence *fences)
1228 {
1229 	uint32_t fence_count = wait->in.fence_count;
1230 	unsigned int i;
1231 	long r = 1;
1232 
1233 	for (i = 0; i < fence_count; i++) {
1234 		struct dma_fence *fence;
1235 		unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout_ns);
1236 
1237 		fence = amdgpu_cs_get_fence(adev, filp, &fences[i]);
1238 		if (IS_ERR(fence))
1239 			return PTR_ERR(fence);
1240 		else if (!fence)
1241 			continue;
1242 
1243 		r = dma_fence_wait_timeout(fence, true, timeout);
1244 		if (r < 0)
1245 			return r;
1246 
1247 		if (r == 0)
1248 			break;
1249 	}
1250 
1251 	memset(wait, 0, sizeof(*wait));
1252 	wait->out.status = (r > 0);
1253 
1254 	return 0;
1255 }
1256 
1257 /**
1258  * amdgpu_cs_wait_any_fence - wait on any fence to signal
1259  *
1260  * @adev: amdgpu device
1261  * @filp: file private
1262  * @wait: wait parameters
1263  * @fences: array of drm_amdgpu_fence
1264  */
1265 static int amdgpu_cs_wait_any_fence(struct amdgpu_device *adev,
1266 				    struct drm_file *filp,
1267 				    union drm_amdgpu_wait_fences *wait,
1268 				    struct drm_amdgpu_fence *fences)
1269 {
1270 	unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout_ns);
1271 	uint32_t fence_count = wait->in.fence_count;
1272 	uint32_t first = ~0;
1273 	struct dma_fence **array;
1274 	unsigned int i;
1275 	long r;
1276 
1277 	/* Prepare the fence array */
1278 	array = kcalloc(fence_count, sizeof(struct dma_fence *), GFP_KERNEL);
1279 
1280 	if (array == NULL)
1281 		return -ENOMEM;
1282 
1283 	for (i = 0; i < fence_count; i++) {
1284 		struct dma_fence *fence;
1285 
1286 		fence = amdgpu_cs_get_fence(adev, filp, &fences[i]);
1287 		if (IS_ERR(fence)) {
1288 			r = PTR_ERR(fence);
1289 			goto err_free_fence_array;
1290 		} else if (fence) {
1291 			array[i] = fence;
1292 		} else { /* NULL, the fence has been already signaled */
1293 			r = 1;
1294 			goto out;
1295 		}
1296 	}
1297 
1298 	r = dma_fence_wait_any_timeout(array, fence_count, true, timeout,
1299 				       &first);
1300 	if (r < 0)
1301 		goto err_free_fence_array;
1302 
1303 out:
1304 	memset(wait, 0, sizeof(*wait));
1305 	wait->out.status = (r > 0);
1306 	wait->out.first_signaled = first;
1307 	/* set return value 0 to indicate success */
1308 	r = 0;
1309 
1310 err_free_fence_array:
1311 	for (i = 0; i < fence_count; i++)
1312 		dma_fence_put(array[i]);
1313 	kfree(array);
1314 
1315 	return r;
1316 }
1317 
1318 /**
1319  * amdgpu_cs_wait_fences_ioctl - wait for multiple command submissions to finish
1320  *
1321  * @dev: drm device
1322  * @data: data from userspace
1323  * @filp: file private
1324  */
1325 int amdgpu_cs_wait_fences_ioctl(struct drm_device *dev, void *data,
1326 				struct drm_file *filp)
1327 {
1328 	struct amdgpu_device *adev = dev->dev_private;
1329 	union drm_amdgpu_wait_fences *wait = data;
1330 	uint32_t fence_count = wait->in.fence_count;
1331 	struct drm_amdgpu_fence *fences_user;
1332 	struct drm_amdgpu_fence *fences;
1333 	int r;
1334 
1335 	/* Get the fences from userspace */
1336 	fences = kmalloc_array(fence_count, sizeof(struct drm_amdgpu_fence),
1337 			GFP_KERNEL);
1338 	if (fences == NULL)
1339 		return -ENOMEM;
1340 
1341 	fences_user = (void __user *)(unsigned long)(wait->in.fences);
1342 	if (copy_from_user(fences, fences_user,
1343 		sizeof(struct drm_amdgpu_fence) * fence_count)) {
1344 		r = -EFAULT;
1345 		goto err_free_fences;
1346 	}
1347 
1348 	if (wait->in.wait_all)
1349 		r = amdgpu_cs_wait_all_fences(adev, filp, wait, fences);
1350 	else
1351 		r = amdgpu_cs_wait_any_fence(adev, filp, wait, fences);
1352 
1353 err_free_fences:
1354 	kfree(fences);
1355 
1356 	return r;
1357 }
1358 
1359 /**
1360  * amdgpu_cs_find_bo_va - find bo_va for VM address
1361  *
1362  * @parser: command submission parser context
1363  * @addr: VM address
1364  * @bo: resulting BO of the mapping found
1365  *
1366  * Search the buffer objects in the command submission context for a certain
1367  * virtual memory address. Returns allocation structure when found, NULL
1368  * otherwise.
1369  */
1370 struct amdgpu_bo_va_mapping *
1371 amdgpu_cs_find_mapping(struct amdgpu_cs_parser *parser,
1372 		       uint64_t addr, struct amdgpu_bo **bo)
1373 {
1374 	struct amdgpu_bo_va_mapping *mapping;
1375 	unsigned i;
1376 
1377 	if (!parser->bo_list)
1378 		return NULL;
1379 
1380 	addr /= AMDGPU_GPU_PAGE_SIZE;
1381 
1382 	for (i = 0; i < parser->bo_list->num_entries; i++) {
1383 		struct amdgpu_bo_list_entry *lobj;
1384 
1385 		lobj = &parser->bo_list->array[i];
1386 		if (!lobj->bo_va)
1387 			continue;
1388 
1389 		list_for_each_entry(mapping, &lobj->bo_va->valids, list) {
1390 			if (mapping->it.start > addr ||
1391 			    addr > mapping->it.last)
1392 				continue;
1393 
1394 			*bo = lobj->bo_va->bo;
1395 			return mapping;
1396 		}
1397 
1398 		list_for_each_entry(mapping, &lobj->bo_va->invalids, list) {
1399 			if (mapping->it.start > addr ||
1400 			    addr > mapping->it.last)
1401 				continue;
1402 
1403 			*bo = lobj->bo_va->bo;
1404 			return mapping;
1405 		}
1406 	}
1407 
1408 	return NULL;
1409 }
1410 
1411 /**
1412  * amdgpu_cs_sysvm_access_required - make BOs accessible by the system VM
1413  *
1414  * @parser: command submission parser context
1415  *
1416  * Helper for UVD/VCE VM emulation, make sure BOs are accessible by the system VM.
1417  */
1418 int amdgpu_cs_sysvm_access_required(struct amdgpu_cs_parser *parser)
1419 {
1420 	unsigned i;
1421 	int r;
1422 
1423 	if (!parser->bo_list)
1424 		return 0;
1425 
1426 	for (i = 0; i < parser->bo_list->num_entries; i++) {
1427 		struct amdgpu_bo *bo = parser->bo_list->array[i].robj;
1428 
1429 		r = amdgpu_ttm_bind(&bo->tbo, &bo->tbo.mem);
1430 		if (unlikely(r))
1431 			return r;
1432 
1433 		if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS)
1434 			continue;
1435 
1436 		bo->flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
1437 		amdgpu_ttm_placement_from_domain(bo, bo->allowed_domains);
1438 		r = ttm_bo_validate(&bo->tbo, &bo->placement, false, false);
1439 		if (unlikely(r))
1440 			return r;
1441 	}
1442 
1443 	return 0;
1444 }
1445