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