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