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