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