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