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