xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c (revision a10ea943356b9d70c5616a0a06f6fa97cfdaccb1)
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 is_cow_mapping(vm_flags) false.
381 	 */
382 	if (is_cow_mapping(vma->vm_flags) &&
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 const struct drm_gem_object_funcs amdgpu_gem_object_funcs = {
390 	.free = amdgpu_gem_object_free,
391 	.open = amdgpu_gem_object_open,
392 	.close = amdgpu_gem_object_close,
393 	.export = amdgpu_gem_prime_export,
394 	.vmap = drm_gem_ttm_vmap,
395 	.vunmap = drm_gem_ttm_vunmap,
396 	.mmap = amdgpu_gem_object_mmap,
397 	.vm_ops = &amdgpu_gem_vm_ops,
398 };
399 
400 /*
401  * GEM ioctls.
402  */
403 int amdgpu_gem_create_ioctl(struct drm_device *dev, void *data,
404 			    struct drm_file *filp)
405 {
406 	struct amdgpu_device *adev = drm_to_adev(dev);
407 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
408 	struct amdgpu_vm *vm = &fpriv->vm;
409 	union drm_amdgpu_gem_create *args = data;
410 	uint64_t flags = args->in.domain_flags;
411 	uint64_t size = args->in.bo_size;
412 	struct dma_resv *resv = NULL;
413 	struct drm_gem_object *gobj;
414 	uint32_t handle, initial_domain;
415 	int r;
416 
417 	/* reject invalid gem flags */
418 	if (flags & ~AMDGPU_GEM_CREATE_SETTABLE_MASK)
419 		return -EINVAL;
420 
421 	/* reject invalid gem domains */
422 	if (args->in.domains & ~AMDGPU_GEM_DOMAIN_MASK)
423 		return -EINVAL;
424 
425 	if (!amdgpu_is_tmz(adev) && (flags & AMDGPU_GEM_CREATE_ENCRYPTED)) {
426 		DRM_NOTE_ONCE("Cannot allocate secure buffer since TMZ is disabled\n");
427 		return -EINVAL;
428 	}
429 
430 	/* always clear VRAM */
431 	flags |= AMDGPU_GEM_CREATE_VRAM_CLEARED;
432 
433 	/* create a gem object to contain this object in */
434 	if (args->in.domains & (AMDGPU_GEM_DOMAIN_GDS |
435 	    AMDGPU_GEM_DOMAIN_GWS | AMDGPU_GEM_DOMAIN_OA)) {
436 		if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
437 			/* if gds bo is created from user space, it must be
438 			 * passed to bo list
439 			 */
440 			DRM_ERROR("GDS bo cannot be per-vm-bo\n");
441 			return -EINVAL;
442 		}
443 		flags |= AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
444 	}
445 
446 	if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
447 		r = amdgpu_bo_reserve(vm->root.bo, false);
448 		if (r)
449 			return r;
450 
451 		resv = vm->root.bo->tbo.base.resv;
452 	}
453 
454 	initial_domain = (u32)(0xffffffff & args->in.domains);
455 retry:
456 	r = amdgpu_gem_object_create(adev, size, args->in.alignment,
457 				     initial_domain,
458 				     flags, ttm_bo_type_device, resv, &gobj, fpriv->xcp_id + 1);
459 	if (r && r != -ERESTARTSYS) {
460 		if (flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) {
461 			flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
462 			goto retry;
463 		}
464 
465 		if (initial_domain == AMDGPU_GEM_DOMAIN_VRAM) {
466 			initial_domain |= AMDGPU_GEM_DOMAIN_GTT;
467 			goto retry;
468 		}
469 		DRM_DEBUG("Failed to allocate GEM object (%llu, %d, %llu, %d)\n",
470 				size, initial_domain, args->in.alignment, r);
471 	}
472 
473 	if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
474 		if (!r) {
475 			struct amdgpu_bo *abo = gem_to_amdgpu_bo(gobj);
476 
477 			abo->parent = amdgpu_bo_ref(vm->root.bo);
478 		}
479 		amdgpu_bo_unreserve(vm->root.bo);
480 	}
481 	if (r)
482 		return r;
483 
484 	r = drm_gem_handle_create(filp, gobj, &handle);
485 	/* drop reference from allocate - handle holds it now */
486 	drm_gem_object_put(gobj);
487 	if (r)
488 		return r;
489 
490 	memset(args, 0, sizeof(*args));
491 	args->out.handle = handle;
492 	return 0;
493 }
494 
495 int amdgpu_gem_userptr_ioctl(struct drm_device *dev, void *data,
496 			     struct drm_file *filp)
497 {
498 	struct ttm_operation_ctx ctx = { true, false };
499 	struct amdgpu_device *adev = drm_to_adev(dev);
500 	struct drm_amdgpu_gem_userptr *args = data;
501 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
502 	struct drm_gem_object *gobj;
503 	struct amdgpu_hmm_range *range;
504 	struct amdgpu_bo *bo;
505 	uint32_t handle;
506 	int r;
507 
508 	args->addr = untagged_addr(args->addr);
509 
510 	if (offset_in_page(args->addr | args->size))
511 		return -EINVAL;
512 
513 	if (!access_ok((void __user *)(uintptr_t)args->addr, args->size))
514 		return -EFAULT;
515 
516 	/* reject unknown flag values */
517 	if (args->flags & ~(AMDGPU_GEM_USERPTR_READONLY |
518 	    AMDGPU_GEM_USERPTR_ANONONLY | AMDGPU_GEM_USERPTR_VALIDATE |
519 	    AMDGPU_GEM_USERPTR_REGISTER))
520 		return -EINVAL;
521 
522 	if (!(args->flags & AMDGPU_GEM_USERPTR_READONLY) &&
523 	     !(args->flags & AMDGPU_GEM_USERPTR_REGISTER)) {
524 
525 		/* if we want to write to it we must install a MMU notifier */
526 		return -EACCES;
527 	}
528 
529 	/* create a gem object to contain this object in */
530 	r = amdgpu_gem_object_create(adev, args->size, 0, AMDGPU_GEM_DOMAIN_CPU,
531 				     0, ttm_bo_type_device, NULL, &gobj, fpriv->xcp_id + 1);
532 	if (r)
533 		return r;
534 
535 	bo = gem_to_amdgpu_bo(gobj);
536 	bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
537 	bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
538 	bo->parent = amdgpu_bo_ref(fpriv->vm.root.bo);
539 	r = amdgpu_ttm_tt_set_userptr(&bo->tbo, args->addr, args->flags);
540 	if (r)
541 		goto release_object;
542 
543 	r = amdgpu_hmm_register(bo, args->addr);
544 	if (r)
545 		goto release_object;
546 
547 	if (args->flags & AMDGPU_GEM_USERPTR_VALIDATE) {
548 		range = amdgpu_hmm_range_alloc(NULL);
549 		if (unlikely(!range))
550 			return -ENOMEM;
551 		r = amdgpu_ttm_tt_get_user_pages(bo, range);
552 		if (r) {
553 			amdgpu_hmm_range_free(range);
554 			goto release_object;
555 		}
556 		r = amdgpu_bo_reserve(bo, true);
557 		if (r)
558 			goto user_pages_done;
559 
560 		amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, range);
561 
562 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
563 		r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
564 		amdgpu_bo_unreserve(bo);
565 		if (r)
566 			goto user_pages_done;
567 	}
568 
569 	r = drm_gem_handle_create(filp, gobj, &handle);
570 	if (r)
571 		goto user_pages_done;
572 
573 	args->handle = handle;
574 
575 user_pages_done:
576 	if (args->flags & AMDGPU_GEM_USERPTR_VALIDATE)
577 		amdgpu_hmm_range_free(range);
578 release_object:
579 	drm_gem_object_put(gobj);
580 
581 	return r;
582 }
583 
584 int amdgpu_mode_dumb_mmap(struct drm_file *filp,
585 			  struct drm_device *dev,
586 			  uint32_t handle, uint64_t *offset_p)
587 {
588 	struct drm_gem_object *gobj;
589 	struct amdgpu_bo *robj;
590 
591 	gobj = drm_gem_object_lookup(filp, handle);
592 	if (!gobj)
593 		return -ENOENT;
594 
595 	robj = gem_to_amdgpu_bo(gobj);
596 	if (amdgpu_ttm_tt_get_usermm(robj->tbo.ttm) ||
597 	    (robj->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)) {
598 		drm_gem_object_put(gobj);
599 		return -EPERM;
600 	}
601 	*offset_p = amdgpu_bo_mmap_offset(robj);
602 	drm_gem_object_put(gobj);
603 	return 0;
604 }
605 
606 int amdgpu_gem_mmap_ioctl(struct drm_device *dev, void *data,
607 			  struct drm_file *filp)
608 {
609 	union drm_amdgpu_gem_mmap *args = data;
610 	uint32_t handle = args->in.handle;
611 
612 	memset(args, 0, sizeof(*args));
613 	return amdgpu_mode_dumb_mmap(filp, dev, handle, &args->out.addr_ptr);
614 }
615 
616 /**
617  * amdgpu_gem_timeout - calculate jiffies timeout from absolute value
618  *
619  * @timeout_ns: timeout in ns
620  *
621  * Calculate the timeout in jiffies from an absolute timeout in ns.
622  */
623 unsigned long amdgpu_gem_timeout(uint64_t timeout_ns)
624 {
625 	unsigned long timeout_jiffies;
626 	ktime_t timeout;
627 
628 	/* clamp timeout if it's to large */
629 	if (((int64_t)timeout_ns) < 0)
630 		return MAX_SCHEDULE_TIMEOUT;
631 
632 	timeout = ktime_sub(ns_to_ktime(timeout_ns), ktime_get());
633 	if (ktime_to_ns(timeout) < 0)
634 		return 0;
635 
636 	timeout_jiffies = nsecs_to_jiffies(ktime_to_ns(timeout));
637 	/*  clamp timeout to avoid unsigned-> signed overflow */
638 	if (timeout_jiffies > MAX_SCHEDULE_TIMEOUT)
639 		return MAX_SCHEDULE_TIMEOUT - 1;
640 
641 	return timeout_jiffies;
642 }
643 
644 int amdgpu_gem_wait_idle_ioctl(struct drm_device *dev, void *data,
645 			      struct drm_file *filp)
646 {
647 	union drm_amdgpu_gem_wait_idle *args = data;
648 	struct drm_gem_object *gobj;
649 	struct amdgpu_bo *robj;
650 	uint32_t handle = args->in.handle;
651 	unsigned long timeout = amdgpu_gem_timeout(args->in.timeout);
652 	int r = 0;
653 	long ret;
654 
655 	gobj = drm_gem_object_lookup(filp, handle);
656 	if (!gobj)
657 		return -ENOENT;
658 
659 	robj = gem_to_amdgpu_bo(gobj);
660 	ret = dma_resv_wait_timeout(robj->tbo.base.resv, DMA_RESV_USAGE_READ,
661 				    true, timeout);
662 
663 	/* ret == 0 means not signaled,
664 	 * ret > 0 means signaled
665 	 * ret < 0 means interrupted before timeout
666 	 */
667 	if (ret >= 0) {
668 		memset(args, 0, sizeof(*args));
669 		args->out.status = (ret == 0);
670 	} else
671 		r = ret;
672 
673 	drm_gem_object_put(gobj);
674 	return r;
675 }
676 
677 int amdgpu_gem_metadata_ioctl(struct drm_device *dev, void *data,
678 				struct drm_file *filp)
679 {
680 	struct drm_amdgpu_gem_metadata *args = data;
681 	struct drm_gem_object *gobj;
682 	struct amdgpu_bo *robj;
683 	int r = -1;
684 
685 	DRM_DEBUG("%d\n", args->handle);
686 	gobj = drm_gem_object_lookup(filp, args->handle);
687 	if (gobj == NULL)
688 		return -ENOENT;
689 	robj = gem_to_amdgpu_bo(gobj);
690 
691 	r = amdgpu_bo_reserve(robj, false);
692 	if (unlikely(r != 0))
693 		goto out;
694 
695 	/* Reject MMIO_REMAP BOs at IOCTL level: metadata/tiling does not apply. */
696 	if (robj->tbo.resource &&
697 	    robj->tbo.resource->mem_type == AMDGPU_PL_MMIO_REMAP) {
698 		DRM_WARN("metadata ioctl on MMIO_REMAP BO (handle %d)\n",
699 			 args->handle);
700 		r = -EINVAL;
701 		goto unreserve;
702 	}
703 
704 	if (args->op == AMDGPU_GEM_METADATA_OP_GET_METADATA) {
705 		amdgpu_bo_get_tiling_flags(robj, &args->data.tiling_info);
706 		r = amdgpu_bo_get_metadata(robj, args->data.data,
707 					   sizeof(args->data.data),
708 					   &args->data.data_size_bytes,
709 					   &args->data.flags);
710 	} else if (args->op == AMDGPU_GEM_METADATA_OP_SET_METADATA) {
711 		if (args->data.data_size_bytes > sizeof(args->data.data)) {
712 			r = -EINVAL;
713 			goto unreserve;
714 		}
715 		r = amdgpu_bo_set_tiling_flags(robj, args->data.tiling_info);
716 		if (!r)
717 			r = amdgpu_bo_set_metadata(robj, args->data.data,
718 						   args->data.data_size_bytes,
719 						   args->data.flags);
720 	}
721 
722 unreserve:
723 	amdgpu_bo_unreserve(robj);
724 out:
725 	drm_gem_object_put(gobj);
726 	return r;
727 }
728 
729 /**
730  * amdgpu_gem_va_update_vm -update the bo_va in its VM
731  *
732  * @adev: amdgpu_device pointer
733  * @vm: vm to update
734  * @bo_va: bo_va to update
735  * @operation: map, unmap or clear
736  *
737  * Update the bo_va directly after setting its address. Errors are not
738  * vital here, so they are not reported back to userspace.
739  *
740  * Returns resulting fence if freed BO(s) got cleared from the PT.
741  * otherwise stub fence in case of error.
742  */
743 static struct dma_fence *
744 amdgpu_gem_va_update_vm(struct amdgpu_device *adev,
745 			struct amdgpu_vm *vm,
746 			struct amdgpu_bo_va *bo_va,
747 			uint32_t operation)
748 {
749 	struct dma_fence *fence;
750 	int r = 0;
751 
752 	/* If the VM is not ready return only a stub. */
753 	if (!amdgpu_vm_ready(vm))
754 		return dma_fence_get_stub();
755 
756 
757 	/*
758 	 * First clean up any freed mappings in the VM.
759 	 *
760 	 * amdgpu_vm_clear_freed() may replace @fence with a new fence if it
761 	 * schedules GPU work. If nothing needs clearing, @fence can remain as
762 	 * the original vm->last_update.
763 	 */
764 	r = amdgpu_vm_clear_freed(adev, vm, &vm->last_update);
765 	if (r)
766 		goto error;
767 
768 	/* For MAP/REPLACE we also need to update the BO mappings. */
769 	if (operation == AMDGPU_VA_OP_MAP ||
770 	    operation == AMDGPU_VA_OP_REPLACE) {
771 		r = amdgpu_vm_bo_update(adev, bo_va, false);
772 		if (r)
773 			goto error;
774 	}
775 
776 	/* Always update PDEs after we touched the mappings. */
777 	r = amdgpu_vm_update_pdes(adev, vm, false);
778 	if (r)
779 		goto error;
780 
781 	if ((operation == AMDGPU_VA_OP_MAP ||
782 	     operation == AMDGPU_VA_OP_REPLACE) &&
783 	    !amdgpu_vm_is_bo_always_valid(vm, bo_va->base.bo)) {
784 
785 		/*
786 		 * For MAP/REPLACE of non per-VM BOs we need to sync to both the
787 		 * bo_va->last_pt_update and vm->last_update or otherwise we
788 		 * potentially miss the PDE updates.
789 		 */
790 		fence = dma_fence_unwrap_merge(vm->last_update,
791 					       bo_va->last_pt_update);
792 		if (!fence) {
793 			/* As fallback in OOM situations */
794 			dma_fence_wait(vm->last_update, false);
795 			dma_fence_wait(bo_va->last_pt_update, false);
796 			fence = dma_fence_get_stub();
797 		}
798 	} else {
799 		fence = dma_fence_get(vm->last_update);
800 	}
801 
802 	return fence;
803 
804 error:
805 	if (r && r != -ERESTARTSYS)
806 		DRM_ERROR("Couldn't update BO_VA (%d)\n", r);
807 
808 	return dma_fence_get(vm->last_update);
809 }
810 
811 int amdgpu_gem_va_ioctl(struct drm_device *dev, void *data,
812 			  struct drm_file *filp)
813 {
814 	const uint32_t valid_flags = AMDGPU_VM_DELAY_UPDATE |
815 		AMDGPU_VM_PAGE_READABLE | AMDGPU_VM_PAGE_WRITEABLE |
816 		AMDGPU_VM_PAGE_EXECUTABLE | AMDGPU_VM_MTYPE_MASK |
817 		AMDGPU_VM_PAGE_NOALLOC;
818 	const uint32_t prt_flags = AMDGPU_VM_DELAY_UPDATE |
819 		AMDGPU_VM_PAGE_PRT;
820 
821 	struct drm_amdgpu_gem_va *args = data;
822 	struct drm_gem_object *gobj;
823 	struct amdgpu_device *adev = drm_to_adev(dev);
824 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
825 	struct amdgpu_bo *abo;
826 	struct amdgpu_bo_va *bo_va;
827 	struct drm_syncobj *timeline_syncobj = NULL;
828 	struct dma_fence_chain *timeline_chain = NULL;
829 	struct drm_exec exec;
830 	uint64_t vm_size, tmp;
831 	int r = 0;
832 
833 	/* Validate virtual address range against reserved regions. */
834 	if (args->va_address < AMDGPU_VA_RESERVED_BOTTOM) {
835 		dev_dbg(dev->dev,
836 			"va_address 0x%llx is in reserved area 0x%llx\n",
837 			args->va_address, AMDGPU_VA_RESERVED_BOTTOM);
838 		return -EINVAL;
839 	}
840 
841 	if (args->va_address >= AMDGPU_GMC_HOLE_START &&
842 	    args->va_address < AMDGPU_GMC_HOLE_END) {
843 		dev_dbg(dev->dev,
844 			"va_address 0x%llx is in VA hole 0x%llx-0x%llx\n",
845 			args->va_address, AMDGPU_GMC_HOLE_START,
846 			AMDGPU_GMC_HOLE_END);
847 		return -EINVAL;
848 	}
849 
850 	args->va_address &= AMDGPU_GMC_HOLE_MASK;
851 
852 	vm_size = adev->vm_manager.max_pfn * AMDGPU_GPU_PAGE_SIZE;
853 	vm_size -= AMDGPU_VA_RESERVED_TOP;
854 	if (check_add_overflow(args->va_address, args->map_size, &tmp) || tmp > vm_size) {
855 		dev_dbg(dev->dev,
856 			"va_address 0x%llx is in top reserved area 0x%llx\n",
857 			args->va_address + args->map_size, vm_size);
858 		return -EINVAL;
859 	}
860 
861 	if ((args->flags & ~valid_flags) && (args->flags & ~prt_flags)) {
862 		dev_dbg(dev->dev, "invalid flags combination 0x%08X\n",
863 			args->flags);
864 		return -EINVAL;
865 	}
866 
867 	/* Validate operation type. */
868 	switch (args->operation) {
869 	case AMDGPU_VA_OP_MAP:
870 	case AMDGPU_VA_OP_UNMAP:
871 	case AMDGPU_VA_OP_CLEAR:
872 	case AMDGPU_VA_OP_REPLACE:
873 		break;
874 	default:
875 		dev_dbg(dev->dev, "unsupported operation %d\n",
876 			args->operation);
877 		return -EINVAL;
878 	}
879 
880 	if (args->flags & AMDGPU_VM_DELAY_UPDATE &&
881 	    args->vm_timeline_syncobj_out)
882 		return -EINVAL;
883 
884 	if ((args->operation != AMDGPU_VA_OP_CLEAR) &&
885 	    !(args->flags & AMDGPU_VM_PAGE_PRT)) {
886 		gobj = drm_gem_object_lookup(filp, args->handle);
887 		if (gobj == NULL)
888 			return -ENOENT;
889 		abo = gem_to_amdgpu_bo(gobj);
890 	} else {
891 		gobj = NULL;
892 		abo = NULL;
893 	}
894 
895 	/* Add input syncobj fences (if any) for synchronization. */
896 	r = amdgpu_gem_add_input_fence(filp,
897 				       args->input_fence_syncobj_handles,
898 				       args->num_syncobj_handles);
899 	if (r)
900 		goto error_put_gobj;
901 
902 	drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT |
903 		      DRM_EXEC_IGNORE_DUPLICATES, 0);
904 	drm_exec_until_all_locked(&exec) {
905 		if (gobj) {
906 			r = drm_exec_lock_obj(&exec, gobj);
907 			drm_exec_retry_on_contention(&exec);
908 			if (unlikely(r))
909 				goto error;
910 		}
911 
912 		r = amdgpu_vm_lock_pd(&fpriv->vm, &exec, 2);
913 		drm_exec_retry_on_contention(&exec);
914 		if (unlikely(r))
915 			goto error;
916 	}
917 
918 	/* Resolve the BO-VA mapping for this VM/BO combination. */
919 	if (abo) {
920 		bo_va = amdgpu_vm_bo_find(&fpriv->vm, abo);
921 		if (!bo_va) {
922 			r = -ENOENT;
923 			goto error;
924 		}
925 	} else if (args->operation != AMDGPU_VA_OP_CLEAR) {
926 		bo_va = fpriv->prt_va;
927 	} else {
928 		bo_va = NULL;
929 	}
930 
931 	/*
932 	 * Prepare the timeline syncobj node if the user requested a VM
933 	 * timeline update. This only allocates/looks up the syncobj and
934 	 * chain node; the actual fence is attached later.
935 	 */
936 	r = amdgpu_gem_update_timeline_node(filp,
937 					    args->vm_timeline_syncobj_out,
938 					    args->vm_timeline_point,
939 					    &timeline_syncobj,
940 					    &timeline_chain);
941 	if (r)
942 		goto error;
943 
944 	switch (args->operation) {
945 	case AMDGPU_VA_OP_MAP:
946 		r = amdgpu_vm_bo_map(adev, bo_va, args->va_address,
947 				     args->offset_in_bo, args->map_size,
948 				     args->flags);
949 		break;
950 	case AMDGPU_VA_OP_UNMAP:
951 		r = amdgpu_vm_bo_unmap(adev, bo_va, args->va_address);
952 		break;
953 
954 	case AMDGPU_VA_OP_CLEAR:
955 		r = amdgpu_vm_bo_clear_mappings(adev, &fpriv->vm,
956 						args->va_address,
957 						args->map_size);
958 		break;
959 	case AMDGPU_VA_OP_REPLACE:
960 		r = amdgpu_vm_bo_replace_map(adev, bo_va, args->va_address,
961 					     args->offset_in_bo, args->map_size,
962 					     args->flags);
963 		break;
964 	default:
965 		break;
966 	}
967 
968 	/*
969 	 * Once the VA operation is done, update the VM and obtain the fence
970 	 * that represents the last relevant update for this mapping. This
971 	 * fence can then be exported to the user-visible VM timeline.
972 	 */
973 	if (!r && !(args->flags & AMDGPU_VM_DELAY_UPDATE) &&
974 	    (!adev->debug_vm || timeline_syncobj)) {
975 		struct dma_fence *fence;
976 
977 		fence = amdgpu_gem_va_update_vm(adev, &fpriv->vm, bo_va,
978 						args->operation);
979 		if (timeline_syncobj) {
980 			if (!args->vm_timeline_point) {
981 				/* Replace the existing fence when no point is given. */
982 				drm_syncobj_replace_fence(timeline_syncobj,
983 							  fence);
984 			} else {
985 				/* Attach the last-update fence at a specific point. */
986 				drm_syncobj_add_point(timeline_syncobj,
987 						      timeline_chain,
988 						      fence,
989 						      args->vm_timeline_point);
990 				timeline_chain = NULL;
991 			}
992 		}
993 		dma_fence_put(fence);
994 
995 	}
996 
997 error:
998 	dma_fence_chain_free(timeline_chain);
999 	if (timeline_syncobj)
1000 		drm_syncobj_put(timeline_syncobj);
1001 	drm_exec_fini(&exec);
1002 error_put_gobj:
1003 	drm_gem_object_put(gobj);
1004 	return r;
1005 }
1006 
1007 int amdgpu_gem_op_ioctl(struct drm_device *dev, void *data,
1008 			struct drm_file *filp)
1009 {
1010 	struct drm_amdgpu_gem_op *args = data;
1011 	struct drm_gem_object *gobj;
1012 	struct amdgpu_vm_bo_base *base;
1013 	struct amdgpu_bo *robj;
1014 	struct drm_exec exec;
1015 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
1016 	int r;
1017 
1018 	if (args->padding)
1019 		return -EINVAL;
1020 
1021 	gobj = drm_gem_object_lookup(filp, args->handle);
1022 	if (!gobj)
1023 		return -ENOENT;
1024 
1025 	robj = gem_to_amdgpu_bo(gobj);
1026 
1027 	drm_exec_init(&exec, DRM_EXEC_INTERRUPTIBLE_WAIT |
1028 			  DRM_EXEC_IGNORE_DUPLICATES, 0);
1029 	drm_exec_until_all_locked(&exec) {
1030 		r = drm_exec_lock_obj(&exec, gobj);
1031 		drm_exec_retry_on_contention(&exec);
1032 		if (r)
1033 			goto out_exec;
1034 
1035 		if (args->op == AMDGPU_GEM_OP_GET_MAPPING_INFO) {
1036 			r = amdgpu_vm_lock_pd(&fpriv->vm, &exec, 0);
1037 			drm_exec_retry_on_contention(&exec);
1038 			if (r)
1039 				goto out_exec;
1040 		}
1041 	}
1042 
1043 	switch (args->op) {
1044 	case AMDGPU_GEM_OP_GET_GEM_CREATE_INFO: {
1045 		struct drm_amdgpu_gem_create_in info;
1046 		void __user *out = u64_to_user_ptr(args->value);
1047 
1048 		info.bo_size = robj->tbo.base.size;
1049 		info.alignment = robj->tbo.page_alignment << PAGE_SHIFT;
1050 		info.domains = robj->preferred_domains;
1051 		info.domain_flags = robj->flags;
1052 		drm_exec_fini(&exec);
1053 		if (copy_to_user(out, &info, sizeof(info)))
1054 			r = -EFAULT;
1055 		break;
1056 	}
1057 	case AMDGPU_GEM_OP_SET_PLACEMENT:
1058 		if (drm_gem_is_imported(&robj->tbo.base) &&
1059 		    args->value & AMDGPU_GEM_DOMAIN_VRAM) {
1060 			r = -EINVAL;
1061 			goto out_exec;
1062 		}
1063 		if (amdgpu_ttm_tt_get_usermm(robj->tbo.ttm)) {
1064 			r = -EPERM;
1065 			goto out_exec;
1066 		}
1067 		for (base = robj->vm_bo; base; base = base->next)
1068 			if (amdgpu_xgmi_same_hive(amdgpu_ttm_adev(robj->tbo.bdev),
1069 				amdgpu_ttm_adev(base->vm->root.bo->tbo.bdev))) {
1070 				r = -EINVAL;
1071 				goto out_exec;
1072 			}
1073 
1074 
1075 		robj->preferred_domains = args->value & (AMDGPU_GEM_DOMAIN_VRAM |
1076 							AMDGPU_GEM_DOMAIN_GTT |
1077 							AMDGPU_GEM_DOMAIN_CPU);
1078 		robj->allowed_domains = robj->preferred_domains;
1079 		if (robj->allowed_domains == AMDGPU_GEM_DOMAIN_VRAM)
1080 			robj->allowed_domains |= AMDGPU_GEM_DOMAIN_GTT;
1081 
1082 		if (robj->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID)
1083 			amdgpu_vm_bo_invalidate(robj, true);
1084 		drm_exec_fini(&exec);
1085 		break;
1086 	case AMDGPU_GEM_OP_GET_MAPPING_INFO: {
1087 		struct amdgpu_bo_va *bo_va = amdgpu_vm_bo_find(&fpriv->vm, robj);
1088 		struct drm_amdgpu_gem_vm_entry *vm_entries;
1089 		struct amdgpu_bo_va_mapping *mapping;
1090 		int num_mappings = 0;
1091 		/*
1092 		 * num_entries is set as an input to the size of the user-allocated array of
1093 		 * drm_amdgpu_gem_vm_entry stored at args->value.
1094 		 * num_entries is sent back as output as the number of mappings the bo has.
1095 		 * If that number is larger than the size of the array, the ioctl must
1096 		 * be retried.
1097 		 */
1098 		if (!bo_va) {
1099 			r = -ENOENT;
1100 			goto out_exec;
1101 		}
1102 
1103 		if (args->num_entries > INT_MAX / sizeof(*vm_entries)) {
1104 			r = -EINVAL;
1105 			goto out_exec;
1106 		}
1107 
1108 		vm_entries = kvcalloc(args->num_entries, sizeof(*vm_entries), GFP_KERNEL);
1109 		if (!vm_entries) {
1110 			r = -ENOMEM;
1111 			goto out_exec;
1112 		}
1113 
1114 		amdgpu_vm_bo_va_for_each_valid_mapping(bo_va, mapping) {
1115 			if (num_mappings < args->num_entries) {
1116 				vm_entries[num_mappings].addr = mapping->start * AMDGPU_GPU_PAGE_SIZE;
1117 				vm_entries[num_mappings].size = (mapping->last - mapping->start + 1) * AMDGPU_GPU_PAGE_SIZE;
1118 				vm_entries[num_mappings].offset = mapping->offset;
1119 				vm_entries[num_mappings].flags = mapping->flags;
1120 			}
1121 			num_mappings += 1;
1122 		}
1123 
1124 		amdgpu_vm_bo_va_for_each_invalid_mapping(bo_va, mapping) {
1125 			if (num_mappings < args->num_entries) {
1126 				vm_entries[num_mappings].addr = mapping->start * AMDGPU_GPU_PAGE_SIZE;
1127 				vm_entries[num_mappings].size = (mapping->last - mapping->start + 1) * AMDGPU_GPU_PAGE_SIZE;
1128 				vm_entries[num_mappings].offset = mapping->offset;
1129 				vm_entries[num_mappings].flags = mapping->flags;
1130 			}
1131 			num_mappings += 1;
1132 		}
1133 
1134 		drm_exec_fini(&exec);
1135 
1136 		if (num_mappings > 0 && num_mappings <= args->num_entries)
1137 			if (copy_to_user(u64_to_user_ptr(args->value), vm_entries, num_mappings * sizeof(*vm_entries)))
1138 				r = -EFAULT;
1139 
1140 		args->num_entries = num_mappings;
1141 
1142 		kvfree(vm_entries);
1143 		break;
1144 	}
1145 	default:
1146 		drm_exec_fini(&exec);
1147 		r = -EINVAL;
1148 	}
1149 
1150 	drm_gem_object_put(gobj);
1151 	return r;
1152 out_exec:
1153 	drm_exec_fini(&exec);
1154 	drm_gem_object_put(gobj);
1155 	return r;
1156 }
1157 
1158 /**
1159  * amdgpu_gem_list_handles_ioctl - get information about a process' buffer objects
1160  *
1161  * @dev: drm device pointer
1162  * @data: drm_amdgpu_gem_list_handles
1163  * @filp: drm file pointer
1164  *
1165  * num_entries is set as an input to the size of the entries array.
1166  * num_entries is sent back as output as the number of bos in the process.
1167  * If that number is larger than the size of the array, the ioctl must
1168  * be retried.
1169  *
1170  * Returns:
1171  * 0 for success, -errno for errors.
1172  */
1173 int amdgpu_gem_list_handles_ioctl(struct drm_device *dev, void *data,
1174 				  struct drm_file *filp)
1175 {
1176 	struct drm_amdgpu_gem_list_handles *args = data;
1177 	struct drm_amdgpu_gem_list_handles_entry *bo_entries;
1178 	struct drm_gem_object *gobj;
1179 	int id, ret = 0;
1180 	int bo_index = 0;
1181 	int num_bos = 0;
1182 
1183 	spin_lock(&filp->table_lock);
1184 	idr_for_each_entry(&filp->object_idr, gobj, id)
1185 		num_bos += 1;
1186 	spin_unlock(&filp->table_lock);
1187 
1188 	if (args->num_entries < num_bos) {
1189 		args->num_entries = num_bos;
1190 		return 0;
1191 	}
1192 
1193 	if (num_bos == 0) {
1194 		args->num_entries = 0;
1195 		return 0;
1196 	}
1197 
1198 	bo_entries = kvzalloc_objs(*bo_entries, num_bos);
1199 	if (!bo_entries)
1200 		return -ENOMEM;
1201 
1202 	spin_lock(&filp->table_lock);
1203 	idr_for_each_entry(&filp->object_idr, gobj, id) {
1204 		struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
1205 		struct drm_amdgpu_gem_list_handles_entry *bo_entry;
1206 
1207 		if (bo_index >= num_bos) {
1208 			ret = -EAGAIN;
1209 			break;
1210 		}
1211 
1212 		bo_entry = &bo_entries[bo_index];
1213 
1214 		bo_entry->size = amdgpu_bo_size(bo);
1215 		bo_entry->alloc_flags = bo->flags & AMDGPU_GEM_CREATE_SETTABLE_MASK;
1216 		bo_entry->preferred_domains = bo->preferred_domains;
1217 		bo_entry->gem_handle = id;
1218 		bo_entry->alignment = bo->tbo.page_alignment;
1219 
1220 		if (bo->tbo.base.import_attach)
1221 			bo_entry->flags |= AMDGPU_GEM_LIST_HANDLES_FLAG_IS_IMPORT;
1222 
1223 		bo_index += 1;
1224 	}
1225 	spin_unlock(&filp->table_lock);
1226 
1227 	args->num_entries = bo_index;
1228 
1229 	if (!ret)
1230 		if (copy_to_user(u64_to_user_ptr(args->entries), bo_entries, num_bos * sizeof(*bo_entries)))
1231 			ret = -EFAULT;
1232 
1233 	kvfree(bo_entries);
1234 
1235 	return ret;
1236 }
1237 
1238 static unsigned int amdgpu_gem_align_pitch(struct amdgpu_device *adev,
1239 					   unsigned int width,
1240 					   unsigned int cpp,
1241 					   bool tiled)
1242 {
1243 	unsigned int aligned = width;
1244 	unsigned int pitch_mask = 0;
1245 	unsigned int pitch;
1246 
1247 	switch (cpp) {
1248 	case 1:
1249 		pitch_mask = 255;
1250 		break;
1251 	case 2:
1252 		pitch_mask = 127;
1253 		break;
1254 	case 3:
1255 	case 4:
1256 		pitch_mask = 63;
1257 		break;
1258 	}
1259 
1260 	if (check_add_overflow(aligned, pitch_mask, &aligned))
1261 		return 0;
1262 	aligned &= ~pitch_mask;
1263 	if (check_mul_overflow(aligned, cpp, &pitch))
1264 		return 0;
1265 	return pitch;
1266 }
1267 
1268 int amdgpu_mode_dumb_create(struct drm_file *file_priv,
1269 			    struct drm_device *dev,
1270 			    struct drm_mode_create_dumb *args)
1271 {
1272 	struct amdgpu_device *adev = drm_to_adev(dev);
1273 	struct amdgpu_fpriv *fpriv = file_priv->driver_priv;
1274 	struct drm_gem_object *gobj;
1275 	uint32_t handle;
1276 	u64 flags = AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED |
1277 		    AMDGPU_GEM_CREATE_CPU_GTT_USWC |
1278 		    AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
1279 	u32 domain;
1280 	int r;
1281 
1282 	/*
1283 	 * The buffer returned from this function should be cleared, but
1284 	 * it can only be done if the ring is enabled or we'll fail to
1285 	 * create the buffer.
1286 	 */
1287 	if (adev->mman.buffer_funcs_enabled)
1288 		flags |= AMDGPU_GEM_CREATE_VRAM_CLEARED;
1289 
1290 	args->pitch = amdgpu_gem_align_pitch(adev, args->width,
1291 					     DIV_ROUND_UP(args->bpp, 8), 0);
1292 	if (!args->pitch)
1293 		return -EINVAL;
1294 	args->size = (u64)args->pitch * args->height;
1295 	args->size = ALIGN(args->size, PAGE_SIZE);
1296 	if (!args->size)
1297 		return -EINVAL;
1298 	domain = amdgpu_bo_get_preferred_domain(adev,
1299 				amdgpu_display_supported_domains(adev, flags));
1300 	r = amdgpu_gem_object_create(adev, args->size, 0, domain, flags,
1301 				     ttm_bo_type_device, NULL, &gobj, fpriv->xcp_id + 1);
1302 	if (r)
1303 		return -ENOMEM;
1304 
1305 	r = drm_gem_handle_create(file_priv, gobj, &handle);
1306 	/* drop reference from allocate - handle holds it now */
1307 	drm_gem_object_put(gobj);
1308 	if (r)
1309 		return r;
1310 
1311 	args->handle = handle;
1312 	return 0;
1313 }
1314 
1315 #if defined(CONFIG_DEBUG_FS)
1316 static int amdgpu_debugfs_gem_info_show(struct seq_file *m, void *unused)
1317 {
1318 	struct amdgpu_device *adev = m->private;
1319 	struct drm_device *dev = adev_to_drm(adev);
1320 	struct drm_file *file;
1321 	int r;
1322 
1323 	r = mutex_lock_interruptible(&dev->filelist_mutex);
1324 	if (r)
1325 		return r;
1326 
1327 	list_for_each_entry(file, &dev->filelist, lhead) {
1328 		struct task_struct *task;
1329 		struct drm_gem_object *gobj;
1330 		struct pid *pid;
1331 		int id;
1332 
1333 		/*
1334 		 * Although we have a valid reference on file->pid, that does
1335 		 * not guarantee that the task_struct who called get_pid() is
1336 		 * still alive (e.g. get_pid(current) => fork() => exit()).
1337 		 * Therefore, we need to protect this ->comm access using RCU.
1338 		 */
1339 		rcu_read_lock();
1340 		pid = rcu_dereference(file->pid);
1341 		task = pid_task(pid, PIDTYPE_TGID);
1342 		seq_printf(m, "pid %8d command %s:\n", pid_nr(pid),
1343 			   task ? task->comm : "<unknown>");
1344 		rcu_read_unlock();
1345 
1346 		spin_lock(&file->table_lock);
1347 		idr_for_each_entry(&file->object_idr, gobj, id) {
1348 			struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
1349 
1350 			amdgpu_bo_print_info(id, bo, m);
1351 		}
1352 		spin_unlock(&file->table_lock);
1353 	}
1354 
1355 	mutex_unlock(&dev->filelist_mutex);
1356 	return 0;
1357 }
1358 
1359 DEFINE_SHOW_ATTRIBUTE(amdgpu_debugfs_gem_info);
1360 
1361 #endif
1362 
1363 void amdgpu_debugfs_gem_init(struct amdgpu_device *adev)
1364 {
1365 #if defined(CONFIG_DEBUG_FS)
1366 	struct drm_minor *minor = adev_to_drm(adev)->primary;
1367 	struct dentry *root = minor->debugfs_root;
1368 
1369 	debugfs_create_file("amdgpu_gem_info", 0444, root, adev,
1370 			    &amdgpu_debugfs_gem_info_fops);
1371 #endif
1372 }
1373