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