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