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