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