xref: /openbmc/linux/drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c (revision c62d3cd0ddd629606a3830aa22e9dcc6c2a0d3bf)
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 <linux/sync_file.h>
29 #include <drm/drmP.h>
30 #include <drm/amdgpu_drm.h>
31 #include <drm/drm_syncobj.h>
32 #include "amdgpu.h"
33 #include "amdgpu_trace.h"
34 #include "amdgpu_gmc.h"
35 #include "amdgpu_gem.h"
36 
37 static int amdgpu_cs_user_fence_chunk(struct amdgpu_cs_parser *p,
38 				      struct drm_amdgpu_cs_chunk_fence *data,
39 				      uint32_t *offset)
40 {
41 	struct drm_gem_object *gobj;
42 	unsigned long size;
43 
44 	gobj = drm_gem_object_lookup(p->filp, data->handle);
45 	if (gobj == NULL)
46 		return -EINVAL;
47 
48 	p->uf_entry.robj = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj));
49 	p->uf_entry.priority = 0;
50 	p->uf_entry.tv.bo = &p->uf_entry.robj->tbo;
51 	p->uf_entry.tv.shared = true;
52 	p->uf_entry.user_pages = NULL;
53 
54 	size = amdgpu_bo_size(p->uf_entry.robj);
55 	if (size != PAGE_SIZE || (data->offset + 8) > size)
56 		return -EINVAL;
57 
58 	*offset = data->offset;
59 
60 	drm_gem_object_put_unlocked(gobj);
61 
62 	if (amdgpu_ttm_tt_get_usermm(p->uf_entry.robj->tbo.ttm)) {
63 		amdgpu_bo_unref(&p->uf_entry.robj);
64 		return -EINVAL;
65 	}
66 
67 	return 0;
68 }
69 
70 static int amdgpu_cs_bo_handles_chunk(struct amdgpu_cs_parser *p,
71 				      struct drm_amdgpu_bo_list_in *data)
72 {
73 	int r;
74 	struct drm_amdgpu_bo_list_entry *info = NULL;
75 
76 	r = amdgpu_bo_create_list_entry_array(data, &info);
77 	if (r)
78 		return r;
79 
80 	r = amdgpu_bo_list_create(p->adev, p->filp, info, data->bo_number,
81 				  &p->bo_list);
82 	if (r)
83 		goto error_free;
84 
85 	kvfree(info);
86 	return 0;
87 
88 error_free:
89 	if (info)
90 		kvfree(info);
91 
92 	return r;
93 }
94 
95 static int amdgpu_cs_parser_init(struct amdgpu_cs_parser *p, union drm_amdgpu_cs *cs)
96 {
97 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
98 	struct amdgpu_vm *vm = &fpriv->vm;
99 	uint64_t *chunk_array_user;
100 	uint64_t *chunk_array;
101 	unsigned size, num_ibs = 0;
102 	uint32_t uf_offset = 0;
103 	int i;
104 	int ret;
105 
106 	if (cs->in.num_chunks == 0)
107 		return 0;
108 
109 	chunk_array = kmalloc_array(cs->in.num_chunks, sizeof(uint64_t), GFP_KERNEL);
110 	if (!chunk_array)
111 		return -ENOMEM;
112 
113 	p->ctx = amdgpu_ctx_get(fpriv, cs->in.ctx_id);
114 	if (!p->ctx) {
115 		ret = -EINVAL;
116 		goto free_chunk;
117 	}
118 
119 	/* skip guilty context job */
120 	if (atomic_read(&p->ctx->guilty) == 1) {
121 		ret = -ECANCELED;
122 		goto free_chunk;
123 	}
124 
125 	mutex_lock(&p->ctx->lock);
126 
127 	/* get chunks */
128 	chunk_array_user = u64_to_user_ptr(cs->in.chunks);
129 	if (copy_from_user(chunk_array, chunk_array_user,
130 			   sizeof(uint64_t)*cs->in.num_chunks)) {
131 		ret = -EFAULT;
132 		goto free_chunk;
133 	}
134 
135 	p->nchunks = cs->in.num_chunks;
136 	p->chunks = kmalloc_array(p->nchunks, sizeof(struct amdgpu_cs_chunk),
137 			    GFP_KERNEL);
138 	if (!p->chunks) {
139 		ret = -ENOMEM;
140 		goto free_chunk;
141 	}
142 
143 	for (i = 0; i < p->nchunks; i++) {
144 		struct drm_amdgpu_cs_chunk __user **chunk_ptr = NULL;
145 		struct drm_amdgpu_cs_chunk user_chunk;
146 		uint32_t __user *cdata;
147 
148 		chunk_ptr = u64_to_user_ptr(chunk_array[i]);
149 		if (copy_from_user(&user_chunk, chunk_ptr,
150 				       sizeof(struct drm_amdgpu_cs_chunk))) {
151 			ret = -EFAULT;
152 			i--;
153 			goto free_partial_kdata;
154 		}
155 		p->chunks[i].chunk_id = user_chunk.chunk_id;
156 		p->chunks[i].length_dw = user_chunk.length_dw;
157 
158 		size = p->chunks[i].length_dw;
159 		cdata = u64_to_user_ptr(user_chunk.chunk_data);
160 
161 		p->chunks[i].kdata = kvmalloc_array(size, sizeof(uint32_t), GFP_KERNEL);
162 		if (p->chunks[i].kdata == NULL) {
163 			ret = -ENOMEM;
164 			i--;
165 			goto free_partial_kdata;
166 		}
167 		size *= sizeof(uint32_t);
168 		if (copy_from_user(p->chunks[i].kdata, cdata, size)) {
169 			ret = -EFAULT;
170 			goto free_partial_kdata;
171 		}
172 
173 		switch (p->chunks[i].chunk_id) {
174 		case AMDGPU_CHUNK_ID_IB:
175 			++num_ibs;
176 			break;
177 
178 		case AMDGPU_CHUNK_ID_FENCE:
179 			size = sizeof(struct drm_amdgpu_cs_chunk_fence);
180 			if (p->chunks[i].length_dw * sizeof(uint32_t) < size) {
181 				ret = -EINVAL;
182 				goto free_partial_kdata;
183 			}
184 
185 			ret = amdgpu_cs_user_fence_chunk(p, p->chunks[i].kdata,
186 							 &uf_offset);
187 			if (ret)
188 				goto free_partial_kdata;
189 
190 			break;
191 
192 		case AMDGPU_CHUNK_ID_BO_HANDLES:
193 			size = sizeof(struct drm_amdgpu_bo_list_in);
194 			if (p->chunks[i].length_dw * sizeof(uint32_t) < size) {
195 				ret = -EINVAL;
196 				goto free_partial_kdata;
197 			}
198 
199 			ret = amdgpu_cs_bo_handles_chunk(p, p->chunks[i].kdata);
200 			if (ret)
201 				goto free_partial_kdata;
202 
203 			break;
204 
205 		case AMDGPU_CHUNK_ID_DEPENDENCIES:
206 		case AMDGPU_CHUNK_ID_SYNCOBJ_IN:
207 		case AMDGPU_CHUNK_ID_SYNCOBJ_OUT:
208 			break;
209 
210 		default:
211 			ret = -EINVAL;
212 			goto free_partial_kdata;
213 		}
214 	}
215 
216 	ret = amdgpu_job_alloc(p->adev, num_ibs, &p->job, vm);
217 	if (ret)
218 		goto free_all_kdata;
219 
220 	if (p->ctx->vram_lost_counter != p->job->vram_lost_counter) {
221 		ret = -ECANCELED;
222 		goto free_all_kdata;
223 	}
224 
225 	if (p->uf_entry.robj)
226 		p->job->uf_addr = uf_offset;
227 	kfree(chunk_array);
228 
229 	/* Use this opportunity to fill in task info for the vm */
230 	amdgpu_vm_set_task_info(vm);
231 
232 	return 0;
233 
234 free_all_kdata:
235 	i = p->nchunks - 1;
236 free_partial_kdata:
237 	for (; i >= 0; i--)
238 		kvfree(p->chunks[i].kdata);
239 	kfree(p->chunks);
240 	p->chunks = NULL;
241 	p->nchunks = 0;
242 free_chunk:
243 	kfree(chunk_array);
244 
245 	return ret;
246 }
247 
248 /* Convert microseconds to bytes. */
249 static u64 us_to_bytes(struct amdgpu_device *adev, s64 us)
250 {
251 	if (us <= 0 || !adev->mm_stats.log2_max_MBps)
252 		return 0;
253 
254 	/* Since accum_us is incremented by a million per second, just
255 	 * multiply it by the number of MB/s to get the number of bytes.
256 	 */
257 	return us << adev->mm_stats.log2_max_MBps;
258 }
259 
260 static s64 bytes_to_us(struct amdgpu_device *adev, u64 bytes)
261 {
262 	if (!adev->mm_stats.log2_max_MBps)
263 		return 0;
264 
265 	return bytes >> adev->mm_stats.log2_max_MBps;
266 }
267 
268 /* Returns how many bytes TTM can move right now. If no bytes can be moved,
269  * it returns 0. If it returns non-zero, it's OK to move at least one buffer,
270  * which means it can go over the threshold once. If that happens, the driver
271  * will be in debt and no other buffer migrations can be done until that debt
272  * is repaid.
273  *
274  * This approach allows moving a buffer of any size (it's important to allow
275  * that).
276  *
277  * The currency is simply time in microseconds and it increases as the clock
278  * ticks. The accumulated microseconds (us) are converted to bytes and
279  * returned.
280  */
281 static void amdgpu_cs_get_threshold_for_moves(struct amdgpu_device *adev,
282 					      u64 *max_bytes,
283 					      u64 *max_vis_bytes)
284 {
285 	s64 time_us, increment_us;
286 	u64 free_vram, total_vram, used_vram;
287 
288 	/* Allow a maximum of 200 accumulated ms. This is basically per-IB
289 	 * throttling.
290 	 *
291 	 * It means that in order to get full max MBps, at least 5 IBs per
292 	 * second must be submitted and not more than 200ms apart from each
293 	 * other.
294 	 */
295 	const s64 us_upper_bound = 200000;
296 
297 	if (!adev->mm_stats.log2_max_MBps) {
298 		*max_bytes = 0;
299 		*max_vis_bytes = 0;
300 		return;
301 	}
302 
303 	total_vram = adev->gmc.real_vram_size - atomic64_read(&adev->vram_pin_size);
304 	used_vram = amdgpu_vram_mgr_usage(&adev->mman.bdev.man[TTM_PL_VRAM]);
305 	free_vram = used_vram >= total_vram ? 0 : total_vram - used_vram;
306 
307 	spin_lock(&adev->mm_stats.lock);
308 
309 	/* Increase the amount of accumulated us. */
310 	time_us = ktime_to_us(ktime_get());
311 	increment_us = time_us - adev->mm_stats.last_update_us;
312 	adev->mm_stats.last_update_us = time_us;
313 	adev->mm_stats.accum_us = min(adev->mm_stats.accum_us + increment_us,
314                                       us_upper_bound);
315 
316 	/* This prevents the short period of low performance when the VRAM
317 	 * usage is low and the driver is in debt or doesn't have enough
318 	 * accumulated us to fill VRAM quickly.
319 	 *
320 	 * The situation can occur in these cases:
321 	 * - a lot of VRAM is freed by userspace
322 	 * - the presence of a big buffer causes a lot of evictions
323 	 *   (solution: split buffers into smaller ones)
324 	 *
325 	 * If 128 MB or 1/8th of VRAM is free, start filling it now by setting
326 	 * accum_us to a positive number.
327 	 */
328 	if (free_vram >= 128 * 1024 * 1024 || free_vram >= total_vram / 8) {
329 		s64 min_us;
330 
331 		/* Be more aggresive on dGPUs. Try to fill a portion of free
332 		 * VRAM now.
333 		 */
334 		if (!(adev->flags & AMD_IS_APU))
335 			min_us = bytes_to_us(adev, free_vram / 4);
336 		else
337 			min_us = 0; /* Reset accum_us on APUs. */
338 
339 		adev->mm_stats.accum_us = max(min_us, adev->mm_stats.accum_us);
340 	}
341 
342 	/* This is set to 0 if the driver is in debt to disallow (optional)
343 	 * buffer moves.
344 	 */
345 	*max_bytes = us_to_bytes(adev, adev->mm_stats.accum_us);
346 
347 	/* Do the same for visible VRAM if half of it is free */
348 	if (!amdgpu_gmc_vram_full_visible(&adev->gmc)) {
349 		u64 total_vis_vram = adev->gmc.visible_vram_size;
350 		u64 used_vis_vram =
351 			amdgpu_vram_mgr_vis_usage(&adev->mman.bdev.man[TTM_PL_VRAM]);
352 
353 		if (used_vis_vram < total_vis_vram) {
354 			u64 free_vis_vram = total_vis_vram - used_vis_vram;
355 			adev->mm_stats.accum_us_vis = min(adev->mm_stats.accum_us_vis +
356 							  increment_us, us_upper_bound);
357 
358 			if (free_vis_vram >= total_vis_vram / 2)
359 				adev->mm_stats.accum_us_vis =
360 					max(bytes_to_us(adev, free_vis_vram / 2),
361 					    adev->mm_stats.accum_us_vis);
362 		}
363 
364 		*max_vis_bytes = us_to_bytes(adev, adev->mm_stats.accum_us_vis);
365 	} else {
366 		*max_vis_bytes = 0;
367 	}
368 
369 	spin_unlock(&adev->mm_stats.lock);
370 }
371 
372 /* Report how many bytes have really been moved for the last command
373  * submission. This can result in a debt that can stop buffer migrations
374  * temporarily.
375  */
376 void amdgpu_cs_report_moved_bytes(struct amdgpu_device *adev, u64 num_bytes,
377 				  u64 num_vis_bytes)
378 {
379 	spin_lock(&adev->mm_stats.lock);
380 	adev->mm_stats.accum_us -= bytes_to_us(adev, num_bytes);
381 	adev->mm_stats.accum_us_vis -= bytes_to_us(adev, num_vis_bytes);
382 	spin_unlock(&adev->mm_stats.lock);
383 }
384 
385 static int amdgpu_cs_bo_validate(struct amdgpu_cs_parser *p,
386 				 struct amdgpu_bo *bo)
387 {
388 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
389 	struct ttm_operation_ctx ctx = {
390 		.interruptible = true,
391 		.no_wait_gpu = false,
392 		.resv = bo->tbo.resv,
393 		.flags = 0
394 	};
395 	uint32_t domain;
396 	int r;
397 
398 	if (bo->pin_count)
399 		return 0;
400 
401 	/* Don't move this buffer if we have depleted our allowance
402 	 * to move it. Don't move anything if the threshold is zero.
403 	 */
404 	if (p->bytes_moved < p->bytes_moved_threshold) {
405 		if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
406 		    (bo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED)) {
407 			/* And don't move a CPU_ACCESS_REQUIRED BO to limited
408 			 * visible VRAM if we've depleted our allowance to do
409 			 * that.
410 			 */
411 			if (p->bytes_moved_vis < p->bytes_moved_vis_threshold)
412 				domain = bo->preferred_domains;
413 			else
414 				domain = bo->allowed_domains;
415 		} else {
416 			domain = bo->preferred_domains;
417 		}
418 	} else {
419 		domain = bo->allowed_domains;
420 	}
421 
422 retry:
423 	amdgpu_bo_placement_from_domain(bo, domain);
424 	r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
425 
426 	p->bytes_moved += ctx.bytes_moved;
427 	if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
428 	    amdgpu_bo_in_cpu_visible_vram(bo))
429 		p->bytes_moved_vis += ctx.bytes_moved;
430 
431 	if (unlikely(r == -ENOMEM) && domain != bo->allowed_domains) {
432 		domain = bo->allowed_domains;
433 		goto retry;
434 	}
435 
436 	return r;
437 }
438 
439 /* Last resort, try to evict something from the current working set */
440 static bool amdgpu_cs_try_evict(struct amdgpu_cs_parser *p,
441 				struct amdgpu_bo *validated)
442 {
443 	uint32_t domain = validated->allowed_domains;
444 	struct ttm_operation_ctx ctx = { true, false };
445 	int r;
446 
447 	if (!p->evictable)
448 		return false;
449 
450 	for (;&p->evictable->tv.head != &p->validated;
451 	     p->evictable = list_prev_entry(p->evictable, tv.head)) {
452 
453 		struct amdgpu_bo_list_entry *candidate = p->evictable;
454 		struct amdgpu_bo *bo = candidate->robj;
455 		struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
456 		bool update_bytes_moved_vis;
457 		uint32_t other;
458 
459 		/* If we reached our current BO we can forget it */
460 		if (candidate->robj == validated)
461 			break;
462 
463 		/* We can't move pinned BOs here */
464 		if (bo->pin_count)
465 			continue;
466 
467 		other = amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type);
468 
469 		/* Check if this BO is in one of the domains we need space for */
470 		if (!(other & domain))
471 			continue;
472 
473 		/* Check if we can move this BO somewhere else */
474 		other = bo->allowed_domains & ~domain;
475 		if (!other)
476 			continue;
477 
478 		/* Good we can try to move this BO somewhere else */
479 		update_bytes_moved_vis =
480 				!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
481 				amdgpu_bo_in_cpu_visible_vram(bo);
482 		amdgpu_bo_placement_from_domain(bo, other);
483 		r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
484 		p->bytes_moved += ctx.bytes_moved;
485 		if (update_bytes_moved_vis)
486 			p->bytes_moved_vis += ctx.bytes_moved;
487 
488 		if (unlikely(r))
489 			break;
490 
491 		p->evictable = list_prev_entry(p->evictable, tv.head);
492 		list_move(&candidate->tv.head, &p->validated);
493 
494 		return true;
495 	}
496 
497 	return false;
498 }
499 
500 static int amdgpu_cs_validate(void *param, struct amdgpu_bo *bo)
501 {
502 	struct amdgpu_cs_parser *p = param;
503 	int r;
504 
505 	do {
506 		r = amdgpu_cs_bo_validate(p, bo);
507 	} while (r == -ENOMEM && amdgpu_cs_try_evict(p, bo));
508 	if (r)
509 		return r;
510 
511 	if (bo->shadow)
512 		r = amdgpu_cs_bo_validate(p, bo->shadow);
513 
514 	return r;
515 }
516 
517 static int amdgpu_cs_list_validate(struct amdgpu_cs_parser *p,
518 			    struct list_head *validated)
519 {
520 	struct ttm_operation_ctx ctx = { true, false };
521 	struct amdgpu_bo_list_entry *lobj;
522 	int r;
523 
524 	list_for_each_entry(lobj, validated, tv.head) {
525 		struct amdgpu_bo *bo = lobj->robj;
526 		bool binding_userptr = false;
527 		struct mm_struct *usermm;
528 
529 		usermm = amdgpu_ttm_tt_get_usermm(bo->tbo.ttm);
530 		if (usermm && usermm != current->mm)
531 			return -EPERM;
532 
533 		/* Check if we have user pages and nobody bound the BO already */
534 		if (amdgpu_ttm_tt_userptr_needs_pages(bo->tbo.ttm) &&
535 		    lobj->user_pages) {
536 			amdgpu_bo_placement_from_domain(bo,
537 							AMDGPU_GEM_DOMAIN_CPU);
538 			r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
539 			if (r)
540 				return r;
541 			amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm,
542 						     lobj->user_pages);
543 			binding_userptr = true;
544 		}
545 
546 		if (p->evictable == lobj)
547 			p->evictable = NULL;
548 
549 		r = amdgpu_cs_validate(p, bo);
550 		if (r)
551 			return r;
552 
553 		if (binding_userptr) {
554 			kvfree(lobj->user_pages);
555 			lobj->user_pages = NULL;
556 		}
557 	}
558 	return 0;
559 }
560 
561 static int amdgpu_cs_parser_bos(struct amdgpu_cs_parser *p,
562 				union drm_amdgpu_cs *cs)
563 {
564 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
565 	struct amdgpu_vm *vm = &fpriv->vm;
566 	struct amdgpu_bo_list_entry *e;
567 	struct list_head duplicates;
568 	struct amdgpu_bo *gds;
569 	struct amdgpu_bo *gws;
570 	struct amdgpu_bo *oa;
571 	unsigned tries = 10;
572 	int r;
573 
574 	INIT_LIST_HEAD(&p->validated);
575 
576 	/* p->bo_list could already be assigned if AMDGPU_CHUNK_ID_BO_HANDLES is present */
577 	if (cs->in.bo_list_handle) {
578 		if (p->bo_list)
579 			return -EINVAL;
580 
581 		r = amdgpu_bo_list_get(fpriv, cs->in.bo_list_handle,
582 				       &p->bo_list);
583 		if (r)
584 			return r;
585 	} else if (!p->bo_list) {
586 		/* Create a empty bo_list when no handle is provided */
587 		r = amdgpu_bo_list_create(p->adev, p->filp, NULL, 0,
588 					  &p->bo_list);
589 		if (r)
590 			return r;
591 	}
592 
593 	amdgpu_bo_list_get_list(p->bo_list, &p->validated);
594 	if (p->bo_list->first_userptr != p->bo_list->num_entries)
595 		p->mn = amdgpu_mn_get(p->adev, AMDGPU_MN_TYPE_GFX);
596 
597 	INIT_LIST_HEAD(&duplicates);
598 	amdgpu_vm_get_pd_bo(&fpriv->vm, &p->validated, &p->vm_pd);
599 
600 	if (p->uf_entry.robj && !p->uf_entry.robj->parent)
601 		list_add(&p->uf_entry.tv.head, &p->validated);
602 
603 	while (1) {
604 		struct list_head need_pages;
605 
606 		r = ttm_eu_reserve_buffers(&p->ticket, &p->validated, true,
607 					   &duplicates);
608 		if (unlikely(r != 0)) {
609 			if (r != -ERESTARTSYS)
610 				DRM_ERROR("ttm_eu_reserve_buffers failed.\n");
611 			goto error_free_pages;
612 		}
613 
614 		INIT_LIST_HEAD(&need_pages);
615 		amdgpu_bo_list_for_each_userptr_entry(e, p->bo_list) {
616 			struct amdgpu_bo *bo = e->robj;
617 
618 			if (amdgpu_ttm_tt_userptr_invalidated(bo->tbo.ttm,
619 				 &e->user_invalidated) && e->user_pages) {
620 
621 				/* We acquired a page array, but somebody
622 				 * invalidated it. Free it and try again
623 				 */
624 				release_pages(e->user_pages,
625 					      bo->tbo.ttm->num_pages);
626 				kvfree(e->user_pages);
627 				e->user_pages = NULL;
628 			}
629 
630 			if (amdgpu_ttm_tt_userptr_needs_pages(bo->tbo.ttm) &&
631 			    !e->user_pages) {
632 				list_del(&e->tv.head);
633 				list_add(&e->tv.head, &need_pages);
634 
635 				amdgpu_bo_unreserve(e->robj);
636 			}
637 		}
638 
639 		if (list_empty(&need_pages))
640 			break;
641 
642 		/* Unreserve everything again. */
643 		ttm_eu_backoff_reservation(&p->ticket, &p->validated);
644 
645 		/* We tried too many times, just abort */
646 		if (!--tries) {
647 			r = -EDEADLK;
648 			DRM_ERROR("deadlock in %s\n", __func__);
649 			goto error_free_pages;
650 		}
651 
652 		/* Fill the page arrays for all userptrs. */
653 		list_for_each_entry(e, &need_pages, tv.head) {
654 			struct ttm_tt *ttm = e->robj->tbo.ttm;
655 
656 			e->user_pages = kvmalloc_array(ttm->num_pages,
657 							 sizeof(struct page*),
658 							 GFP_KERNEL | __GFP_ZERO);
659 			if (!e->user_pages) {
660 				r = -ENOMEM;
661 				DRM_ERROR("calloc failure in %s\n", __func__);
662 				goto error_free_pages;
663 			}
664 
665 			r = amdgpu_ttm_tt_get_user_pages(ttm, e->user_pages);
666 			if (r) {
667 				DRM_ERROR("amdgpu_ttm_tt_get_user_pages failed.\n");
668 				kvfree(e->user_pages);
669 				e->user_pages = NULL;
670 				goto error_free_pages;
671 			}
672 		}
673 
674 		/* And try again. */
675 		list_splice(&need_pages, &p->validated);
676 	}
677 
678 	amdgpu_cs_get_threshold_for_moves(p->adev, &p->bytes_moved_threshold,
679 					  &p->bytes_moved_vis_threshold);
680 	p->bytes_moved = 0;
681 	p->bytes_moved_vis = 0;
682 	p->evictable = list_last_entry(&p->validated,
683 				       struct amdgpu_bo_list_entry,
684 				       tv.head);
685 
686 	r = amdgpu_vm_validate_pt_bos(p->adev, &fpriv->vm,
687 				      amdgpu_cs_validate, p);
688 	if (r) {
689 		DRM_ERROR("amdgpu_vm_validate_pt_bos() failed.\n");
690 		goto error_validate;
691 	}
692 
693 	r = amdgpu_cs_list_validate(p, &duplicates);
694 	if (r) {
695 		DRM_ERROR("amdgpu_cs_list_validate(duplicates) failed.\n");
696 		goto error_validate;
697 	}
698 
699 	r = amdgpu_cs_list_validate(p, &p->validated);
700 	if (r) {
701 		DRM_ERROR("amdgpu_cs_list_validate(validated) failed.\n");
702 		goto error_validate;
703 	}
704 
705 	amdgpu_cs_report_moved_bytes(p->adev, p->bytes_moved,
706 				     p->bytes_moved_vis);
707 
708 	gds = p->bo_list->gds_obj;
709 	gws = p->bo_list->gws_obj;
710 	oa = p->bo_list->oa_obj;
711 
712 	amdgpu_bo_list_for_each_entry(e, p->bo_list)
713 		e->bo_va = amdgpu_vm_bo_find(vm, e->robj);
714 
715 	if (gds) {
716 		p->job->gds_base = amdgpu_bo_gpu_offset(gds);
717 		p->job->gds_size = amdgpu_bo_size(gds);
718 	}
719 	if (gws) {
720 		p->job->gws_base = amdgpu_bo_gpu_offset(gws);
721 		p->job->gws_size = amdgpu_bo_size(gws);
722 	}
723 	if (oa) {
724 		p->job->oa_base = amdgpu_bo_gpu_offset(oa);
725 		p->job->oa_size = amdgpu_bo_size(oa);
726 	}
727 
728 	if (!r && p->uf_entry.robj) {
729 		struct amdgpu_bo *uf = p->uf_entry.robj;
730 
731 		r = amdgpu_ttm_alloc_gart(&uf->tbo);
732 		p->job->uf_addr += amdgpu_bo_gpu_offset(uf);
733 	}
734 
735 error_validate:
736 	if (r)
737 		ttm_eu_backoff_reservation(&p->ticket, &p->validated);
738 
739 error_free_pages:
740 
741 	amdgpu_bo_list_for_each_userptr_entry(e, p->bo_list) {
742 		if (!e->user_pages)
743 			continue;
744 
745 		release_pages(e->user_pages,
746 			      e->robj->tbo.ttm->num_pages);
747 		kvfree(e->user_pages);
748 	}
749 
750 	return r;
751 }
752 
753 static int amdgpu_cs_sync_rings(struct amdgpu_cs_parser *p)
754 {
755 	struct amdgpu_bo_list_entry *e;
756 	int r;
757 
758 	list_for_each_entry(e, &p->validated, tv.head) {
759 		struct reservation_object *resv = e->robj->tbo.resv;
760 		r = amdgpu_sync_resv(p->adev, &p->job->sync, resv, p->filp,
761 				     amdgpu_bo_explicit_sync(e->robj));
762 
763 		if (r)
764 			return r;
765 	}
766 	return 0;
767 }
768 
769 /**
770  * cs_parser_fini() - clean parser states
771  * @parser:	parser structure holding parsing context.
772  * @error:	error number
773  *
774  * If error is set than unvalidate buffer, otherwise just free memory
775  * used by parsing context.
776  **/
777 static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser, int error,
778 				  bool backoff)
779 {
780 	unsigned i;
781 
782 	if (error && backoff)
783 		ttm_eu_backoff_reservation(&parser->ticket,
784 					   &parser->validated);
785 
786 	for (i = 0; i < parser->num_post_dep_syncobjs; i++)
787 		drm_syncobj_put(parser->post_dep_syncobjs[i]);
788 	kfree(parser->post_dep_syncobjs);
789 
790 	dma_fence_put(parser->fence);
791 
792 	if (parser->ctx) {
793 		mutex_unlock(&parser->ctx->lock);
794 		amdgpu_ctx_put(parser->ctx);
795 	}
796 	if (parser->bo_list)
797 		amdgpu_bo_list_put(parser->bo_list);
798 
799 	for (i = 0; i < parser->nchunks; i++)
800 		kvfree(parser->chunks[i].kdata);
801 	kfree(parser->chunks);
802 	if (parser->job)
803 		amdgpu_job_free(parser->job);
804 	amdgpu_bo_unref(&parser->uf_entry.robj);
805 }
806 
807 static int amdgpu_bo_vm_update_pte(struct amdgpu_cs_parser *p)
808 {
809 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
810 	struct amdgpu_device *adev = p->adev;
811 	struct amdgpu_vm *vm = &fpriv->vm;
812 	struct amdgpu_bo_list_entry *e;
813 	struct amdgpu_bo_va *bo_va;
814 	struct amdgpu_bo *bo;
815 	int r;
816 
817 	r = amdgpu_vm_clear_freed(adev, vm, NULL);
818 	if (r)
819 		return r;
820 
821 	r = amdgpu_vm_bo_update(adev, fpriv->prt_va, false);
822 	if (r)
823 		return r;
824 
825 	r = amdgpu_sync_fence(adev, &p->job->sync,
826 			      fpriv->prt_va->last_pt_update, false);
827 	if (r)
828 		return r;
829 
830 	if (amdgpu_sriov_vf(adev)) {
831 		struct dma_fence *f;
832 
833 		bo_va = fpriv->csa_va;
834 		BUG_ON(!bo_va);
835 		r = amdgpu_vm_bo_update(adev, bo_va, false);
836 		if (r)
837 			return r;
838 
839 		f = bo_va->last_pt_update;
840 		r = amdgpu_sync_fence(adev, &p->job->sync, f, false);
841 		if (r)
842 			return r;
843 	}
844 
845 	amdgpu_bo_list_for_each_entry(e, p->bo_list) {
846 		struct dma_fence *f;
847 
848 		/* ignore duplicates */
849 		bo = e->robj;
850 		if (!bo)
851 			continue;
852 
853 		bo_va = e->bo_va;
854 		if (bo_va == NULL)
855 			continue;
856 
857 		r = amdgpu_vm_bo_update(adev, bo_va, false);
858 		if (r)
859 			return r;
860 
861 		f = bo_va->last_pt_update;
862 		r = amdgpu_sync_fence(adev, &p->job->sync, f, false);
863 		if (r)
864 			return r;
865 	}
866 
867 	r = amdgpu_vm_handle_moved(adev, vm);
868 	if (r)
869 		return r;
870 
871 	r = amdgpu_vm_update_directories(adev, vm);
872 	if (r)
873 		return r;
874 
875 	r = amdgpu_sync_fence(adev, &p->job->sync, vm->last_update, false);
876 	if (r)
877 		return r;
878 
879 	if (amdgpu_vm_debug) {
880 		/* Invalidate all BOs to test for userspace bugs */
881 		amdgpu_bo_list_for_each_entry(e, p->bo_list) {
882 			/* ignore duplicates */
883 			if (!e->robj)
884 				continue;
885 
886 			amdgpu_vm_bo_invalidate(adev, e->robj, false);
887 		}
888 	}
889 
890 	return r;
891 }
892 
893 static int amdgpu_cs_ib_vm_chunk(struct amdgpu_device *adev,
894 				 struct amdgpu_cs_parser *p)
895 {
896 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
897 	struct amdgpu_vm *vm = &fpriv->vm;
898 	struct amdgpu_ring *ring = p->ring;
899 	int r;
900 
901 	/* Only for UVD/VCE VM emulation */
902 	if (p->ring->funcs->parse_cs || p->ring->funcs->patch_cs_in_place) {
903 		unsigned i, j;
904 
905 		for (i = 0, j = 0; i < p->nchunks && j < p->job->num_ibs; i++) {
906 			struct drm_amdgpu_cs_chunk_ib *chunk_ib;
907 			struct amdgpu_bo_va_mapping *m;
908 			struct amdgpu_bo *aobj = NULL;
909 			struct amdgpu_cs_chunk *chunk;
910 			uint64_t offset, va_start;
911 			struct amdgpu_ib *ib;
912 			uint8_t *kptr;
913 
914 			chunk = &p->chunks[i];
915 			ib = &p->job->ibs[j];
916 			chunk_ib = chunk->kdata;
917 
918 			if (chunk->chunk_id != AMDGPU_CHUNK_ID_IB)
919 				continue;
920 
921 			va_start = chunk_ib->va_start & AMDGPU_VA_HOLE_MASK;
922 			r = amdgpu_cs_find_mapping(p, va_start, &aobj, &m);
923 			if (r) {
924 				DRM_ERROR("IB va_start is invalid\n");
925 				return r;
926 			}
927 
928 			if ((va_start + chunk_ib->ib_bytes) >
929 			    (m->last + 1) * AMDGPU_GPU_PAGE_SIZE) {
930 				DRM_ERROR("IB va_start+ib_bytes is invalid\n");
931 				return -EINVAL;
932 			}
933 
934 			/* the IB should be reserved at this point */
935 			r = amdgpu_bo_kmap(aobj, (void **)&kptr);
936 			if (r) {
937 				return r;
938 			}
939 
940 			offset = m->start * AMDGPU_GPU_PAGE_SIZE;
941 			kptr += va_start - offset;
942 
943 			if (p->ring->funcs->parse_cs) {
944 				memcpy(ib->ptr, kptr, chunk_ib->ib_bytes);
945 				amdgpu_bo_kunmap(aobj);
946 
947 				r = amdgpu_ring_parse_cs(ring, p, j);
948 				if (r)
949 					return r;
950 			} else {
951 				ib->ptr = (uint32_t *)kptr;
952 				r = amdgpu_ring_patch_cs_in_place(ring, p, j);
953 				amdgpu_bo_kunmap(aobj);
954 				if (r)
955 					return r;
956 			}
957 
958 			j++;
959 		}
960 	}
961 
962 	if (p->job->vm) {
963 		p->job->vm_pd_addr = amdgpu_bo_gpu_offset(vm->root.base.bo);
964 
965 		r = amdgpu_bo_vm_update_pte(p);
966 		if (r)
967 			return r;
968 
969 		r = reservation_object_reserve_shared(vm->root.base.bo->tbo.resv);
970 		if (r)
971 			return r;
972 	}
973 
974 	return amdgpu_cs_sync_rings(p);
975 }
976 
977 static int amdgpu_cs_ib_fill(struct amdgpu_device *adev,
978 			     struct amdgpu_cs_parser *parser)
979 {
980 	struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
981 	struct amdgpu_vm *vm = &fpriv->vm;
982 	int i, j;
983 	int r, ce_preempt = 0, de_preempt = 0;
984 
985 	for (i = 0, j = 0; i < parser->nchunks && j < parser->job->num_ibs; i++) {
986 		struct amdgpu_cs_chunk *chunk;
987 		struct amdgpu_ib *ib;
988 		struct drm_amdgpu_cs_chunk_ib *chunk_ib;
989 		struct amdgpu_ring *ring;
990 
991 		chunk = &parser->chunks[i];
992 		ib = &parser->job->ibs[j];
993 		chunk_ib = (struct drm_amdgpu_cs_chunk_ib *)chunk->kdata;
994 
995 		if (chunk->chunk_id != AMDGPU_CHUNK_ID_IB)
996 			continue;
997 
998 		if (chunk_ib->ip_type == AMDGPU_HW_IP_GFX && amdgpu_sriov_vf(adev)) {
999 			if (chunk_ib->flags & AMDGPU_IB_FLAG_PREEMPT) {
1000 				if (chunk_ib->flags & AMDGPU_IB_FLAG_CE)
1001 					ce_preempt++;
1002 				else
1003 					de_preempt++;
1004 			}
1005 
1006 			/* each GFX command submit allows 0 or 1 IB preemptible for CE & DE */
1007 			if (ce_preempt > 1 || de_preempt > 1)
1008 				return -EINVAL;
1009 		}
1010 
1011 		r = amdgpu_queue_mgr_map(adev, &parser->ctx->queue_mgr, chunk_ib->ip_type,
1012 					 chunk_ib->ip_instance, chunk_ib->ring, &ring);
1013 		if (r)
1014 			return r;
1015 
1016 		if (chunk_ib->flags & AMDGPU_IB_FLAG_PREAMBLE)
1017 			parser->job->preamble_status |=
1018 				AMDGPU_PREAMBLE_IB_PRESENT;
1019 
1020 		if (parser->ring && parser->ring != ring)
1021 			return -EINVAL;
1022 
1023 		parser->ring = ring;
1024 
1025 		r =  amdgpu_ib_get(adev, vm,
1026 					ring->funcs->parse_cs ? chunk_ib->ib_bytes : 0,
1027 					ib);
1028 		if (r) {
1029 			DRM_ERROR("Failed to get ib !\n");
1030 			return r;
1031 		}
1032 
1033 		ib->gpu_addr = chunk_ib->va_start;
1034 		ib->length_dw = chunk_ib->ib_bytes / 4;
1035 		ib->flags = chunk_ib->flags;
1036 
1037 		j++;
1038 	}
1039 
1040 	/* UVD & VCE fw doesn't support user fences */
1041 	if (parser->job->uf_addr && (
1042 	    parser->ring->funcs->type == AMDGPU_RING_TYPE_UVD ||
1043 	    parser->ring->funcs->type == AMDGPU_RING_TYPE_VCE))
1044 		return -EINVAL;
1045 
1046 	return amdgpu_ctx_wait_prev_fence(parser->ctx, parser->ring->idx);
1047 }
1048 
1049 static int amdgpu_cs_process_fence_dep(struct amdgpu_cs_parser *p,
1050 				       struct amdgpu_cs_chunk *chunk)
1051 {
1052 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
1053 	unsigned num_deps;
1054 	int i, r;
1055 	struct drm_amdgpu_cs_chunk_dep *deps;
1056 
1057 	deps = (struct drm_amdgpu_cs_chunk_dep *)chunk->kdata;
1058 	num_deps = chunk->length_dw * 4 /
1059 		sizeof(struct drm_amdgpu_cs_chunk_dep);
1060 
1061 	for (i = 0; i < num_deps; ++i) {
1062 		struct amdgpu_ring *ring;
1063 		struct amdgpu_ctx *ctx;
1064 		struct dma_fence *fence;
1065 
1066 		ctx = amdgpu_ctx_get(fpriv, deps[i].ctx_id);
1067 		if (ctx == NULL)
1068 			return -EINVAL;
1069 
1070 		r = amdgpu_queue_mgr_map(p->adev, &ctx->queue_mgr,
1071 					 deps[i].ip_type,
1072 					 deps[i].ip_instance,
1073 					 deps[i].ring, &ring);
1074 		if (r) {
1075 			amdgpu_ctx_put(ctx);
1076 			return r;
1077 		}
1078 
1079 		fence = amdgpu_ctx_get_fence(ctx, ring,
1080 					     deps[i].handle);
1081 		if (IS_ERR(fence)) {
1082 			r = PTR_ERR(fence);
1083 			amdgpu_ctx_put(ctx);
1084 			return r;
1085 		} else if (fence) {
1086 			r = amdgpu_sync_fence(p->adev, &p->job->sync, fence,
1087 					true);
1088 			dma_fence_put(fence);
1089 			amdgpu_ctx_put(ctx);
1090 			if (r)
1091 				return r;
1092 		}
1093 	}
1094 	return 0;
1095 }
1096 
1097 static int amdgpu_syncobj_lookup_and_add_to_sync(struct amdgpu_cs_parser *p,
1098 						 uint32_t handle)
1099 {
1100 	int r;
1101 	struct dma_fence *fence;
1102 	r = drm_syncobj_find_fence(p->filp, handle, &fence);
1103 	if (r)
1104 		return r;
1105 
1106 	r = amdgpu_sync_fence(p->adev, &p->job->sync, fence, true);
1107 	dma_fence_put(fence);
1108 
1109 	return r;
1110 }
1111 
1112 static int amdgpu_cs_process_syncobj_in_dep(struct amdgpu_cs_parser *p,
1113 					    struct amdgpu_cs_chunk *chunk)
1114 {
1115 	unsigned num_deps;
1116 	int i, r;
1117 	struct drm_amdgpu_cs_chunk_sem *deps;
1118 
1119 	deps = (struct drm_amdgpu_cs_chunk_sem *)chunk->kdata;
1120 	num_deps = chunk->length_dw * 4 /
1121 		sizeof(struct drm_amdgpu_cs_chunk_sem);
1122 
1123 	for (i = 0; i < num_deps; ++i) {
1124 		r = amdgpu_syncobj_lookup_and_add_to_sync(p, deps[i].handle);
1125 		if (r)
1126 			return r;
1127 	}
1128 	return 0;
1129 }
1130 
1131 static int amdgpu_cs_process_syncobj_out_dep(struct amdgpu_cs_parser *p,
1132 					     struct amdgpu_cs_chunk *chunk)
1133 {
1134 	unsigned num_deps;
1135 	int i;
1136 	struct drm_amdgpu_cs_chunk_sem *deps;
1137 	deps = (struct drm_amdgpu_cs_chunk_sem *)chunk->kdata;
1138 	num_deps = chunk->length_dw * 4 /
1139 		sizeof(struct drm_amdgpu_cs_chunk_sem);
1140 
1141 	p->post_dep_syncobjs = kmalloc_array(num_deps,
1142 					     sizeof(struct drm_syncobj *),
1143 					     GFP_KERNEL);
1144 	p->num_post_dep_syncobjs = 0;
1145 
1146 	if (!p->post_dep_syncobjs)
1147 		return -ENOMEM;
1148 
1149 	for (i = 0; i < num_deps; ++i) {
1150 		p->post_dep_syncobjs[i] = drm_syncobj_find(p->filp, deps[i].handle);
1151 		if (!p->post_dep_syncobjs[i])
1152 			return -EINVAL;
1153 		p->num_post_dep_syncobjs++;
1154 	}
1155 	return 0;
1156 }
1157 
1158 static int amdgpu_cs_dependencies(struct amdgpu_device *adev,
1159 				  struct amdgpu_cs_parser *p)
1160 {
1161 	int i, r;
1162 
1163 	for (i = 0; i < p->nchunks; ++i) {
1164 		struct amdgpu_cs_chunk *chunk;
1165 
1166 		chunk = &p->chunks[i];
1167 
1168 		if (chunk->chunk_id == AMDGPU_CHUNK_ID_DEPENDENCIES) {
1169 			r = amdgpu_cs_process_fence_dep(p, chunk);
1170 			if (r)
1171 				return r;
1172 		} else if (chunk->chunk_id == AMDGPU_CHUNK_ID_SYNCOBJ_IN) {
1173 			r = amdgpu_cs_process_syncobj_in_dep(p, chunk);
1174 			if (r)
1175 				return r;
1176 		} else if (chunk->chunk_id == AMDGPU_CHUNK_ID_SYNCOBJ_OUT) {
1177 			r = amdgpu_cs_process_syncobj_out_dep(p, chunk);
1178 			if (r)
1179 				return r;
1180 		}
1181 	}
1182 
1183 	return 0;
1184 }
1185 
1186 static void amdgpu_cs_post_dependencies(struct amdgpu_cs_parser *p)
1187 {
1188 	int i;
1189 
1190 	for (i = 0; i < p->num_post_dep_syncobjs; ++i)
1191 		drm_syncobj_replace_fence(p->post_dep_syncobjs[i], p->fence);
1192 }
1193 
1194 static int amdgpu_cs_submit(struct amdgpu_cs_parser *p,
1195 			    union drm_amdgpu_cs *cs)
1196 {
1197 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
1198 	struct amdgpu_ring *ring = p->ring;
1199 	struct drm_sched_entity *entity = &p->ctx->rings[ring->idx].entity;
1200 	enum drm_sched_priority priority;
1201 	struct amdgpu_bo_list_entry *e;
1202 	struct amdgpu_job *job;
1203 	uint64_t seq;
1204 
1205 	int r;
1206 
1207 	amdgpu_mn_lock(p->mn);
1208 	amdgpu_bo_list_for_each_userptr_entry(e, p->bo_list) {
1209 		struct amdgpu_bo *bo = e->robj;
1210 
1211 		if (amdgpu_ttm_tt_userptr_needs_pages(bo->tbo.ttm)) {
1212 			amdgpu_mn_unlock(p->mn);
1213 			return -ERESTARTSYS;
1214 		}
1215 	}
1216 
1217 	job = p->job;
1218 	p->job = NULL;
1219 
1220 	r = drm_sched_job_init(&job->base, entity, p->filp);
1221 	if (r) {
1222 		amdgpu_job_free(job);
1223 		amdgpu_mn_unlock(p->mn);
1224 		return r;
1225 	}
1226 
1227 	job->owner = p->filp;
1228 	p->fence = dma_fence_get(&job->base.s_fence->finished);
1229 
1230 	r = amdgpu_ctx_add_fence(p->ctx, ring, p->fence, &seq);
1231 	if (r) {
1232 		dma_fence_put(p->fence);
1233 		dma_fence_put(&job->base.s_fence->finished);
1234 		amdgpu_job_free(job);
1235 		amdgpu_mn_unlock(p->mn);
1236 		return r;
1237 	}
1238 
1239 	amdgpu_cs_post_dependencies(p);
1240 
1241 	if ((job->preamble_status & AMDGPU_PREAMBLE_IB_PRESENT) &&
1242 	    !p->ctx->preamble_presented) {
1243 		job->preamble_status |= AMDGPU_PREAMBLE_IB_PRESENT_FIRST;
1244 		p->ctx->preamble_presented = true;
1245 	}
1246 
1247 	cs->out.handle = seq;
1248 	job->uf_sequence = seq;
1249 
1250 	amdgpu_job_free_resources(job);
1251 
1252 	trace_amdgpu_cs_ioctl(job);
1253 	amdgpu_vm_bo_trace_cs(&fpriv->vm, &p->ticket);
1254 	priority = job->base.s_priority;
1255 	drm_sched_entity_push_job(&job->base, entity);
1256 
1257 	ring = to_amdgpu_ring(entity->rq->sched);
1258 	amdgpu_ring_priority_get(ring, priority);
1259 
1260 	ttm_eu_fence_buffer_objects(&p->ticket, &p->validated, p->fence);
1261 	amdgpu_mn_unlock(p->mn);
1262 
1263 	return 0;
1264 }
1265 
1266 int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
1267 {
1268 	struct amdgpu_device *adev = dev->dev_private;
1269 	union drm_amdgpu_cs *cs = data;
1270 	struct amdgpu_cs_parser parser = {};
1271 	bool reserved_buffers = false;
1272 	int i, r;
1273 
1274 	if (!adev->accel_working)
1275 		return -EBUSY;
1276 
1277 	parser.adev = adev;
1278 	parser.filp = filp;
1279 
1280 	r = amdgpu_cs_parser_init(&parser, data);
1281 	if (r) {
1282 		DRM_ERROR("Failed to initialize parser !\n");
1283 		goto out;
1284 	}
1285 
1286 	r = amdgpu_cs_ib_fill(adev, &parser);
1287 	if (r)
1288 		goto out;
1289 
1290 	r = amdgpu_cs_parser_bos(&parser, data);
1291 	if (r) {
1292 		if (r == -ENOMEM)
1293 			DRM_ERROR("Not enough memory for command submission!\n");
1294 		else if (r != -ERESTARTSYS)
1295 			DRM_ERROR("Failed to process the buffer list %d!\n", r);
1296 		goto out;
1297 	}
1298 
1299 	reserved_buffers = true;
1300 
1301 	r = amdgpu_cs_dependencies(adev, &parser);
1302 	if (r) {
1303 		DRM_ERROR("Failed in the dependencies handling %d!\n", r);
1304 		goto out;
1305 	}
1306 
1307 	for (i = 0; i < parser.job->num_ibs; i++)
1308 		trace_amdgpu_cs(&parser, i);
1309 
1310 	r = amdgpu_cs_ib_vm_chunk(adev, &parser);
1311 	if (r)
1312 		goto out;
1313 
1314 	r = amdgpu_cs_submit(&parser, cs);
1315 
1316 out:
1317 	amdgpu_cs_parser_fini(&parser, r, reserved_buffers);
1318 	return r;
1319 }
1320 
1321 /**
1322  * amdgpu_cs_wait_ioctl - wait for a command submission to finish
1323  *
1324  * @dev: drm device
1325  * @data: data from userspace
1326  * @filp: file private
1327  *
1328  * Wait for the command submission identified by handle to finish.
1329  */
1330 int amdgpu_cs_wait_ioctl(struct drm_device *dev, void *data,
1331 			 struct drm_file *filp)
1332 {
1333 	union drm_amdgpu_wait_cs *wait = data;
1334 	struct amdgpu_device *adev = dev->dev_private;
1335 	unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout);
1336 	struct amdgpu_ring *ring = NULL;
1337 	struct amdgpu_ctx *ctx;
1338 	struct dma_fence *fence;
1339 	long r;
1340 
1341 	ctx = amdgpu_ctx_get(filp->driver_priv, wait->in.ctx_id);
1342 	if (ctx == NULL)
1343 		return -EINVAL;
1344 
1345 	r = amdgpu_queue_mgr_map(adev, &ctx->queue_mgr,
1346 				 wait->in.ip_type, wait->in.ip_instance,
1347 				 wait->in.ring, &ring);
1348 	if (r) {
1349 		amdgpu_ctx_put(ctx);
1350 		return r;
1351 	}
1352 
1353 	fence = amdgpu_ctx_get_fence(ctx, ring, wait->in.handle);
1354 	if (IS_ERR(fence))
1355 		r = PTR_ERR(fence);
1356 	else if (fence) {
1357 		r = dma_fence_wait_timeout(fence, true, timeout);
1358 		if (r > 0 && fence->error)
1359 			r = fence->error;
1360 		dma_fence_put(fence);
1361 	} else
1362 		r = 1;
1363 
1364 	amdgpu_ctx_put(ctx);
1365 	if (r < 0)
1366 		return r;
1367 
1368 	memset(wait, 0, sizeof(*wait));
1369 	wait->out.status = (r == 0);
1370 
1371 	return 0;
1372 }
1373 
1374 /**
1375  * amdgpu_cs_get_fence - helper to get fence from drm_amdgpu_fence
1376  *
1377  * @adev: amdgpu device
1378  * @filp: file private
1379  * @user: drm_amdgpu_fence copied from user space
1380  */
1381 static struct dma_fence *amdgpu_cs_get_fence(struct amdgpu_device *adev,
1382 					     struct drm_file *filp,
1383 					     struct drm_amdgpu_fence *user)
1384 {
1385 	struct amdgpu_ring *ring;
1386 	struct amdgpu_ctx *ctx;
1387 	struct dma_fence *fence;
1388 	int r;
1389 
1390 	ctx = amdgpu_ctx_get(filp->driver_priv, user->ctx_id);
1391 	if (ctx == NULL)
1392 		return ERR_PTR(-EINVAL);
1393 
1394 	r = amdgpu_queue_mgr_map(adev, &ctx->queue_mgr, user->ip_type,
1395 				 user->ip_instance, user->ring, &ring);
1396 	if (r) {
1397 		amdgpu_ctx_put(ctx);
1398 		return ERR_PTR(r);
1399 	}
1400 
1401 	fence = amdgpu_ctx_get_fence(ctx, ring, user->seq_no);
1402 	amdgpu_ctx_put(ctx);
1403 
1404 	return fence;
1405 }
1406 
1407 int amdgpu_cs_fence_to_handle_ioctl(struct drm_device *dev, void *data,
1408 				    struct drm_file *filp)
1409 {
1410 	struct amdgpu_device *adev = dev->dev_private;
1411 	union drm_amdgpu_fence_to_handle *info = data;
1412 	struct dma_fence *fence;
1413 	struct drm_syncobj *syncobj;
1414 	struct sync_file *sync_file;
1415 	int fd, r;
1416 
1417 	fence = amdgpu_cs_get_fence(adev, filp, &info->in.fence);
1418 	if (IS_ERR(fence))
1419 		return PTR_ERR(fence);
1420 
1421 	switch (info->in.what) {
1422 	case AMDGPU_FENCE_TO_HANDLE_GET_SYNCOBJ:
1423 		r = drm_syncobj_create(&syncobj, 0, fence);
1424 		dma_fence_put(fence);
1425 		if (r)
1426 			return r;
1427 		r = drm_syncobj_get_handle(filp, syncobj, &info->out.handle);
1428 		drm_syncobj_put(syncobj);
1429 		return r;
1430 
1431 	case AMDGPU_FENCE_TO_HANDLE_GET_SYNCOBJ_FD:
1432 		r = drm_syncobj_create(&syncobj, 0, fence);
1433 		dma_fence_put(fence);
1434 		if (r)
1435 			return r;
1436 		r = drm_syncobj_get_fd(syncobj, (int*)&info->out.handle);
1437 		drm_syncobj_put(syncobj);
1438 		return r;
1439 
1440 	case AMDGPU_FENCE_TO_HANDLE_GET_SYNC_FILE_FD:
1441 		fd = get_unused_fd_flags(O_CLOEXEC);
1442 		if (fd < 0) {
1443 			dma_fence_put(fence);
1444 			return fd;
1445 		}
1446 
1447 		sync_file = sync_file_create(fence);
1448 		dma_fence_put(fence);
1449 		if (!sync_file) {
1450 			put_unused_fd(fd);
1451 			return -ENOMEM;
1452 		}
1453 
1454 		fd_install(fd, sync_file->file);
1455 		info->out.handle = fd;
1456 		return 0;
1457 
1458 	default:
1459 		return -EINVAL;
1460 	}
1461 }
1462 
1463 /**
1464  * amdgpu_cs_wait_all_fence - wait on all fences to signal
1465  *
1466  * @adev: amdgpu device
1467  * @filp: file private
1468  * @wait: wait parameters
1469  * @fences: array of drm_amdgpu_fence
1470  */
1471 static int amdgpu_cs_wait_all_fences(struct amdgpu_device *adev,
1472 				     struct drm_file *filp,
1473 				     union drm_amdgpu_wait_fences *wait,
1474 				     struct drm_amdgpu_fence *fences)
1475 {
1476 	uint32_t fence_count = wait->in.fence_count;
1477 	unsigned int i;
1478 	long r = 1;
1479 
1480 	for (i = 0; i < fence_count; i++) {
1481 		struct dma_fence *fence;
1482 		unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout_ns);
1483 
1484 		fence = amdgpu_cs_get_fence(adev, filp, &fences[i]);
1485 		if (IS_ERR(fence))
1486 			return PTR_ERR(fence);
1487 		else if (!fence)
1488 			continue;
1489 
1490 		r = dma_fence_wait_timeout(fence, true, timeout);
1491 		dma_fence_put(fence);
1492 		if (r < 0)
1493 			return r;
1494 
1495 		if (r == 0)
1496 			break;
1497 
1498 		if (fence->error)
1499 			return fence->error;
1500 	}
1501 
1502 	memset(wait, 0, sizeof(*wait));
1503 	wait->out.status = (r > 0);
1504 
1505 	return 0;
1506 }
1507 
1508 /**
1509  * amdgpu_cs_wait_any_fence - wait on any fence to signal
1510  *
1511  * @adev: amdgpu device
1512  * @filp: file private
1513  * @wait: wait parameters
1514  * @fences: array of drm_amdgpu_fence
1515  */
1516 static int amdgpu_cs_wait_any_fence(struct amdgpu_device *adev,
1517 				    struct drm_file *filp,
1518 				    union drm_amdgpu_wait_fences *wait,
1519 				    struct drm_amdgpu_fence *fences)
1520 {
1521 	unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout_ns);
1522 	uint32_t fence_count = wait->in.fence_count;
1523 	uint32_t first = ~0;
1524 	struct dma_fence **array;
1525 	unsigned int i;
1526 	long r;
1527 
1528 	/* Prepare the fence array */
1529 	array = kcalloc(fence_count, sizeof(struct dma_fence *), GFP_KERNEL);
1530 
1531 	if (array == NULL)
1532 		return -ENOMEM;
1533 
1534 	for (i = 0; i < fence_count; i++) {
1535 		struct dma_fence *fence;
1536 
1537 		fence = amdgpu_cs_get_fence(adev, filp, &fences[i]);
1538 		if (IS_ERR(fence)) {
1539 			r = PTR_ERR(fence);
1540 			goto err_free_fence_array;
1541 		} else if (fence) {
1542 			array[i] = fence;
1543 		} else { /* NULL, the fence has been already signaled */
1544 			r = 1;
1545 			first = i;
1546 			goto out;
1547 		}
1548 	}
1549 
1550 	r = dma_fence_wait_any_timeout(array, fence_count, true, timeout,
1551 				       &first);
1552 	if (r < 0)
1553 		goto err_free_fence_array;
1554 
1555 out:
1556 	memset(wait, 0, sizeof(*wait));
1557 	wait->out.status = (r > 0);
1558 	wait->out.first_signaled = first;
1559 
1560 	if (first < fence_count && array[first])
1561 		r = array[first]->error;
1562 	else
1563 		r = 0;
1564 
1565 err_free_fence_array:
1566 	for (i = 0; i < fence_count; i++)
1567 		dma_fence_put(array[i]);
1568 	kfree(array);
1569 
1570 	return r;
1571 }
1572 
1573 /**
1574  * amdgpu_cs_wait_fences_ioctl - wait for multiple command submissions to finish
1575  *
1576  * @dev: drm device
1577  * @data: data from userspace
1578  * @filp: file private
1579  */
1580 int amdgpu_cs_wait_fences_ioctl(struct drm_device *dev, void *data,
1581 				struct drm_file *filp)
1582 {
1583 	struct amdgpu_device *adev = dev->dev_private;
1584 	union drm_amdgpu_wait_fences *wait = data;
1585 	uint32_t fence_count = wait->in.fence_count;
1586 	struct drm_amdgpu_fence *fences_user;
1587 	struct drm_amdgpu_fence *fences;
1588 	int r;
1589 
1590 	/* Get the fences from userspace */
1591 	fences = kmalloc_array(fence_count, sizeof(struct drm_amdgpu_fence),
1592 			GFP_KERNEL);
1593 	if (fences == NULL)
1594 		return -ENOMEM;
1595 
1596 	fences_user = u64_to_user_ptr(wait->in.fences);
1597 	if (copy_from_user(fences, fences_user,
1598 		sizeof(struct drm_amdgpu_fence) * fence_count)) {
1599 		r = -EFAULT;
1600 		goto err_free_fences;
1601 	}
1602 
1603 	if (wait->in.wait_all)
1604 		r = amdgpu_cs_wait_all_fences(adev, filp, wait, fences);
1605 	else
1606 		r = amdgpu_cs_wait_any_fence(adev, filp, wait, fences);
1607 
1608 err_free_fences:
1609 	kfree(fences);
1610 
1611 	return r;
1612 }
1613 
1614 /**
1615  * amdgpu_cs_find_bo_va - find bo_va for VM address
1616  *
1617  * @parser: command submission parser context
1618  * @addr: VM address
1619  * @bo: resulting BO of the mapping found
1620  *
1621  * Search the buffer objects in the command submission context for a certain
1622  * virtual memory address. Returns allocation structure when found, NULL
1623  * otherwise.
1624  */
1625 int amdgpu_cs_find_mapping(struct amdgpu_cs_parser *parser,
1626 			   uint64_t addr, struct amdgpu_bo **bo,
1627 			   struct amdgpu_bo_va_mapping **map)
1628 {
1629 	struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
1630 	struct ttm_operation_ctx ctx = { false, false };
1631 	struct amdgpu_vm *vm = &fpriv->vm;
1632 	struct amdgpu_bo_va_mapping *mapping;
1633 	int r;
1634 
1635 	addr /= AMDGPU_GPU_PAGE_SIZE;
1636 
1637 	mapping = amdgpu_vm_bo_lookup_mapping(vm, addr);
1638 	if (!mapping || !mapping->bo_va || !mapping->bo_va->base.bo)
1639 		return -EINVAL;
1640 
1641 	*bo = mapping->bo_va->base.bo;
1642 	*map = mapping;
1643 
1644 	/* Double check that the BO is reserved by this CS */
1645 	if (READ_ONCE((*bo)->tbo.resv->lock.ctx) != &parser->ticket)
1646 		return -EINVAL;
1647 
1648 	if (!((*bo)->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS)) {
1649 		(*bo)->flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
1650 		amdgpu_bo_placement_from_domain(*bo, (*bo)->allowed_domains);
1651 		r = ttm_bo_validate(&(*bo)->tbo, &(*bo)->placement, &ctx);
1652 		if (r)
1653 			return r;
1654 	}
1655 
1656 	return amdgpu_ttm_alloc_gart(&(*bo)->tbo);
1657 }
1658