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