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