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