1 /*
2  * Copyright 2014-2018 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  */
22 #include <linux/dma-buf.h>
23 #include <linux/list.h>
24 #include <linux/pagemap.h>
25 #include <linux/sched/mm.h>
26 #include <linux/sched/task.h>
27 
28 #include "amdgpu_object.h"
29 #include "amdgpu_gem.h"
30 #include "amdgpu_vm.h"
31 #include "amdgpu_amdkfd.h"
32 #include "amdgpu_dma_buf.h"
33 #include <uapi/linux/kfd_ioctl.h>
34 #include "amdgpu_xgmi.h"
35 
36 /* Userptr restore delay, just long enough to allow consecutive VM
37  * changes to accumulate
38  */
39 #define AMDGPU_USERPTR_RESTORE_DELAY_MS 1
40 
41 /* Impose limit on how much memory KFD can use */
42 static struct {
43 	uint64_t max_system_mem_limit;
44 	uint64_t max_ttm_mem_limit;
45 	int64_t system_mem_used;
46 	int64_t ttm_mem_used;
47 	spinlock_t mem_limit_lock;
48 } kfd_mem_limit;
49 
50 static const char * const domain_bit_to_string[] = {
51 		"CPU",
52 		"GTT",
53 		"VRAM",
54 		"GDS",
55 		"GWS",
56 		"OA"
57 };
58 
59 #define domain_string(domain) domain_bit_to_string[ffs(domain)-1]
60 
61 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work);
62 
63 static bool kfd_mem_is_attached(struct amdgpu_vm *avm,
64 		struct kgd_mem *mem)
65 {
66 	struct kfd_mem_attachment *entry;
67 
68 	list_for_each_entry(entry, &mem->attachments, list)
69 		if (entry->bo_va->base.vm == avm)
70 			return true;
71 
72 	return false;
73 }
74 
75 /* Set memory usage limits. Current, limits are
76  *  System (TTM + userptr) memory - 15/16th System RAM
77  *  TTM memory - 3/8th System RAM
78  */
79 void amdgpu_amdkfd_gpuvm_init_mem_limits(void)
80 {
81 	struct sysinfo si;
82 	uint64_t mem;
83 
84 	si_meminfo(&si);
85 	mem = si.freeram - si.freehigh;
86 	mem *= si.mem_unit;
87 
88 	spin_lock_init(&kfd_mem_limit.mem_limit_lock);
89 	kfd_mem_limit.max_system_mem_limit = mem - (mem >> 4);
90 	kfd_mem_limit.max_ttm_mem_limit = (mem >> 1) - (mem >> 3);
91 	pr_debug("Kernel memory limit %lluM, TTM limit %lluM\n",
92 		(kfd_mem_limit.max_system_mem_limit >> 20),
93 		(kfd_mem_limit.max_ttm_mem_limit >> 20));
94 }
95 
96 void amdgpu_amdkfd_reserve_system_mem(uint64_t size)
97 {
98 	kfd_mem_limit.system_mem_used += size;
99 }
100 
101 /* Estimate page table size needed to represent a given memory size
102  *
103  * With 4KB pages, we need one 8 byte PTE for each 4KB of memory
104  * (factor 512, >> 9). With 2MB pages, we need one 8 byte PTE for 2MB
105  * of memory (factor 256K, >> 18). ROCm user mode tries to optimize
106  * for 2MB pages for TLB efficiency. However, small allocations and
107  * fragmented system memory still need some 4KB pages. We choose a
108  * compromise that should work in most cases without reserving too
109  * much memory for page tables unnecessarily (factor 16K, >> 14).
110  */
111 #define ESTIMATE_PT_SIZE(mem_size) ((mem_size) >> 14)
112 
113 static size_t amdgpu_amdkfd_acc_size(uint64_t size)
114 {
115 	size >>= PAGE_SHIFT;
116 	size *= sizeof(dma_addr_t) + sizeof(void *);
117 
118 	return __roundup_pow_of_two(sizeof(struct amdgpu_bo)) +
119 		__roundup_pow_of_two(sizeof(struct ttm_tt)) +
120 		PAGE_ALIGN(size);
121 }
122 
123 /**
124  * @amdgpu_amdkfd_reserve_mem_limit() - Decrease available memory by size
125  * of buffer including any reserved for control structures
126  *
127  * @adev: Device to which allocated BO belongs to
128  * @size: Size of buffer, in bytes, encapsulated by B0. This should be
129  * equivalent to amdgpu_bo_size(BO)
130  * @alloc_flag: Flag used in allocating a BO as noted above
131  *
132  * Return: returns -ENOMEM in case of error, ZERO otherwise
133  */
134 static int amdgpu_amdkfd_reserve_mem_limit(struct amdgpu_device *adev,
135 		uint64_t size, u32 alloc_flag)
136 {
137 	uint64_t reserved_for_pt =
138 		ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);
139 	size_t acc_size, system_mem_needed, ttm_mem_needed, vram_needed;
140 	int ret = 0;
141 
142 	acc_size = amdgpu_amdkfd_acc_size(size);
143 
144 	vram_needed = 0;
145 	if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
146 		system_mem_needed = acc_size + size;
147 		ttm_mem_needed = acc_size + size;
148 	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
149 		system_mem_needed = acc_size;
150 		ttm_mem_needed = acc_size;
151 		vram_needed = size;
152 	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
153 		system_mem_needed = acc_size + size;
154 		ttm_mem_needed = acc_size;
155 	} else if (alloc_flag &
156 		   (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
157 		    KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
158 		system_mem_needed = acc_size;
159 		ttm_mem_needed = acc_size;
160 	} else {
161 		pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
162 		return -ENOMEM;
163 	}
164 
165 	spin_lock(&kfd_mem_limit.mem_limit_lock);
166 
167 	if (kfd_mem_limit.system_mem_used + system_mem_needed >
168 	    kfd_mem_limit.max_system_mem_limit)
169 		pr_debug("Set no_system_mem_limit=1 if using shared memory\n");
170 
171 	if ((kfd_mem_limit.system_mem_used + system_mem_needed >
172 	     kfd_mem_limit.max_system_mem_limit && !no_system_mem_limit) ||
173 	    (kfd_mem_limit.ttm_mem_used + ttm_mem_needed >
174 	     kfd_mem_limit.max_ttm_mem_limit) ||
175 	    (adev->kfd.vram_used + vram_needed >
176 	     adev->gmc.real_vram_size - reserved_for_pt)) {
177 		ret = -ENOMEM;
178 		goto release;
179 	}
180 
181 	/* Update memory accounting by decreasing available system
182 	 * memory, TTM memory and GPU memory as computed above
183 	 */
184 	adev->kfd.vram_used += vram_needed;
185 	kfd_mem_limit.system_mem_used += system_mem_needed;
186 	kfd_mem_limit.ttm_mem_used += ttm_mem_needed;
187 
188 release:
189 	spin_unlock(&kfd_mem_limit.mem_limit_lock);
190 	return ret;
191 }
192 
193 static void unreserve_mem_limit(struct amdgpu_device *adev,
194 		uint64_t size, u32 alloc_flag)
195 {
196 	size_t acc_size;
197 
198 	acc_size = amdgpu_amdkfd_acc_size(size);
199 
200 	spin_lock(&kfd_mem_limit.mem_limit_lock);
201 
202 	if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
203 		kfd_mem_limit.system_mem_used -= (acc_size + size);
204 		kfd_mem_limit.ttm_mem_used -= (acc_size + size);
205 	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
206 		kfd_mem_limit.system_mem_used -= acc_size;
207 		kfd_mem_limit.ttm_mem_used -= acc_size;
208 		adev->kfd.vram_used -= size;
209 	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
210 		kfd_mem_limit.system_mem_used -= (acc_size + size);
211 		kfd_mem_limit.ttm_mem_used -= acc_size;
212 	} else if (alloc_flag &
213 		   (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
214 		    KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
215 		kfd_mem_limit.system_mem_used -= acc_size;
216 		kfd_mem_limit.ttm_mem_used -= acc_size;
217 	} else {
218 		pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
219 		goto release;
220 	}
221 
222 	WARN_ONCE(adev->kfd.vram_used < 0,
223 		  "KFD VRAM memory accounting unbalanced");
224 	WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0,
225 		  "KFD TTM memory accounting unbalanced");
226 	WARN_ONCE(kfd_mem_limit.system_mem_used < 0,
227 		  "KFD system memory accounting unbalanced");
228 
229 release:
230 	spin_unlock(&kfd_mem_limit.mem_limit_lock);
231 }
232 
233 void amdgpu_amdkfd_release_notify(struct amdgpu_bo *bo)
234 {
235 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
236 	u32 alloc_flags = bo->kfd_bo->alloc_flags;
237 	u64 size = amdgpu_bo_size(bo);
238 
239 	unreserve_mem_limit(adev, size, alloc_flags);
240 
241 	kfree(bo->kfd_bo);
242 }
243 
244 /* amdgpu_amdkfd_remove_eviction_fence - Removes eviction fence from BO's
245  *  reservation object.
246  *
247  * @bo: [IN] Remove eviction fence(s) from this BO
248  * @ef: [IN] This eviction fence is removed if it
249  *  is present in the shared list.
250  *
251  * NOTE: Must be called with BO reserved i.e. bo->tbo.resv->lock held.
252  */
253 static int amdgpu_amdkfd_remove_eviction_fence(struct amdgpu_bo *bo,
254 					struct amdgpu_amdkfd_fence *ef)
255 {
256 	struct dma_resv *resv = bo->tbo.base.resv;
257 	struct dma_resv_list *old, *new;
258 	unsigned int i, j, k;
259 
260 	if (!ef)
261 		return -EINVAL;
262 
263 	old = dma_resv_shared_list(resv);
264 	if (!old)
265 		return 0;
266 
267 	new = kmalloc(struct_size(new, shared, old->shared_max), GFP_KERNEL);
268 	if (!new)
269 		return -ENOMEM;
270 
271 	/* Go through all the shared fences in the resevation object and sort
272 	 * the interesting ones to the end of the list.
273 	 */
274 	for (i = 0, j = old->shared_count, k = 0; i < old->shared_count; ++i) {
275 		struct dma_fence *f;
276 
277 		f = rcu_dereference_protected(old->shared[i],
278 					      dma_resv_held(resv));
279 
280 		if (f->context == ef->base.context)
281 			RCU_INIT_POINTER(new->shared[--j], f);
282 		else
283 			RCU_INIT_POINTER(new->shared[k++], f);
284 	}
285 	new->shared_max = old->shared_max;
286 	new->shared_count = k;
287 
288 	/* Install the new fence list, seqcount provides the barriers */
289 	write_seqcount_begin(&resv->seq);
290 	RCU_INIT_POINTER(resv->fence, new);
291 	write_seqcount_end(&resv->seq);
292 
293 	/* Drop the references to the removed fences or move them to ef_list */
294 	for (i = j; i < old->shared_count; ++i) {
295 		struct dma_fence *f;
296 
297 		f = rcu_dereference_protected(new->shared[i],
298 					      dma_resv_held(resv));
299 		dma_fence_put(f);
300 	}
301 	kfree_rcu(old, rcu);
302 
303 	return 0;
304 }
305 
306 int amdgpu_amdkfd_remove_fence_on_pt_pd_bos(struct amdgpu_bo *bo)
307 {
308 	struct amdgpu_bo *root = bo;
309 	struct amdgpu_vm_bo_base *vm_bo;
310 	struct amdgpu_vm *vm;
311 	struct amdkfd_process_info *info;
312 	struct amdgpu_amdkfd_fence *ef;
313 	int ret;
314 
315 	/* we can always get vm_bo from root PD bo.*/
316 	while (root->parent)
317 		root = root->parent;
318 
319 	vm_bo = root->vm_bo;
320 	if (!vm_bo)
321 		return 0;
322 
323 	vm = vm_bo->vm;
324 	if (!vm)
325 		return 0;
326 
327 	info = vm->process_info;
328 	if (!info || !info->eviction_fence)
329 		return 0;
330 
331 	ef = container_of(dma_fence_get(&info->eviction_fence->base),
332 			struct amdgpu_amdkfd_fence, base);
333 
334 	BUG_ON(!dma_resv_trylock(bo->tbo.base.resv));
335 	ret = amdgpu_amdkfd_remove_eviction_fence(bo, ef);
336 	dma_resv_unlock(bo->tbo.base.resv);
337 
338 	dma_fence_put(&ef->base);
339 	return ret;
340 }
341 
342 static int amdgpu_amdkfd_bo_validate(struct amdgpu_bo *bo, uint32_t domain,
343 				     bool wait)
344 {
345 	struct ttm_operation_ctx ctx = { false, false };
346 	int ret;
347 
348 	if (WARN(amdgpu_ttm_tt_get_usermm(bo->tbo.ttm),
349 		 "Called with userptr BO"))
350 		return -EINVAL;
351 
352 	amdgpu_bo_placement_from_domain(bo, domain);
353 
354 	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
355 	if (ret)
356 		goto validate_fail;
357 	if (wait)
358 		amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
359 
360 validate_fail:
361 	return ret;
362 }
363 
364 static int amdgpu_amdkfd_validate_vm_bo(void *_unused, struct amdgpu_bo *bo)
365 {
366 	return amdgpu_amdkfd_bo_validate(bo, bo->allowed_domains, false);
367 }
368 
369 /* vm_validate_pt_pd_bos - Validate page table and directory BOs
370  *
371  * Page directories are not updated here because huge page handling
372  * during page table updates can invalidate page directory entries
373  * again. Page directories are only updated after updating page
374  * tables.
375  */
376 static int vm_validate_pt_pd_bos(struct amdgpu_vm *vm)
377 {
378 	struct amdgpu_bo *pd = vm->root.bo;
379 	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
380 	int ret;
381 
382 	ret = amdgpu_vm_validate_pt_bos(adev, vm, amdgpu_amdkfd_validate_vm_bo, NULL);
383 	if (ret) {
384 		pr_err("failed to validate PT BOs\n");
385 		return ret;
386 	}
387 
388 	ret = amdgpu_amdkfd_validate_vm_bo(NULL, pd);
389 	if (ret) {
390 		pr_err("failed to validate PD\n");
391 		return ret;
392 	}
393 
394 	vm->pd_phys_addr = amdgpu_gmc_pd_addr(vm->root.bo);
395 
396 	if (vm->use_cpu_for_update) {
397 		ret = amdgpu_bo_kmap(pd, NULL);
398 		if (ret) {
399 			pr_err("failed to kmap PD, ret=%d\n", ret);
400 			return ret;
401 		}
402 	}
403 
404 	return 0;
405 }
406 
407 static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync)
408 {
409 	struct amdgpu_bo *pd = vm->root.bo;
410 	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
411 	int ret;
412 
413 	ret = amdgpu_vm_update_pdes(adev, vm, false);
414 	if (ret)
415 		return ret;
416 
417 	return amdgpu_sync_fence(sync, vm->last_update);
418 }
419 
420 static uint64_t get_pte_flags(struct amdgpu_device *adev, struct kgd_mem *mem)
421 {
422 	struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);
423 	bool coherent = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_COHERENT;
424 	bool uncached = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED;
425 	uint32_t mapping_flags;
426 	uint64_t pte_flags;
427 	bool snoop = false;
428 
429 	mapping_flags = AMDGPU_VM_PAGE_READABLE;
430 	if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE)
431 		mapping_flags |= AMDGPU_VM_PAGE_WRITEABLE;
432 	if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE)
433 		mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE;
434 
435 	switch (adev->asic_type) {
436 	case CHIP_ARCTURUS:
437 		if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
438 			if (bo_adev == adev)
439 				mapping_flags |= coherent ?
440 					AMDGPU_VM_MTYPE_CC : AMDGPU_VM_MTYPE_RW;
441 			else
442 				mapping_flags |= coherent ?
443 					AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
444 		} else {
445 			mapping_flags |= coherent ?
446 				AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
447 		}
448 		break;
449 	case CHIP_ALDEBARAN:
450 		if (coherent && uncached) {
451 			if (adev->gmc.xgmi.connected_to_cpu ||
452 				!(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM))
453 				snoop = true;
454 			mapping_flags |= AMDGPU_VM_MTYPE_UC;
455 		} else if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
456 			if (bo_adev == adev) {
457 				mapping_flags |= coherent ?
458 					AMDGPU_VM_MTYPE_CC : AMDGPU_VM_MTYPE_RW;
459 				if (adev->gmc.xgmi.connected_to_cpu)
460 					snoop = true;
461 			} else {
462 				mapping_flags |= coherent ?
463 					AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
464 				if (amdgpu_xgmi_same_hive(adev, bo_adev))
465 					snoop = true;
466 			}
467 		} else {
468 			snoop = true;
469 			mapping_flags |= coherent ?
470 				AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
471 		}
472 		break;
473 	default:
474 		mapping_flags |= coherent ?
475 			AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
476 	}
477 
478 	pte_flags = amdgpu_gem_va_map_flags(adev, mapping_flags);
479 	pte_flags |= snoop ? AMDGPU_PTE_SNOOPED : 0;
480 
481 	return pte_flags;
482 }
483 
484 static int
485 kfd_mem_dmamap_userptr(struct kgd_mem *mem,
486 		       struct kfd_mem_attachment *attachment)
487 {
488 	enum dma_data_direction direction =
489 		mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
490 		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
491 	struct ttm_operation_ctx ctx = {.interruptible = true};
492 	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
493 	struct amdgpu_device *adev = attachment->adev;
494 	struct ttm_tt *src_ttm = mem->bo->tbo.ttm;
495 	struct ttm_tt *ttm = bo->tbo.ttm;
496 	int ret;
497 
498 	ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL);
499 	if (unlikely(!ttm->sg))
500 		return -ENOMEM;
501 
502 	if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
503 		return -EINVAL;
504 
505 	/* Same sequence as in amdgpu_ttm_tt_pin_userptr */
506 	ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages,
507 					ttm->num_pages, 0,
508 					(u64)ttm->num_pages << PAGE_SHIFT,
509 					GFP_KERNEL);
510 	if (unlikely(ret))
511 		goto free_sg;
512 
513 	ret = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
514 	if (unlikely(ret))
515 		goto release_sg;
516 
517 	drm_prime_sg_to_dma_addr_array(ttm->sg, ttm->dma_address,
518 				       ttm->num_pages);
519 
520 	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
521 	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
522 	if (ret)
523 		goto unmap_sg;
524 
525 	return 0;
526 
527 unmap_sg:
528 	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
529 release_sg:
530 	pr_err("DMA map userptr failed: %d\n", ret);
531 	sg_free_table(ttm->sg);
532 free_sg:
533 	kfree(ttm->sg);
534 	ttm->sg = NULL;
535 	return ret;
536 }
537 
538 static int
539 kfd_mem_dmamap_dmabuf(struct kfd_mem_attachment *attachment)
540 {
541 	struct ttm_operation_ctx ctx = {.interruptible = true};
542 	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
543 
544 	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
545 	return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
546 }
547 
548 static int
549 kfd_mem_dmamap_attachment(struct kgd_mem *mem,
550 			  struct kfd_mem_attachment *attachment)
551 {
552 	switch (attachment->type) {
553 	case KFD_MEM_ATT_SHARED:
554 		return 0;
555 	case KFD_MEM_ATT_USERPTR:
556 		return kfd_mem_dmamap_userptr(mem, attachment);
557 	case KFD_MEM_ATT_DMABUF:
558 		return kfd_mem_dmamap_dmabuf(attachment);
559 	default:
560 		WARN_ON_ONCE(1);
561 	}
562 	return -EINVAL;
563 }
564 
565 static void
566 kfd_mem_dmaunmap_userptr(struct kgd_mem *mem,
567 			 struct kfd_mem_attachment *attachment)
568 {
569 	enum dma_data_direction direction =
570 		mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
571 		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
572 	struct ttm_operation_ctx ctx = {.interruptible = false};
573 	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
574 	struct amdgpu_device *adev = attachment->adev;
575 	struct ttm_tt *ttm = bo->tbo.ttm;
576 
577 	if (unlikely(!ttm->sg))
578 		return;
579 
580 	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
581 	ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
582 
583 	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
584 	sg_free_table(ttm->sg);
585 	kfree(ttm->sg);
586 	ttm->sg = NULL;
587 }
588 
589 static void
590 kfd_mem_dmaunmap_dmabuf(struct kfd_mem_attachment *attachment)
591 {
592 	struct ttm_operation_ctx ctx = {.interruptible = true};
593 	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
594 
595 	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
596 	ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
597 }
598 
599 static void
600 kfd_mem_dmaunmap_attachment(struct kgd_mem *mem,
601 			    struct kfd_mem_attachment *attachment)
602 {
603 	switch (attachment->type) {
604 	case KFD_MEM_ATT_SHARED:
605 		break;
606 	case KFD_MEM_ATT_USERPTR:
607 		kfd_mem_dmaunmap_userptr(mem, attachment);
608 		break;
609 	case KFD_MEM_ATT_DMABUF:
610 		kfd_mem_dmaunmap_dmabuf(attachment);
611 		break;
612 	default:
613 		WARN_ON_ONCE(1);
614 	}
615 }
616 
617 static int
618 kfd_mem_attach_userptr(struct amdgpu_device *adev, struct kgd_mem *mem,
619 		       struct amdgpu_bo **bo)
620 {
621 	unsigned long bo_size = mem->bo->tbo.base.size;
622 	struct drm_gem_object *gobj;
623 	int ret;
624 
625 	ret = amdgpu_bo_reserve(mem->bo, false);
626 	if (ret)
627 		return ret;
628 
629 	ret = amdgpu_gem_object_create(adev, bo_size, 1,
630 				       AMDGPU_GEM_DOMAIN_CPU,
631 				       AMDGPU_GEM_CREATE_PREEMPTIBLE,
632 				       ttm_bo_type_sg, mem->bo->tbo.base.resv,
633 				       &gobj);
634 	amdgpu_bo_unreserve(mem->bo);
635 	if (ret)
636 		return ret;
637 
638 	*bo = gem_to_amdgpu_bo(gobj);
639 	(*bo)->parent = amdgpu_bo_ref(mem->bo);
640 
641 	return 0;
642 }
643 
644 static int
645 kfd_mem_attach_dmabuf(struct amdgpu_device *adev, struct kgd_mem *mem,
646 		      struct amdgpu_bo **bo)
647 {
648 	struct drm_gem_object *gobj;
649 	int ret;
650 
651 	if (!mem->dmabuf) {
652 		mem->dmabuf = amdgpu_gem_prime_export(&mem->bo->tbo.base,
653 			mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
654 				DRM_RDWR : 0);
655 		if (IS_ERR(mem->dmabuf)) {
656 			ret = PTR_ERR(mem->dmabuf);
657 			mem->dmabuf = NULL;
658 			return ret;
659 		}
660 	}
661 
662 	gobj = amdgpu_gem_prime_import(adev_to_drm(adev), mem->dmabuf);
663 	if (IS_ERR(gobj))
664 		return PTR_ERR(gobj);
665 
666 	*bo = gem_to_amdgpu_bo(gobj);
667 	(*bo)->flags |= AMDGPU_GEM_CREATE_PREEMPTIBLE;
668 	(*bo)->parent = amdgpu_bo_ref(mem->bo);
669 
670 	return 0;
671 }
672 
673 /* kfd_mem_attach - Add a BO to a VM
674  *
675  * Everything that needs to bo done only once when a BO is first added
676  * to a VM. It can later be mapped and unmapped many times without
677  * repeating these steps.
678  *
679  * 0. Create BO for DMA mapping, if needed
680  * 1. Allocate and initialize BO VA entry data structure
681  * 2. Add BO to the VM
682  * 3. Determine ASIC-specific PTE flags
683  * 4. Alloc page tables and directories if needed
684  * 4a.  Validate new page tables and directories
685  */
686 static int kfd_mem_attach(struct amdgpu_device *adev, struct kgd_mem *mem,
687 		struct amdgpu_vm *vm, bool is_aql)
688 {
689 	struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);
690 	unsigned long bo_size = mem->bo->tbo.base.size;
691 	uint64_t va = mem->va;
692 	struct kfd_mem_attachment *attachment[2] = {NULL, NULL};
693 	struct amdgpu_bo *bo[2] = {NULL, NULL};
694 	int i, ret;
695 
696 	if (!va) {
697 		pr_err("Invalid VA when adding BO to VM\n");
698 		return -EINVAL;
699 	}
700 
701 	for (i = 0; i <= is_aql; i++) {
702 		attachment[i] = kzalloc(sizeof(*attachment[i]), GFP_KERNEL);
703 		if (unlikely(!attachment[i])) {
704 			ret = -ENOMEM;
705 			goto unwind;
706 		}
707 
708 		pr_debug("\t add VA 0x%llx - 0x%llx to vm %p\n", va,
709 			 va + bo_size, vm);
710 
711 		if (adev == bo_adev || (mem->domain == AMDGPU_GEM_DOMAIN_VRAM &&
712 					amdgpu_xgmi_same_hive(adev, bo_adev))) {
713 			/* Mappings on the local GPU and VRAM mappings in the
714 			 * local hive share the original BO
715 			 */
716 			attachment[i]->type = KFD_MEM_ATT_SHARED;
717 			bo[i] = mem->bo;
718 			drm_gem_object_get(&bo[i]->tbo.base);
719 		} else if (i > 0) {
720 			/* Multiple mappings on the same GPU share the BO */
721 			attachment[i]->type = KFD_MEM_ATT_SHARED;
722 			bo[i] = bo[0];
723 			drm_gem_object_get(&bo[i]->tbo.base);
724 		} else if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {
725 			/* Create an SG BO to DMA-map userptrs on other GPUs */
726 			attachment[i]->type = KFD_MEM_ATT_USERPTR;
727 			ret = kfd_mem_attach_userptr(adev, mem, &bo[i]);
728 			if (ret)
729 				goto unwind;
730 		} else if (mem->domain == AMDGPU_GEM_DOMAIN_GTT &&
731 			   mem->bo->tbo.type != ttm_bo_type_sg) {
732 			/* GTT BOs use DMA-mapping ability of dynamic-attach
733 			 * DMA bufs. TODO: The same should work for VRAM on
734 			 * large-BAR GPUs.
735 			 */
736 			attachment[i]->type = KFD_MEM_ATT_DMABUF;
737 			ret = kfd_mem_attach_dmabuf(adev, mem, &bo[i]);
738 			if (ret)
739 				goto unwind;
740 		} else {
741 			/* FIXME: Need to DMA-map other BO types:
742 			 * large-BAR VRAM, doorbells, MMIO remap
743 			 */
744 			attachment[i]->type = KFD_MEM_ATT_SHARED;
745 			bo[i] = mem->bo;
746 			drm_gem_object_get(&bo[i]->tbo.base);
747 		}
748 
749 		/* Add BO to VM internal data structures */
750 		ret = amdgpu_bo_reserve(bo[i], false);
751 		if (ret) {
752 			pr_debug("Unable to reserve BO during memory attach");
753 			goto unwind;
754 		}
755 		attachment[i]->bo_va = amdgpu_vm_bo_add(adev, vm, bo[i]);
756 		amdgpu_bo_unreserve(bo[i]);
757 		if (unlikely(!attachment[i]->bo_va)) {
758 			ret = -ENOMEM;
759 			pr_err("Failed to add BO object to VM. ret == %d\n",
760 			       ret);
761 			goto unwind;
762 		}
763 		attachment[i]->va = va;
764 		attachment[i]->pte_flags = get_pte_flags(adev, mem);
765 		attachment[i]->adev = adev;
766 		list_add(&attachment[i]->list, &mem->attachments);
767 
768 		va += bo_size;
769 	}
770 
771 	return 0;
772 
773 unwind:
774 	for (; i >= 0; i--) {
775 		if (!attachment[i])
776 			continue;
777 		if (attachment[i]->bo_va) {
778 			amdgpu_bo_reserve(bo[i], true);
779 			amdgpu_vm_bo_rmv(adev, attachment[i]->bo_va);
780 			amdgpu_bo_unreserve(bo[i]);
781 			list_del(&attachment[i]->list);
782 		}
783 		if (bo[i])
784 			drm_gem_object_put(&bo[i]->tbo.base);
785 		kfree(attachment[i]);
786 	}
787 	return ret;
788 }
789 
790 static void kfd_mem_detach(struct kfd_mem_attachment *attachment)
791 {
792 	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
793 
794 	pr_debug("\t remove VA 0x%llx in entry %p\n",
795 			attachment->va, attachment);
796 	amdgpu_vm_bo_rmv(attachment->adev, attachment->bo_va);
797 	drm_gem_object_put(&bo->tbo.base);
798 	list_del(&attachment->list);
799 	kfree(attachment);
800 }
801 
802 static void add_kgd_mem_to_kfd_bo_list(struct kgd_mem *mem,
803 				struct amdkfd_process_info *process_info,
804 				bool userptr)
805 {
806 	struct ttm_validate_buffer *entry = &mem->validate_list;
807 	struct amdgpu_bo *bo = mem->bo;
808 
809 	INIT_LIST_HEAD(&entry->head);
810 	entry->num_shared = 1;
811 	entry->bo = &bo->tbo;
812 	mutex_lock(&process_info->lock);
813 	if (userptr)
814 		list_add_tail(&entry->head, &process_info->userptr_valid_list);
815 	else
816 		list_add_tail(&entry->head, &process_info->kfd_bo_list);
817 	mutex_unlock(&process_info->lock);
818 }
819 
820 static void remove_kgd_mem_from_kfd_bo_list(struct kgd_mem *mem,
821 		struct amdkfd_process_info *process_info)
822 {
823 	struct ttm_validate_buffer *bo_list_entry;
824 
825 	bo_list_entry = &mem->validate_list;
826 	mutex_lock(&process_info->lock);
827 	list_del(&bo_list_entry->head);
828 	mutex_unlock(&process_info->lock);
829 }
830 
831 /* Initializes user pages. It registers the MMU notifier and validates
832  * the userptr BO in the GTT domain.
833  *
834  * The BO must already be on the userptr_valid_list. Otherwise an
835  * eviction and restore may happen that leaves the new BO unmapped
836  * with the user mode queues running.
837  *
838  * Takes the process_info->lock to protect against concurrent restore
839  * workers.
840  *
841  * Returns 0 for success, negative errno for errors.
842  */
843 static int init_user_pages(struct kgd_mem *mem, uint64_t user_addr)
844 {
845 	struct amdkfd_process_info *process_info = mem->process_info;
846 	struct amdgpu_bo *bo = mem->bo;
847 	struct ttm_operation_ctx ctx = { true, false };
848 	int ret = 0;
849 
850 	mutex_lock(&process_info->lock);
851 
852 	ret = amdgpu_ttm_tt_set_userptr(&bo->tbo, user_addr, 0);
853 	if (ret) {
854 		pr_err("%s: Failed to set userptr: %d\n", __func__, ret);
855 		goto out;
856 	}
857 
858 	ret = amdgpu_mn_register(bo, user_addr);
859 	if (ret) {
860 		pr_err("%s: Failed to register MMU notifier: %d\n",
861 		       __func__, ret);
862 		goto out;
863 	}
864 
865 	ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages);
866 	if (ret) {
867 		pr_err("%s: Failed to get user pages: %d\n", __func__, ret);
868 		goto unregister_out;
869 	}
870 
871 	ret = amdgpu_bo_reserve(bo, true);
872 	if (ret) {
873 		pr_err("%s: Failed to reserve BO\n", __func__);
874 		goto release_out;
875 	}
876 	amdgpu_bo_placement_from_domain(bo, mem->domain);
877 	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
878 	if (ret)
879 		pr_err("%s: failed to validate BO\n", __func__);
880 	amdgpu_bo_unreserve(bo);
881 
882 release_out:
883 	amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm);
884 unregister_out:
885 	if (ret)
886 		amdgpu_mn_unregister(bo);
887 out:
888 	mutex_unlock(&process_info->lock);
889 	return ret;
890 }
891 
892 /* Reserving a BO and its page table BOs must happen atomically to
893  * avoid deadlocks. Some operations update multiple VMs at once. Track
894  * all the reservation info in a context structure. Optionally a sync
895  * object can track VM updates.
896  */
897 struct bo_vm_reservation_context {
898 	struct amdgpu_bo_list_entry kfd_bo; /* BO list entry for the KFD BO */
899 	unsigned int n_vms;		    /* Number of VMs reserved	    */
900 	struct amdgpu_bo_list_entry *vm_pd; /* Array of VM BO list entries  */
901 	struct ww_acquire_ctx ticket;	    /* Reservation ticket	    */
902 	struct list_head list, duplicates;  /* BO lists			    */
903 	struct amdgpu_sync *sync;	    /* Pointer to sync object	    */
904 	bool reserved;			    /* Whether BOs are reserved	    */
905 };
906 
907 enum bo_vm_match {
908 	BO_VM_NOT_MAPPED = 0,	/* Match VMs where a BO is not mapped */
909 	BO_VM_MAPPED,		/* Match VMs where a BO is mapped     */
910 	BO_VM_ALL,		/* Match all VMs a BO was added to    */
911 };
912 
913 /**
914  * reserve_bo_and_vm - reserve a BO and a VM unconditionally.
915  * @mem: KFD BO structure.
916  * @vm: the VM to reserve.
917  * @ctx: the struct that will be used in unreserve_bo_and_vms().
918  */
919 static int reserve_bo_and_vm(struct kgd_mem *mem,
920 			      struct amdgpu_vm *vm,
921 			      struct bo_vm_reservation_context *ctx)
922 {
923 	struct amdgpu_bo *bo = mem->bo;
924 	int ret;
925 
926 	WARN_ON(!vm);
927 
928 	ctx->reserved = false;
929 	ctx->n_vms = 1;
930 	ctx->sync = &mem->sync;
931 
932 	INIT_LIST_HEAD(&ctx->list);
933 	INIT_LIST_HEAD(&ctx->duplicates);
934 
935 	ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd), GFP_KERNEL);
936 	if (!ctx->vm_pd)
937 		return -ENOMEM;
938 
939 	ctx->kfd_bo.priority = 0;
940 	ctx->kfd_bo.tv.bo = &bo->tbo;
941 	ctx->kfd_bo.tv.num_shared = 1;
942 	list_add(&ctx->kfd_bo.tv.head, &ctx->list);
943 
944 	amdgpu_vm_get_pd_bo(vm, &ctx->list, &ctx->vm_pd[0]);
945 
946 	ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
947 				     false, &ctx->duplicates);
948 	if (ret) {
949 		pr_err("Failed to reserve buffers in ttm.\n");
950 		kfree(ctx->vm_pd);
951 		ctx->vm_pd = NULL;
952 		return ret;
953 	}
954 
955 	ctx->reserved = true;
956 	return 0;
957 }
958 
959 /**
960  * reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally
961  * @mem: KFD BO structure.
962  * @vm: the VM to reserve. If NULL, then all VMs associated with the BO
963  * is used. Otherwise, a single VM associated with the BO.
964  * @map_type: the mapping status that will be used to filter the VMs.
965  * @ctx: the struct that will be used in unreserve_bo_and_vms().
966  *
967  * Returns 0 for success, negative for failure.
968  */
969 static int reserve_bo_and_cond_vms(struct kgd_mem *mem,
970 				struct amdgpu_vm *vm, enum bo_vm_match map_type,
971 				struct bo_vm_reservation_context *ctx)
972 {
973 	struct amdgpu_bo *bo = mem->bo;
974 	struct kfd_mem_attachment *entry;
975 	unsigned int i;
976 	int ret;
977 
978 	ctx->reserved = false;
979 	ctx->n_vms = 0;
980 	ctx->vm_pd = NULL;
981 	ctx->sync = &mem->sync;
982 
983 	INIT_LIST_HEAD(&ctx->list);
984 	INIT_LIST_HEAD(&ctx->duplicates);
985 
986 	list_for_each_entry(entry, &mem->attachments, list) {
987 		if ((vm && vm != entry->bo_va->base.vm) ||
988 			(entry->is_mapped != map_type
989 			&& map_type != BO_VM_ALL))
990 			continue;
991 
992 		ctx->n_vms++;
993 	}
994 
995 	if (ctx->n_vms != 0) {
996 		ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd),
997 				     GFP_KERNEL);
998 		if (!ctx->vm_pd)
999 			return -ENOMEM;
1000 	}
1001 
1002 	ctx->kfd_bo.priority = 0;
1003 	ctx->kfd_bo.tv.bo = &bo->tbo;
1004 	ctx->kfd_bo.tv.num_shared = 1;
1005 	list_add(&ctx->kfd_bo.tv.head, &ctx->list);
1006 
1007 	i = 0;
1008 	list_for_each_entry(entry, &mem->attachments, list) {
1009 		if ((vm && vm != entry->bo_va->base.vm) ||
1010 			(entry->is_mapped != map_type
1011 			&& map_type != BO_VM_ALL))
1012 			continue;
1013 
1014 		amdgpu_vm_get_pd_bo(entry->bo_va->base.vm, &ctx->list,
1015 				&ctx->vm_pd[i]);
1016 		i++;
1017 	}
1018 
1019 	ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
1020 				     false, &ctx->duplicates);
1021 	if (ret) {
1022 		pr_err("Failed to reserve buffers in ttm.\n");
1023 		kfree(ctx->vm_pd);
1024 		ctx->vm_pd = NULL;
1025 		return ret;
1026 	}
1027 
1028 	ctx->reserved = true;
1029 	return 0;
1030 }
1031 
1032 /**
1033  * unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context
1034  * @ctx: Reservation context to unreserve
1035  * @wait: Optionally wait for a sync object representing pending VM updates
1036  * @intr: Whether the wait is interruptible
1037  *
1038  * Also frees any resources allocated in
1039  * reserve_bo_and_(cond_)vm(s). Returns the status from
1040  * amdgpu_sync_wait.
1041  */
1042 static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx,
1043 				 bool wait, bool intr)
1044 {
1045 	int ret = 0;
1046 
1047 	if (wait)
1048 		ret = amdgpu_sync_wait(ctx->sync, intr);
1049 
1050 	if (ctx->reserved)
1051 		ttm_eu_backoff_reservation(&ctx->ticket, &ctx->list);
1052 	kfree(ctx->vm_pd);
1053 
1054 	ctx->sync = NULL;
1055 
1056 	ctx->reserved = false;
1057 	ctx->vm_pd = NULL;
1058 
1059 	return ret;
1060 }
1061 
1062 static void unmap_bo_from_gpuvm(struct kgd_mem *mem,
1063 				struct kfd_mem_attachment *entry,
1064 				struct amdgpu_sync *sync)
1065 {
1066 	struct amdgpu_bo_va *bo_va = entry->bo_va;
1067 	struct amdgpu_device *adev = entry->adev;
1068 	struct amdgpu_vm *vm = bo_va->base.vm;
1069 
1070 	amdgpu_vm_bo_unmap(adev, bo_va, entry->va);
1071 
1072 	amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update);
1073 
1074 	amdgpu_sync_fence(sync, bo_va->last_pt_update);
1075 
1076 	kfd_mem_dmaunmap_attachment(mem, entry);
1077 }
1078 
1079 static int update_gpuvm_pte(struct kgd_mem *mem,
1080 			    struct kfd_mem_attachment *entry,
1081 			    struct amdgpu_sync *sync,
1082 			    bool *table_freed)
1083 {
1084 	struct amdgpu_bo_va *bo_va = entry->bo_va;
1085 	struct amdgpu_device *adev = entry->adev;
1086 	int ret;
1087 
1088 	ret = kfd_mem_dmamap_attachment(mem, entry);
1089 	if (ret)
1090 		return ret;
1091 
1092 	/* Update the page tables  */
1093 	ret = amdgpu_vm_bo_update(adev, bo_va, false, table_freed);
1094 	if (ret) {
1095 		pr_err("amdgpu_vm_bo_update failed\n");
1096 		return ret;
1097 	}
1098 
1099 	return amdgpu_sync_fence(sync, bo_va->last_pt_update);
1100 }
1101 
1102 static int map_bo_to_gpuvm(struct kgd_mem *mem,
1103 			   struct kfd_mem_attachment *entry,
1104 			   struct amdgpu_sync *sync,
1105 			   bool no_update_pte,
1106 			   bool *table_freed)
1107 {
1108 	int ret;
1109 
1110 	/* Set virtual address for the allocation */
1111 	ret = amdgpu_vm_bo_map(entry->adev, entry->bo_va, entry->va, 0,
1112 			       amdgpu_bo_size(entry->bo_va->base.bo),
1113 			       entry->pte_flags);
1114 	if (ret) {
1115 		pr_err("Failed to map VA 0x%llx in vm. ret %d\n",
1116 				entry->va, ret);
1117 		return ret;
1118 	}
1119 
1120 	if (no_update_pte)
1121 		return 0;
1122 
1123 	ret = update_gpuvm_pte(mem, entry, sync, table_freed);
1124 	if (ret) {
1125 		pr_err("update_gpuvm_pte() failed\n");
1126 		goto update_gpuvm_pte_failed;
1127 	}
1128 
1129 	return 0;
1130 
1131 update_gpuvm_pte_failed:
1132 	unmap_bo_from_gpuvm(mem, entry, sync);
1133 	return ret;
1134 }
1135 
1136 static struct sg_table *create_doorbell_sg(uint64_t addr, uint32_t size)
1137 {
1138 	struct sg_table *sg = kmalloc(sizeof(*sg), GFP_KERNEL);
1139 
1140 	if (!sg)
1141 		return NULL;
1142 	if (sg_alloc_table(sg, 1, GFP_KERNEL)) {
1143 		kfree(sg);
1144 		return NULL;
1145 	}
1146 	sg->sgl->dma_address = addr;
1147 	sg->sgl->length = size;
1148 #ifdef CONFIG_NEED_SG_DMA_LENGTH
1149 	sg->sgl->dma_length = size;
1150 #endif
1151 	return sg;
1152 }
1153 
1154 static int process_validate_vms(struct amdkfd_process_info *process_info)
1155 {
1156 	struct amdgpu_vm *peer_vm;
1157 	int ret;
1158 
1159 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
1160 			    vm_list_node) {
1161 		ret = vm_validate_pt_pd_bos(peer_vm);
1162 		if (ret)
1163 			return ret;
1164 	}
1165 
1166 	return 0;
1167 }
1168 
1169 static int process_sync_pds_resv(struct amdkfd_process_info *process_info,
1170 				 struct amdgpu_sync *sync)
1171 {
1172 	struct amdgpu_vm *peer_vm;
1173 	int ret;
1174 
1175 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
1176 			    vm_list_node) {
1177 		struct amdgpu_bo *pd = peer_vm->root.bo;
1178 
1179 		ret = amdgpu_sync_resv(NULL, sync, pd->tbo.base.resv,
1180 				       AMDGPU_SYNC_NE_OWNER,
1181 				       AMDGPU_FENCE_OWNER_KFD);
1182 		if (ret)
1183 			return ret;
1184 	}
1185 
1186 	return 0;
1187 }
1188 
1189 static int process_update_pds(struct amdkfd_process_info *process_info,
1190 			      struct amdgpu_sync *sync)
1191 {
1192 	struct amdgpu_vm *peer_vm;
1193 	int ret;
1194 
1195 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
1196 			    vm_list_node) {
1197 		ret = vm_update_pds(peer_vm, sync);
1198 		if (ret)
1199 			return ret;
1200 	}
1201 
1202 	return 0;
1203 }
1204 
1205 static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info,
1206 		       struct dma_fence **ef)
1207 {
1208 	struct amdkfd_process_info *info = NULL;
1209 	int ret;
1210 
1211 	if (!*process_info) {
1212 		info = kzalloc(sizeof(*info), GFP_KERNEL);
1213 		if (!info)
1214 			return -ENOMEM;
1215 
1216 		mutex_init(&info->lock);
1217 		INIT_LIST_HEAD(&info->vm_list_head);
1218 		INIT_LIST_HEAD(&info->kfd_bo_list);
1219 		INIT_LIST_HEAD(&info->userptr_valid_list);
1220 		INIT_LIST_HEAD(&info->userptr_inval_list);
1221 
1222 		info->eviction_fence =
1223 			amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),
1224 						   current->mm,
1225 						   NULL);
1226 		if (!info->eviction_fence) {
1227 			pr_err("Failed to create eviction fence\n");
1228 			ret = -ENOMEM;
1229 			goto create_evict_fence_fail;
1230 		}
1231 
1232 		info->pid = get_task_pid(current->group_leader, PIDTYPE_PID);
1233 		atomic_set(&info->evicted_bos, 0);
1234 		INIT_DELAYED_WORK(&info->restore_userptr_work,
1235 				  amdgpu_amdkfd_restore_userptr_worker);
1236 
1237 		*process_info = info;
1238 		*ef = dma_fence_get(&info->eviction_fence->base);
1239 	}
1240 
1241 	vm->process_info = *process_info;
1242 
1243 	/* Validate page directory and attach eviction fence */
1244 	ret = amdgpu_bo_reserve(vm->root.bo, true);
1245 	if (ret)
1246 		goto reserve_pd_fail;
1247 	ret = vm_validate_pt_pd_bos(vm);
1248 	if (ret) {
1249 		pr_err("validate_pt_pd_bos() failed\n");
1250 		goto validate_pd_fail;
1251 	}
1252 	ret = amdgpu_bo_sync_wait(vm->root.bo,
1253 				  AMDGPU_FENCE_OWNER_KFD, false);
1254 	if (ret)
1255 		goto wait_pd_fail;
1256 	ret = dma_resv_reserve_shared(vm->root.bo->tbo.base.resv, 1);
1257 	if (ret)
1258 		goto reserve_shared_fail;
1259 	amdgpu_bo_fence(vm->root.bo,
1260 			&vm->process_info->eviction_fence->base, true);
1261 	amdgpu_bo_unreserve(vm->root.bo);
1262 
1263 	/* Update process info */
1264 	mutex_lock(&vm->process_info->lock);
1265 	list_add_tail(&vm->vm_list_node,
1266 			&(vm->process_info->vm_list_head));
1267 	vm->process_info->n_vms++;
1268 	mutex_unlock(&vm->process_info->lock);
1269 
1270 	return 0;
1271 
1272 reserve_shared_fail:
1273 wait_pd_fail:
1274 validate_pd_fail:
1275 	amdgpu_bo_unreserve(vm->root.bo);
1276 reserve_pd_fail:
1277 	vm->process_info = NULL;
1278 	if (info) {
1279 		/* Two fence references: one in info and one in *ef */
1280 		dma_fence_put(&info->eviction_fence->base);
1281 		dma_fence_put(*ef);
1282 		*ef = NULL;
1283 		*process_info = NULL;
1284 		put_pid(info->pid);
1285 create_evict_fence_fail:
1286 		mutex_destroy(&info->lock);
1287 		kfree(info);
1288 	}
1289 	return ret;
1290 }
1291 
1292 /**
1293  * amdgpu_amdkfd_gpuvm_pin_bo() - Pins a BO using following criteria
1294  * @bo: Handle of buffer object being pinned
1295  * @domain: Domain into which BO should be pinned
1296  *
1297  *   - USERPTR BOs are UNPINNABLE and will return error
1298  *   - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
1299  *     PIN count incremented. It is valid to PIN a BO multiple times
1300  *
1301  * Return: ZERO if successful in pinning, Non-Zero in case of error.
1302  */
1303 static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain)
1304 {
1305 	int ret = 0;
1306 
1307 	ret = amdgpu_bo_reserve(bo, false);
1308 	if (unlikely(ret))
1309 		return ret;
1310 
1311 	ret = amdgpu_bo_pin_restricted(bo, domain, 0, 0);
1312 	if (ret)
1313 		pr_err("Error in Pinning BO to domain: %d\n", domain);
1314 
1315 	amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
1316 	amdgpu_bo_unreserve(bo);
1317 
1318 	return ret;
1319 }
1320 
1321 /**
1322  * amdgpu_amdkfd_gpuvm_unpin_bo() - Unpins BO using following criteria
1323  * @bo: Handle of buffer object being unpinned
1324  *
1325  *   - Is a illegal request for USERPTR BOs and is ignored
1326  *   - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
1327  *     PIN count decremented. Calls to UNPIN must balance calls to PIN
1328  */
1329 static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo)
1330 {
1331 	int ret = 0;
1332 
1333 	ret = amdgpu_bo_reserve(bo, false);
1334 	if (unlikely(ret))
1335 		return;
1336 
1337 	amdgpu_bo_unpin(bo);
1338 	amdgpu_bo_unreserve(bo);
1339 }
1340 
1341 int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct amdgpu_device *adev,
1342 					   struct file *filp, u32 pasid,
1343 					   void **process_info,
1344 					   struct dma_fence **ef)
1345 {
1346 	struct amdgpu_fpriv *drv_priv;
1347 	struct amdgpu_vm *avm;
1348 	int ret;
1349 
1350 	ret = amdgpu_file_to_fpriv(filp, &drv_priv);
1351 	if (ret)
1352 		return ret;
1353 	avm = &drv_priv->vm;
1354 
1355 	/* Already a compute VM? */
1356 	if (avm->process_info)
1357 		return -EINVAL;
1358 
1359 	/* Free the original amdgpu allocated pasid,
1360 	 * will be replaced with kfd allocated pasid.
1361 	 */
1362 	if (avm->pasid) {
1363 		amdgpu_pasid_free(avm->pasid);
1364 		amdgpu_vm_set_pasid(adev, avm, 0);
1365 	}
1366 
1367 	/* Convert VM into a compute VM */
1368 	ret = amdgpu_vm_make_compute(adev, avm);
1369 	if (ret)
1370 		return ret;
1371 
1372 	ret = amdgpu_vm_set_pasid(adev, avm, pasid);
1373 	if (ret)
1374 		return ret;
1375 	/* Initialize KFD part of the VM and process info */
1376 	ret = init_kfd_vm(avm, process_info, ef);
1377 	if (ret)
1378 		return ret;
1379 
1380 	amdgpu_vm_set_task_info(avm);
1381 
1382 	return 0;
1383 }
1384 
1385 void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,
1386 				    struct amdgpu_vm *vm)
1387 {
1388 	struct amdkfd_process_info *process_info = vm->process_info;
1389 	struct amdgpu_bo *pd = vm->root.bo;
1390 
1391 	if (!process_info)
1392 		return;
1393 
1394 	/* Release eviction fence from PD */
1395 	amdgpu_bo_reserve(pd, false);
1396 	amdgpu_bo_fence(pd, NULL, false);
1397 	amdgpu_bo_unreserve(pd);
1398 
1399 	/* Update process info */
1400 	mutex_lock(&process_info->lock);
1401 	process_info->n_vms--;
1402 	list_del(&vm->vm_list_node);
1403 	mutex_unlock(&process_info->lock);
1404 
1405 	vm->process_info = NULL;
1406 
1407 	/* Release per-process resources when last compute VM is destroyed */
1408 	if (!process_info->n_vms) {
1409 		WARN_ON(!list_empty(&process_info->kfd_bo_list));
1410 		WARN_ON(!list_empty(&process_info->userptr_valid_list));
1411 		WARN_ON(!list_empty(&process_info->userptr_inval_list));
1412 
1413 		dma_fence_put(&process_info->eviction_fence->base);
1414 		cancel_delayed_work_sync(&process_info->restore_userptr_work);
1415 		put_pid(process_info->pid);
1416 		mutex_destroy(&process_info->lock);
1417 		kfree(process_info);
1418 	}
1419 }
1420 
1421 void amdgpu_amdkfd_gpuvm_release_process_vm(struct amdgpu_device *adev,
1422 					    void *drm_priv)
1423 {
1424 	struct amdgpu_vm *avm;
1425 
1426 	if (WARN_ON(!adev || !drm_priv))
1427 		return;
1428 
1429 	avm = drm_priv_to_vm(drm_priv);
1430 
1431 	pr_debug("Releasing process vm %p\n", avm);
1432 
1433 	/* The original pasid of amdgpu vm has already been
1434 	 * released during making a amdgpu vm to a compute vm
1435 	 * The current pasid is managed by kfd and will be
1436 	 * released on kfd process destroy. Set amdgpu pasid
1437 	 * to 0 to avoid duplicate release.
1438 	 */
1439 	amdgpu_vm_release_compute(adev, avm);
1440 }
1441 
1442 uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)
1443 {
1444 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1445 	struct amdgpu_bo *pd = avm->root.bo;
1446 	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
1447 
1448 	if (adev->asic_type < CHIP_VEGA10)
1449 		return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT;
1450 	return avm->pd_phys_addr;
1451 }
1452 
1453 int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(
1454 		struct amdgpu_device *adev, uint64_t va, uint64_t size,
1455 		void *drm_priv, struct kgd_mem **mem,
1456 		uint64_t *offset, uint32_t flags)
1457 {
1458 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1459 	enum ttm_bo_type bo_type = ttm_bo_type_device;
1460 	struct sg_table *sg = NULL;
1461 	uint64_t user_addr = 0;
1462 	struct amdgpu_bo *bo;
1463 	struct drm_gem_object *gobj = NULL;
1464 	u32 domain, alloc_domain;
1465 	u64 alloc_flags;
1466 	int ret;
1467 
1468 	/*
1469 	 * Check on which domain to allocate BO
1470 	 */
1471 	if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
1472 		domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;
1473 		alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;
1474 		alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ?
1475 			AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0;
1476 	} else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
1477 		domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
1478 		alloc_flags = 0;
1479 	} else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
1480 		domain = AMDGPU_GEM_DOMAIN_GTT;
1481 		alloc_domain = AMDGPU_GEM_DOMAIN_CPU;
1482 		alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE;
1483 		if (!offset || !*offset)
1484 			return -EINVAL;
1485 		user_addr = untagged_addr(*offset);
1486 	} else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1487 			KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1488 		domain = AMDGPU_GEM_DOMAIN_GTT;
1489 		alloc_domain = AMDGPU_GEM_DOMAIN_CPU;
1490 		bo_type = ttm_bo_type_sg;
1491 		alloc_flags = 0;
1492 		if (size > UINT_MAX)
1493 			return -EINVAL;
1494 		sg = create_doorbell_sg(*offset, size);
1495 		if (!sg)
1496 			return -ENOMEM;
1497 	} else {
1498 		return -EINVAL;
1499 	}
1500 
1501 	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
1502 	if (!*mem) {
1503 		ret = -ENOMEM;
1504 		goto err;
1505 	}
1506 	INIT_LIST_HEAD(&(*mem)->attachments);
1507 	mutex_init(&(*mem)->lock);
1508 	(*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);
1509 
1510 	/* Workaround for AQL queue wraparound bug. Map the same
1511 	 * memory twice. That means we only actually allocate half
1512 	 * the memory.
1513 	 */
1514 	if ((*mem)->aql_queue)
1515 		size = size >> 1;
1516 
1517 	(*mem)->alloc_flags = flags;
1518 
1519 	amdgpu_sync_create(&(*mem)->sync);
1520 
1521 	ret = amdgpu_amdkfd_reserve_mem_limit(adev, size, flags);
1522 	if (ret) {
1523 		pr_debug("Insufficient memory\n");
1524 		goto err_reserve_limit;
1525 	}
1526 
1527 	pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s\n",
1528 			va, size, domain_string(alloc_domain));
1529 
1530 	ret = amdgpu_gem_object_create(adev, size, 1, alloc_domain, alloc_flags,
1531 				       bo_type, NULL, &gobj);
1532 	if (ret) {
1533 		pr_debug("Failed to create BO on domain %s. ret %d\n",
1534 			 domain_string(alloc_domain), ret);
1535 		goto err_bo_create;
1536 	}
1537 	ret = drm_vma_node_allow(&gobj->vma_node, drm_priv);
1538 	if (ret) {
1539 		pr_debug("Failed to allow vma node access. ret %d\n", ret);
1540 		goto err_node_allow;
1541 	}
1542 	bo = gem_to_amdgpu_bo(gobj);
1543 	if (bo_type == ttm_bo_type_sg) {
1544 		bo->tbo.sg = sg;
1545 		bo->tbo.ttm->sg = sg;
1546 	}
1547 	bo->kfd_bo = *mem;
1548 	(*mem)->bo = bo;
1549 	if (user_addr)
1550 		bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO;
1551 
1552 	(*mem)->va = va;
1553 	(*mem)->domain = domain;
1554 	(*mem)->mapped_to_gpu_memory = 0;
1555 	(*mem)->process_info = avm->process_info;
1556 	add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);
1557 
1558 	if (user_addr) {
1559 		ret = init_user_pages(*mem, user_addr);
1560 		if (ret)
1561 			goto allocate_init_user_pages_failed;
1562 	} else  if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1563 				KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1564 		ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT);
1565 		if (ret) {
1566 			pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n");
1567 			goto err_pin_bo;
1568 		}
1569 		bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
1570 		bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
1571 	}
1572 
1573 	if (offset)
1574 		*offset = amdgpu_bo_mmap_offset(bo);
1575 
1576 	return 0;
1577 
1578 allocate_init_user_pages_failed:
1579 err_pin_bo:
1580 	remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);
1581 	drm_vma_node_revoke(&gobj->vma_node, drm_priv);
1582 err_node_allow:
1583 	/* Don't unreserve system mem limit twice */
1584 	goto err_reserve_limit;
1585 err_bo_create:
1586 	unreserve_mem_limit(adev, size, flags);
1587 err_reserve_limit:
1588 	mutex_destroy(&(*mem)->lock);
1589 	if (gobj)
1590 		drm_gem_object_put(gobj);
1591 	else
1592 		kfree(*mem);
1593 err:
1594 	if (sg) {
1595 		sg_free_table(sg);
1596 		kfree(sg);
1597 	}
1598 	return ret;
1599 }
1600 
1601 int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(
1602 		struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv,
1603 		uint64_t *size)
1604 {
1605 	struct amdkfd_process_info *process_info = mem->process_info;
1606 	unsigned long bo_size = mem->bo->tbo.base.size;
1607 	struct kfd_mem_attachment *entry, *tmp;
1608 	struct bo_vm_reservation_context ctx;
1609 	struct ttm_validate_buffer *bo_list_entry;
1610 	unsigned int mapped_to_gpu_memory;
1611 	int ret;
1612 	bool is_imported = false;
1613 
1614 	mutex_lock(&mem->lock);
1615 
1616 	/* Unpin MMIO/DOORBELL BO's that were pinnned during allocation */
1617 	if (mem->alloc_flags &
1618 	    (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1619 	     KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1620 		amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo);
1621 	}
1622 
1623 	mapped_to_gpu_memory = mem->mapped_to_gpu_memory;
1624 	is_imported = mem->is_imported;
1625 	mutex_unlock(&mem->lock);
1626 	/* lock is not needed after this, since mem is unused and will
1627 	 * be freed anyway
1628 	 */
1629 
1630 	if (mapped_to_gpu_memory > 0) {
1631 		pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",
1632 				mem->va, bo_size);
1633 		return -EBUSY;
1634 	}
1635 
1636 	/* Make sure restore workers don't access the BO any more */
1637 	bo_list_entry = &mem->validate_list;
1638 	mutex_lock(&process_info->lock);
1639 	list_del(&bo_list_entry->head);
1640 	mutex_unlock(&process_info->lock);
1641 
1642 	/* No more MMU notifiers */
1643 	amdgpu_mn_unregister(mem->bo);
1644 
1645 	ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);
1646 	if (unlikely(ret))
1647 		return ret;
1648 
1649 	/* The eviction fence should be removed by the last unmap.
1650 	 * TODO: Log an error condition if the bo still has the eviction fence
1651 	 * attached
1652 	 */
1653 	amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1654 					process_info->eviction_fence);
1655 	pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,
1656 		mem->va + bo_size * (1 + mem->aql_queue));
1657 
1658 	/* Remove from VM internal data structures */
1659 	list_for_each_entry_safe(entry, tmp, &mem->attachments, list)
1660 		kfd_mem_detach(entry);
1661 
1662 	ret = unreserve_bo_and_vms(&ctx, false, false);
1663 
1664 	/* Free the sync object */
1665 	amdgpu_sync_free(&mem->sync);
1666 
1667 	/* If the SG is not NULL, it's one we created for a doorbell or mmio
1668 	 * remap BO. We need to free it.
1669 	 */
1670 	if (mem->bo->tbo.sg) {
1671 		sg_free_table(mem->bo->tbo.sg);
1672 		kfree(mem->bo->tbo.sg);
1673 	}
1674 
1675 	/* Update the size of the BO being freed if it was allocated from
1676 	 * VRAM and is not imported.
1677 	 */
1678 	if (size) {
1679 		if ((mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_VRAM) &&
1680 		    (!is_imported))
1681 			*size = bo_size;
1682 		else
1683 			*size = 0;
1684 	}
1685 
1686 	/* Free the BO*/
1687 	drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv);
1688 	if (mem->dmabuf)
1689 		dma_buf_put(mem->dmabuf);
1690 	mutex_destroy(&mem->lock);
1691 
1692 	/* If this releases the last reference, it will end up calling
1693 	 * amdgpu_amdkfd_release_notify and kfree the mem struct. That's why
1694 	 * this needs to be the last call here.
1695 	 */
1696 	drm_gem_object_put(&mem->bo->tbo.base);
1697 
1698 	return ret;
1699 }
1700 
1701 int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1702 		struct amdgpu_device *adev, struct kgd_mem *mem,
1703 		void *drm_priv, bool *table_freed)
1704 {
1705 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1706 	int ret;
1707 	struct amdgpu_bo *bo;
1708 	uint32_t domain;
1709 	struct kfd_mem_attachment *entry;
1710 	struct bo_vm_reservation_context ctx;
1711 	unsigned long bo_size;
1712 	bool is_invalid_userptr = false;
1713 
1714 	bo = mem->bo;
1715 	if (!bo) {
1716 		pr_err("Invalid BO when mapping memory to GPU\n");
1717 		return -EINVAL;
1718 	}
1719 
1720 	/* Make sure restore is not running concurrently. Since we
1721 	 * don't map invalid userptr BOs, we rely on the next restore
1722 	 * worker to do the mapping
1723 	 */
1724 	mutex_lock(&mem->process_info->lock);
1725 
1726 	/* Lock mmap-sem. If we find an invalid userptr BO, we can be
1727 	 * sure that the MMU notifier is no longer running
1728 	 * concurrently and the queues are actually stopped
1729 	 */
1730 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1731 		mmap_write_lock(current->mm);
1732 		is_invalid_userptr = atomic_read(&mem->invalid);
1733 		mmap_write_unlock(current->mm);
1734 	}
1735 
1736 	mutex_lock(&mem->lock);
1737 
1738 	domain = mem->domain;
1739 	bo_size = bo->tbo.base.size;
1740 
1741 	pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",
1742 			mem->va,
1743 			mem->va + bo_size * (1 + mem->aql_queue),
1744 			avm, domain_string(domain));
1745 
1746 	if (!kfd_mem_is_attached(avm, mem)) {
1747 		ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue);
1748 		if (ret)
1749 			goto out;
1750 	}
1751 
1752 	ret = reserve_bo_and_vm(mem, avm, &ctx);
1753 	if (unlikely(ret))
1754 		goto out;
1755 
1756 	/* Userptr can be marked as "not invalid", but not actually be
1757 	 * validated yet (still in the system domain). In that case
1758 	 * the queues are still stopped and we can leave mapping for
1759 	 * the next restore worker
1760 	 */
1761 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&
1762 	    bo->tbo.resource->mem_type == TTM_PL_SYSTEM)
1763 		is_invalid_userptr = true;
1764 
1765 	ret = vm_validate_pt_pd_bos(avm);
1766 	if (unlikely(ret))
1767 		goto out_unreserve;
1768 
1769 	if (mem->mapped_to_gpu_memory == 0 &&
1770 	    !amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1771 		/* Validate BO only once. The eviction fence gets added to BO
1772 		 * the first time it is mapped. Validate will wait for all
1773 		 * background evictions to complete.
1774 		 */
1775 		ret = amdgpu_amdkfd_bo_validate(bo, domain, true);
1776 		if (ret) {
1777 			pr_debug("Validate failed\n");
1778 			goto out_unreserve;
1779 		}
1780 	}
1781 
1782 	list_for_each_entry(entry, &mem->attachments, list) {
1783 		if (entry->bo_va->base.vm != avm || entry->is_mapped)
1784 			continue;
1785 
1786 		pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",
1787 			 entry->va, entry->va + bo_size, entry);
1788 
1789 		ret = map_bo_to_gpuvm(mem, entry, ctx.sync,
1790 				      is_invalid_userptr, table_freed);
1791 		if (ret) {
1792 			pr_err("Failed to map bo to gpuvm\n");
1793 			goto out_unreserve;
1794 		}
1795 
1796 		ret = vm_update_pds(avm, ctx.sync);
1797 		if (ret) {
1798 			pr_err("Failed to update page directories\n");
1799 			goto out_unreserve;
1800 		}
1801 
1802 		entry->is_mapped = true;
1803 		mem->mapped_to_gpu_memory++;
1804 		pr_debug("\t INC mapping count %d\n",
1805 			 mem->mapped_to_gpu_memory);
1806 	}
1807 
1808 	if (!amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) && !bo->tbo.pin_count)
1809 		amdgpu_bo_fence(bo,
1810 				&avm->process_info->eviction_fence->base,
1811 				true);
1812 	ret = unreserve_bo_and_vms(&ctx, false, false);
1813 
1814 	/* Only apply no TLB flush on Aldebaran to
1815 	 * workaround regressions on other Asics.
1816 	 */
1817 	if (table_freed && (adev->asic_type != CHIP_ALDEBARAN))
1818 		*table_freed = true;
1819 
1820 	goto out;
1821 
1822 out_unreserve:
1823 	unreserve_bo_and_vms(&ctx, false, false);
1824 out:
1825 	mutex_unlock(&mem->process_info->lock);
1826 	mutex_unlock(&mem->lock);
1827 	return ret;
1828 }
1829 
1830 int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
1831 		struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv)
1832 {
1833 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1834 	struct amdkfd_process_info *process_info = avm->process_info;
1835 	unsigned long bo_size = mem->bo->tbo.base.size;
1836 	struct kfd_mem_attachment *entry;
1837 	struct bo_vm_reservation_context ctx;
1838 	int ret;
1839 
1840 	mutex_lock(&mem->lock);
1841 
1842 	ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx);
1843 	if (unlikely(ret))
1844 		goto out;
1845 	/* If no VMs were reserved, it means the BO wasn't actually mapped */
1846 	if (ctx.n_vms == 0) {
1847 		ret = -EINVAL;
1848 		goto unreserve_out;
1849 	}
1850 
1851 	ret = vm_validate_pt_pd_bos(avm);
1852 	if (unlikely(ret))
1853 		goto unreserve_out;
1854 
1855 	pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",
1856 		mem->va,
1857 		mem->va + bo_size * (1 + mem->aql_queue),
1858 		avm);
1859 
1860 	list_for_each_entry(entry, &mem->attachments, list) {
1861 		if (entry->bo_va->base.vm != avm || !entry->is_mapped)
1862 			continue;
1863 
1864 		pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",
1865 			 entry->va, entry->va + bo_size, entry);
1866 
1867 		unmap_bo_from_gpuvm(mem, entry, ctx.sync);
1868 		entry->is_mapped = false;
1869 
1870 		mem->mapped_to_gpu_memory--;
1871 		pr_debug("\t DEC mapping count %d\n",
1872 			 mem->mapped_to_gpu_memory);
1873 	}
1874 
1875 	/* If BO is unmapped from all VMs, unfence it. It can be evicted if
1876 	 * required.
1877 	 */
1878 	if (mem->mapped_to_gpu_memory == 0 &&
1879 	    !amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) &&
1880 	    !mem->bo->tbo.pin_count)
1881 		amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1882 						process_info->eviction_fence);
1883 
1884 unreserve_out:
1885 	unreserve_bo_and_vms(&ctx, false, false);
1886 out:
1887 	mutex_unlock(&mem->lock);
1888 	return ret;
1889 }
1890 
1891 int amdgpu_amdkfd_gpuvm_sync_memory(
1892 		struct amdgpu_device *adev, struct kgd_mem *mem, bool intr)
1893 {
1894 	struct amdgpu_sync sync;
1895 	int ret;
1896 
1897 	amdgpu_sync_create(&sync);
1898 
1899 	mutex_lock(&mem->lock);
1900 	amdgpu_sync_clone(&mem->sync, &sync);
1901 	mutex_unlock(&mem->lock);
1902 
1903 	ret = amdgpu_sync_wait(&sync, intr);
1904 	amdgpu_sync_free(&sync);
1905 	return ret;
1906 }
1907 
1908 int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct amdgpu_device *adev,
1909 		struct kgd_mem *mem, void **kptr, uint64_t *size)
1910 {
1911 	int ret;
1912 	struct amdgpu_bo *bo = mem->bo;
1913 
1914 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1915 		pr_err("userptr can't be mapped to kernel\n");
1916 		return -EINVAL;
1917 	}
1918 
1919 	/* delete kgd_mem from kfd_bo_list to avoid re-validating
1920 	 * this BO in BO's restoring after eviction.
1921 	 */
1922 	mutex_lock(&mem->process_info->lock);
1923 
1924 	ret = amdgpu_bo_reserve(bo, true);
1925 	if (ret) {
1926 		pr_err("Failed to reserve bo. ret %d\n", ret);
1927 		goto bo_reserve_failed;
1928 	}
1929 
1930 	ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
1931 	if (ret) {
1932 		pr_err("Failed to pin bo. ret %d\n", ret);
1933 		goto pin_failed;
1934 	}
1935 
1936 	ret = amdgpu_bo_kmap(bo, kptr);
1937 	if (ret) {
1938 		pr_err("Failed to map bo to kernel. ret %d\n", ret);
1939 		goto kmap_failed;
1940 	}
1941 
1942 	amdgpu_amdkfd_remove_eviction_fence(
1943 		bo, mem->process_info->eviction_fence);
1944 	list_del_init(&mem->validate_list.head);
1945 
1946 	if (size)
1947 		*size = amdgpu_bo_size(bo);
1948 
1949 	amdgpu_bo_unreserve(bo);
1950 
1951 	mutex_unlock(&mem->process_info->lock);
1952 	return 0;
1953 
1954 kmap_failed:
1955 	amdgpu_bo_unpin(bo);
1956 pin_failed:
1957 	amdgpu_bo_unreserve(bo);
1958 bo_reserve_failed:
1959 	mutex_unlock(&mem->process_info->lock);
1960 
1961 	return ret;
1962 }
1963 
1964 void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct amdgpu_device *adev,
1965 						  struct kgd_mem *mem)
1966 {
1967 	struct amdgpu_bo *bo = mem->bo;
1968 
1969 	amdgpu_bo_reserve(bo, true);
1970 	amdgpu_bo_kunmap(bo);
1971 	amdgpu_bo_unpin(bo);
1972 	amdgpu_bo_unreserve(bo);
1973 }
1974 
1975 int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev,
1976 					  struct kfd_vm_fault_info *mem)
1977 {
1978 	if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) {
1979 		*mem = *adev->gmc.vm_fault_info;
1980 		mb();
1981 		atomic_set(&adev->gmc.vm_fault_info_updated, 0);
1982 	}
1983 	return 0;
1984 }
1985 
1986 int amdgpu_amdkfd_gpuvm_import_dmabuf(struct amdgpu_device *adev,
1987 				      struct dma_buf *dma_buf,
1988 				      uint64_t va, void *drm_priv,
1989 				      struct kgd_mem **mem, uint64_t *size,
1990 				      uint64_t *mmap_offset)
1991 {
1992 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1993 	struct drm_gem_object *obj;
1994 	struct amdgpu_bo *bo;
1995 	int ret;
1996 
1997 	if (dma_buf->ops != &amdgpu_dmabuf_ops)
1998 		/* Can't handle non-graphics buffers */
1999 		return -EINVAL;
2000 
2001 	obj = dma_buf->priv;
2002 	if (drm_to_adev(obj->dev) != adev)
2003 		/* Can't handle buffers from other devices */
2004 		return -EINVAL;
2005 
2006 	bo = gem_to_amdgpu_bo(obj);
2007 	if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM |
2008 				    AMDGPU_GEM_DOMAIN_GTT)))
2009 		/* Only VRAM and GTT BOs are supported */
2010 		return -EINVAL;
2011 
2012 	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
2013 	if (!*mem)
2014 		return -ENOMEM;
2015 
2016 	ret = drm_vma_node_allow(&obj->vma_node, drm_priv);
2017 	if (ret) {
2018 		kfree(mem);
2019 		return ret;
2020 	}
2021 
2022 	if (size)
2023 		*size = amdgpu_bo_size(bo);
2024 
2025 	if (mmap_offset)
2026 		*mmap_offset = amdgpu_bo_mmap_offset(bo);
2027 
2028 	INIT_LIST_HEAD(&(*mem)->attachments);
2029 	mutex_init(&(*mem)->lock);
2030 
2031 	(*mem)->alloc_flags =
2032 		((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
2033 		KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT)
2034 		| KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE
2035 		| KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;
2036 
2037 	drm_gem_object_get(&bo->tbo.base);
2038 	(*mem)->bo = bo;
2039 	(*mem)->va = va;
2040 	(*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
2041 		AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT;
2042 	(*mem)->mapped_to_gpu_memory = 0;
2043 	(*mem)->process_info = avm->process_info;
2044 	add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false);
2045 	amdgpu_sync_create(&(*mem)->sync);
2046 	(*mem)->is_imported = true;
2047 
2048 	return 0;
2049 }
2050 
2051 /* Evict a userptr BO by stopping the queues if necessary
2052  *
2053  * Runs in MMU notifier, may be in RECLAIM_FS context. This means it
2054  * cannot do any memory allocations, and cannot take any locks that
2055  * are held elsewhere while allocating memory. Therefore this is as
2056  * simple as possible, using atomic counters.
2057  *
2058  * It doesn't do anything to the BO itself. The real work happens in
2059  * restore, where we get updated page addresses. This function only
2060  * ensures that GPU access to the BO is stopped.
2061  */
2062 int amdgpu_amdkfd_evict_userptr(struct kgd_mem *mem,
2063 				struct mm_struct *mm)
2064 {
2065 	struct amdkfd_process_info *process_info = mem->process_info;
2066 	int evicted_bos;
2067 	int r = 0;
2068 
2069 	atomic_inc(&mem->invalid);
2070 	evicted_bos = atomic_inc_return(&process_info->evicted_bos);
2071 	if (evicted_bos == 1) {
2072 		/* First eviction, stop the queues */
2073 		r = kgd2kfd_quiesce_mm(mm);
2074 		if (r)
2075 			pr_err("Failed to quiesce KFD\n");
2076 		schedule_delayed_work(&process_info->restore_userptr_work,
2077 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2078 	}
2079 
2080 	return r;
2081 }
2082 
2083 /* Update invalid userptr BOs
2084  *
2085  * Moves invalidated (evicted) userptr BOs from userptr_valid_list to
2086  * userptr_inval_list and updates user pages for all BOs that have
2087  * been invalidated since their last update.
2088  */
2089 static int update_invalid_user_pages(struct amdkfd_process_info *process_info,
2090 				     struct mm_struct *mm)
2091 {
2092 	struct kgd_mem *mem, *tmp_mem;
2093 	struct amdgpu_bo *bo;
2094 	struct ttm_operation_ctx ctx = { false, false };
2095 	int invalid, ret;
2096 
2097 	/* Move all invalidated BOs to the userptr_inval_list and
2098 	 * release their user pages by migration to the CPU domain
2099 	 */
2100 	list_for_each_entry_safe(mem, tmp_mem,
2101 				 &process_info->userptr_valid_list,
2102 				 validate_list.head) {
2103 		if (!atomic_read(&mem->invalid))
2104 			continue; /* BO is still valid */
2105 
2106 		bo = mem->bo;
2107 
2108 		if (amdgpu_bo_reserve(bo, true))
2109 			return -EAGAIN;
2110 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
2111 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2112 		amdgpu_bo_unreserve(bo);
2113 		if (ret) {
2114 			pr_err("%s: Failed to invalidate userptr BO\n",
2115 			       __func__);
2116 			return -EAGAIN;
2117 		}
2118 
2119 		list_move_tail(&mem->validate_list.head,
2120 			       &process_info->userptr_inval_list);
2121 	}
2122 
2123 	if (list_empty(&process_info->userptr_inval_list))
2124 		return 0; /* All evicted userptr BOs were freed */
2125 
2126 	/* Go through userptr_inval_list and update any invalid user_pages */
2127 	list_for_each_entry(mem, &process_info->userptr_inval_list,
2128 			    validate_list.head) {
2129 		invalid = atomic_read(&mem->invalid);
2130 		if (!invalid)
2131 			/* BO hasn't been invalidated since the last
2132 			 * revalidation attempt. Keep its BO list.
2133 			 */
2134 			continue;
2135 
2136 		bo = mem->bo;
2137 
2138 		/* Get updated user pages */
2139 		ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages);
2140 		if (ret) {
2141 			pr_debug("Failed %d to get user pages\n", ret);
2142 
2143 			/* Return -EFAULT bad address error as success. It will
2144 			 * fail later with a VM fault if the GPU tries to access
2145 			 * it. Better than hanging indefinitely with stalled
2146 			 * user mode queues.
2147 			 *
2148 			 * Return other error -EBUSY or -ENOMEM to retry restore
2149 			 */
2150 			if (ret != -EFAULT)
2151 				return ret;
2152 		} else {
2153 
2154 			/*
2155 			 * FIXME: Cannot ignore the return code, must hold
2156 			 * notifier_lock
2157 			 */
2158 			amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm);
2159 		}
2160 
2161 		/* Mark the BO as valid unless it was invalidated
2162 		 * again concurrently.
2163 		 */
2164 		if (atomic_cmpxchg(&mem->invalid, invalid, 0) != invalid)
2165 			return -EAGAIN;
2166 	}
2167 
2168 	return 0;
2169 }
2170 
2171 /* Validate invalid userptr BOs
2172  *
2173  * Validates BOs on the userptr_inval_list, and moves them back to the
2174  * userptr_valid_list. Also updates GPUVM page tables with new page
2175  * addresses and waits for the page table updates to complete.
2176  */
2177 static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)
2178 {
2179 	struct amdgpu_bo_list_entry *pd_bo_list_entries;
2180 	struct list_head resv_list, duplicates;
2181 	struct ww_acquire_ctx ticket;
2182 	struct amdgpu_sync sync;
2183 
2184 	struct amdgpu_vm *peer_vm;
2185 	struct kgd_mem *mem, *tmp_mem;
2186 	struct amdgpu_bo *bo;
2187 	struct ttm_operation_ctx ctx = { false, false };
2188 	int i, ret;
2189 
2190 	pd_bo_list_entries = kcalloc(process_info->n_vms,
2191 				     sizeof(struct amdgpu_bo_list_entry),
2192 				     GFP_KERNEL);
2193 	if (!pd_bo_list_entries) {
2194 		pr_err("%s: Failed to allocate PD BO list entries\n", __func__);
2195 		ret = -ENOMEM;
2196 		goto out_no_mem;
2197 	}
2198 
2199 	INIT_LIST_HEAD(&resv_list);
2200 	INIT_LIST_HEAD(&duplicates);
2201 
2202 	/* Get all the page directory BOs that need to be reserved */
2203 	i = 0;
2204 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2205 			    vm_list_node)
2206 		amdgpu_vm_get_pd_bo(peer_vm, &resv_list,
2207 				    &pd_bo_list_entries[i++]);
2208 	/* Add the userptr_inval_list entries to resv_list */
2209 	list_for_each_entry(mem, &process_info->userptr_inval_list,
2210 			    validate_list.head) {
2211 		list_add_tail(&mem->resv_list.head, &resv_list);
2212 		mem->resv_list.bo = mem->validate_list.bo;
2213 		mem->resv_list.num_shared = mem->validate_list.num_shared;
2214 	}
2215 
2216 	/* Reserve all BOs and page tables for validation */
2217 	ret = ttm_eu_reserve_buffers(&ticket, &resv_list, false, &duplicates);
2218 	WARN(!list_empty(&duplicates), "Duplicates should be empty");
2219 	if (ret)
2220 		goto out_free;
2221 
2222 	amdgpu_sync_create(&sync);
2223 
2224 	ret = process_validate_vms(process_info);
2225 	if (ret)
2226 		goto unreserve_out;
2227 
2228 	/* Validate BOs and update GPUVM page tables */
2229 	list_for_each_entry_safe(mem, tmp_mem,
2230 				 &process_info->userptr_inval_list,
2231 				 validate_list.head) {
2232 		struct kfd_mem_attachment *attachment;
2233 
2234 		bo = mem->bo;
2235 
2236 		/* Validate the BO if we got user pages */
2237 		if (bo->tbo.ttm->pages[0]) {
2238 			amdgpu_bo_placement_from_domain(bo, mem->domain);
2239 			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2240 			if (ret) {
2241 				pr_err("%s: failed to validate BO\n", __func__);
2242 				goto unreserve_out;
2243 			}
2244 		}
2245 
2246 		list_move_tail(&mem->validate_list.head,
2247 			       &process_info->userptr_valid_list);
2248 
2249 		/* Update mapping. If the BO was not validated
2250 		 * (because we couldn't get user pages), this will
2251 		 * clear the page table entries, which will result in
2252 		 * VM faults if the GPU tries to access the invalid
2253 		 * memory.
2254 		 */
2255 		list_for_each_entry(attachment, &mem->attachments, list) {
2256 			if (!attachment->is_mapped)
2257 				continue;
2258 
2259 			kfd_mem_dmaunmap_attachment(mem, attachment);
2260 			ret = update_gpuvm_pte(mem, attachment, &sync, NULL);
2261 			if (ret) {
2262 				pr_err("%s: update PTE failed\n", __func__);
2263 				/* make sure this gets validated again */
2264 				atomic_inc(&mem->invalid);
2265 				goto unreserve_out;
2266 			}
2267 		}
2268 	}
2269 
2270 	/* Update page directories */
2271 	ret = process_update_pds(process_info, &sync);
2272 
2273 unreserve_out:
2274 	ttm_eu_backoff_reservation(&ticket, &resv_list);
2275 	amdgpu_sync_wait(&sync, false);
2276 	amdgpu_sync_free(&sync);
2277 out_free:
2278 	kfree(pd_bo_list_entries);
2279 out_no_mem:
2280 
2281 	return ret;
2282 }
2283 
2284 /* Worker callback to restore evicted userptr BOs
2285  *
2286  * Tries to update and validate all userptr BOs. If successful and no
2287  * concurrent evictions happened, the queues are restarted. Otherwise,
2288  * reschedule for another attempt later.
2289  */
2290 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
2291 {
2292 	struct delayed_work *dwork = to_delayed_work(work);
2293 	struct amdkfd_process_info *process_info =
2294 		container_of(dwork, struct amdkfd_process_info,
2295 			     restore_userptr_work);
2296 	struct task_struct *usertask;
2297 	struct mm_struct *mm;
2298 	int evicted_bos;
2299 
2300 	evicted_bos = atomic_read(&process_info->evicted_bos);
2301 	if (!evicted_bos)
2302 		return;
2303 
2304 	/* Reference task and mm in case of concurrent process termination */
2305 	usertask = get_pid_task(process_info->pid, PIDTYPE_PID);
2306 	if (!usertask)
2307 		return;
2308 	mm = get_task_mm(usertask);
2309 	if (!mm) {
2310 		put_task_struct(usertask);
2311 		return;
2312 	}
2313 
2314 	mutex_lock(&process_info->lock);
2315 
2316 	if (update_invalid_user_pages(process_info, mm))
2317 		goto unlock_out;
2318 	/* userptr_inval_list can be empty if all evicted userptr BOs
2319 	 * have been freed. In that case there is nothing to validate
2320 	 * and we can just restart the queues.
2321 	 */
2322 	if (!list_empty(&process_info->userptr_inval_list)) {
2323 		if (atomic_read(&process_info->evicted_bos) != evicted_bos)
2324 			goto unlock_out; /* Concurrent eviction, try again */
2325 
2326 		if (validate_invalid_user_pages(process_info))
2327 			goto unlock_out;
2328 	}
2329 	/* Final check for concurrent evicton and atomic update. If
2330 	 * another eviction happens after successful update, it will
2331 	 * be a first eviction that calls quiesce_mm. The eviction
2332 	 * reference counting inside KFD will handle this case.
2333 	 */
2334 	if (atomic_cmpxchg(&process_info->evicted_bos, evicted_bos, 0) !=
2335 	    evicted_bos)
2336 		goto unlock_out;
2337 	evicted_bos = 0;
2338 	if (kgd2kfd_resume_mm(mm)) {
2339 		pr_err("%s: Failed to resume KFD\n", __func__);
2340 		/* No recovery from this failure. Probably the CP is
2341 		 * hanging. No point trying again.
2342 		 */
2343 	}
2344 
2345 unlock_out:
2346 	mutex_unlock(&process_info->lock);
2347 	mmput(mm);
2348 	put_task_struct(usertask);
2349 
2350 	/* If validation failed, reschedule another attempt */
2351 	if (evicted_bos)
2352 		schedule_delayed_work(&process_info->restore_userptr_work,
2353 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2354 }
2355 
2356 /** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given
2357  *   KFD process identified by process_info
2358  *
2359  * @process_info: amdkfd_process_info of the KFD process
2360  *
2361  * After memory eviction, restore thread calls this function. The function
2362  * should be called when the Process is still valid. BO restore involves -
2363  *
2364  * 1.  Release old eviction fence and create new one
2365  * 2.  Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.
2366  * 3   Use the second PD list and kfd_bo_list to create a list (ctx.list) of
2367  *     BOs that need to be reserved.
2368  * 4.  Reserve all the BOs
2369  * 5.  Validate of PD and PT BOs.
2370  * 6.  Validate all KFD BOs using kfd_bo_list and Map them and add new fence
2371  * 7.  Add fence to all PD and PT BOs.
2372  * 8.  Unreserve all BOs
2373  */
2374 int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence **ef)
2375 {
2376 	struct amdgpu_bo_list_entry *pd_bo_list;
2377 	struct amdkfd_process_info *process_info = info;
2378 	struct amdgpu_vm *peer_vm;
2379 	struct kgd_mem *mem;
2380 	struct bo_vm_reservation_context ctx;
2381 	struct amdgpu_amdkfd_fence *new_fence;
2382 	int ret = 0, i;
2383 	struct list_head duplicate_save;
2384 	struct amdgpu_sync sync_obj;
2385 	unsigned long failed_size = 0;
2386 	unsigned long total_size = 0;
2387 
2388 	INIT_LIST_HEAD(&duplicate_save);
2389 	INIT_LIST_HEAD(&ctx.list);
2390 	INIT_LIST_HEAD(&ctx.duplicates);
2391 
2392 	pd_bo_list = kcalloc(process_info->n_vms,
2393 			     sizeof(struct amdgpu_bo_list_entry),
2394 			     GFP_KERNEL);
2395 	if (!pd_bo_list)
2396 		return -ENOMEM;
2397 
2398 	i = 0;
2399 	mutex_lock(&process_info->lock);
2400 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2401 			vm_list_node)
2402 		amdgpu_vm_get_pd_bo(peer_vm, &ctx.list, &pd_bo_list[i++]);
2403 
2404 	/* Reserve all BOs and page tables/directory. Add all BOs from
2405 	 * kfd_bo_list to ctx.list
2406 	 */
2407 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2408 			    validate_list.head) {
2409 
2410 		list_add_tail(&mem->resv_list.head, &ctx.list);
2411 		mem->resv_list.bo = mem->validate_list.bo;
2412 		mem->resv_list.num_shared = mem->validate_list.num_shared;
2413 	}
2414 
2415 	ret = ttm_eu_reserve_buffers(&ctx.ticket, &ctx.list,
2416 				     false, &duplicate_save);
2417 	if (ret) {
2418 		pr_debug("Memory eviction: TTM Reserve Failed. Try again\n");
2419 		goto ttm_reserve_fail;
2420 	}
2421 
2422 	amdgpu_sync_create(&sync_obj);
2423 
2424 	/* Validate PDs and PTs */
2425 	ret = process_validate_vms(process_info);
2426 	if (ret)
2427 		goto validate_map_fail;
2428 
2429 	ret = process_sync_pds_resv(process_info, &sync_obj);
2430 	if (ret) {
2431 		pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");
2432 		goto validate_map_fail;
2433 	}
2434 
2435 	/* Validate BOs and map them to GPUVM (update VM page tables). */
2436 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2437 			    validate_list.head) {
2438 
2439 		struct amdgpu_bo *bo = mem->bo;
2440 		uint32_t domain = mem->domain;
2441 		struct kfd_mem_attachment *attachment;
2442 
2443 		total_size += amdgpu_bo_size(bo);
2444 
2445 		ret = amdgpu_amdkfd_bo_validate(bo, domain, false);
2446 		if (ret) {
2447 			pr_debug("Memory eviction: Validate BOs failed\n");
2448 			failed_size += amdgpu_bo_size(bo);
2449 			ret = amdgpu_amdkfd_bo_validate(bo,
2450 						AMDGPU_GEM_DOMAIN_GTT, false);
2451 			if (ret) {
2452 				pr_debug("Memory eviction: Try again\n");
2453 				goto validate_map_fail;
2454 			}
2455 		}
2456 		ret = amdgpu_sync_fence(&sync_obj, bo->tbo.moving);
2457 		if (ret) {
2458 			pr_debug("Memory eviction: Sync BO fence failed. Try again\n");
2459 			goto validate_map_fail;
2460 		}
2461 		list_for_each_entry(attachment, &mem->attachments, list) {
2462 			if (!attachment->is_mapped)
2463 				continue;
2464 
2465 			kfd_mem_dmaunmap_attachment(mem, attachment);
2466 			ret = update_gpuvm_pte(mem, attachment, &sync_obj, NULL);
2467 			if (ret) {
2468 				pr_debug("Memory eviction: update PTE failed. Try again\n");
2469 				goto validate_map_fail;
2470 			}
2471 		}
2472 	}
2473 
2474 	if (failed_size)
2475 		pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size);
2476 
2477 	/* Update page directories */
2478 	ret = process_update_pds(process_info, &sync_obj);
2479 	if (ret) {
2480 		pr_debug("Memory eviction: update PDs failed. Try again\n");
2481 		goto validate_map_fail;
2482 	}
2483 
2484 	/* Wait for validate and PT updates to finish */
2485 	amdgpu_sync_wait(&sync_obj, false);
2486 
2487 	/* Release old eviction fence and create new one, because fence only
2488 	 * goes from unsignaled to signaled, fence cannot be reused.
2489 	 * Use context and mm from the old fence.
2490 	 */
2491 	new_fence = amdgpu_amdkfd_fence_create(
2492 				process_info->eviction_fence->base.context,
2493 				process_info->eviction_fence->mm,
2494 				NULL);
2495 	if (!new_fence) {
2496 		pr_err("Failed to create eviction fence\n");
2497 		ret = -ENOMEM;
2498 		goto validate_map_fail;
2499 	}
2500 	dma_fence_put(&process_info->eviction_fence->base);
2501 	process_info->eviction_fence = new_fence;
2502 	*ef = dma_fence_get(&new_fence->base);
2503 
2504 	/* Attach new eviction fence to all BOs */
2505 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2506 		validate_list.head)
2507 		amdgpu_bo_fence(mem->bo,
2508 			&process_info->eviction_fence->base, true);
2509 
2510 	/* Attach eviction fence to PD / PT BOs */
2511 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2512 			    vm_list_node) {
2513 		struct amdgpu_bo *bo = peer_vm->root.bo;
2514 
2515 		amdgpu_bo_fence(bo, &process_info->eviction_fence->base, true);
2516 	}
2517 
2518 validate_map_fail:
2519 	ttm_eu_backoff_reservation(&ctx.ticket, &ctx.list);
2520 	amdgpu_sync_free(&sync_obj);
2521 ttm_reserve_fail:
2522 	mutex_unlock(&process_info->lock);
2523 	kfree(pd_bo_list);
2524 	return ret;
2525 }
2526 
2527 int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem)
2528 {
2529 	struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
2530 	struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws;
2531 	int ret;
2532 
2533 	if (!info || !gws)
2534 		return -EINVAL;
2535 
2536 	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
2537 	if (!*mem)
2538 		return -ENOMEM;
2539 
2540 	mutex_init(&(*mem)->lock);
2541 	INIT_LIST_HEAD(&(*mem)->attachments);
2542 	(*mem)->bo = amdgpu_bo_ref(gws_bo);
2543 	(*mem)->domain = AMDGPU_GEM_DOMAIN_GWS;
2544 	(*mem)->process_info = process_info;
2545 	add_kgd_mem_to_kfd_bo_list(*mem, process_info, false);
2546 	amdgpu_sync_create(&(*mem)->sync);
2547 
2548 
2549 	/* Validate gws bo the first time it is added to process */
2550 	mutex_lock(&(*mem)->process_info->lock);
2551 	ret = amdgpu_bo_reserve(gws_bo, false);
2552 	if (unlikely(ret)) {
2553 		pr_err("Reserve gws bo failed %d\n", ret);
2554 		goto bo_reservation_failure;
2555 	}
2556 
2557 	ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true);
2558 	if (ret) {
2559 		pr_err("GWS BO validate failed %d\n", ret);
2560 		goto bo_validation_failure;
2561 	}
2562 	/* GWS resource is shared b/t amdgpu and amdkfd
2563 	 * Add process eviction fence to bo so they can
2564 	 * evict each other.
2565 	 */
2566 	ret = dma_resv_reserve_shared(gws_bo->tbo.base.resv, 1);
2567 	if (ret)
2568 		goto reserve_shared_fail;
2569 	amdgpu_bo_fence(gws_bo, &process_info->eviction_fence->base, true);
2570 	amdgpu_bo_unreserve(gws_bo);
2571 	mutex_unlock(&(*mem)->process_info->lock);
2572 
2573 	return ret;
2574 
2575 reserve_shared_fail:
2576 bo_validation_failure:
2577 	amdgpu_bo_unreserve(gws_bo);
2578 bo_reservation_failure:
2579 	mutex_unlock(&(*mem)->process_info->lock);
2580 	amdgpu_sync_free(&(*mem)->sync);
2581 	remove_kgd_mem_from_kfd_bo_list(*mem, process_info);
2582 	amdgpu_bo_unref(&gws_bo);
2583 	mutex_destroy(&(*mem)->lock);
2584 	kfree(*mem);
2585 	*mem = NULL;
2586 	return ret;
2587 }
2588 
2589 int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem)
2590 {
2591 	int ret;
2592 	struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
2593 	struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;
2594 	struct amdgpu_bo *gws_bo = kgd_mem->bo;
2595 
2596 	/* Remove BO from process's validate list so restore worker won't touch
2597 	 * it anymore
2598 	 */
2599 	remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info);
2600 
2601 	ret = amdgpu_bo_reserve(gws_bo, false);
2602 	if (unlikely(ret)) {
2603 		pr_err("Reserve gws bo failed %d\n", ret);
2604 		//TODO add BO back to validate_list?
2605 		return ret;
2606 	}
2607 	amdgpu_amdkfd_remove_eviction_fence(gws_bo,
2608 			process_info->eviction_fence);
2609 	amdgpu_bo_unreserve(gws_bo);
2610 	amdgpu_sync_free(&kgd_mem->sync);
2611 	amdgpu_bo_unref(&gws_bo);
2612 	mutex_destroy(&kgd_mem->lock);
2613 	kfree(mem);
2614 	return 0;
2615 }
2616 
2617 /* Returns GPU-specific tiling mode information */
2618 int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev,
2619 				struct tile_config *config)
2620 {
2621 	config->gb_addr_config = adev->gfx.config.gb_addr_config;
2622 	config->tile_config_ptr = adev->gfx.config.tile_mode_array;
2623 	config->num_tile_configs =
2624 			ARRAY_SIZE(adev->gfx.config.tile_mode_array);
2625 	config->macro_tile_config_ptr =
2626 			adev->gfx.config.macrotile_mode_array;
2627 	config->num_macro_tile_configs =
2628 			ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);
2629 
2630 	/* Those values are not set from GFX9 onwards */
2631 	config->num_banks = adev->gfx.config.num_banks;
2632 	config->num_ranks = adev->gfx.config.num_ranks;
2633 
2634 	return 0;
2635 }
2636