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