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