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