xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c (revision 70ea88787150cbe514156d7ec49c96d3b8acda76)
1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the 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  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  */
28 #include <linux/module.h>
29 #include <linux/overflow.h>
30 #include <linux/pagemap.h>
31 #include <linux/pci.h>
32 #include <linux/dma-buf.h>
33 #include <linux/dma-fence-unwrap.h>
34 #include <linux/uaccess.h>
35 #include <linux/pm_runtime.h>
36 
37 #include <drm/amdgpu_drm.h>
38 #include <drm/drm_drv.h>
39 #include <drm/drm_exec.h>
40 #include <drm/drm_gem_ttm_helper.h>
41 #include <drm/ttm/ttm_tt.h>
42 #include <drm/drm_syncobj.h>
43 #include <drm/drm_timeout.h>
44 
45 #include "amdgpu.h"
46 #include "amdgpu_display.h"
47 #include "amdgpu_dma_buf.h"
48 #include "amdgpu_hmm.h"
49 #include "amdgpu_xgmi.h"
50 #include "amdgpu_vm.h"
51 
52 static int
53 amdgpu_gem_add_input_fence(struct drm_file *filp,
54 			   uint64_t syncobj_handles_array,
55 			   uint32_t num_syncobj_handles)
56 {
57 	struct dma_fence *fence;
58 	uint32_t *syncobj_handles;
59 	int ret, i;
60 
61 	if (!num_syncobj_handles)
62 		return 0;
63 
64 	syncobj_handles = memdup_user(u64_to_user_ptr(syncobj_handles_array),
65 				      size_mul(sizeof(uint32_t), num_syncobj_handles));
66 	if (IS_ERR(syncobj_handles))
67 		return PTR_ERR(syncobj_handles);
68 
69 	for (i = 0; i < num_syncobj_handles; i++) {
70 
71 		if (!syncobj_handles[i]) {
72 			ret = -EINVAL;
73 			goto free_memdup;
74 		}
75 
76 		ret = drm_syncobj_find_fence(filp, syncobj_handles[i], 0, 0, &fence);
77 		if (ret)
78 			goto free_memdup;
79 
80 		dma_fence_wait(fence, false);
81 
82 		/* TODO: optimize async handling */
83 		dma_fence_put(fence);
84 	}
85 
86 free_memdup:
87 	kfree(syncobj_handles);
88 	return ret;
89 }
90 
91 static int
92 amdgpu_gem_update_timeline_node(struct drm_file *filp,
93 				uint32_t syncobj_handle,
94 				uint64_t point,
95 				struct drm_syncobj **syncobj,
96 				struct dma_fence_chain **chain)
97 {
98 	if (!syncobj_handle)
99 		return 0;
100 
101 	/* Find the sync object */
102 	*syncobj = drm_syncobj_find(filp, syncobj_handle);
103 	if (!*syncobj)
104 		return -ENOENT;
105 
106 	if (!point)
107 		return 0;
108 
109 	/* Allocate the chain node */
110 	*chain = dma_fence_chain_alloc();
111 	if (!*chain) {
112 		drm_syncobj_put(*syncobj);
113 		*syncobj = NULL;
114 		return -ENOMEM;
115 	}
116 
117 	return 0;
118 }
119 
120 static vm_fault_t amdgpu_gem_fault(struct vm_fault *vmf)
121 {
122 	struct ttm_buffer_object *bo = vmf->vma->vm_private_data;
123 	struct drm_device *ddev = bo->base.dev;
124 	vm_fault_t ret;
125 	int idx;
126 
127 	ret = ttm_bo_vm_reserve(bo, vmf);
128 	if (ret)
129 		return ret;
130 
131 	if (drm_dev_enter(ddev, &idx)) {
132 		pm_runtime_get_noresume(ddev->dev);
133 
134 		ret = amdgpu_bo_fault_reserve_notify(bo);
135 		if (ret) {
136 			drm_dev_exit(idx);
137 			goto unlock;
138 		}
139 
140 		ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
141 					       TTM_BO_VM_NUM_PREFAULT);
142 
143 		pm_runtime_put_noidle(ddev->dev);
144 		drm_dev_exit(idx);
145 	} else {
146 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
147 	}
148 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
149 		return ret;
150 
151 unlock:
152 	dma_resv_unlock(bo->base.resv);
153 	return ret;
154 }
155 
156 static const struct vm_operations_struct amdgpu_gem_vm_ops = {
157 	.fault = amdgpu_gem_fault,
158 	.open = ttm_bo_vm_open,
159 	.close = ttm_bo_vm_close,
160 	.access = ttm_bo_vm_access
161 };
162 
163 static void amdgpu_gem_object_free(struct drm_gem_object *gobj)
164 {
165 	struct amdgpu_bo *aobj = gem_to_amdgpu_bo(gobj);
166 
167 	amdgpu_hmm_unregister(aobj);
168 	ttm_bo_fini(&aobj->tbo);
169 }
170 
171 int amdgpu_gem_object_create(struct amdgpu_device *adev, unsigned long size,
172 			     int alignment, u32 initial_domain,
173 			     u64 flags, enum ttm_bo_type type,
174 			     struct dma_resv *resv,
175 			     struct drm_gem_object **obj, int8_t xcp_id_plus1)
176 {
177 	struct amdgpu_bo *bo;
178 	struct amdgpu_bo_user *ubo;
179 	struct amdgpu_bo_param bp;
180 	int r;
181 
182 	memset(&bp, 0, sizeof(bp));
183 	*obj = NULL;
184 	flags |= AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;
185 
186 	bp.size = size;
187 	bp.byte_align = alignment;
188 	bp.type = type;
189 	bp.resv = resv;
190 	bp.preferred_domain = initial_domain;
191 	bp.flags = flags;
192 	bp.domain = initial_domain;
193 	bp.bo_ptr_size = sizeof(struct amdgpu_bo);
194 	bp.xcp_id_plus1 = xcp_id_plus1;
195 
196 	r = amdgpu_bo_create_user(adev, &bp, &ubo);
197 	if (r)
198 		return r;
199 
200 	bo = &ubo->bo;
201 	*obj = &bo->tbo.base;
202 
203 	return 0;
204 }
205 
206 void amdgpu_gem_force_release(struct amdgpu_device *adev)
207 {
208 	struct drm_device *ddev = adev_to_drm(adev);
209 	struct drm_file *file;
210 
211 	mutex_lock(&ddev->filelist_mutex);
212 
213 	list_for_each_entry(file, &ddev->filelist, lhead) {
214 		struct drm_gem_object *gobj;
215 		int handle;
216 
217 		WARN_ONCE(1, "Still active user space clients!\n");
218 		spin_lock(&file->table_lock);
219 		idr_for_each_entry(&file->object_idr, gobj, handle) {
220 			WARN_ONCE(1, "And also active allocations!\n");
221 			drm_gem_object_put(gobj);
222 		}
223 		idr_destroy(&file->object_idr);
224 		spin_unlock(&file->table_lock);
225 	}
226 
227 	mutex_unlock(&ddev->filelist_mutex);
228 }
229 
230 /*
231  * Call from drm_gem_handle_create which appear in both new and open ioctl
232  * case.
233  */
234 static int amdgpu_gem_object_open(struct drm_gem_object *obj,
235 				  struct drm_file *file_priv)
236 {
237 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(obj);
238 	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
239 	struct amdgpu_fpriv *fpriv = file_priv->driver_priv;
240 	struct amdgpu_vm *vm = &fpriv->vm;
241 	struct amdgpu_bo_va *bo_va;
242 	struct mm_struct *mm;
243 	struct drm_exec exec;
244 	int r = 0;
245 
246 	mm = amdgpu_ttm_tt_get_usermm(abo->tbo.ttm);
247 	if (mm && mm != current->mm)
248 		return -EPERM;
249 
250 	if (abo->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID &&
251 	    !amdgpu_vm_is_bo_always_valid(vm, abo))
252 		return -EPERM;
253 
254 	/* Validate and add eviction fence to DMABuf imports with dynamic
255 	 * attachment in compute VMs. Re-validation will be done by
256 	 * amdgpu_vm_validate. Fences are on the reservation shared with the
257 	 * export, which is currently required to be validated and fenced
258 	 * already by amdgpu_amdkfd_gpuvm_restore_process_bos.
259 	 *
260 	 * This runs before the BO is added to the VM: drm_gem_handle_create_tail()
261 	 * does not call the close() callback when open() fails, so nothing that
262 	 * would need unwinding may exist yet.
263 	 *
264 	 * Nested locking below for the case that a GEM object is opened in
265 	 * kfd_mem_export_dmabuf. Since the lock below is only taken for imports,
266 	 * but not for export, this is a different lock class that cannot lead to
267 	 * circular lock dependencies.
268 	 */
269 	if (vm->is_compute_context && vm->process_info &&
270 	    drm_gem_is_imported(obj) &&
271 	    dma_buf_is_dynamic(obj->import_attach->dmabuf)) {
272 		mutex_lock_nested(&vm->process_info->lock, 1);
273 		if (!WARN_ON(!vm->process_info->eviction_fence))
274 			r = amdgpu_amdkfd_bo_validate_and_fence(abo,
275 					AMDGPU_GEM_DOMAIN_GTT,
276 					&vm->process_info->eviction_fence->base);
277 		mutex_unlock(&vm->process_info->lock);
278 		if (r) {
279 			struct amdgpu_task_info *ti = amdgpu_vm_get_task_info_vm(vm);
280 
281 			dev_warn(adev->dev, "validate_and_fence failed: %d\n", r);
282 			if (ti) {
283 				dev_warn(adev->dev, "pid %d\n", ti->task.pid);
284 				amdgpu_vm_put_task_info(ti);
285 			}
286 			return r;
287 		}
288 	}
289 
290 	drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);
291 	drm_exec_until_all_locked(&exec) {
292 		r = drm_exec_prepare_obj(&exec, &abo->tbo.base, TTM_NUM_MOVE_FENCES + 1);
293 		drm_exec_retry_on_contention(&exec);
294 		if (unlikely(r))
295 			goto out_unlock;
296 
297 		r = amdgpu_vm_lock_pd(vm, &exec, 0);
298 		drm_exec_retry_on_contention(&exec);
299 		if (unlikely(r))
300 			goto out_unlock;
301 	}
302 
303 	amdgpu_vm_bo_update_shared(abo);
304 	bo_va = amdgpu_vm_bo_find(vm, abo);
305 	if (!bo_va) {
306 		bo_va = amdgpu_vm_bo_add(adev, vm, abo);
307 		if (!bo_va) {
308 			r = -ENOMEM;
309 			goto out_unlock;
310 		}
311 		r = amdgpu_evf_mgr_attach_fence(&fpriv->evf_mgr, abo);
312 		if (r) {
313 			amdgpu_vm_bo_del(adev, bo_va);
314 			goto out_unlock;
315 		}
316 	} else {
317 		++bo_va->ref_count;
318 	}
319 
320 	drm_exec_fini(&exec);
321 	return 0;
322 
323 out_unlock:
324 	drm_exec_fini(&exec);
325 	return r;
326 }
327 
328 static void amdgpu_gem_object_close(struct drm_gem_object *obj,
329 				    struct drm_file *file_priv)
330 {
331 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
332 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
333 	struct amdgpu_fpriv *fpriv = file_priv->driver_priv;
334 	struct amdgpu_vm *vm = &fpriv->vm;
335 
336 	struct dma_fence *fence = NULL;
337 	struct amdgpu_bo_va *bo_va;
338 	struct drm_exec exec;
339 	long r;
340 
341 	drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);
342 	drm_exec_until_all_locked(&exec) {
343 		r = drm_exec_prepare_obj(&exec, &bo->tbo.base, 2); /* clear_freed + last_tlb_inv */
344 		drm_exec_retry_on_contention(&exec);
345 		if (unlikely(r))
346 			goto out_unlock;
347 
348 		r = amdgpu_vm_lock_pd(vm, &exec, 0);
349 		drm_exec_retry_on_contention(&exec);
350 		if (unlikely(r))
351 			goto out_unlock;
352 	}
353 
354 	bo_va = amdgpu_vm_bo_find(vm, bo);
355 	/* the fence is attached once per bo_va, so keep it for other handles */
356 	if (bo_va && --bo_va->ref_count)
357 		goto out_unlock;
358 
359 	if (!amdgpu_vm_is_bo_always_valid(vm, bo))
360 		amdgpu_evf_mgr_detach_fence(&fpriv->evf_mgr, bo);
361 	if (!bo_va)
362 		goto out_unlock;
363 
364 	amdgpu_vm_bo_del(adev, bo_va);
365 	amdgpu_vm_bo_update_shared(bo);
366 	if (!amdgpu_vm_ready(vm))
367 		goto out_unlock;
368 
369 	r = amdgpu_vm_clear_freed(adev, vm, &fence);
370 	if (unlikely(r < 0) && !drm_dev_is_unplugged(adev_to_drm(adev)))
371 		dev_err(adev->dev, "failed to clear page "
372 			"tables on GEM object close (%ld)\n", r);
373 	if (r || !fence)
374 		goto out_tlb;
375 
376 	dma_resv_add_fence(bo->tbo.base.resv, fence, DMA_RESV_USAGE_BOOKKEEP);
377 	dma_fence_put(fence);
378 
379 out_tlb:
380 	dma_resv_add_fence(bo->tbo.base.resv, vm->last_tlb_inv, DMA_RESV_USAGE_BOOKKEEP);
381 
382 out_unlock:
383 	if (r && !drm_dev_is_unplugged(adev_to_drm(adev)))
384 		dev_err(adev->dev, "leaking bo va (%ld)\n", r);
385 	drm_exec_fini(&exec);
386 }
387 
388 static int amdgpu_gem_object_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
389 {
390 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
391 
392 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm))
393 		return -EPERM;
394 	if (bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)
395 		return -EPERM;
396 
397 	/* Workaround for Thunk bug creating PROT_NONE,MAP_PRIVATE mappings
398 	 * for debugger access to invisible VRAM. Should have used MAP_SHARED
399 	 * instead. Clearing VM_MAYWRITE prevents the mapping from ever
400 	 * becoming writable and makes vma_is_cow_mapping(vma) false.
401 	 */
402 	if (vma_is_cow_mapping(vma) &&
403 	    !(vma->vm_flags & VM_ACCESS_FLAGS))
404 		vm_flags_clear(vma, VM_MAYWRITE);
405 
406 	return drm_gem_ttm_mmap(obj, vma);
407 }
408 
409 static void amdgpu_gem_object_handle_free(struct drm_gem_object *gobj)
410 {
411 	struct amdgpu_bo *aobj = gem_to_amdgpu_bo(gobj);
412 
413 	amdgpu_ualink_revoke_exported_memory(aobj);
414 
415 }
416 
417 const struct drm_gem_object_funcs amdgpu_gem_object_funcs = {
418 	.free = amdgpu_gem_object_free,
419 	.open = amdgpu_gem_object_open,
420 	.close = amdgpu_gem_object_close,
421 	.export = amdgpu_gem_prime_export,
422 	.vmap = drm_gem_ttm_vmap,
423 	.vunmap = drm_gem_ttm_vunmap,
424 	.mmap = amdgpu_gem_object_mmap,
425 	.vm_ops = &amdgpu_gem_vm_ops,
426 	.handle_free = amdgpu_gem_object_handle_free
427 };
428 
429 static bool amdgpu_gem_are_domains_valid(u32 domains)
430 {
431 	u32 normal = AMDGPU_GEM_DOMAIN_CPU |
432 		     AMDGPU_GEM_DOMAIN_GTT |
433 		     AMDGPU_GEM_DOMAIN_VRAM;
434 	/* Treat all non CPU/GTT/VRAM domains as special domains. */
435 	u32 special = AMDGPU_GEM_DOMAIN_MASK & ~normal;
436 	u32 normal_mask = domains & normal;
437 	u32 special_mask = domains & special;
438 
439 	if (!special_mask)
440 		return true;
441 
442 	if (normal_mask)
443 		return false;
444 
445 	return !(special_mask & (special_mask - 1));
446 }
447 
448 /*
449  * GEM ioctls.
450  */
451 int amdgpu_gem_create_ioctl(struct drm_device *dev, void *data,
452 			    struct drm_file *filp)
453 {
454 	struct amdgpu_device *adev = drm_to_adev(dev);
455 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
456 	struct amdgpu_vm *vm = &fpriv->vm;
457 	union drm_amdgpu_gem_create *args = data;
458 	uint64_t flags = args->in.domain_flags;
459 	uint64_t size = args->in.bo_size;
460 	struct dma_resv *resv = NULL;
461 	struct drm_gem_object *gobj;
462 	uint32_t handle, initial_domain;
463 	int r;
464 
465 	PM_RUNTIME_ACQUIRE_IF_ENABLED_AUTOSUSPEND(dev->dev, lock);
466 
467 	r = PM_RUNTIME_ACQUIRE_ERR(&lock);
468 	if (r)
469 		return r;
470 
471 	/* reject invalid gem flags */
472 	if (flags & ~AMDGPU_GEM_CREATE_SETTABLE_MASK)
473 		return -EINVAL;
474 
475 	/* reject invalid gem domains */
476 	if (args->in.domains & ~AMDGPU_GEM_DOMAIN_MASK)
477 		return -EINVAL;
478 	if (!amdgpu_gem_are_domains_valid(args->in.domains))
479 		return -EINVAL;
480 
481 	if (!amdgpu_is_tmz(adev) && (flags & AMDGPU_GEM_CREATE_ENCRYPTED)) {
482 		DRM_NOTE_ONCE("Cannot allocate secure buffer since TMZ is disabled\n");
483 		return -EINVAL;
484 	}
485 
486 	/* always clear VRAM */
487 	flags |= AMDGPU_GEM_CREATE_VRAM_CLEARED;
488 
489 	/* create a gem object to contain this object in */
490 	if (args->in.domains & (AMDGPU_GEM_DOMAIN_GDS |
491 	    AMDGPU_GEM_DOMAIN_GWS | AMDGPU_GEM_DOMAIN_OA)) {
492 		if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
493 			/* if gds bo is created from user space, it must be
494 			 * passed to bo list
495 			 */
496 			DRM_ERROR("GDS bo cannot be per-vm-bo\n");
497 			return -EINVAL;
498 		}
499 		flags |= AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
500 	}
501 
502 	if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
503 		r = amdgpu_bo_reserve(vm->root.bo, false);
504 		if (r)
505 			return r;
506 
507 		resv = vm->root.bo->tbo.base.resv;
508 	}
509 
510 	initial_domain = (u32)(0xffffffff & args->in.domains);
511 retry:
512 	r = amdgpu_gem_object_create(adev, size, args->in.alignment,
513 				     initial_domain,
514 				     flags, ttm_bo_type_device, resv, &gobj, fpriv->xcp_id + 1);
515 	if (r && r != -ERESTARTSYS) {
516 		if (flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) {
517 			flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
518 			goto retry;
519 		}
520 
521 		if (initial_domain == AMDGPU_GEM_DOMAIN_VRAM) {
522 			initial_domain |= AMDGPU_GEM_DOMAIN_GTT;
523 			goto retry;
524 		}
525 		DRM_DEBUG("Failed to allocate GEM object (%llu, %d, %llu, %d)\n",
526 				size, initial_domain, args->in.alignment, r);
527 	}
528 
529 	if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
530 		if (!r) {
531 			struct amdgpu_bo *abo = gem_to_amdgpu_bo(gobj);
532 
533 			abo->parent = amdgpu_bo_ref(vm->root.bo);
534 		}
535 		amdgpu_bo_unreserve(vm->root.bo);
536 	}
537 	if (r)
538 		return r;
539 
540 	r = drm_gem_handle_create(filp, gobj, &handle);
541 	/* drop reference from allocate - handle holds it now */
542 	drm_gem_object_put(gobj);
543 	if (r)
544 		return r;
545 
546 	memset(args, 0, sizeof(*args));
547 	args->out.handle = handle;
548 	return 0;
549 }
550 
551 int amdgpu_gem_userptr_ioctl(struct drm_device *dev, void *data,
552 			     struct drm_file *filp)
553 {
554 	struct ttm_operation_ctx ctx = { true, false };
555 	struct amdgpu_device *adev = drm_to_adev(dev);
556 	struct drm_amdgpu_gem_userptr *args = data;
557 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
558 	struct drm_gem_object *gobj;
559 	struct amdgpu_hmm_range *range;
560 	struct amdgpu_bo *bo;
561 	uint32_t handle;
562 	int r;
563 
564 	args->addr = untagged_addr(args->addr);
565 
566 	if (offset_in_page(args->addr | args->size))
567 		return -EINVAL;
568 
569 	if (!access_ok((void __user *)(uintptr_t)args->addr, args->size))
570 		return -EFAULT;
571 
572 	/* reject unknown flag values */
573 	if (args->flags & ~(AMDGPU_GEM_USERPTR_READONLY |
574 	    AMDGPU_GEM_USERPTR_ANONONLY | AMDGPU_GEM_USERPTR_VALIDATE |
575 	    AMDGPU_GEM_USERPTR_REGISTER))
576 		return -EINVAL;
577 
578 	if (!(args->flags & AMDGPU_GEM_USERPTR_READONLY) &&
579 	     !(args->flags & AMDGPU_GEM_USERPTR_REGISTER)) {
580 
581 		/* if we want to write to it we must install a MMU notifier */
582 		return -EACCES;
583 	}
584 
585 	/* create a gem object to contain this object in */
586 	r = amdgpu_gem_object_create(adev, args->size, 0, AMDGPU_GEM_DOMAIN_CPU,
587 				     0, ttm_bo_type_device, NULL, &gobj, fpriv->xcp_id + 1);
588 	if (r)
589 		return r;
590 
591 	bo = gem_to_amdgpu_bo(gobj);
592 	bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
593 	bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
594 	bo->parent = amdgpu_bo_ref(fpriv->vm.root.bo);
595 	r = amdgpu_ttm_tt_set_userptr(&bo->tbo, args->addr, args->flags);
596 	if (r)
597 		goto release_object;
598 
599 	r = amdgpu_hmm_register(bo, args->addr);
600 	if (r)
601 		goto release_object;
602 
603 	if (args->flags & AMDGPU_GEM_USERPTR_VALIDATE) {
604 		range = amdgpu_hmm_range_alloc(NULL);
605 		if (unlikely(!range)) {
606 			r = -ENOMEM;
607 			goto release_object;
608 		}
609 		r = amdgpu_ttm_tt_get_user_pages(bo, range);
610 		if (r) {
611 			amdgpu_hmm_range_free(range);
612 			goto release_object;
613 		}
614 
615 		r = pm_runtime_resume_and_get(adev->dev);
616 		if (r < 0)
617 			goto user_pages_done;
618 
619 		r = amdgpu_bo_reserve(bo, true);
620 		if (r)
621 			goto user_pages_done;
622 
623 		amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, range);
624 
625 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
626 		r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
627 		amdgpu_bo_unreserve(bo);
628 
629 		pm_runtime_put_autosuspend(adev->dev);
630 
631 		if (r)
632 			goto user_pages_done;
633 	}
634 
635 	r = drm_gem_handle_create(filp, gobj, &handle);
636 	if (r)
637 		goto user_pages_done;
638 
639 	args->handle = handle;
640 
641 user_pages_done:
642 	if (args->flags & AMDGPU_GEM_USERPTR_VALIDATE)
643 		amdgpu_hmm_range_free(range);
644 release_object:
645 	drm_gem_object_put(gobj);
646 
647 	return r;
648 }
649 
650 int amdgpu_mode_dumb_mmap(struct drm_file *filp,
651 			  struct drm_device *dev,
652 			  uint32_t handle, uint64_t *offset_p)
653 {
654 	struct drm_gem_object *gobj;
655 	struct amdgpu_bo *robj;
656 
657 	gobj = drm_gem_object_lookup(filp, handle);
658 	if (!gobj)
659 		return -ENOENT;
660 
661 	robj = gem_to_amdgpu_bo(gobj);
662 	if (amdgpu_ttm_tt_get_usermm(robj->tbo.ttm) ||
663 	    (robj->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)) {
664 		drm_gem_object_put(gobj);
665 		return -EPERM;
666 	}
667 	*offset_p = amdgpu_bo_mmap_offset(robj);
668 	drm_gem_object_put(gobj);
669 	return 0;
670 }
671 
672 int amdgpu_gem_mmap_ioctl(struct drm_device *dev, void *data,
673 			  struct drm_file *filp)
674 {
675 	union drm_amdgpu_gem_mmap *args = data;
676 	uint32_t handle = args->in.handle;
677 
678 	memset(args, 0, sizeof(*args));
679 	return amdgpu_mode_dumb_mmap(filp, dev, handle, &args->out.addr_ptr);
680 }
681 
682 /**
683  * amdgpu_gem_timeout - calculate jiffies timeout from absolute value
684  *
685  * @timeout_ns: timeout in ns
686  *
687  * Calculate the timeout in jiffies from an absolute timeout in ns.
688  */
689 unsigned long amdgpu_gem_timeout(uint64_t timeout_ns)
690 {
691 	/* Map anything that doesn't fit in a s64 to an infinite wait */
692 	if (timeout_ns > S64_MAX)
693 		return MAX_SCHEDULE_TIMEOUT;
694 
695 	return drm_timeout_abs_to_jiffies(timeout_ns);
696 }
697 
698 int amdgpu_gem_wait_idle_ioctl(struct drm_device *dev, void *data,
699 			      struct drm_file *filp)
700 {
701 	union drm_amdgpu_gem_wait_idle *args = data;
702 	struct drm_gem_object *gobj;
703 	struct amdgpu_bo *robj;
704 	uint32_t handle = args->in.handle;
705 	unsigned long timeout = amdgpu_gem_timeout(args->in.timeout);
706 	int r = 0;
707 	long ret;
708 
709 	gobj = drm_gem_object_lookup(filp, handle);
710 	if (!gobj)
711 		return -ENOENT;
712 
713 	robj = gem_to_amdgpu_bo(gobj);
714 	ret = dma_resv_wait_timeout(robj->tbo.base.resv, DMA_RESV_USAGE_READ,
715 				    true, timeout);
716 
717 	/* ret == 0 means not signaled,
718 	 * ret > 0 means signaled
719 	 * ret < 0 means interrupted before timeout
720 	 */
721 	if (ret >= 0) {
722 		memset(args, 0, sizeof(*args));
723 		args->out.status = (ret == 0);
724 	} else
725 		r = ret;
726 
727 	drm_gem_object_put(gobj);
728 	return r;
729 }
730 
731 int amdgpu_gem_metadata_ioctl(struct drm_device *dev, void *data,
732 				struct drm_file *filp)
733 {
734 	struct drm_amdgpu_gem_metadata *args = data;
735 	struct drm_gem_object *gobj;
736 	struct amdgpu_bo *robj;
737 	int r = -1;
738 
739 	DRM_DEBUG("%d\n", args->handle);
740 	gobj = drm_gem_object_lookup(filp, args->handle);
741 	if (gobj == NULL)
742 		return -ENOENT;
743 	robj = gem_to_amdgpu_bo(gobj);
744 
745 	r = amdgpu_bo_reserve(robj, false);
746 	if (unlikely(r != 0))
747 		goto out;
748 
749 	/* Reject MMIO_REMAP BOs at IOCTL level: metadata/tiling does not apply. */
750 	if (robj->tbo.resource &&
751 	    robj->tbo.resource->mem_type == AMDGPU_PL_MMIO_REMAP) {
752 		DRM_WARN("metadata ioctl on MMIO_REMAP BO (handle %d)\n",
753 			 args->handle);
754 		r = -EINVAL;
755 		goto unreserve;
756 	}
757 
758 	if (args->op == AMDGPU_GEM_METADATA_OP_GET_METADATA) {
759 		amdgpu_bo_get_tiling_flags(robj, &args->data.tiling_info);
760 		r = amdgpu_bo_get_metadata(robj, args->data.data,
761 					   sizeof(args->data.data),
762 					   &args->data.data_size_bytes,
763 					   &args->data.flags);
764 	} else if (args->op == AMDGPU_GEM_METADATA_OP_SET_METADATA) {
765 		if (args->data.data_size_bytes > sizeof(args->data.data)) {
766 			r = -EINVAL;
767 			goto unreserve;
768 		}
769 		r = amdgpu_bo_set_tiling_flags(robj, args->data.tiling_info);
770 		if (!r)
771 			r = amdgpu_bo_set_metadata(robj, args->data.data,
772 						   args->data.data_size_bytes,
773 						   args->data.flags);
774 	}
775 
776 unreserve:
777 	amdgpu_bo_unreserve(robj);
778 out:
779 	drm_gem_object_put(gobj);
780 	return r;
781 }
782 
783 /**
784  * amdgpu_gem_va_update_vm -update the bo_va in its VM
785  *
786  * @adev: amdgpu_device pointer
787  * @vm: vm to update
788  * @bo_va: bo_va to update
789  * @operation: map, unmap or clear
790  *
791  * Update the bo_va directly after setting its address. Errors are not
792  * vital here, so they are not reported back to userspace.
793  *
794  * Returns resulting fence if freed BO(s) got cleared from the PT.
795  * otherwise stub fence in case of error.
796  */
797 static struct dma_fence *
798 amdgpu_gem_va_update_vm(struct amdgpu_device *adev,
799 			struct amdgpu_vm *vm,
800 			struct amdgpu_bo_va *bo_va,
801 			uint32_t operation)
802 {
803 	struct dma_fence *fence;
804 	int r = 0;
805 
806 	/* If the VM is not ready return only a stub. */
807 	if (!amdgpu_vm_ready(vm))
808 		return dma_fence_get_stub();
809 
810 
811 	/*
812 	 * First clean up any freed mappings in the VM.
813 	 *
814 	 * amdgpu_vm_clear_freed() may replace @fence with a new fence if it
815 	 * schedules GPU work. If nothing needs clearing, @fence can remain as
816 	 * the original vm->last_update.
817 	 */
818 	r = amdgpu_vm_clear_freed(adev, vm, &vm->last_update);
819 	if (r)
820 		goto error;
821 
822 	/* For MAP/REPLACE we also need to update the BO mappings. */
823 	if (operation == AMDGPU_VA_OP_MAP ||
824 	    operation == AMDGPU_VA_OP_REPLACE) {
825 		r = amdgpu_vm_bo_update(adev, bo_va, false);
826 		if (r)
827 			goto error;
828 	}
829 
830 	/* Always update PDEs after we touched the mappings. */
831 	r = amdgpu_vm_update_pdes(adev, vm, false);
832 
833 error:
834 	if (r && r != -ERESTARTSYS)
835 		DRM_ERROR("Couldn't update BO_VA (%d)\n", r);
836 
837 	if ((operation == AMDGPU_VA_OP_MAP ||
838 	     operation == AMDGPU_VA_OP_REPLACE) &&
839 	    !amdgpu_vm_is_bo_always_valid(vm, bo_va->base.bo)) {
840 
841 		/*
842 		 * For MAP/REPLACE of non per-VM BOs we need to sync to both the
843 		 * bo_va->last_pt_update and vm->last_update or otherwise we
844 		 * potentially miss the PDE updates or TLB invalidation.
845 		 */
846 		fence = dma_fence_unwrap_merge(vm->last_update,
847 					       vm->last_tlb_inv,
848 					       bo_va->last_pt_update);
849 		if (!fence)
850 			dma_fence_wait(bo_va->last_pt_update, false);
851 
852 	} else {
853 		fence = dma_fence_unwrap_merge(vm->last_update,
854 					       vm->last_tlb_inv);
855 	}
856 
857 	if (!fence) {
858 		/* As fallback in OOM situations */
859 		dma_fence_wait(vm->last_update, false);
860 		dma_fence_wait(vm->last_tlb_inv, false);
861 		fence = dma_fence_get_stub();
862 	}
863 
864 	return fence;
865 }
866 
867 int amdgpu_gem_va_ioctl(struct drm_device *dev, void *data,
868 			  struct drm_file *filp)
869 {
870 	const uint32_t valid_flags = AMDGPU_VM_DELAY_UPDATE |
871 		AMDGPU_VM_PAGE_READABLE | AMDGPU_VM_PAGE_WRITEABLE |
872 		AMDGPU_VM_PAGE_EXECUTABLE | AMDGPU_VM_MTYPE_MASK |
873 		AMDGPU_VM_PAGE_NOALLOC;
874 	const uint32_t prt_flags = AMDGPU_VM_DELAY_UPDATE |
875 		AMDGPU_VM_PAGE_PRT;
876 
877 	struct drm_amdgpu_gem_va *args = data;
878 	struct drm_gem_object *gobj;
879 	struct amdgpu_device *adev = drm_to_adev(dev);
880 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
881 	struct amdgpu_bo *abo;
882 	struct amdgpu_bo_va *bo_va;
883 	struct drm_syncobj *timeline_syncobj = NULL;
884 	struct dma_fence_chain *timeline_chain = NULL;
885 	struct drm_exec exec;
886 	uint64_t vm_size, tmp;
887 	int r = 0;
888 
889 	/* Validate virtual address range against reserved regions. */
890 	if (args->va_address < AMDGPU_VA_RESERVED_BOTTOM) {
891 		dev_dbg(dev->dev,
892 			"va_address 0x%llx is in reserved area 0x%llx\n",
893 			args->va_address, AMDGPU_VA_RESERVED_BOTTOM);
894 		return -EINVAL;
895 	}
896 
897 	if (args->va_address >= AMDGPU_GMC_HOLE_START &&
898 	    args->va_address < AMDGPU_GMC_HOLE_END) {
899 		dev_dbg(dev->dev,
900 			"va_address 0x%llx is in VA hole 0x%llx-0x%llx\n",
901 			args->va_address, AMDGPU_GMC_HOLE_START,
902 			AMDGPU_GMC_HOLE_END);
903 		return -EINVAL;
904 	}
905 
906 	args->va_address &= AMDGPU_GMC_HOLE_MASK;
907 
908 	vm_size = adev->vm_manager.max_pfn * AMDGPU_GPU_PAGE_SIZE;
909 	vm_size -= AMDGPU_VA_RESERVED_TOP;
910 	if (check_add_overflow(args->va_address, args->map_size, &tmp) || tmp > vm_size) {
911 		dev_dbg(dev->dev,
912 			"va_address 0x%llx is in top reserved area 0x%llx\n",
913 			args->va_address + args->map_size, vm_size);
914 		return -EINVAL;
915 	}
916 
917 	if ((args->flags & ~valid_flags) && (args->flags & ~prt_flags)) {
918 		dev_dbg(dev->dev, "invalid flags combination 0x%08X\n",
919 			args->flags);
920 		return -EINVAL;
921 	}
922 
923 	/* Validate operation type. */
924 	switch (args->operation) {
925 	case AMDGPU_VA_OP_MAP:
926 	case AMDGPU_VA_OP_UNMAP:
927 	case AMDGPU_VA_OP_CLEAR:
928 	case AMDGPU_VA_OP_REPLACE:
929 		break;
930 	default:
931 		dev_dbg(dev->dev, "unsupported operation %d\n",
932 			args->operation);
933 		return -EINVAL;
934 	}
935 
936 	if (args->flags & AMDGPU_VM_DELAY_UPDATE &&
937 	    args->vm_timeline_syncobj_out)
938 		return -EINVAL;
939 
940 	if ((args->operation != AMDGPU_VA_OP_CLEAR) &&
941 	    !(args->flags & AMDGPU_VM_PAGE_PRT)) {
942 		gobj = drm_gem_object_lookup(filp, args->handle);
943 		if (gobj == NULL)
944 			return -ENOENT;
945 		abo = gem_to_amdgpu_bo(gobj);
946 	} else {
947 		gobj = NULL;
948 		abo = NULL;
949 	}
950 
951 	PM_RUNTIME_ACQUIRE_IF_ENABLED_AUTOSUSPEND(dev->dev, lock);
952 
953 	r = PM_RUNTIME_ACQUIRE_ERR(&lock);
954 	if (r)
955 		goto error_put_gobj;
956 
957 	/* Add input syncobj fences (if any) for synchronization. */
958 	r = amdgpu_gem_add_input_fence(filp,
959 				       args->input_fence_syncobj_handles,
960 				       args->num_syncobj_handles);
961 	if (r)
962 		goto error_put_gobj;
963 
964 	drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT |
965 		      DRM_EXEC_IGNORE_DUPLICATES, 0);
966 	drm_exec_until_all_locked(&exec) {
967 		if (gobj) {
968 			r = drm_exec_lock_obj(&exec, gobj);
969 			drm_exec_retry_on_contention(&exec);
970 			if (unlikely(r))
971 				goto error;
972 		}
973 
974 		r = amdgpu_vm_lock_pd(&fpriv->vm, &exec, 2);
975 		drm_exec_retry_on_contention(&exec);
976 		if (unlikely(r))
977 			goto error;
978 	}
979 
980 	/* Resolve the BO-VA mapping for this VM/BO combination. */
981 	if (abo) {
982 		bo_va = amdgpu_vm_bo_find(&fpriv->vm, abo);
983 		if (!bo_va) {
984 			r = -ENOENT;
985 			goto error;
986 		}
987 	} else if (args->operation != AMDGPU_VA_OP_CLEAR) {
988 		bo_va = fpriv->prt_va;
989 	} else {
990 		bo_va = NULL;
991 	}
992 
993 	/*
994 	 * Prepare the timeline syncobj node if the user requested a VM
995 	 * timeline update. This only allocates/looks up the syncobj and
996 	 * chain node; the actual fence is attached later.
997 	 */
998 	r = amdgpu_gem_update_timeline_node(filp,
999 					    args->vm_timeline_syncobj_out,
1000 					    args->vm_timeline_point,
1001 					    &timeline_syncobj,
1002 					    &timeline_chain);
1003 	if (r)
1004 		goto error;
1005 
1006 	switch (args->operation) {
1007 	case AMDGPU_VA_OP_MAP:
1008 		r = amdgpu_vm_bo_map(adev, bo_va, args->va_address,
1009 				     args->offset_in_bo, args->map_size,
1010 				     args->flags);
1011 		break;
1012 	case AMDGPU_VA_OP_UNMAP:
1013 		r = amdgpu_vm_bo_unmap(adev, bo_va, args->va_address);
1014 		break;
1015 
1016 	case AMDGPU_VA_OP_CLEAR:
1017 		r = amdgpu_vm_bo_clear_mappings(adev, &fpriv->vm,
1018 						args->va_address,
1019 						args->map_size);
1020 		break;
1021 	case AMDGPU_VA_OP_REPLACE:
1022 		r = amdgpu_vm_bo_replace_map(adev, bo_va, args->va_address,
1023 					     args->offset_in_bo, args->map_size,
1024 					     args->flags);
1025 		break;
1026 	default:
1027 		break;
1028 	}
1029 
1030 	/*
1031 	 * Once the VA operation is done, update the VM and obtain the fence
1032 	 * that represents the last relevant update for this mapping. This
1033 	 * fence can then be exported to the user-visible VM timeline.
1034 	 */
1035 	if (!r && !(args->flags & AMDGPU_VM_DELAY_UPDATE) &&
1036 	    (!adev->debug_vm || timeline_syncobj)) {
1037 		struct dma_fence *fence;
1038 
1039 		fence = amdgpu_gem_va_update_vm(adev, &fpriv->vm, bo_va,
1040 						args->operation);
1041 		if (timeline_syncobj) {
1042 			if (!args->vm_timeline_point) {
1043 				/* Replace the existing fence when no point is given. */
1044 				drm_syncobj_replace_fence(timeline_syncobj,
1045 							  fence);
1046 			} else {
1047 				/* Attach the last-update fence at a specific point. */
1048 				drm_syncobj_add_point(timeline_syncobj,
1049 						      timeline_chain,
1050 						      fence,
1051 						      args->vm_timeline_point);
1052 				timeline_chain = NULL;
1053 			}
1054 		}
1055 		dma_fence_put(fence);
1056 
1057 	}
1058 
1059 error:
1060 	dma_fence_chain_free(timeline_chain);
1061 	if (timeline_syncobj)
1062 		drm_syncobj_put(timeline_syncobj);
1063 	drm_exec_fini(&exec);
1064 error_put_gobj:
1065 	drm_gem_object_put(gobj);
1066 	return r;
1067 }
1068 
1069 int amdgpu_gem_op_ioctl(struct drm_device *dev, void *data,
1070 			struct drm_file *filp)
1071 {
1072 	struct amdgpu_device *adev = drm_to_adev(dev);
1073 	struct drm_amdgpu_gem_op *args = data;
1074 	struct drm_gem_object *gobj;
1075 	struct amdgpu_vm_bo_base *base;
1076 	struct amdgpu_bo *robj;
1077 	struct drm_exec exec;
1078 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
1079 	int r;
1080 
1081 	if (args->padding)
1082 		return -EINVAL;
1083 
1084 	gobj = drm_gem_object_lookup(filp, args->handle);
1085 	if (!gobj)
1086 		return -ENOENT;
1087 
1088 	robj = gem_to_amdgpu_bo(gobj);
1089 
1090 	drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT |
1091 			  DRM_EXEC_IGNORE_DUPLICATES, 0);
1092 	drm_exec_until_all_locked(&exec) {
1093 		r = drm_exec_lock_obj(&exec, gobj);
1094 		drm_exec_retry_on_contention(&exec);
1095 		if (r)
1096 			goto out_exec;
1097 
1098 		if (args->op == AMDGPU_GEM_OP_GET_MAPPING_INFO) {
1099 			r = amdgpu_vm_lock_pd(&fpriv->vm, &exec, 0);
1100 			drm_exec_retry_on_contention(&exec);
1101 			if (r)
1102 				goto out_exec;
1103 		}
1104 	}
1105 
1106 	switch (args->op) {
1107 	case AMDGPU_GEM_OP_GET_GEM_CREATE_INFO: {
1108 		struct drm_amdgpu_gem_create_in info;
1109 		void __user *out = u64_to_user_ptr(args->value);
1110 
1111 		info.bo_size = robj->tbo.base.size;
1112 		info.alignment = robj->tbo.page_alignment << PAGE_SHIFT;
1113 		info.domains = robj->preferred_domains;
1114 		info.domain_flags = robj->flags;
1115 		drm_exec_fini(&exec);
1116 		if (copy_to_user(out, &info, sizeof(info)))
1117 			r = -EFAULT;
1118 		break;
1119 	}
1120 	case AMDGPU_GEM_OP_SET_PLACEMENT:
1121 		if (drm_gem_is_imported(&robj->tbo.base) &&
1122 		    args->value & AMDGPU_GEM_DOMAIN_VRAM) {
1123 			r = -EINVAL;
1124 			goto out_exec;
1125 		}
1126 		if (amdgpu_ttm_tt_get_usermm(robj->tbo.ttm)) {
1127 			r = -EPERM;
1128 			goto out_exec;
1129 		}
1130 		for (base = robj->vm_bo; base; base = base->next)
1131 			if (amdgpu_xgmi_same_hive(amdgpu_ttm_adev(robj->tbo.bdev),
1132 				amdgpu_ttm_adev(base->vm->root.bo->tbo.bdev))) {
1133 				r = -EINVAL;
1134 				goto out_exec;
1135 			}
1136 
1137 
1138 		robj->preferred_domains = args->value & (AMDGPU_GEM_DOMAIN_VRAM |
1139 							AMDGPU_GEM_DOMAIN_GTT |
1140 							AMDGPU_GEM_DOMAIN_CPU);
1141 		robj->allowed_domains = robj->preferred_domains;
1142 		if (robj->allowed_domains == AMDGPU_GEM_DOMAIN_VRAM)
1143 			robj->allowed_domains |= AMDGPU_GEM_DOMAIN_GTT;
1144 
1145 		if (robj->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID)
1146 			amdgpu_vm_bo_invalidate(robj, true);
1147 		drm_exec_fini(&exec);
1148 		break;
1149 	case AMDGPU_GEM_OP_GET_MAPPING_INFO: {
1150 		struct amdgpu_bo_va *bo_va = amdgpu_vm_bo_find(&fpriv->vm, robj);
1151 		struct drm_amdgpu_gem_vm_entry *vm_entries;
1152 		struct amdgpu_bo_va_mapping *mapping;
1153 		int num_mappings = 0;
1154 		/*
1155 		 * num_entries is set as an input to the size of the user-allocated array of
1156 		 * drm_amdgpu_gem_vm_entry stored at args->value.
1157 		 * num_entries is sent back as output as the number of mappings the bo has.
1158 		 * If that number is larger than the size of the array, the ioctl must
1159 		 * be retried.
1160 		 */
1161 		if (!bo_va) {
1162 			r = -ENOENT;
1163 			goto out_exec;
1164 		}
1165 
1166 		if (args->num_entries > INT_MAX / sizeof(*vm_entries)) {
1167 			r = -EINVAL;
1168 			goto out_exec;
1169 		}
1170 
1171 		vm_entries = kvzalloc_objs(*vm_entries, args->num_entries);
1172 		if (!vm_entries) {
1173 			r = -ENOMEM;
1174 			goto out_exec;
1175 		}
1176 
1177 		amdgpu_vm_bo_va_for_each_valid_mapping(bo_va, mapping) {
1178 			if (num_mappings < args->num_entries) {
1179 				vm_entries[num_mappings].addr =
1180 					amdgpu_gmc_sign_extend(mapping->start * AMDGPU_GPU_PAGE_SIZE);
1181 				vm_entries[num_mappings].size = (mapping->last - mapping->start + 1) * AMDGPU_GPU_PAGE_SIZE;
1182 				vm_entries[num_mappings].offset = mapping->offset;
1183 				vm_entries[num_mappings].flags = mapping->flags;
1184 			}
1185 			num_mappings += 1;
1186 		}
1187 
1188 		amdgpu_vm_bo_va_for_each_invalid_mapping(bo_va, mapping) {
1189 			if (num_mappings < args->num_entries) {
1190 				vm_entries[num_mappings].addr =
1191 					amdgpu_gmc_sign_extend(mapping->start * AMDGPU_GPU_PAGE_SIZE);
1192 				vm_entries[num_mappings].size = (mapping->last - mapping->start + 1) * AMDGPU_GPU_PAGE_SIZE;
1193 				vm_entries[num_mappings].offset = mapping->offset;
1194 				vm_entries[num_mappings].flags = mapping->flags;
1195 			}
1196 			num_mappings += 1;
1197 		}
1198 
1199 		drm_exec_fini(&exec);
1200 
1201 		if (num_mappings > 0 && num_mappings <= args->num_entries)
1202 			if (copy_to_user(u64_to_user_ptr(args->value), vm_entries, num_mappings * sizeof(*vm_entries)))
1203 				r = -EFAULT;
1204 
1205 		args->num_entries = num_mappings;
1206 
1207 		kvfree(vm_entries);
1208 		break;
1209 	}
1210 	default:
1211 		drm_exec_fini(&exec);
1212 		r = -EINVAL;
1213 	}
1214 
1215 	drm_gem_object_put(gobj);
1216 	return r;
1217 out_exec:
1218 	drm_exec_fini(&exec);
1219 	drm_gem_object_put(gobj);
1220 	return r;
1221 }
1222 
1223 /**
1224  * amdgpu_gem_list_handles_ioctl - get information about a process' buffer objects
1225  *
1226  * @dev: drm device pointer
1227  * @data: drm_amdgpu_gem_list_handles
1228  * @filp: drm file pointer
1229  *
1230  * num_entries is set as an input to the size of the entries array.
1231  * num_entries is sent back as output as the number of bos in the process.
1232  * If that number is larger than the size of the array, the ioctl must
1233  * be retried.
1234  *
1235  * Returns:
1236  * 0 for success, -errno for errors.
1237  */
1238 int amdgpu_gem_list_handles_ioctl(struct drm_device *dev, void *data,
1239 				  struct drm_file *filp)
1240 {
1241 	struct drm_amdgpu_gem_list_handles *args = data;
1242 	struct drm_amdgpu_gem_list_handles_entry *bo_entries;
1243 	struct drm_gem_object *gobj;
1244 	int id, ret = 0;
1245 	int bo_index = 0;
1246 	int num_bos = 0;
1247 
1248 	spin_lock(&filp->table_lock);
1249 	idr_for_each_entry(&filp->object_idr, gobj, id)
1250 		num_bos += 1;
1251 	spin_unlock(&filp->table_lock);
1252 
1253 	if (args->num_entries < num_bos) {
1254 		args->num_entries = num_bos;
1255 		return 0;
1256 	}
1257 
1258 	if (num_bos == 0) {
1259 		args->num_entries = 0;
1260 		return 0;
1261 	}
1262 
1263 	bo_entries = kvzalloc_objs(*bo_entries, num_bos);
1264 	if (!bo_entries)
1265 		return -ENOMEM;
1266 
1267 	spin_lock(&filp->table_lock);
1268 	idr_for_each_entry(&filp->object_idr, gobj, id) {
1269 		struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
1270 		struct drm_amdgpu_gem_list_handles_entry *bo_entry;
1271 
1272 		if (bo_index >= num_bos) {
1273 			ret = -EAGAIN;
1274 			break;
1275 		}
1276 
1277 		bo_entry = &bo_entries[bo_index];
1278 
1279 		bo_entry->size = amdgpu_bo_size(bo);
1280 		bo_entry->alloc_flags = bo->flags & AMDGPU_GEM_CREATE_SETTABLE_MASK;
1281 		bo_entry->preferred_domains = bo->preferred_domains;
1282 		bo_entry->gem_handle = id;
1283 		bo_entry->alignment = (u64)bo->tbo.page_alignment << PAGE_SHIFT;
1284 
1285 		if (bo->tbo.base.import_attach)
1286 			bo_entry->flags |= AMDGPU_GEM_LIST_HANDLES_FLAG_IS_IMPORT;
1287 
1288 		bo_index += 1;
1289 	}
1290 	spin_unlock(&filp->table_lock);
1291 
1292 	args->num_entries = bo_index;
1293 
1294 	if (!ret)
1295 		if (copy_to_user(u64_to_user_ptr(args->entries), bo_entries, num_bos * sizeof(*bo_entries)))
1296 			ret = -EFAULT;
1297 
1298 	kvfree(bo_entries);
1299 
1300 	return ret;
1301 }
1302 
1303 static unsigned int amdgpu_gem_align_pitch(struct amdgpu_device *adev,
1304 					   unsigned int width,
1305 					   unsigned int cpp,
1306 					   bool tiled)
1307 {
1308 	unsigned int aligned = width;
1309 	unsigned int pitch_mask = 0;
1310 	unsigned int pitch;
1311 
1312 	switch (cpp) {
1313 	case 1:
1314 		pitch_mask = 255;
1315 		break;
1316 	case 2:
1317 		pitch_mask = 127;
1318 		break;
1319 	case 3:
1320 	case 4:
1321 		pitch_mask = 63;
1322 		break;
1323 	}
1324 
1325 	if (check_add_overflow(aligned, pitch_mask, &aligned))
1326 		return 0;
1327 	aligned &= ~pitch_mask;
1328 	if (check_mul_overflow(aligned, cpp, &pitch))
1329 		return 0;
1330 	return pitch;
1331 }
1332 
1333 int amdgpu_mode_dumb_create(struct drm_file *file_priv,
1334 			    struct drm_device *dev,
1335 			    struct drm_mode_create_dumb *args)
1336 {
1337 	struct amdgpu_device *adev = drm_to_adev(dev);
1338 	struct amdgpu_fpriv *fpriv = file_priv->driver_priv;
1339 	struct drm_gem_object *gobj;
1340 	uint32_t handle;
1341 	u64 flags = AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED |
1342 		    AMDGPU_GEM_CREATE_CPU_GTT_USWC |
1343 		    AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
1344 	u32 domain;
1345 	int r;
1346 
1347 	/*
1348 	 * The buffer returned from this function should be cleared, but
1349 	 * it can only be done if the ring is enabled or we'll fail to
1350 	 * create the buffer.
1351 	 */
1352 	if (adev->mman.buffer_funcs_enabled)
1353 		flags |= AMDGPU_GEM_CREATE_VRAM_CLEARED;
1354 
1355 	args->pitch = amdgpu_gem_align_pitch(adev, args->width,
1356 					     DIV_ROUND_UP(args->bpp, 8), 0);
1357 	if (!args->pitch)
1358 		return -EINVAL;
1359 	args->size = (u64)args->pitch * args->height;
1360 	args->size = ALIGN(args->size, PAGE_SIZE);
1361 	if (!args->size)
1362 		return -EINVAL;
1363 	domain = amdgpu_bo_get_preferred_domain(adev,
1364 				amdgpu_display_supported_domains(adev, flags));
1365 	r = amdgpu_gem_object_create(adev, args->size, 0, domain, flags,
1366 				     ttm_bo_type_device, NULL, &gobj, fpriv->xcp_id + 1);
1367 	if (r)
1368 		return -ENOMEM;
1369 
1370 	r = drm_gem_handle_create(file_priv, gobj, &handle);
1371 	/* drop reference from allocate - handle holds it now */
1372 	drm_gem_object_put(gobj);
1373 	if (r)
1374 		return r;
1375 
1376 	args->handle = handle;
1377 	return 0;
1378 }
1379 
1380 #if defined(CONFIG_DEBUG_FS)
1381 static int amdgpu_debugfs_gem_info_show(struct seq_file *m, void *unused)
1382 {
1383 	struct amdgpu_device *adev = m->private;
1384 	struct drm_device *dev = adev_to_drm(adev);
1385 	struct drm_file *file;
1386 	int r;
1387 
1388 	r = mutex_lock_interruptible(&dev->filelist_mutex);
1389 	if (r)
1390 		return r;
1391 
1392 	list_for_each_entry(file, &dev->filelist, lhead) {
1393 		struct task_struct *task;
1394 		struct drm_gem_object *gobj;
1395 		struct pid *pid;
1396 		int id;
1397 
1398 		/*
1399 		 * Although we have a valid reference on file->pid, that does
1400 		 * not guarantee that the task_struct who called get_pid() is
1401 		 * still alive (e.g. get_pid(current) => fork() => exit()).
1402 		 * Therefore, we need to protect this ->comm access using RCU.
1403 		 */
1404 		rcu_read_lock();
1405 		pid = rcu_dereference(file->pid);
1406 		task = pid_task(pid, PIDTYPE_TGID);
1407 		seq_printf(m, "pid %8d command %s:\n", pid_nr(pid),
1408 			   task ? task->comm : "<unknown>");
1409 		rcu_read_unlock();
1410 
1411 		spin_lock(&file->table_lock);
1412 		idr_for_each_entry(&file->object_idr, gobj, id) {
1413 			struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
1414 
1415 			amdgpu_bo_print_info(id, bo, m);
1416 		}
1417 		spin_unlock(&file->table_lock);
1418 	}
1419 
1420 	mutex_unlock(&dev->filelist_mutex);
1421 	return 0;
1422 }
1423 
1424 DEFINE_SHOW_ATTRIBUTE(amdgpu_debugfs_gem_info);
1425 
1426 #endif
1427 
1428 void amdgpu_debugfs_gem_init(struct amdgpu_device *adev)
1429 {
1430 #if defined(CONFIG_DEBUG_FS)
1431 	struct drm_minor *minor = adev_to_drm(adev)->primary;
1432 	struct dentry *root = minor->debugfs_root;
1433 
1434 	debugfs_create_file("amdgpu_gem_info", 0444, root, adev,
1435 			    &amdgpu_debugfs_gem_info_fops);
1436 #endif
1437 }
1438