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