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