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