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