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