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