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