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