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