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