xref: /openbmc/linux/drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c (revision 029f7f3b8701cc7aca8bdb31f0c7edd6a479e357)
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 #include <linux/list_sort.h>
28 #include <drm/drmP.h>
29 #include <drm/amdgpu_drm.h>
30 #include "amdgpu.h"
31 #include "amdgpu_trace.h"
32 
33 #define AMDGPU_CS_MAX_PRIORITY		32u
34 #define AMDGPU_CS_NUM_BUCKETS		(AMDGPU_CS_MAX_PRIORITY + 1)
35 
36 /* This is based on the bucket sort with O(n) time complexity.
37  * An item with priority "i" is added to bucket[i]. The lists are then
38  * concatenated in descending order.
39  */
40 struct amdgpu_cs_buckets {
41 	struct list_head bucket[AMDGPU_CS_NUM_BUCKETS];
42 };
43 
44 static void amdgpu_cs_buckets_init(struct amdgpu_cs_buckets *b)
45 {
46 	unsigned i;
47 
48 	for (i = 0; i < AMDGPU_CS_NUM_BUCKETS; i++)
49 		INIT_LIST_HEAD(&b->bucket[i]);
50 }
51 
52 static void amdgpu_cs_buckets_add(struct amdgpu_cs_buckets *b,
53 				  struct list_head *item, unsigned priority)
54 {
55 	/* Since buffers which appear sooner in the relocation list are
56 	 * likely to be used more often than buffers which appear later
57 	 * in the list, the sort mustn't change the ordering of buffers
58 	 * with the same priority, i.e. it must be stable.
59 	 */
60 	list_add_tail(item, &b->bucket[min(priority, AMDGPU_CS_MAX_PRIORITY)]);
61 }
62 
63 static void amdgpu_cs_buckets_get_list(struct amdgpu_cs_buckets *b,
64 				       struct list_head *out_list)
65 {
66 	unsigned i;
67 
68 	/* Connect the sorted buckets in the output list. */
69 	for (i = 0; i < AMDGPU_CS_NUM_BUCKETS; i++) {
70 		list_splice(&b->bucket[i], out_list);
71 	}
72 }
73 
74 int amdgpu_cs_get_ring(struct amdgpu_device *adev, u32 ip_type,
75 		       u32 ip_instance, u32 ring,
76 		       struct amdgpu_ring **out_ring)
77 {
78 	/* Right now all IPs have only one instance - multiple rings. */
79 	if (ip_instance != 0) {
80 		DRM_ERROR("invalid ip instance: %d\n", ip_instance);
81 		return -EINVAL;
82 	}
83 
84 	switch (ip_type) {
85 	default:
86 		DRM_ERROR("unknown ip type: %d\n", ip_type);
87 		return -EINVAL;
88 	case AMDGPU_HW_IP_GFX:
89 		if (ring < adev->gfx.num_gfx_rings) {
90 			*out_ring = &adev->gfx.gfx_ring[ring];
91 		} else {
92 			DRM_ERROR("only %d gfx rings are supported now\n",
93 				  adev->gfx.num_gfx_rings);
94 			return -EINVAL;
95 		}
96 		break;
97 	case AMDGPU_HW_IP_COMPUTE:
98 		if (ring < adev->gfx.num_compute_rings) {
99 			*out_ring = &adev->gfx.compute_ring[ring];
100 		} else {
101 			DRM_ERROR("only %d compute rings are supported now\n",
102 				  adev->gfx.num_compute_rings);
103 			return -EINVAL;
104 		}
105 		break;
106 	case AMDGPU_HW_IP_DMA:
107 		if (ring < adev->sdma.num_instances) {
108 			*out_ring = &adev->sdma.instance[ring].ring;
109 		} else {
110 			DRM_ERROR("only %d SDMA rings are supported\n",
111 				  adev->sdma.num_instances);
112 			return -EINVAL;
113 		}
114 		break;
115 	case AMDGPU_HW_IP_UVD:
116 		*out_ring = &adev->uvd.ring;
117 		break;
118 	case AMDGPU_HW_IP_VCE:
119 		if (ring < 2){
120 			*out_ring = &adev->vce.ring[ring];
121 		} else {
122 			DRM_ERROR("only two VCE rings are supported\n");
123 			return -EINVAL;
124 		}
125 		break;
126 	}
127 	return 0;
128 }
129 
130 struct amdgpu_cs_parser *amdgpu_cs_parser_create(struct amdgpu_device *adev,
131                                                struct drm_file *filp,
132                                                struct amdgpu_ctx *ctx,
133                                                struct amdgpu_ib *ibs,
134                                                uint32_t num_ibs)
135 {
136 	struct amdgpu_cs_parser *parser;
137 	int i;
138 
139 	parser = kzalloc(sizeof(struct amdgpu_cs_parser), GFP_KERNEL);
140 	if (!parser)
141 		return NULL;
142 
143 	parser->adev = adev;
144 	parser->filp = filp;
145 	parser->ctx = ctx;
146 	parser->ibs = ibs;
147 	parser->num_ibs = num_ibs;
148 	for (i = 0; i < num_ibs; i++)
149 		ibs[i].ctx = ctx;
150 
151 	return parser;
152 }
153 
154 int amdgpu_cs_parser_init(struct amdgpu_cs_parser *p, void *data)
155 {
156 	union drm_amdgpu_cs *cs = data;
157 	uint64_t *chunk_array_user;
158 	uint64_t *chunk_array;
159 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
160 	unsigned size;
161 	int i;
162 	int ret;
163 
164 	if (cs->in.num_chunks == 0)
165 		return 0;
166 
167 	chunk_array = kmalloc_array(cs->in.num_chunks, sizeof(uint64_t), GFP_KERNEL);
168 	if (!chunk_array)
169 		return -ENOMEM;
170 
171 	p->ctx = amdgpu_ctx_get(fpriv, cs->in.ctx_id);
172 	if (!p->ctx) {
173 		ret = -EINVAL;
174 		goto free_chunk;
175 	}
176 
177 	p->bo_list = amdgpu_bo_list_get(fpriv, cs->in.bo_list_handle);
178 
179 	/* get chunks */
180 	INIT_LIST_HEAD(&p->validated);
181 	chunk_array_user = (uint64_t __user *)(unsigned long)(cs->in.chunks);
182 	if (copy_from_user(chunk_array, chunk_array_user,
183 			   sizeof(uint64_t)*cs->in.num_chunks)) {
184 		ret = -EFAULT;
185 		goto put_bo_list;
186 	}
187 
188 	p->nchunks = cs->in.num_chunks;
189 	p->chunks = kmalloc_array(p->nchunks, sizeof(struct amdgpu_cs_chunk),
190 			    GFP_KERNEL);
191 	if (!p->chunks) {
192 		ret = -ENOMEM;
193 		goto put_bo_list;
194 	}
195 
196 	for (i = 0; i < p->nchunks; i++) {
197 		struct drm_amdgpu_cs_chunk __user **chunk_ptr = NULL;
198 		struct drm_amdgpu_cs_chunk user_chunk;
199 		uint32_t __user *cdata;
200 
201 		chunk_ptr = (void __user *)(unsigned long)chunk_array[i];
202 		if (copy_from_user(&user_chunk, chunk_ptr,
203 				       sizeof(struct drm_amdgpu_cs_chunk))) {
204 			ret = -EFAULT;
205 			i--;
206 			goto free_partial_kdata;
207 		}
208 		p->chunks[i].chunk_id = user_chunk.chunk_id;
209 		p->chunks[i].length_dw = user_chunk.length_dw;
210 
211 		size = p->chunks[i].length_dw;
212 		cdata = (void __user *)(unsigned long)user_chunk.chunk_data;
213 		p->chunks[i].user_ptr = cdata;
214 
215 		p->chunks[i].kdata = drm_malloc_ab(size, sizeof(uint32_t));
216 		if (p->chunks[i].kdata == NULL) {
217 			ret = -ENOMEM;
218 			i--;
219 			goto free_partial_kdata;
220 		}
221 		size *= sizeof(uint32_t);
222 		if (copy_from_user(p->chunks[i].kdata, cdata, size)) {
223 			ret = -EFAULT;
224 			goto free_partial_kdata;
225 		}
226 
227 		switch (p->chunks[i].chunk_id) {
228 		case AMDGPU_CHUNK_ID_IB:
229 			p->num_ibs++;
230 			break;
231 
232 		case AMDGPU_CHUNK_ID_FENCE:
233 			size = sizeof(struct drm_amdgpu_cs_chunk_fence);
234 			if (p->chunks[i].length_dw * sizeof(uint32_t) >= size) {
235 				uint32_t handle;
236 				struct drm_gem_object *gobj;
237 				struct drm_amdgpu_cs_chunk_fence *fence_data;
238 
239 				fence_data = (void *)p->chunks[i].kdata;
240 				handle = fence_data->handle;
241 				gobj = drm_gem_object_lookup(p->adev->ddev,
242 							     p->filp, handle);
243 				if (gobj == NULL) {
244 					ret = -EINVAL;
245 					goto free_partial_kdata;
246 				}
247 
248 				p->uf.bo = gem_to_amdgpu_bo(gobj);
249 				p->uf.offset = fence_data->offset;
250 			} else {
251 				ret = -EINVAL;
252 				goto free_partial_kdata;
253 			}
254 			break;
255 
256 		case AMDGPU_CHUNK_ID_DEPENDENCIES:
257 			break;
258 
259 		default:
260 			ret = -EINVAL;
261 			goto free_partial_kdata;
262 		}
263 	}
264 
265 
266 	p->ibs = kcalloc(p->num_ibs, sizeof(struct amdgpu_ib), GFP_KERNEL);
267 	if (!p->ibs) {
268 		ret = -ENOMEM;
269 		goto free_all_kdata;
270 	}
271 
272 	kfree(chunk_array);
273 	return 0;
274 
275 free_all_kdata:
276 	i = p->nchunks - 1;
277 free_partial_kdata:
278 	for (; i >= 0; i--)
279 		drm_free_large(p->chunks[i].kdata);
280 	kfree(p->chunks);
281 put_bo_list:
282 	if (p->bo_list)
283 		amdgpu_bo_list_put(p->bo_list);
284 	amdgpu_ctx_put(p->ctx);
285 free_chunk:
286 	kfree(chunk_array);
287 
288 	return ret;
289 }
290 
291 /* Returns how many bytes TTM can move per IB.
292  */
293 static u64 amdgpu_cs_get_threshold_for_moves(struct amdgpu_device *adev)
294 {
295 	u64 real_vram_size = adev->mc.real_vram_size;
296 	u64 vram_usage = atomic64_read(&adev->vram_usage);
297 
298 	/* This function is based on the current VRAM usage.
299 	 *
300 	 * - If all of VRAM is free, allow relocating the number of bytes that
301 	 *   is equal to 1/4 of the size of VRAM for this IB.
302 
303 	 * - If more than one half of VRAM is occupied, only allow relocating
304 	 *   1 MB of data for this IB.
305 	 *
306 	 * - From 0 to one half of used VRAM, the threshold decreases
307 	 *   linearly.
308 	 *         __________________
309 	 * 1/4 of -|\               |
310 	 * VRAM    | \              |
311 	 *         |  \             |
312 	 *         |   \            |
313 	 *         |    \           |
314 	 *         |     \          |
315 	 *         |      \         |
316 	 *         |       \________|1 MB
317 	 *         |----------------|
318 	 *    VRAM 0 %             100 %
319 	 *         used            used
320 	 *
321 	 * Note: It's a threshold, not a limit. The threshold must be crossed
322 	 * for buffer relocations to stop, so any buffer of an arbitrary size
323 	 * can be moved as long as the threshold isn't crossed before
324 	 * the relocation takes place. We don't want to disable buffer
325 	 * relocations completely.
326 	 *
327 	 * The idea is that buffers should be placed in VRAM at creation time
328 	 * and TTM should only do a minimum number of relocations during
329 	 * command submission. In practice, you need to submit at least
330 	 * a dozen IBs to move all buffers to VRAM if they are in GTT.
331 	 *
332 	 * Also, things can get pretty crazy under memory pressure and actual
333 	 * VRAM usage can change a lot, so playing safe even at 50% does
334 	 * consistently increase performance.
335 	 */
336 
337 	u64 half_vram = real_vram_size >> 1;
338 	u64 half_free_vram = vram_usage >= half_vram ? 0 : half_vram - vram_usage;
339 	u64 bytes_moved_threshold = half_free_vram >> 1;
340 	return max(bytes_moved_threshold, 1024*1024ull);
341 }
342 
343 int amdgpu_cs_list_validate(struct amdgpu_device *adev,
344 			    struct amdgpu_vm *vm,
345 			    struct list_head *validated)
346 {
347 	struct amdgpu_bo_list_entry *lobj;
348 	struct amdgpu_bo *bo;
349 	u64 bytes_moved = 0, initial_bytes_moved;
350 	u64 bytes_moved_threshold = amdgpu_cs_get_threshold_for_moves(adev);
351 	int r;
352 
353 	list_for_each_entry(lobj, validated, tv.head) {
354 		bo = lobj->robj;
355 		if (!bo->pin_count) {
356 			u32 domain = lobj->prefered_domains;
357 			u32 current_domain =
358 				amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type);
359 
360 			/* Check if this buffer will be moved and don't move it
361 			 * if we have moved too many buffers for this IB already.
362 			 *
363 			 * Note that this allows moving at least one buffer of
364 			 * any size, because it doesn't take the current "bo"
365 			 * into account. We don't want to disallow buffer moves
366 			 * completely.
367 			 */
368 			if ((lobj->allowed_domains & current_domain) != 0 &&
369 			    (domain & current_domain) == 0 && /* will be moved */
370 			    bytes_moved > bytes_moved_threshold) {
371 				/* don't move it */
372 				domain = current_domain;
373 			}
374 
375 		retry:
376 			amdgpu_ttm_placement_from_domain(bo, domain);
377 			initial_bytes_moved = atomic64_read(&adev->num_bytes_moved);
378 			r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
379 			bytes_moved += atomic64_read(&adev->num_bytes_moved) -
380 				       initial_bytes_moved;
381 
382 			if (unlikely(r)) {
383 				if (r != -ERESTARTSYS && domain != lobj->allowed_domains) {
384 					domain = lobj->allowed_domains;
385 					goto retry;
386 				}
387 				return r;
388 			}
389 		}
390 		lobj->bo_va = amdgpu_vm_bo_find(vm, bo);
391 	}
392 	return 0;
393 }
394 
395 static int amdgpu_cs_parser_relocs(struct amdgpu_cs_parser *p)
396 {
397 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
398 	struct amdgpu_cs_buckets buckets;
399 	struct list_head duplicates;
400 	bool need_mmap_lock = false;
401 	int i, r;
402 
403 	if (p->bo_list) {
404 		need_mmap_lock = p->bo_list->has_userptr;
405 		amdgpu_cs_buckets_init(&buckets);
406 		for (i = 0; i < p->bo_list->num_entries; i++)
407 			amdgpu_cs_buckets_add(&buckets, &p->bo_list->array[i].tv.head,
408 								  p->bo_list->array[i].priority);
409 
410 		amdgpu_cs_buckets_get_list(&buckets, &p->validated);
411 	}
412 
413 	p->vm_bos = amdgpu_vm_get_bos(p->adev, &fpriv->vm,
414 				      &p->validated);
415 
416 	if (need_mmap_lock)
417 		down_read(&current->mm->mmap_sem);
418 
419 	INIT_LIST_HEAD(&duplicates);
420 	r = ttm_eu_reserve_buffers(&p->ticket, &p->validated, true, &duplicates);
421 	if (unlikely(r != 0))
422 		goto error_reserve;
423 
424 	r = amdgpu_cs_list_validate(p->adev, &fpriv->vm, &p->validated);
425 	if (r)
426 		goto error_validate;
427 
428 	r = amdgpu_cs_list_validate(p->adev, &fpriv->vm, &duplicates);
429 
430 error_validate:
431 	if (r)
432 		ttm_eu_backoff_reservation(&p->ticket, &p->validated);
433 
434 error_reserve:
435 	if (need_mmap_lock)
436 		up_read(&current->mm->mmap_sem);
437 
438 	return r;
439 }
440 
441 static int amdgpu_cs_sync_rings(struct amdgpu_cs_parser *p)
442 {
443 	struct amdgpu_bo_list_entry *e;
444 	int r;
445 
446 	list_for_each_entry(e, &p->validated, tv.head) {
447 		struct reservation_object *resv = e->robj->tbo.resv;
448 		r = amdgpu_sync_resv(p->adev, &p->ibs[0].sync, resv, p->filp);
449 
450 		if (r)
451 			return r;
452 	}
453 	return 0;
454 }
455 
456 static int cmp_size_smaller_first(void *priv, struct list_head *a,
457 				  struct list_head *b)
458 {
459 	struct amdgpu_bo_list_entry *la = list_entry(a, struct amdgpu_bo_list_entry, tv.head);
460 	struct amdgpu_bo_list_entry *lb = list_entry(b, struct amdgpu_bo_list_entry, tv.head);
461 
462 	/* Sort A before B if A is smaller. */
463 	return (int)la->robj->tbo.num_pages - (int)lb->robj->tbo.num_pages;
464 }
465 
466 static void amdgpu_cs_parser_fini_early(struct amdgpu_cs_parser *parser, int error, bool backoff)
467 {
468 	if (!error) {
469 		/* Sort the buffer list from the smallest to largest buffer,
470 		 * which affects the order of buffers in the LRU list.
471 		 * This assures that the smallest buffers are added first
472 		 * to the LRU list, so they are likely to be later evicted
473 		 * first, instead of large buffers whose eviction is more
474 		 * expensive.
475 		 *
476 		 * This slightly lowers the number of bytes moved by TTM
477 		 * per frame under memory pressure.
478 		 */
479 		list_sort(NULL, &parser->validated, cmp_size_smaller_first);
480 
481 		ttm_eu_fence_buffer_objects(&parser->ticket,
482 				&parser->validated,
483 				&parser->ibs[parser->num_ibs-1].fence->base);
484 	} else if (backoff) {
485 		ttm_eu_backoff_reservation(&parser->ticket,
486 					   &parser->validated);
487 	}
488 }
489 
490 static void amdgpu_cs_parser_fini_late(struct amdgpu_cs_parser *parser)
491 {
492 	unsigned i;
493 	if (parser->ctx)
494 		amdgpu_ctx_put(parser->ctx);
495 	if (parser->bo_list)
496 		amdgpu_bo_list_put(parser->bo_list);
497 
498 	drm_free_large(parser->vm_bos);
499 	for (i = 0; i < parser->nchunks; i++)
500 		drm_free_large(parser->chunks[i].kdata);
501 	kfree(parser->chunks);
502 	if (!amdgpu_enable_scheduler)
503 	{
504 		if (parser->ibs)
505 			for (i = 0; i < parser->num_ibs; i++)
506 				amdgpu_ib_free(parser->adev, &parser->ibs[i]);
507 		kfree(parser->ibs);
508 		if (parser->uf.bo)
509 			drm_gem_object_unreference_unlocked(&parser->uf.bo->gem_base);
510 	}
511 
512 	kfree(parser);
513 }
514 
515 /**
516  * cs_parser_fini() - clean parser states
517  * @parser:	parser structure holding parsing context.
518  * @error:	error number
519  *
520  * If error is set than unvalidate buffer, otherwise just free memory
521  * used by parsing context.
522  **/
523 static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser, int error, bool backoff)
524 {
525        amdgpu_cs_parser_fini_early(parser, error, backoff);
526        amdgpu_cs_parser_fini_late(parser);
527 }
528 
529 static int amdgpu_bo_vm_update_pte(struct amdgpu_cs_parser *p,
530 				   struct amdgpu_vm *vm)
531 {
532 	struct amdgpu_device *adev = p->adev;
533 	struct amdgpu_bo_va *bo_va;
534 	struct amdgpu_bo *bo;
535 	int i, r;
536 
537 	r = amdgpu_vm_update_page_directory(adev, vm);
538 	if (r)
539 		return r;
540 
541 	r = amdgpu_sync_fence(adev, &p->ibs[0].sync, vm->page_directory_fence);
542 	if (r)
543 		return r;
544 
545 	r = amdgpu_vm_clear_freed(adev, vm);
546 	if (r)
547 		return r;
548 
549 	if (p->bo_list) {
550 		for (i = 0; i < p->bo_list->num_entries; i++) {
551 			struct fence *f;
552 
553 			/* ignore duplicates */
554 			bo = p->bo_list->array[i].robj;
555 			if (!bo)
556 				continue;
557 
558 			bo_va = p->bo_list->array[i].bo_va;
559 			if (bo_va == NULL)
560 				continue;
561 
562 			r = amdgpu_vm_bo_update(adev, bo_va, &bo->tbo.mem);
563 			if (r)
564 				return r;
565 
566 			f = bo_va->last_pt_update;
567 			r = amdgpu_sync_fence(adev, &p->ibs[0].sync, f);
568 			if (r)
569 				return r;
570 		}
571 
572 	}
573 
574 	r = amdgpu_vm_clear_invalids(adev, vm, &p->ibs[0].sync);
575 
576 	if (amdgpu_vm_debug && p->bo_list) {
577 		/* Invalidate all BOs to test for userspace bugs */
578 		for (i = 0; i < p->bo_list->num_entries; i++) {
579 			/* ignore duplicates */
580 			bo = p->bo_list->array[i].robj;
581 			if (!bo)
582 				continue;
583 
584 			amdgpu_vm_bo_invalidate(adev, bo);
585 		}
586 	}
587 
588 	return r;
589 }
590 
591 static int amdgpu_cs_ib_vm_chunk(struct amdgpu_device *adev,
592 				 struct amdgpu_cs_parser *parser)
593 {
594 	struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
595 	struct amdgpu_vm *vm = &fpriv->vm;
596 	struct amdgpu_ring *ring;
597 	int i, r;
598 
599 	if (parser->num_ibs == 0)
600 		return 0;
601 
602 	/* Only for UVD/VCE VM emulation */
603 	for (i = 0; i < parser->num_ibs; i++) {
604 		ring = parser->ibs[i].ring;
605 		if (ring->funcs->parse_cs) {
606 			r = amdgpu_ring_parse_cs(ring, parser, i);
607 			if (r)
608 				return r;
609 		}
610 	}
611 
612 	r = amdgpu_bo_vm_update_pte(parser, vm);
613 	if (r) {
614 		goto out;
615 	}
616 	amdgpu_cs_sync_rings(parser);
617 	if (!amdgpu_enable_scheduler)
618 		r = amdgpu_ib_schedule(adev, parser->num_ibs, parser->ibs,
619 				       parser->filp);
620 
621 out:
622 	return r;
623 }
624 
625 static int amdgpu_cs_handle_lockup(struct amdgpu_device *adev, int r)
626 {
627 	if (r == -EDEADLK) {
628 		r = amdgpu_gpu_reset(adev);
629 		if (!r)
630 			r = -EAGAIN;
631 	}
632 	return r;
633 }
634 
635 static int amdgpu_cs_ib_fill(struct amdgpu_device *adev,
636 			     struct amdgpu_cs_parser *parser)
637 {
638 	struct amdgpu_fpriv *fpriv = parser->filp->driver_priv;
639 	struct amdgpu_vm *vm = &fpriv->vm;
640 	int i, j;
641 	int r;
642 
643 	for (i = 0, j = 0; i < parser->nchunks && j < parser->num_ibs; i++) {
644 		struct amdgpu_cs_chunk *chunk;
645 		struct amdgpu_ib *ib;
646 		struct drm_amdgpu_cs_chunk_ib *chunk_ib;
647 		struct amdgpu_ring *ring;
648 
649 		chunk = &parser->chunks[i];
650 		ib = &parser->ibs[j];
651 		chunk_ib = (struct drm_amdgpu_cs_chunk_ib *)chunk->kdata;
652 
653 		if (chunk->chunk_id != AMDGPU_CHUNK_ID_IB)
654 			continue;
655 
656 		r = amdgpu_cs_get_ring(adev, chunk_ib->ip_type,
657 				       chunk_ib->ip_instance, chunk_ib->ring,
658 				       &ring);
659 		if (r)
660 			return r;
661 
662 		if (ring->funcs->parse_cs) {
663 			struct amdgpu_bo_va_mapping *m;
664 			struct amdgpu_bo *aobj = NULL;
665 			uint64_t offset;
666 			uint8_t *kptr;
667 
668 			m = amdgpu_cs_find_mapping(parser, chunk_ib->va_start,
669 						   &aobj);
670 			if (!aobj) {
671 				DRM_ERROR("IB va_start is invalid\n");
672 				return -EINVAL;
673 			}
674 
675 			if ((chunk_ib->va_start + chunk_ib->ib_bytes) >
676 			    (m->it.last + 1) * AMDGPU_GPU_PAGE_SIZE) {
677 				DRM_ERROR("IB va_start+ib_bytes is invalid\n");
678 				return -EINVAL;
679 			}
680 
681 			/* the IB should be reserved at this point */
682 			r = amdgpu_bo_kmap(aobj, (void **)&kptr);
683 			if (r) {
684 				return r;
685 			}
686 
687 			offset = ((uint64_t)m->it.start) * AMDGPU_GPU_PAGE_SIZE;
688 			kptr += chunk_ib->va_start - offset;
689 
690 			r =  amdgpu_ib_get(ring, NULL, chunk_ib->ib_bytes, ib);
691 			if (r) {
692 				DRM_ERROR("Failed to get ib !\n");
693 				return r;
694 			}
695 
696 			memcpy(ib->ptr, kptr, chunk_ib->ib_bytes);
697 			amdgpu_bo_kunmap(aobj);
698 		} else {
699 			r =  amdgpu_ib_get(ring, vm, 0, ib);
700 			if (r) {
701 				DRM_ERROR("Failed to get ib !\n");
702 				return r;
703 			}
704 
705 			ib->gpu_addr = chunk_ib->va_start;
706 		}
707 
708 		ib->length_dw = chunk_ib->ib_bytes / 4;
709 		ib->flags = chunk_ib->flags;
710 		ib->ctx = parser->ctx;
711 		j++;
712 	}
713 
714 	if (!parser->num_ibs)
715 		return 0;
716 
717 	/* add GDS resources to first IB */
718 	if (parser->bo_list) {
719 		struct amdgpu_bo *gds = parser->bo_list->gds_obj;
720 		struct amdgpu_bo *gws = parser->bo_list->gws_obj;
721 		struct amdgpu_bo *oa = parser->bo_list->oa_obj;
722 		struct amdgpu_ib *ib = &parser->ibs[0];
723 
724 		if (gds) {
725 			ib->gds_base = amdgpu_bo_gpu_offset(gds);
726 			ib->gds_size = amdgpu_bo_size(gds);
727 		}
728 		if (gws) {
729 			ib->gws_base = amdgpu_bo_gpu_offset(gws);
730 			ib->gws_size = amdgpu_bo_size(gws);
731 		}
732 		if (oa) {
733 			ib->oa_base = amdgpu_bo_gpu_offset(oa);
734 			ib->oa_size = amdgpu_bo_size(oa);
735 		}
736 	}
737 	/* wrap the last IB with user fence */
738 	if (parser->uf.bo) {
739 		struct amdgpu_ib *ib = &parser->ibs[parser->num_ibs - 1];
740 
741 		/* UVD & VCE fw doesn't support user fences */
742 		if (ib->ring->type == AMDGPU_RING_TYPE_UVD ||
743 		    ib->ring->type == AMDGPU_RING_TYPE_VCE)
744 			return -EINVAL;
745 
746 		ib->user = &parser->uf;
747 	}
748 
749 	return 0;
750 }
751 
752 static int amdgpu_cs_dependencies(struct amdgpu_device *adev,
753 				  struct amdgpu_cs_parser *p)
754 {
755 	struct amdgpu_fpriv *fpriv = p->filp->driver_priv;
756 	struct amdgpu_ib *ib;
757 	int i, j, r;
758 
759 	if (!p->num_ibs)
760 		return 0;
761 
762 	/* Add dependencies to first IB */
763 	ib = &p->ibs[0];
764 	for (i = 0; i < p->nchunks; ++i) {
765 		struct drm_amdgpu_cs_chunk_dep *deps;
766 		struct amdgpu_cs_chunk *chunk;
767 		unsigned num_deps;
768 
769 		chunk = &p->chunks[i];
770 
771 		if (chunk->chunk_id != AMDGPU_CHUNK_ID_DEPENDENCIES)
772 			continue;
773 
774 		deps = (struct drm_amdgpu_cs_chunk_dep *)chunk->kdata;
775 		num_deps = chunk->length_dw * 4 /
776 			sizeof(struct drm_amdgpu_cs_chunk_dep);
777 
778 		for (j = 0; j < num_deps; ++j) {
779 			struct amdgpu_ring *ring;
780 			struct amdgpu_ctx *ctx;
781 			struct fence *fence;
782 
783 			r = amdgpu_cs_get_ring(adev, deps[j].ip_type,
784 					       deps[j].ip_instance,
785 					       deps[j].ring, &ring);
786 			if (r)
787 				return r;
788 
789 			ctx = amdgpu_ctx_get(fpriv, deps[j].ctx_id);
790 			if (ctx == NULL)
791 				return -EINVAL;
792 
793 			fence = amdgpu_ctx_get_fence(ctx, ring,
794 						     deps[j].handle);
795 			if (IS_ERR(fence)) {
796 				r = PTR_ERR(fence);
797 				amdgpu_ctx_put(ctx);
798 				return r;
799 
800 			} else if (fence) {
801 				r = amdgpu_sync_fence(adev, &ib->sync, fence);
802 				fence_put(fence);
803 				amdgpu_ctx_put(ctx);
804 				if (r)
805 					return r;
806 			}
807 		}
808 	}
809 
810 	return 0;
811 }
812 
813 static int amdgpu_cs_free_job(struct amdgpu_job *job)
814 {
815 	int i;
816 	if (job->ibs)
817 		for (i = 0; i < job->num_ibs; i++)
818 			amdgpu_ib_free(job->adev, &job->ibs[i]);
819 	kfree(job->ibs);
820 	if (job->uf.bo)
821 		drm_gem_object_unreference_unlocked(&job->uf.bo->gem_base);
822 	return 0;
823 }
824 
825 int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
826 {
827 	struct amdgpu_device *adev = dev->dev_private;
828 	union drm_amdgpu_cs *cs = data;
829 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
830 	struct amdgpu_vm *vm = &fpriv->vm;
831 	struct amdgpu_cs_parser *parser;
832 	bool reserved_buffers = false;
833 	int i, r;
834 
835 	if (!adev->accel_working)
836 		return -EBUSY;
837 
838 	parser = amdgpu_cs_parser_create(adev, filp, NULL, NULL, 0);
839 	if (!parser)
840 		return -ENOMEM;
841 	r = amdgpu_cs_parser_init(parser, data);
842 	if (r) {
843 		DRM_ERROR("Failed to initialize parser !\n");
844 		amdgpu_cs_parser_fini(parser, r, false);
845 		r = amdgpu_cs_handle_lockup(adev, r);
846 		return r;
847 	}
848 	mutex_lock(&vm->mutex);
849 	r = amdgpu_cs_parser_relocs(parser);
850 	if (r == -ENOMEM)
851 		DRM_ERROR("Not enough memory for command submission!\n");
852 	else if (r && r != -ERESTARTSYS)
853 		DRM_ERROR("Failed to process the buffer list %d!\n", r);
854 	else if (!r) {
855 		reserved_buffers = true;
856 		r = amdgpu_cs_ib_fill(adev, parser);
857 	}
858 
859 	if (!r) {
860 		r = amdgpu_cs_dependencies(adev, parser);
861 		if (r)
862 			DRM_ERROR("Failed in the dependencies handling %d!\n", r);
863 	}
864 
865 	if (r)
866 		goto out;
867 
868 	for (i = 0; i < parser->num_ibs; i++)
869 		trace_amdgpu_cs(parser, i);
870 
871 	r = amdgpu_cs_ib_vm_chunk(adev, parser);
872 	if (r)
873 		goto out;
874 
875 	if (amdgpu_enable_scheduler && parser->num_ibs) {
876 		struct amdgpu_job *job;
877 		struct amdgpu_ring * ring =  parser->ibs->ring;
878 		job = kzalloc(sizeof(struct amdgpu_job), GFP_KERNEL);
879 		if (!job) {
880 			r = -ENOMEM;
881 			goto out;
882 		}
883 		job->base.sched = &ring->sched;
884 		job->base.s_entity = &parser->ctx->rings[ring->idx].entity;
885 		job->adev = parser->adev;
886 		job->ibs = parser->ibs;
887 		job->num_ibs = parser->num_ibs;
888 		job->base.owner = parser->filp;
889 		mutex_init(&job->job_lock);
890 		if (job->ibs[job->num_ibs - 1].user) {
891 			memcpy(&job->uf,  &parser->uf,
892 			       sizeof(struct amdgpu_user_fence));
893 			job->ibs[job->num_ibs - 1].user = &job->uf;
894 		}
895 
896 		job->free_job = amdgpu_cs_free_job;
897 		mutex_lock(&job->job_lock);
898 		r = amd_sched_entity_push_job(&job->base);
899 		if (r) {
900 			mutex_unlock(&job->job_lock);
901 			amdgpu_cs_free_job(job);
902 			kfree(job);
903 			goto out;
904 		}
905 		cs->out.handle =
906 			amdgpu_ctx_add_fence(parser->ctx, ring,
907 					     &job->base.s_fence->base);
908 		parser->ibs[parser->num_ibs - 1].sequence = cs->out.handle;
909 
910 		list_sort(NULL, &parser->validated, cmp_size_smaller_first);
911 		ttm_eu_fence_buffer_objects(&parser->ticket,
912 				&parser->validated,
913 				&job->base.s_fence->base);
914 
915 		mutex_unlock(&job->job_lock);
916 		amdgpu_cs_parser_fini_late(parser);
917 		mutex_unlock(&vm->mutex);
918 		return 0;
919 	}
920 
921 	cs->out.handle = parser->ibs[parser->num_ibs - 1].sequence;
922 out:
923 	amdgpu_cs_parser_fini(parser, r, reserved_buffers);
924 	mutex_unlock(&vm->mutex);
925 	r = amdgpu_cs_handle_lockup(adev, r);
926 	return r;
927 }
928 
929 /**
930  * amdgpu_cs_wait_ioctl - wait for a command submission to finish
931  *
932  * @dev: drm device
933  * @data: data from userspace
934  * @filp: file private
935  *
936  * Wait for the command submission identified by handle to finish.
937  */
938 int amdgpu_cs_wait_ioctl(struct drm_device *dev, void *data,
939 			 struct drm_file *filp)
940 {
941 	union drm_amdgpu_wait_cs *wait = data;
942 	struct amdgpu_device *adev = dev->dev_private;
943 	unsigned long timeout = amdgpu_gem_timeout(wait->in.timeout);
944 	struct amdgpu_ring *ring = NULL;
945 	struct amdgpu_ctx *ctx;
946 	struct fence *fence;
947 	long r;
948 
949 	r = amdgpu_cs_get_ring(adev, wait->in.ip_type, wait->in.ip_instance,
950 			       wait->in.ring, &ring);
951 	if (r)
952 		return r;
953 
954 	ctx = amdgpu_ctx_get(filp->driver_priv, wait->in.ctx_id);
955 	if (ctx == NULL)
956 		return -EINVAL;
957 
958 	fence = amdgpu_ctx_get_fence(ctx, ring, wait->in.handle);
959 	if (IS_ERR(fence))
960 		r = PTR_ERR(fence);
961 	else if (fence) {
962 		r = fence_wait_timeout(fence, true, timeout);
963 		fence_put(fence);
964 	} else
965 		r = 1;
966 
967 	amdgpu_ctx_put(ctx);
968 	if (r < 0)
969 		return r;
970 
971 	memset(wait, 0, sizeof(*wait));
972 	wait->out.status = (r == 0);
973 
974 	return 0;
975 }
976 
977 /**
978  * amdgpu_cs_find_bo_va - find bo_va for VM address
979  *
980  * @parser: command submission parser context
981  * @addr: VM address
982  * @bo: resulting BO of the mapping found
983  *
984  * Search the buffer objects in the command submission context for a certain
985  * virtual memory address. Returns allocation structure when found, NULL
986  * otherwise.
987  */
988 struct amdgpu_bo_va_mapping *
989 amdgpu_cs_find_mapping(struct amdgpu_cs_parser *parser,
990 		       uint64_t addr, struct amdgpu_bo **bo)
991 {
992 	struct amdgpu_bo_list_entry *reloc;
993 	struct amdgpu_bo_va_mapping *mapping;
994 
995 	addr /= AMDGPU_GPU_PAGE_SIZE;
996 
997 	list_for_each_entry(reloc, &parser->validated, tv.head) {
998 		if (!reloc->bo_va)
999 			continue;
1000 
1001 		list_for_each_entry(mapping, &reloc->bo_va->valids, list) {
1002 			if (mapping->it.start > addr ||
1003 			    addr > mapping->it.last)
1004 				continue;
1005 
1006 			*bo = reloc->bo_va->bo;
1007 			return mapping;
1008 		}
1009 
1010 		list_for_each_entry(mapping, &reloc->bo_va->invalids, list) {
1011 			if (mapping->it.start > addr ||
1012 			    addr > mapping->it.last)
1013 				continue;
1014 
1015 			*bo = reloc->bo_va->bo;
1016 			return mapping;
1017 		}
1018 	}
1019 
1020 	return NULL;
1021 }
1022