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