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