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/pagemap.h>
31 #include <linux/pci.h>
32 #include <linux/dma-buf.h>
33 
34 #include <drm/amdgpu_drm.h>
35 #include <drm/drm_drv.h>
36 #include <drm/drm_gem_ttm_helper.h>
37 
38 #include "amdgpu.h"
39 #include "amdgpu_display.h"
40 #include "amdgpu_dma_buf.h"
41 #include "amdgpu_xgmi.h"
42 
43 static const struct drm_gem_object_funcs amdgpu_gem_object_funcs;
44 
45 static vm_fault_t amdgpu_gem_fault(struct vm_fault *vmf)
46 {
47 	struct ttm_buffer_object *bo = vmf->vma->vm_private_data;
48 	struct drm_device *ddev = bo->base.dev;
49 	vm_fault_t ret;
50 	int idx;
51 
52 	ret = ttm_bo_vm_reserve(bo, vmf);
53 	if (ret)
54 		return ret;
55 
56 	if (drm_dev_enter(ddev, &idx)) {
57 		ret = amdgpu_bo_fault_reserve_notify(bo);
58 		if (ret) {
59 			drm_dev_exit(idx);
60 			goto unlock;
61 		}
62 
63 		 ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
64 						TTM_BO_VM_NUM_PREFAULT, 1);
65 
66 		 drm_dev_exit(idx);
67 	} else {
68 		ret = ttm_bo_vm_dummy_page(vmf, vmf->vma->vm_page_prot);
69 	}
70 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
71 		return ret;
72 
73 unlock:
74 	dma_resv_unlock(bo->base.resv);
75 	return ret;
76 }
77 
78 static const struct vm_operations_struct amdgpu_gem_vm_ops = {
79 	.fault = amdgpu_gem_fault,
80 	.open = ttm_bo_vm_open,
81 	.close = ttm_bo_vm_close,
82 	.access = ttm_bo_vm_access
83 };
84 
85 static void amdgpu_gem_object_free(struct drm_gem_object *gobj)
86 {
87 	struct amdgpu_bo *robj = gem_to_amdgpu_bo(gobj);
88 
89 	if (robj) {
90 		amdgpu_mn_unregister(robj);
91 		amdgpu_bo_unref(&robj);
92 	}
93 }
94 
95 int amdgpu_gem_object_create(struct amdgpu_device *adev, unsigned long size,
96 			     int alignment, u32 initial_domain,
97 			     u64 flags, enum ttm_bo_type type,
98 			     struct dma_resv *resv,
99 			     struct drm_gem_object **obj)
100 {
101 	struct amdgpu_bo *bo;
102 	struct amdgpu_bo_user *ubo;
103 	struct amdgpu_bo_param bp;
104 	int r;
105 
106 	memset(&bp, 0, sizeof(bp));
107 	*obj = NULL;
108 
109 	bp.size = size;
110 	bp.byte_align = alignment;
111 	bp.type = type;
112 	bp.resv = resv;
113 	bp.preferred_domain = initial_domain;
114 	bp.flags = flags;
115 	bp.domain = initial_domain;
116 	bp.bo_ptr_size = sizeof(struct amdgpu_bo);
117 
118 	r = amdgpu_bo_create_user(adev, &bp, &ubo);
119 	if (r)
120 		return r;
121 
122 	bo = &ubo->bo;
123 	*obj = &bo->tbo.base;
124 	(*obj)->funcs = &amdgpu_gem_object_funcs;
125 
126 	return 0;
127 }
128 
129 void amdgpu_gem_force_release(struct amdgpu_device *adev)
130 {
131 	struct drm_device *ddev = adev_to_drm(adev);
132 	struct drm_file *file;
133 
134 	mutex_lock(&ddev->filelist_mutex);
135 
136 	list_for_each_entry(file, &ddev->filelist, lhead) {
137 		struct drm_gem_object *gobj;
138 		int handle;
139 
140 		WARN_ONCE(1, "Still active user space clients!\n");
141 		spin_lock(&file->table_lock);
142 		idr_for_each_entry(&file->object_idr, gobj, handle) {
143 			WARN_ONCE(1, "And also active allocations!\n");
144 			drm_gem_object_put(gobj);
145 		}
146 		idr_destroy(&file->object_idr);
147 		spin_unlock(&file->table_lock);
148 	}
149 
150 	mutex_unlock(&ddev->filelist_mutex);
151 }
152 
153 /*
154  * Call from drm_gem_handle_create which appear in both new and open ioctl
155  * case.
156  */
157 static int amdgpu_gem_object_open(struct drm_gem_object *obj,
158 				  struct drm_file *file_priv)
159 {
160 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(obj);
161 	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
162 	struct amdgpu_fpriv *fpriv = file_priv->driver_priv;
163 	struct amdgpu_vm *vm = &fpriv->vm;
164 	struct amdgpu_bo_va *bo_va;
165 	struct mm_struct *mm;
166 	int r;
167 
168 	mm = amdgpu_ttm_tt_get_usermm(abo->tbo.ttm);
169 	if (mm && mm != current->mm)
170 		return -EPERM;
171 
172 	if (abo->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID &&
173 	    abo->tbo.base.resv != vm->root.bo->tbo.base.resv)
174 		return -EPERM;
175 
176 	r = amdgpu_bo_reserve(abo, false);
177 	if (r)
178 		return r;
179 
180 	bo_va = amdgpu_vm_bo_find(vm, abo);
181 	if (!bo_va) {
182 		bo_va = amdgpu_vm_bo_add(adev, vm, abo);
183 	} else {
184 		++bo_va->ref_count;
185 	}
186 	amdgpu_bo_unreserve(abo);
187 	return 0;
188 }
189 
190 static void amdgpu_gem_object_close(struct drm_gem_object *obj,
191 				    struct drm_file *file_priv)
192 {
193 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
194 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
195 	struct amdgpu_fpriv *fpriv = file_priv->driver_priv;
196 	struct amdgpu_vm *vm = &fpriv->vm;
197 
198 	struct amdgpu_bo_list_entry vm_pd;
199 	struct list_head list, duplicates;
200 	struct dma_fence *fence = NULL;
201 	struct ttm_validate_buffer tv;
202 	struct ww_acquire_ctx ticket;
203 	struct amdgpu_bo_va *bo_va;
204 	long r;
205 
206 	INIT_LIST_HEAD(&list);
207 	INIT_LIST_HEAD(&duplicates);
208 
209 	tv.bo = &bo->tbo;
210 	tv.num_shared = 2;
211 	list_add(&tv.head, &list);
212 
213 	amdgpu_vm_get_pd_bo(vm, &list, &vm_pd);
214 
215 	r = ttm_eu_reserve_buffers(&ticket, &list, false, &duplicates);
216 	if (r) {
217 		dev_err(adev->dev, "leaking bo va because "
218 			"we fail to reserve bo (%ld)\n", r);
219 		return;
220 	}
221 	bo_va = amdgpu_vm_bo_find(vm, bo);
222 	if (!bo_va || --bo_va->ref_count)
223 		goto out_unlock;
224 
225 	amdgpu_vm_bo_rmv(adev, bo_va);
226 	if (!amdgpu_vm_ready(vm))
227 		goto out_unlock;
228 
229 	fence = dma_resv_excl_fence(bo->tbo.base.resv);
230 	if (fence) {
231 		amdgpu_bo_fence(bo, fence, true);
232 		fence = NULL;
233 	}
234 
235 	r = amdgpu_vm_clear_freed(adev, vm, &fence);
236 	if (r || !fence)
237 		goto out_unlock;
238 
239 	amdgpu_bo_fence(bo, fence, true);
240 	dma_fence_put(fence);
241 
242 out_unlock:
243 	if (unlikely(r < 0))
244 		dev_err(adev->dev, "failed to clear page "
245 			"tables on GEM object close (%ld)\n", r);
246 	ttm_eu_backoff_reservation(&ticket, &list);
247 }
248 
249 static int amdgpu_gem_object_mmap(struct drm_gem_object *obj, struct vm_area_struct *vma)
250 {
251 	struct amdgpu_bo *bo = gem_to_amdgpu_bo(obj);
252 
253 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm))
254 		return -EPERM;
255 	if (bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)
256 		return -EPERM;
257 
258 	/* Workaround for Thunk bug creating PROT_NONE,MAP_PRIVATE mappings
259 	 * for debugger access to invisible VRAM. Should have used MAP_SHARED
260 	 * instead. Clearing VM_MAYWRITE prevents the mapping from ever
261 	 * becoming writable and makes is_cow_mapping(vm_flags) false.
262 	 */
263 	if (is_cow_mapping(vma->vm_flags) &&
264 	    !(vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC)))
265 		vma->vm_flags &= ~VM_MAYWRITE;
266 
267 	return drm_gem_ttm_mmap(obj, vma);
268 }
269 
270 static const struct drm_gem_object_funcs amdgpu_gem_object_funcs = {
271 	.free = amdgpu_gem_object_free,
272 	.open = amdgpu_gem_object_open,
273 	.close = amdgpu_gem_object_close,
274 	.export = amdgpu_gem_prime_export,
275 	.vmap = drm_gem_ttm_vmap,
276 	.vunmap = drm_gem_ttm_vunmap,
277 	.mmap = amdgpu_gem_object_mmap,
278 	.vm_ops = &amdgpu_gem_vm_ops,
279 };
280 
281 /*
282  * GEM ioctls.
283  */
284 int amdgpu_gem_create_ioctl(struct drm_device *dev, void *data,
285 			    struct drm_file *filp)
286 {
287 	struct amdgpu_device *adev = drm_to_adev(dev);
288 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
289 	struct amdgpu_vm *vm = &fpriv->vm;
290 	union drm_amdgpu_gem_create *args = data;
291 	uint64_t flags = args->in.domain_flags;
292 	uint64_t size = args->in.bo_size;
293 	struct dma_resv *resv = NULL;
294 	struct drm_gem_object *gobj;
295 	uint32_t handle, initial_domain;
296 	int r;
297 
298 	/* reject invalid gem flags */
299 	if (flags & ~(AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED |
300 		      AMDGPU_GEM_CREATE_NO_CPU_ACCESS |
301 		      AMDGPU_GEM_CREATE_CPU_GTT_USWC |
302 		      AMDGPU_GEM_CREATE_VRAM_CLEARED |
303 		      AMDGPU_GEM_CREATE_VM_ALWAYS_VALID |
304 		      AMDGPU_GEM_CREATE_EXPLICIT_SYNC |
305 		      AMDGPU_GEM_CREATE_ENCRYPTED))
306 
307 		return -EINVAL;
308 
309 	/* reject invalid gem domains */
310 	if (args->in.domains & ~AMDGPU_GEM_DOMAIN_MASK)
311 		return -EINVAL;
312 
313 	if (!amdgpu_is_tmz(adev) && (flags & AMDGPU_GEM_CREATE_ENCRYPTED)) {
314 		DRM_NOTE_ONCE("Cannot allocate secure buffer since TMZ is disabled\n");
315 		return -EINVAL;
316 	}
317 
318 	/* create a gem object to contain this object in */
319 	if (args->in.domains & (AMDGPU_GEM_DOMAIN_GDS |
320 	    AMDGPU_GEM_DOMAIN_GWS | AMDGPU_GEM_DOMAIN_OA)) {
321 		if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
322 			/* if gds bo is created from user space, it must be
323 			 * passed to bo list
324 			 */
325 			DRM_ERROR("GDS bo cannot be per-vm-bo\n");
326 			return -EINVAL;
327 		}
328 		flags |= AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
329 	}
330 
331 	if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
332 		r = amdgpu_bo_reserve(vm->root.bo, false);
333 		if (r)
334 			return r;
335 
336 		resv = vm->root.bo->tbo.base.resv;
337 	}
338 
339 	initial_domain = (u32)(0xffffffff & args->in.domains);
340 retry:
341 	r = amdgpu_gem_object_create(adev, size, args->in.alignment,
342 				     initial_domain,
343 				     flags, ttm_bo_type_device, resv, &gobj);
344 	if (r) {
345 		if (r != -ERESTARTSYS) {
346 			if (flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) {
347 				flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
348 				goto retry;
349 			}
350 
351 			if (initial_domain == AMDGPU_GEM_DOMAIN_VRAM) {
352 				initial_domain |= AMDGPU_GEM_DOMAIN_GTT;
353 				goto retry;
354 			}
355 			DRM_DEBUG("Failed to allocate GEM object (%llu, %d, %llu, %d)\n",
356 				  size, initial_domain, args->in.alignment, r);
357 		}
358 		return r;
359 	}
360 
361 	if (flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID) {
362 		if (!r) {
363 			struct amdgpu_bo *abo = gem_to_amdgpu_bo(gobj);
364 
365 			abo->parent = amdgpu_bo_ref(vm->root.bo);
366 		}
367 		amdgpu_bo_unreserve(vm->root.bo);
368 	}
369 	if (r)
370 		return r;
371 
372 	r = drm_gem_handle_create(filp, gobj, &handle);
373 	/* drop reference from allocate - handle holds it now */
374 	drm_gem_object_put(gobj);
375 	if (r)
376 		return r;
377 
378 	memset(args, 0, sizeof(*args));
379 	args->out.handle = handle;
380 	return 0;
381 }
382 
383 int amdgpu_gem_userptr_ioctl(struct drm_device *dev, void *data,
384 			     struct drm_file *filp)
385 {
386 	struct ttm_operation_ctx ctx = { true, false };
387 	struct amdgpu_device *adev = drm_to_adev(dev);
388 	struct drm_amdgpu_gem_userptr *args = data;
389 	struct drm_gem_object *gobj;
390 	struct amdgpu_bo *bo;
391 	uint32_t handle;
392 	int r;
393 
394 	args->addr = untagged_addr(args->addr);
395 
396 	if (offset_in_page(args->addr | args->size))
397 		return -EINVAL;
398 
399 	/* reject unknown flag values */
400 	if (args->flags & ~(AMDGPU_GEM_USERPTR_READONLY |
401 	    AMDGPU_GEM_USERPTR_ANONONLY | AMDGPU_GEM_USERPTR_VALIDATE |
402 	    AMDGPU_GEM_USERPTR_REGISTER))
403 		return -EINVAL;
404 
405 	if (!(args->flags & AMDGPU_GEM_USERPTR_READONLY) &&
406 	     !(args->flags & AMDGPU_GEM_USERPTR_REGISTER)) {
407 
408 		/* if we want to write to it we must install a MMU notifier */
409 		return -EACCES;
410 	}
411 
412 	/* create a gem object to contain this object in */
413 	r = amdgpu_gem_object_create(adev, args->size, 0, AMDGPU_GEM_DOMAIN_CPU,
414 				     0, ttm_bo_type_device, NULL, &gobj);
415 	if (r)
416 		return r;
417 
418 	bo = gem_to_amdgpu_bo(gobj);
419 	bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
420 	bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
421 	r = amdgpu_ttm_tt_set_userptr(&bo->tbo, args->addr, args->flags);
422 	if (r)
423 		goto release_object;
424 
425 	if (args->flags & AMDGPU_GEM_USERPTR_REGISTER) {
426 		r = amdgpu_mn_register(bo, args->addr);
427 		if (r)
428 			goto release_object;
429 	}
430 
431 	if (args->flags & AMDGPU_GEM_USERPTR_VALIDATE) {
432 		r = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages);
433 		if (r)
434 			goto release_object;
435 
436 		r = amdgpu_bo_reserve(bo, true);
437 		if (r)
438 			goto user_pages_done;
439 
440 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
441 		r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
442 		amdgpu_bo_unreserve(bo);
443 		if (r)
444 			goto user_pages_done;
445 	}
446 
447 	r = drm_gem_handle_create(filp, gobj, &handle);
448 	if (r)
449 		goto user_pages_done;
450 
451 	args->handle = handle;
452 
453 user_pages_done:
454 	if (args->flags & AMDGPU_GEM_USERPTR_VALIDATE)
455 		amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm);
456 
457 release_object:
458 	drm_gem_object_put(gobj);
459 
460 	return r;
461 }
462 
463 int amdgpu_mode_dumb_mmap(struct drm_file *filp,
464 			  struct drm_device *dev,
465 			  uint32_t handle, uint64_t *offset_p)
466 {
467 	struct drm_gem_object *gobj;
468 	struct amdgpu_bo *robj;
469 
470 	gobj = drm_gem_object_lookup(filp, handle);
471 	if (gobj == NULL) {
472 		return -ENOENT;
473 	}
474 	robj = gem_to_amdgpu_bo(gobj);
475 	if (amdgpu_ttm_tt_get_usermm(robj->tbo.ttm) ||
476 	    (robj->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)) {
477 		drm_gem_object_put(gobj);
478 		return -EPERM;
479 	}
480 	*offset_p = amdgpu_bo_mmap_offset(robj);
481 	drm_gem_object_put(gobj);
482 	return 0;
483 }
484 
485 int amdgpu_gem_mmap_ioctl(struct drm_device *dev, void *data,
486 			  struct drm_file *filp)
487 {
488 	union drm_amdgpu_gem_mmap *args = data;
489 	uint32_t handle = args->in.handle;
490 	memset(args, 0, sizeof(*args));
491 	return amdgpu_mode_dumb_mmap(filp, dev, handle, &args->out.addr_ptr);
492 }
493 
494 /**
495  * amdgpu_gem_timeout - calculate jiffies timeout from absolute value
496  *
497  * @timeout_ns: timeout in ns
498  *
499  * Calculate the timeout in jiffies from an absolute timeout in ns.
500  */
501 unsigned long amdgpu_gem_timeout(uint64_t timeout_ns)
502 {
503 	unsigned long timeout_jiffies;
504 	ktime_t timeout;
505 
506 	/* clamp timeout if it's to large */
507 	if (((int64_t)timeout_ns) < 0)
508 		return MAX_SCHEDULE_TIMEOUT;
509 
510 	timeout = ktime_sub(ns_to_ktime(timeout_ns), ktime_get());
511 	if (ktime_to_ns(timeout) < 0)
512 		return 0;
513 
514 	timeout_jiffies = nsecs_to_jiffies(ktime_to_ns(timeout));
515 	/*  clamp timeout to avoid unsigned-> signed overflow */
516 	if (timeout_jiffies > MAX_SCHEDULE_TIMEOUT )
517 		return MAX_SCHEDULE_TIMEOUT - 1;
518 
519 	return timeout_jiffies;
520 }
521 
522 int amdgpu_gem_wait_idle_ioctl(struct drm_device *dev, void *data,
523 			      struct drm_file *filp)
524 {
525 	union drm_amdgpu_gem_wait_idle *args = data;
526 	struct drm_gem_object *gobj;
527 	struct amdgpu_bo *robj;
528 	uint32_t handle = args->in.handle;
529 	unsigned long timeout = amdgpu_gem_timeout(args->in.timeout);
530 	int r = 0;
531 	long ret;
532 
533 	gobj = drm_gem_object_lookup(filp, handle);
534 	if (gobj == NULL) {
535 		return -ENOENT;
536 	}
537 	robj = gem_to_amdgpu_bo(gobj);
538 	ret = dma_resv_wait_timeout(robj->tbo.base.resv, true, true, timeout);
539 
540 	/* ret == 0 means not signaled,
541 	 * ret > 0 means signaled
542 	 * ret < 0 means interrupted before timeout
543 	 */
544 	if (ret >= 0) {
545 		memset(args, 0, sizeof(*args));
546 		args->out.status = (ret == 0);
547 	} else
548 		r = ret;
549 
550 	drm_gem_object_put(gobj);
551 	return r;
552 }
553 
554 int amdgpu_gem_metadata_ioctl(struct drm_device *dev, void *data,
555 				struct drm_file *filp)
556 {
557 	struct drm_amdgpu_gem_metadata *args = data;
558 	struct drm_gem_object *gobj;
559 	struct amdgpu_bo *robj;
560 	int r = -1;
561 
562 	DRM_DEBUG("%d \n", args->handle);
563 	gobj = drm_gem_object_lookup(filp, args->handle);
564 	if (gobj == NULL)
565 		return -ENOENT;
566 	robj = gem_to_amdgpu_bo(gobj);
567 
568 	r = amdgpu_bo_reserve(robj, false);
569 	if (unlikely(r != 0))
570 		goto out;
571 
572 	if (args->op == AMDGPU_GEM_METADATA_OP_GET_METADATA) {
573 		amdgpu_bo_get_tiling_flags(robj, &args->data.tiling_info);
574 		r = amdgpu_bo_get_metadata(robj, args->data.data,
575 					   sizeof(args->data.data),
576 					   &args->data.data_size_bytes,
577 					   &args->data.flags);
578 	} else if (args->op == AMDGPU_GEM_METADATA_OP_SET_METADATA) {
579 		if (args->data.data_size_bytes > sizeof(args->data.data)) {
580 			r = -EINVAL;
581 			goto unreserve;
582 		}
583 		r = amdgpu_bo_set_tiling_flags(robj, args->data.tiling_info);
584 		if (!r)
585 			r = amdgpu_bo_set_metadata(robj, args->data.data,
586 						   args->data.data_size_bytes,
587 						   args->data.flags);
588 	}
589 
590 unreserve:
591 	amdgpu_bo_unreserve(robj);
592 out:
593 	drm_gem_object_put(gobj);
594 	return r;
595 }
596 
597 /**
598  * amdgpu_gem_va_update_vm -update the bo_va in its VM
599  *
600  * @adev: amdgpu_device pointer
601  * @vm: vm to update
602  * @bo_va: bo_va to update
603  * @operation: map, unmap or clear
604  *
605  * Update the bo_va directly after setting its address. Errors are not
606  * vital here, so they are not reported back to userspace.
607  */
608 static void amdgpu_gem_va_update_vm(struct amdgpu_device *adev,
609 				    struct amdgpu_vm *vm,
610 				    struct amdgpu_bo_va *bo_va,
611 				    uint32_t operation)
612 {
613 	int r;
614 
615 	if (!amdgpu_vm_ready(vm))
616 		return;
617 
618 	r = amdgpu_vm_clear_freed(adev, vm, NULL);
619 	if (r)
620 		goto error;
621 
622 	if (operation == AMDGPU_VA_OP_MAP ||
623 	    operation == AMDGPU_VA_OP_REPLACE) {
624 		r = amdgpu_vm_bo_update(adev, bo_va, false);
625 		if (r)
626 			goto error;
627 	}
628 
629 	r = amdgpu_vm_update_pdes(adev, vm, false);
630 
631 error:
632 	if (r && r != -ERESTARTSYS)
633 		DRM_ERROR("Couldn't update BO_VA (%d)\n", r);
634 }
635 
636 /**
637  * amdgpu_gem_va_map_flags - map GEM UAPI flags into hardware flags
638  *
639  * @adev: amdgpu_device pointer
640  * @flags: GEM UAPI flags
641  *
642  * Returns the GEM UAPI flags mapped into hardware for the ASIC.
643  */
644 uint64_t amdgpu_gem_va_map_flags(struct amdgpu_device *adev, uint32_t flags)
645 {
646 	uint64_t pte_flag = 0;
647 
648 	if (flags & AMDGPU_VM_PAGE_EXECUTABLE)
649 		pte_flag |= AMDGPU_PTE_EXECUTABLE;
650 	if (flags & AMDGPU_VM_PAGE_READABLE)
651 		pte_flag |= AMDGPU_PTE_READABLE;
652 	if (flags & AMDGPU_VM_PAGE_WRITEABLE)
653 		pte_flag |= AMDGPU_PTE_WRITEABLE;
654 	if (flags & AMDGPU_VM_PAGE_PRT)
655 		pte_flag |= AMDGPU_PTE_PRT;
656 
657 	if (adev->gmc.gmc_funcs->map_mtype)
658 		pte_flag |= amdgpu_gmc_map_mtype(adev,
659 						 flags & AMDGPU_VM_MTYPE_MASK);
660 
661 	return pte_flag;
662 }
663 
664 int amdgpu_gem_va_ioctl(struct drm_device *dev, void *data,
665 			  struct drm_file *filp)
666 {
667 	const uint32_t valid_flags = AMDGPU_VM_DELAY_UPDATE |
668 		AMDGPU_VM_PAGE_READABLE | AMDGPU_VM_PAGE_WRITEABLE |
669 		AMDGPU_VM_PAGE_EXECUTABLE | AMDGPU_VM_MTYPE_MASK;
670 	const uint32_t prt_flags = AMDGPU_VM_DELAY_UPDATE |
671 		AMDGPU_VM_PAGE_PRT;
672 
673 	struct drm_amdgpu_gem_va *args = data;
674 	struct drm_gem_object *gobj;
675 	struct amdgpu_device *adev = drm_to_adev(dev);
676 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
677 	struct amdgpu_bo *abo;
678 	struct amdgpu_bo_va *bo_va;
679 	struct amdgpu_bo_list_entry vm_pd;
680 	struct ttm_validate_buffer tv;
681 	struct ww_acquire_ctx ticket;
682 	struct list_head list, duplicates;
683 	uint64_t va_flags;
684 	uint64_t vm_size;
685 	int r = 0;
686 
687 	if (args->va_address < AMDGPU_VA_RESERVED_SIZE) {
688 		dev_dbg(dev->dev,
689 			"va_address 0x%LX is in reserved area 0x%LX\n",
690 			args->va_address, AMDGPU_VA_RESERVED_SIZE);
691 		return -EINVAL;
692 	}
693 
694 	if (args->va_address >= AMDGPU_GMC_HOLE_START &&
695 	    args->va_address < AMDGPU_GMC_HOLE_END) {
696 		dev_dbg(dev->dev,
697 			"va_address 0x%LX is in VA hole 0x%LX-0x%LX\n",
698 			args->va_address, AMDGPU_GMC_HOLE_START,
699 			AMDGPU_GMC_HOLE_END);
700 		return -EINVAL;
701 	}
702 
703 	args->va_address &= AMDGPU_GMC_HOLE_MASK;
704 
705 	vm_size = adev->vm_manager.max_pfn * AMDGPU_GPU_PAGE_SIZE;
706 	vm_size -= AMDGPU_VA_RESERVED_SIZE;
707 	if (args->va_address + args->map_size > vm_size) {
708 		dev_dbg(dev->dev,
709 			"va_address 0x%llx is in top reserved area 0x%llx\n",
710 			args->va_address + args->map_size, vm_size);
711 		return -EINVAL;
712 	}
713 
714 	if ((args->flags & ~valid_flags) && (args->flags & ~prt_flags)) {
715 		dev_dbg(dev->dev, "invalid flags combination 0x%08X\n",
716 			args->flags);
717 		return -EINVAL;
718 	}
719 
720 	switch (args->operation) {
721 	case AMDGPU_VA_OP_MAP:
722 	case AMDGPU_VA_OP_UNMAP:
723 	case AMDGPU_VA_OP_CLEAR:
724 	case AMDGPU_VA_OP_REPLACE:
725 		break;
726 	default:
727 		dev_dbg(dev->dev, "unsupported operation %d\n",
728 			args->operation);
729 		return -EINVAL;
730 	}
731 
732 	INIT_LIST_HEAD(&list);
733 	INIT_LIST_HEAD(&duplicates);
734 	if ((args->operation != AMDGPU_VA_OP_CLEAR) &&
735 	    !(args->flags & AMDGPU_VM_PAGE_PRT)) {
736 		gobj = drm_gem_object_lookup(filp, args->handle);
737 		if (gobj == NULL)
738 			return -ENOENT;
739 		abo = gem_to_amdgpu_bo(gobj);
740 		tv.bo = &abo->tbo;
741 		if (abo->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID)
742 			tv.num_shared = 1;
743 		else
744 			tv.num_shared = 0;
745 		list_add(&tv.head, &list);
746 	} else {
747 		gobj = NULL;
748 		abo = NULL;
749 	}
750 
751 	amdgpu_vm_get_pd_bo(&fpriv->vm, &list, &vm_pd);
752 
753 	r = ttm_eu_reserve_buffers(&ticket, &list, true, &duplicates);
754 	if (r)
755 		goto error_unref;
756 
757 	if (abo) {
758 		bo_va = amdgpu_vm_bo_find(&fpriv->vm, abo);
759 		if (!bo_va) {
760 			r = -ENOENT;
761 			goto error_backoff;
762 		}
763 	} else if (args->operation != AMDGPU_VA_OP_CLEAR) {
764 		bo_va = fpriv->prt_va;
765 	} else {
766 		bo_va = NULL;
767 	}
768 
769 	switch (args->operation) {
770 	case AMDGPU_VA_OP_MAP:
771 		va_flags = amdgpu_gem_va_map_flags(adev, args->flags);
772 		r = amdgpu_vm_bo_map(adev, bo_va, args->va_address,
773 				     args->offset_in_bo, args->map_size,
774 				     va_flags);
775 		break;
776 	case AMDGPU_VA_OP_UNMAP:
777 		r = amdgpu_vm_bo_unmap(adev, bo_va, args->va_address);
778 		break;
779 
780 	case AMDGPU_VA_OP_CLEAR:
781 		r = amdgpu_vm_bo_clear_mappings(adev, &fpriv->vm,
782 						args->va_address,
783 						args->map_size);
784 		break;
785 	case AMDGPU_VA_OP_REPLACE:
786 		va_flags = amdgpu_gem_va_map_flags(adev, args->flags);
787 		r = amdgpu_vm_bo_replace_map(adev, bo_va, args->va_address,
788 					     args->offset_in_bo, args->map_size,
789 					     va_flags);
790 		break;
791 	default:
792 		break;
793 	}
794 	if (!r && !(args->flags & AMDGPU_VM_DELAY_UPDATE) && !amdgpu_vm_debug)
795 		amdgpu_gem_va_update_vm(adev, &fpriv->vm, bo_va,
796 					args->operation);
797 
798 error_backoff:
799 	ttm_eu_backoff_reservation(&ticket, &list);
800 
801 error_unref:
802 	drm_gem_object_put(gobj);
803 	return r;
804 }
805 
806 int amdgpu_gem_op_ioctl(struct drm_device *dev, void *data,
807 			struct drm_file *filp)
808 {
809 	struct amdgpu_device *adev = drm_to_adev(dev);
810 	struct drm_amdgpu_gem_op *args = data;
811 	struct drm_gem_object *gobj;
812 	struct amdgpu_vm_bo_base *base;
813 	struct amdgpu_bo *robj;
814 	int r;
815 
816 	gobj = drm_gem_object_lookup(filp, args->handle);
817 	if (gobj == NULL) {
818 		return -ENOENT;
819 	}
820 	robj = gem_to_amdgpu_bo(gobj);
821 
822 	r = amdgpu_bo_reserve(robj, false);
823 	if (unlikely(r))
824 		goto out;
825 
826 	switch (args->op) {
827 	case AMDGPU_GEM_OP_GET_GEM_CREATE_INFO: {
828 		struct drm_amdgpu_gem_create_in info;
829 		void __user *out = u64_to_user_ptr(args->value);
830 
831 		info.bo_size = robj->tbo.base.size;
832 		info.alignment = robj->tbo.page_alignment << PAGE_SHIFT;
833 		info.domains = robj->preferred_domains;
834 		info.domain_flags = robj->flags;
835 		amdgpu_bo_unreserve(robj);
836 		if (copy_to_user(out, &info, sizeof(info)))
837 			r = -EFAULT;
838 		break;
839 	}
840 	case AMDGPU_GEM_OP_SET_PLACEMENT:
841 		if (robj->prime_shared_count && (args->value & AMDGPU_GEM_DOMAIN_VRAM)) {
842 			r = -EINVAL;
843 			amdgpu_bo_unreserve(robj);
844 			break;
845 		}
846 		if (amdgpu_ttm_tt_get_usermm(robj->tbo.ttm)) {
847 			r = -EPERM;
848 			amdgpu_bo_unreserve(robj);
849 			break;
850 		}
851 		for (base = robj->vm_bo; base; base = base->next)
852 			if (amdgpu_xgmi_same_hive(amdgpu_ttm_adev(robj->tbo.bdev),
853 				amdgpu_ttm_adev(base->vm->root.bo->tbo.bdev))) {
854 				r = -EINVAL;
855 				amdgpu_bo_unreserve(robj);
856 				goto out;
857 			}
858 
859 
860 		robj->preferred_domains = args->value & (AMDGPU_GEM_DOMAIN_VRAM |
861 							AMDGPU_GEM_DOMAIN_GTT |
862 							AMDGPU_GEM_DOMAIN_CPU);
863 		robj->allowed_domains = robj->preferred_domains;
864 		if (robj->allowed_domains == AMDGPU_GEM_DOMAIN_VRAM)
865 			robj->allowed_domains |= AMDGPU_GEM_DOMAIN_GTT;
866 
867 		if (robj->flags & AMDGPU_GEM_CREATE_VM_ALWAYS_VALID)
868 			amdgpu_vm_bo_invalidate(adev, robj, true);
869 
870 		amdgpu_bo_unreserve(robj);
871 		break;
872 	default:
873 		amdgpu_bo_unreserve(robj);
874 		r = -EINVAL;
875 	}
876 
877 out:
878 	drm_gem_object_put(gobj);
879 	return r;
880 }
881 
882 int amdgpu_mode_dumb_create(struct drm_file *file_priv,
883 			    struct drm_device *dev,
884 			    struct drm_mode_create_dumb *args)
885 {
886 	struct amdgpu_device *adev = drm_to_adev(dev);
887 	struct drm_gem_object *gobj;
888 	uint32_t handle;
889 	u64 flags = AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED |
890 		    AMDGPU_GEM_CREATE_CPU_GTT_USWC;
891 	u32 domain;
892 	int r;
893 
894 	/*
895 	 * The buffer returned from this function should be cleared, but
896 	 * it can only be done if the ring is enabled or we'll fail to
897 	 * create the buffer.
898 	 */
899 	if (adev->mman.buffer_funcs_enabled)
900 		flags |= AMDGPU_GEM_CREATE_VRAM_CLEARED;
901 
902 	args->pitch = amdgpu_align_pitch(adev, args->width,
903 					 DIV_ROUND_UP(args->bpp, 8), 0);
904 	args->size = (u64)args->pitch * args->height;
905 	args->size = ALIGN(args->size, PAGE_SIZE);
906 	domain = amdgpu_bo_get_preferred_pin_domain(adev,
907 				amdgpu_display_supported_domains(adev, flags));
908 	r = amdgpu_gem_object_create(adev, args->size, 0, domain, flags,
909 				     ttm_bo_type_device, NULL, &gobj);
910 	if (r)
911 		return -ENOMEM;
912 
913 	r = drm_gem_handle_create(file_priv, gobj, &handle);
914 	/* drop reference from allocate - handle holds it now */
915 	drm_gem_object_put(gobj);
916 	if (r) {
917 		return r;
918 	}
919 	args->handle = handle;
920 	return 0;
921 }
922 
923 #if defined(CONFIG_DEBUG_FS)
924 static int amdgpu_debugfs_gem_info_show(struct seq_file *m, void *unused)
925 {
926 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
927 	struct drm_device *dev = adev_to_drm(adev);
928 	struct drm_file *file;
929 	int r;
930 
931 	r = mutex_lock_interruptible(&dev->filelist_mutex);
932 	if (r)
933 		return r;
934 
935 	list_for_each_entry(file, &dev->filelist, lhead) {
936 		struct task_struct *task;
937 		struct drm_gem_object *gobj;
938 		int id;
939 
940 		/*
941 		 * Although we have a valid reference on file->pid, that does
942 		 * not guarantee that the task_struct who called get_pid() is
943 		 * still alive (e.g. get_pid(current) => fork() => exit()).
944 		 * Therefore, we need to protect this ->comm access using RCU.
945 		 */
946 		rcu_read_lock();
947 		task = pid_task(file->pid, PIDTYPE_PID);
948 		seq_printf(m, "pid %8d command %s:\n", pid_nr(file->pid),
949 			   task ? task->comm : "<unknown>");
950 		rcu_read_unlock();
951 
952 		spin_lock(&file->table_lock);
953 		idr_for_each_entry(&file->object_idr, gobj, id) {
954 			struct amdgpu_bo *bo = gem_to_amdgpu_bo(gobj);
955 
956 			amdgpu_bo_print_info(id, bo, m);
957 		}
958 		spin_unlock(&file->table_lock);
959 	}
960 
961 	mutex_unlock(&dev->filelist_mutex);
962 	return 0;
963 }
964 
965 DEFINE_SHOW_ATTRIBUTE(amdgpu_debugfs_gem_info);
966 
967 #endif
968 
969 void amdgpu_debugfs_gem_init(struct amdgpu_device *adev)
970 {
971 #if defined(CONFIG_DEBUG_FS)
972 	struct drm_minor *minor = adev_to_drm(adev)->primary;
973 	struct dentry *root = minor->debugfs_root;
974 
975 	debugfs_create_file("amdgpu_gem_info", 0444, root, adev,
976 			    &amdgpu_debugfs_gem_info_fops);
977 #endif
978 }
979