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