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