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