• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 	uint64_t aligned_size;
1657 	u64 alloc_flags;
1658 	int ret;
1659 
1660 	/*
1661 	 * Check on which domain to allocate BO
1662 	 */
1663 	if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
1664 		domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;
1665 		alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;
1666 		alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ?
1667 			AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0;
1668 	} else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
1669 		domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
1670 		alloc_flags = 0;
1671 	} else {
1672 		domain = AMDGPU_GEM_DOMAIN_GTT;
1673 		alloc_domain = AMDGPU_GEM_DOMAIN_CPU;
1674 		alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE;
1675 
1676 		if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
1677 			if (!offset || !*offset)
1678 				return -EINVAL;
1679 			user_addr = untagged_addr(*offset);
1680 		} else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1681 				    KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1682 			bo_type = ttm_bo_type_sg;
1683 			if (size > UINT_MAX)
1684 				return -EINVAL;
1685 			sg = create_sg_table(*offset, size);
1686 			if (!sg)
1687 				return -ENOMEM;
1688 		} else {
1689 			return -EINVAL;
1690 		}
1691 	}
1692 
1693 	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
1694 	if (!*mem) {
1695 		ret = -ENOMEM;
1696 		goto err;
1697 	}
1698 	INIT_LIST_HEAD(&(*mem)->attachments);
1699 	mutex_init(&(*mem)->lock);
1700 	(*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);
1701 
1702 	/* Workaround for AQL queue wraparound bug. Map the same
1703 	 * memory twice. That means we only actually allocate half
1704 	 * the memory.
1705 	 */
1706 	if ((*mem)->aql_queue)
1707 		size >>= 1;
1708 	aligned_size = PAGE_ALIGN(size);
1709 
1710 	(*mem)->alloc_flags = flags;
1711 
1712 	amdgpu_sync_create(&(*mem)->sync);
1713 
1714 	ret = amdgpu_amdkfd_reserve_mem_limit(adev, aligned_size, flags);
1715 	if (ret) {
1716 		pr_debug("Insufficient memory\n");
1717 		goto err_reserve_limit;
1718 	}
1719 
1720 	pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s\n",
1721 			va, (*mem)->aql_queue ? size << 1 : size, domain_string(alloc_domain));
1722 
1723 	ret = amdgpu_gem_object_create(adev, aligned_size, 1, alloc_domain, alloc_flags,
1724 				       bo_type, NULL, &gobj);
1725 	if (ret) {
1726 		pr_debug("Failed to create BO on domain %s. ret %d\n",
1727 			 domain_string(alloc_domain), ret);
1728 		goto err_bo_create;
1729 	}
1730 	ret = drm_vma_node_allow(&gobj->vma_node, drm_priv);
1731 	if (ret) {
1732 		pr_debug("Failed to allow vma node access. ret %d\n", ret);
1733 		goto err_node_allow;
1734 	}
1735 	bo = gem_to_amdgpu_bo(gobj);
1736 	if (bo_type == ttm_bo_type_sg) {
1737 		bo->tbo.sg = sg;
1738 		bo->tbo.ttm->sg = sg;
1739 	}
1740 	bo->kfd_bo = *mem;
1741 	(*mem)->bo = bo;
1742 	if (user_addr)
1743 		bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO;
1744 
1745 	(*mem)->va = va;
1746 	(*mem)->domain = domain;
1747 	(*mem)->mapped_to_gpu_memory = 0;
1748 	(*mem)->process_info = avm->process_info;
1749 	add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);
1750 
1751 	if (user_addr) {
1752 		pr_debug("creating userptr BO for user_addr = %llx\n", user_addr);
1753 		ret = init_user_pages(*mem, user_addr, criu_resume);
1754 		if (ret)
1755 			goto allocate_init_user_pages_failed;
1756 	} else  if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1757 				KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1758 		ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT);
1759 		if (ret) {
1760 			pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n");
1761 			goto err_pin_bo;
1762 		}
1763 		bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
1764 		bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
1765 	}
1766 
1767 	if (offset)
1768 		*offset = amdgpu_bo_mmap_offset(bo);
1769 
1770 	return 0;
1771 
1772 allocate_init_user_pages_failed:
1773 err_pin_bo:
1774 	remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);
1775 	drm_vma_node_revoke(&gobj->vma_node, drm_priv);
1776 err_node_allow:
1777 	/* Don't unreserve system mem limit twice */
1778 	goto err_reserve_limit;
1779 err_bo_create:
1780 	amdgpu_amdkfd_unreserve_mem_limit(adev, aligned_size, flags);
1781 err_reserve_limit:
1782 	mutex_destroy(&(*mem)->lock);
1783 	if (gobj)
1784 		drm_gem_object_put(gobj);
1785 	else
1786 		kfree(*mem);
1787 err:
1788 	if (sg) {
1789 		sg_free_table(sg);
1790 		kfree(sg);
1791 	}
1792 	return ret;
1793 }
1794 
amdgpu_amdkfd_gpuvm_free_memory_of_gpu(struct amdgpu_device * adev,struct kgd_mem * mem,void * drm_priv,uint64_t * size)1795 int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(
1796 		struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv,
1797 		uint64_t *size)
1798 {
1799 	struct amdkfd_process_info *process_info = mem->process_info;
1800 	unsigned long bo_size = mem->bo->tbo.base.size;
1801 	bool use_release_notifier = (mem->bo->kfd_bo == mem);
1802 	struct kfd_mem_attachment *entry, *tmp;
1803 	struct bo_vm_reservation_context ctx;
1804 	struct ttm_validate_buffer *bo_list_entry;
1805 	unsigned int mapped_to_gpu_memory;
1806 	int ret;
1807 	bool is_imported = false;
1808 
1809 	mutex_lock(&mem->lock);
1810 
1811 	/* Unpin MMIO/DOORBELL BO's that were pinned during allocation */
1812 	if (mem->alloc_flags &
1813 	    (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1814 	     KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1815 		amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo);
1816 	}
1817 
1818 	mapped_to_gpu_memory = mem->mapped_to_gpu_memory;
1819 	is_imported = mem->is_imported;
1820 	mutex_unlock(&mem->lock);
1821 	/* lock is not needed after this, since mem is unused and will
1822 	 * be freed anyway
1823 	 */
1824 
1825 	if (mapped_to_gpu_memory > 0) {
1826 		pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",
1827 				mem->va, bo_size);
1828 		return -EBUSY;
1829 	}
1830 
1831 	/* Make sure restore workers don't access the BO any more */
1832 	bo_list_entry = &mem->validate_list;
1833 	mutex_lock(&process_info->lock);
1834 	list_del(&bo_list_entry->head);
1835 	mutex_unlock(&process_info->lock);
1836 
1837 	/* No more MMU notifiers */
1838 	amdgpu_mn_unregister(mem->bo);
1839 
1840 	ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);
1841 	if (unlikely(ret))
1842 		return ret;
1843 
1844 	/* The eviction fence should be removed by the last unmap.
1845 	 * TODO: Log an error condition if the bo still has the eviction fence
1846 	 * attached
1847 	 */
1848 	amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1849 					process_info->eviction_fence);
1850 	pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,
1851 		mem->va + bo_size * (1 + mem->aql_queue));
1852 
1853 	/* Remove from VM internal data structures */
1854 	list_for_each_entry_safe(entry, tmp, &mem->attachments, list)
1855 		kfd_mem_detach(entry);
1856 
1857 	ret = unreserve_bo_and_vms(&ctx, false, false);
1858 
1859 	/* Free the sync object */
1860 	amdgpu_sync_free(&mem->sync);
1861 
1862 	/* If the SG is not NULL, it's one we created for a doorbell or mmio
1863 	 * remap BO. We need to free it.
1864 	 */
1865 	if (mem->bo->tbo.sg) {
1866 		sg_free_table(mem->bo->tbo.sg);
1867 		kfree(mem->bo->tbo.sg);
1868 	}
1869 
1870 	/* Update the size of the BO being freed if it was allocated from
1871 	 * VRAM and is not imported.
1872 	 */
1873 	if (size) {
1874 		if ((mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_VRAM) &&
1875 		    (!is_imported))
1876 			*size = bo_size;
1877 		else
1878 			*size = 0;
1879 	}
1880 
1881 	/* Free the BO*/
1882 	drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv);
1883 	if (mem->dmabuf)
1884 		dma_buf_put(mem->dmabuf);
1885 	mutex_destroy(&mem->lock);
1886 
1887 	/* If this releases the last reference, it will end up calling
1888 	 * amdgpu_amdkfd_release_notify and kfree the mem struct. That's why
1889 	 * this needs to be the last call here.
1890 	 */
1891 	drm_gem_object_put(&mem->bo->tbo.base);
1892 
1893 	/*
1894 	 * For kgd_mem allocated in amdgpu_amdkfd_gpuvm_import_dmabuf(),
1895 	 * explicitly free it here.
1896 	 */
1897 	if (!use_release_notifier)
1898 		kfree(mem);
1899 
1900 	return ret;
1901 }
1902 
amdgpu_amdkfd_gpuvm_map_memory_to_gpu(struct amdgpu_device * adev,struct kgd_mem * mem,void * drm_priv)1903 int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1904 		struct amdgpu_device *adev, struct kgd_mem *mem,
1905 		void *drm_priv)
1906 {
1907 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1908 	int ret;
1909 	struct amdgpu_bo *bo;
1910 	uint32_t domain;
1911 	struct kfd_mem_attachment *entry;
1912 	struct bo_vm_reservation_context ctx;
1913 	unsigned long bo_size;
1914 	bool is_invalid_userptr = false;
1915 
1916 	bo = mem->bo;
1917 	if (!bo) {
1918 		pr_err("Invalid BO when mapping memory to GPU\n");
1919 		return -EINVAL;
1920 	}
1921 
1922 	/* Make sure restore is not running concurrently. Since we
1923 	 * don't map invalid userptr BOs, we rely on the next restore
1924 	 * worker to do the mapping
1925 	 */
1926 	mutex_lock(&mem->process_info->lock);
1927 
1928 	/* Lock mmap-sem. If we find an invalid userptr BO, we can be
1929 	 * sure that the MMU notifier is no longer running
1930 	 * concurrently and the queues are actually stopped
1931 	 */
1932 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1933 		mmap_write_lock(current->mm);
1934 		is_invalid_userptr = atomic_read(&mem->invalid);
1935 		mmap_write_unlock(current->mm);
1936 	}
1937 
1938 	mutex_lock(&mem->lock);
1939 
1940 	domain = mem->domain;
1941 	bo_size = bo->tbo.base.size;
1942 
1943 	pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",
1944 			mem->va,
1945 			mem->va + bo_size * (1 + mem->aql_queue),
1946 			avm, domain_string(domain));
1947 
1948 	if (!kfd_mem_is_attached(avm, mem)) {
1949 		ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue);
1950 		if (ret)
1951 			goto out;
1952 	}
1953 
1954 	ret = reserve_bo_and_vm(mem, avm, &ctx);
1955 	if (unlikely(ret))
1956 		goto out;
1957 
1958 	/* Userptr can be marked as "not invalid", but not actually be
1959 	 * validated yet (still in the system domain). In that case
1960 	 * the queues are still stopped and we can leave mapping for
1961 	 * the next restore worker
1962 	 */
1963 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&
1964 	    bo->tbo.resource->mem_type == TTM_PL_SYSTEM)
1965 		is_invalid_userptr = true;
1966 
1967 	ret = vm_validate_pt_pd_bos(avm);
1968 	if (unlikely(ret))
1969 		goto out_unreserve;
1970 
1971 	if (mem->mapped_to_gpu_memory == 0 &&
1972 	    !amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1973 		/* Validate BO only once. The eviction fence gets added to BO
1974 		 * the first time it is mapped. Validate will wait for all
1975 		 * background evictions to complete.
1976 		 */
1977 		ret = amdgpu_amdkfd_bo_validate(bo, domain, true);
1978 		if (ret) {
1979 			pr_debug("Validate failed\n");
1980 			goto out_unreserve;
1981 		}
1982 	}
1983 
1984 	list_for_each_entry(entry, &mem->attachments, list) {
1985 		if (entry->bo_va->base.vm != avm || entry->is_mapped)
1986 			continue;
1987 
1988 		pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",
1989 			 entry->va, entry->va + bo_size, entry);
1990 
1991 		ret = map_bo_to_gpuvm(mem, entry, ctx.sync,
1992 				      is_invalid_userptr);
1993 		if (ret) {
1994 			pr_err("Failed to map bo to gpuvm\n");
1995 			goto out_unreserve;
1996 		}
1997 
1998 		ret = vm_update_pds(avm, ctx.sync);
1999 		if (ret) {
2000 			pr_err("Failed to update page directories\n");
2001 			goto out_unreserve;
2002 		}
2003 
2004 		entry->is_mapped = true;
2005 		mem->mapped_to_gpu_memory++;
2006 		pr_debug("\t INC mapping count %d\n",
2007 			 mem->mapped_to_gpu_memory);
2008 	}
2009 
2010 	if (!amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) && !bo->tbo.pin_count)
2011 		dma_resv_add_fence(bo->tbo.base.resv,
2012 				   &avm->process_info->eviction_fence->base,
2013 				   DMA_RESV_USAGE_BOOKKEEP);
2014 	ret = unreserve_bo_and_vms(&ctx, false, false);
2015 
2016 	goto out;
2017 
2018 out_unreserve:
2019 	unreserve_bo_and_vms(&ctx, false, false);
2020 out:
2021 	mutex_unlock(&mem->process_info->lock);
2022 	mutex_unlock(&mem->lock);
2023 	return ret;
2024 }
2025 
amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(struct amdgpu_device * adev,struct kgd_mem * mem,void * drm_priv)2026 int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
2027 		struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv)
2028 {
2029 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
2030 	struct amdkfd_process_info *process_info = avm->process_info;
2031 	unsigned long bo_size = mem->bo->tbo.base.size;
2032 	struct kfd_mem_attachment *entry;
2033 	struct bo_vm_reservation_context ctx;
2034 	int ret;
2035 
2036 	mutex_lock(&mem->lock);
2037 
2038 	ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx);
2039 	if (unlikely(ret))
2040 		goto out;
2041 	/* If no VMs were reserved, it means the BO wasn't actually mapped */
2042 	if (ctx.n_vms == 0) {
2043 		ret = -EINVAL;
2044 		goto unreserve_out;
2045 	}
2046 
2047 	ret = vm_validate_pt_pd_bos(avm);
2048 	if (unlikely(ret))
2049 		goto unreserve_out;
2050 
2051 	pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",
2052 		mem->va,
2053 		mem->va + bo_size * (1 + mem->aql_queue),
2054 		avm);
2055 
2056 	list_for_each_entry(entry, &mem->attachments, list) {
2057 		if (entry->bo_va->base.vm != avm || !entry->is_mapped)
2058 			continue;
2059 
2060 		pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",
2061 			 entry->va, entry->va + bo_size, entry);
2062 
2063 		unmap_bo_from_gpuvm(mem, entry, ctx.sync);
2064 		entry->is_mapped = false;
2065 
2066 		mem->mapped_to_gpu_memory--;
2067 		pr_debug("\t DEC mapping count %d\n",
2068 			 mem->mapped_to_gpu_memory);
2069 	}
2070 
2071 	/* If BO is unmapped from all VMs, unfence it. It can be evicted if
2072 	 * required.
2073 	 */
2074 	if (mem->mapped_to_gpu_memory == 0 &&
2075 	    !amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) &&
2076 	    !mem->bo->tbo.pin_count)
2077 		amdgpu_amdkfd_remove_eviction_fence(mem->bo,
2078 						process_info->eviction_fence);
2079 
2080 unreserve_out:
2081 	unreserve_bo_and_vms(&ctx, false, false);
2082 out:
2083 	mutex_unlock(&mem->lock);
2084 	return ret;
2085 }
2086 
amdgpu_amdkfd_gpuvm_sync_memory(struct amdgpu_device * adev,struct kgd_mem * mem,bool intr)2087 int amdgpu_amdkfd_gpuvm_sync_memory(
2088 		struct amdgpu_device *adev, struct kgd_mem *mem, bool intr)
2089 {
2090 	struct amdgpu_sync sync;
2091 	int ret;
2092 
2093 	amdgpu_sync_create(&sync);
2094 
2095 	mutex_lock(&mem->lock);
2096 	amdgpu_sync_clone(&mem->sync, &sync);
2097 	mutex_unlock(&mem->lock);
2098 
2099 	ret = amdgpu_sync_wait(&sync, intr);
2100 	amdgpu_sync_free(&sync);
2101 	return ret;
2102 }
2103 
2104 /**
2105  * amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count
2106  * @adev: Device to which allocated BO belongs
2107  * @bo: Buffer object to be mapped
2108  *
2109  * Before return, bo reference count is incremented. To release the reference and unpin/
2110  * unmap the BO, call amdgpu_amdkfd_free_gtt_mem.
2111  */
amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_device * adev,struct amdgpu_bo * bo)2112 int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_device *adev, struct amdgpu_bo *bo)
2113 {
2114 	int ret;
2115 
2116 	ret = amdgpu_bo_reserve(bo, true);
2117 	if (ret) {
2118 		pr_err("Failed to reserve bo. ret %d\n", ret);
2119 		goto err_reserve_bo_failed;
2120 	}
2121 
2122 	ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
2123 	if (ret) {
2124 		pr_err("Failed to pin bo. ret %d\n", ret);
2125 		goto err_pin_bo_failed;
2126 	}
2127 
2128 	ret = amdgpu_ttm_alloc_gart(&bo->tbo);
2129 	if (ret) {
2130 		pr_err("Failed to bind bo to GART. ret %d\n", ret);
2131 		goto err_map_bo_gart_failed;
2132 	}
2133 
2134 	amdgpu_amdkfd_remove_eviction_fence(
2135 		bo, bo->vm_bo->vm->process_info->eviction_fence);
2136 
2137 	amdgpu_bo_unreserve(bo);
2138 
2139 	bo = amdgpu_bo_ref(bo);
2140 
2141 	return 0;
2142 
2143 err_map_bo_gart_failed:
2144 	amdgpu_bo_unpin(bo);
2145 err_pin_bo_failed:
2146 	amdgpu_bo_unreserve(bo);
2147 err_reserve_bo_failed:
2148 
2149 	return ret;
2150 }
2151 
2152 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Map a GTT BO for kernel CPU access
2153  *
2154  * @mem: Buffer object to be mapped for CPU access
2155  * @kptr[out]: pointer in kernel CPU address space
2156  * @size[out]: size of the buffer
2157  *
2158  * Pins the BO and maps it for kernel CPU access. The eviction fence is removed
2159  * from the BO, since pinned BOs cannot be evicted. The bo must remain on the
2160  * validate_list, so the GPU mapping can be restored after a page table was
2161  * evicted.
2162  *
2163  * Return: 0 on success, error code on failure
2164  */
amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem * mem,void ** kptr,uint64_t * size)2165 int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem,
2166 					     void **kptr, uint64_t *size)
2167 {
2168 	int ret;
2169 	struct amdgpu_bo *bo = mem->bo;
2170 
2171 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
2172 		pr_err("userptr can't be mapped to kernel\n");
2173 		return -EINVAL;
2174 	}
2175 
2176 	mutex_lock(&mem->process_info->lock);
2177 
2178 	ret = amdgpu_bo_reserve(bo, true);
2179 	if (ret) {
2180 		pr_err("Failed to reserve bo. ret %d\n", ret);
2181 		goto bo_reserve_failed;
2182 	}
2183 
2184 	ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
2185 	if (ret) {
2186 		pr_err("Failed to pin bo. ret %d\n", ret);
2187 		goto pin_failed;
2188 	}
2189 
2190 	ret = amdgpu_bo_kmap(bo, kptr);
2191 	if (ret) {
2192 		pr_err("Failed to map bo to kernel. ret %d\n", ret);
2193 		goto kmap_failed;
2194 	}
2195 
2196 	amdgpu_amdkfd_remove_eviction_fence(
2197 		bo, mem->process_info->eviction_fence);
2198 
2199 	if (size)
2200 		*size = amdgpu_bo_size(bo);
2201 
2202 	amdgpu_bo_unreserve(bo);
2203 
2204 	mutex_unlock(&mem->process_info->lock);
2205 	return 0;
2206 
2207 kmap_failed:
2208 	amdgpu_bo_unpin(bo);
2209 pin_failed:
2210 	amdgpu_bo_unreserve(bo);
2211 bo_reserve_failed:
2212 	mutex_unlock(&mem->process_info->lock);
2213 
2214 	return ret;
2215 }
2216 
2217 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Unmap a GTT BO for kernel CPU access
2218  *
2219  * @mem: Buffer object to be unmapped for CPU access
2220  *
2221  * Removes the kernel CPU mapping and unpins the BO. It does not restore the
2222  * eviction fence, so this function should only be used for cleanup before the
2223  * BO is destroyed.
2224  */
amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem * mem)2225 void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem *mem)
2226 {
2227 	struct amdgpu_bo *bo = mem->bo;
2228 
2229 	amdgpu_bo_reserve(bo, true);
2230 	amdgpu_bo_kunmap(bo);
2231 	amdgpu_bo_unpin(bo);
2232 	amdgpu_bo_unreserve(bo);
2233 }
2234 
amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device * adev,struct kfd_vm_fault_info * mem)2235 int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev,
2236 					  struct kfd_vm_fault_info *mem)
2237 {
2238 	if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) {
2239 		*mem = *adev->gmc.vm_fault_info;
2240 		mb(); /* make sure read happened */
2241 		atomic_set(&adev->gmc.vm_fault_info_updated, 0);
2242 	}
2243 	return 0;
2244 }
2245 
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)2246 int amdgpu_amdkfd_gpuvm_import_dmabuf(struct amdgpu_device *adev,
2247 				      struct dma_buf *dma_buf,
2248 				      uint64_t va, void *drm_priv,
2249 				      struct kgd_mem **mem, uint64_t *size,
2250 				      uint64_t *mmap_offset)
2251 {
2252 	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
2253 	struct drm_gem_object *obj;
2254 	struct amdgpu_bo *bo;
2255 	int ret;
2256 
2257 	if (dma_buf->ops != &amdgpu_dmabuf_ops)
2258 		/* Can't handle non-graphics buffers */
2259 		return -EINVAL;
2260 
2261 	obj = dma_buf->priv;
2262 	if (drm_to_adev(obj->dev) != adev)
2263 		/* Can't handle buffers from other devices */
2264 		return -EINVAL;
2265 
2266 	bo = gem_to_amdgpu_bo(obj);
2267 	if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM |
2268 				    AMDGPU_GEM_DOMAIN_GTT)))
2269 		/* Only VRAM and GTT BOs are supported */
2270 		return -EINVAL;
2271 
2272 	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
2273 	if (!*mem)
2274 		return -ENOMEM;
2275 
2276 	ret = drm_vma_node_allow(&obj->vma_node, drm_priv);
2277 	if (ret) {
2278 		kfree(*mem);
2279 		return ret;
2280 	}
2281 
2282 	if (size)
2283 		*size = amdgpu_bo_size(bo);
2284 
2285 	if (mmap_offset)
2286 		*mmap_offset = amdgpu_bo_mmap_offset(bo);
2287 
2288 	INIT_LIST_HEAD(&(*mem)->attachments);
2289 	mutex_init(&(*mem)->lock);
2290 
2291 	(*mem)->alloc_flags =
2292 		((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
2293 		KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT)
2294 		| KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE
2295 		| KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;
2296 
2297 	drm_gem_object_get(&bo->tbo.base);
2298 	(*mem)->bo = bo;
2299 	(*mem)->va = va;
2300 	(*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
2301 		AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT;
2302 	(*mem)->mapped_to_gpu_memory = 0;
2303 	(*mem)->process_info = avm->process_info;
2304 	add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false);
2305 	amdgpu_sync_create(&(*mem)->sync);
2306 	(*mem)->is_imported = true;
2307 
2308 	return 0;
2309 }
2310 
2311 /* Evict a userptr BO by stopping the queues if necessary
2312  *
2313  * Runs in MMU notifier, may be in RECLAIM_FS context. This means it
2314  * cannot do any memory allocations, and cannot take any locks that
2315  * are held elsewhere while allocating memory. Therefore this is as
2316  * simple as possible, using atomic counters.
2317  *
2318  * It doesn't do anything to the BO itself. The real work happens in
2319  * restore, where we get updated page addresses. This function only
2320  * ensures that GPU access to the BO is stopped.
2321  */
amdgpu_amdkfd_evict_userptr(struct kgd_mem * mem,struct mm_struct * mm)2322 int amdgpu_amdkfd_evict_userptr(struct kgd_mem *mem,
2323 				struct mm_struct *mm)
2324 {
2325 	struct amdkfd_process_info *process_info = mem->process_info;
2326 	int evicted_bos;
2327 	int r = 0;
2328 
2329 	/* Do not process MMU notifications until stage-4 IOCTL is received */
2330 	if (READ_ONCE(process_info->block_mmu_notifications))
2331 		return 0;
2332 
2333 	atomic_inc(&mem->invalid);
2334 	evicted_bos = atomic_inc_return(&process_info->evicted_bos);
2335 	if (evicted_bos == 1) {
2336 		/* First eviction, stop the queues */
2337 		r = kgd2kfd_quiesce_mm(mm, KFD_QUEUE_EVICTION_TRIGGER_USERPTR);
2338 		if (r)
2339 			pr_err("Failed to quiesce KFD\n");
2340 		schedule_delayed_work(&process_info->restore_userptr_work,
2341 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2342 	}
2343 
2344 	return r;
2345 }
2346 
2347 /* Update invalid userptr BOs
2348  *
2349  * Moves invalidated (evicted) userptr BOs from userptr_valid_list to
2350  * userptr_inval_list and updates user pages for all BOs that have
2351  * been invalidated since their last update.
2352  */
update_invalid_user_pages(struct amdkfd_process_info * process_info,struct mm_struct * mm)2353 static int update_invalid_user_pages(struct amdkfd_process_info *process_info,
2354 				     struct mm_struct *mm)
2355 {
2356 	struct kgd_mem *mem, *tmp_mem;
2357 	struct amdgpu_bo *bo;
2358 	struct ttm_operation_ctx ctx = { false, false };
2359 	int invalid, ret;
2360 
2361 	/* Move all invalidated BOs to the userptr_inval_list and
2362 	 * release their user pages by migration to the CPU domain
2363 	 */
2364 	list_for_each_entry_safe(mem, tmp_mem,
2365 				 &process_info->userptr_valid_list,
2366 				 validate_list.head) {
2367 		if (!atomic_read(&mem->invalid))
2368 			continue; /* BO is still valid */
2369 
2370 		bo = mem->bo;
2371 
2372 		if (amdgpu_bo_reserve(bo, true))
2373 			return -EAGAIN;
2374 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
2375 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2376 		amdgpu_bo_unreserve(bo);
2377 		if (ret) {
2378 			pr_err("%s: Failed to invalidate userptr BO\n",
2379 			       __func__);
2380 			return -EAGAIN;
2381 		}
2382 
2383 		list_move_tail(&mem->validate_list.head,
2384 			       &process_info->userptr_inval_list);
2385 	}
2386 
2387 	if (list_empty(&process_info->userptr_inval_list))
2388 		return 0; /* All evicted userptr BOs were freed */
2389 
2390 	/* Go through userptr_inval_list and update any invalid user_pages */
2391 	list_for_each_entry(mem, &process_info->userptr_inval_list,
2392 			    validate_list.head) {
2393 		struct hmm_range *range;
2394 
2395 		invalid = atomic_read(&mem->invalid);
2396 		if (!invalid)
2397 			/* BO hasn't been invalidated since the last
2398 			 * revalidation attempt. Keep its BO list.
2399 			 */
2400 			continue;
2401 
2402 		bo = mem->bo;
2403 
2404 		/* Get updated user pages */
2405 		ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages,
2406 						   &range);
2407 		if (ret) {
2408 			pr_debug("Failed %d to get user pages\n", ret);
2409 
2410 			/* Return -EFAULT bad address error as success. It will
2411 			 * fail later with a VM fault if the GPU tries to access
2412 			 * it. Better than hanging indefinitely with stalled
2413 			 * user mode queues.
2414 			 *
2415 			 * Return other error -EBUSY or -ENOMEM to retry restore
2416 			 */
2417 			if (ret != -EFAULT)
2418 				return ret;
2419 		} else {
2420 
2421 			/*
2422 			 * FIXME: Cannot ignore the return code, must hold
2423 			 * notifier_lock
2424 			 */
2425 			amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm, range);
2426 		}
2427 
2428 		/* Mark the BO as valid unless it was invalidated
2429 		 * again concurrently.
2430 		 */
2431 		if (atomic_cmpxchg(&mem->invalid, invalid, 0) != invalid)
2432 			return -EAGAIN;
2433 	}
2434 
2435 	return 0;
2436 }
2437 
2438 /* Validate invalid userptr BOs
2439  *
2440  * Validates BOs on the userptr_inval_list, and moves them back to the
2441  * userptr_valid_list. Also updates GPUVM page tables with new page
2442  * addresses and waits for the page table updates to complete.
2443  */
validate_invalid_user_pages(struct amdkfd_process_info * process_info)2444 static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)
2445 {
2446 	struct amdgpu_bo_list_entry *pd_bo_list_entries;
2447 	struct list_head resv_list, duplicates;
2448 	struct ww_acquire_ctx ticket;
2449 	struct amdgpu_sync sync;
2450 
2451 	struct amdgpu_vm *peer_vm;
2452 	struct kgd_mem *mem, *tmp_mem;
2453 	struct amdgpu_bo *bo;
2454 	struct ttm_operation_ctx ctx = { false, false };
2455 	int i, ret;
2456 
2457 	pd_bo_list_entries = kcalloc(process_info->n_vms,
2458 				     sizeof(struct amdgpu_bo_list_entry),
2459 				     GFP_KERNEL);
2460 	if (!pd_bo_list_entries) {
2461 		pr_err("%s: Failed to allocate PD BO list entries\n", __func__);
2462 		ret = -ENOMEM;
2463 		goto out_no_mem;
2464 	}
2465 
2466 	INIT_LIST_HEAD(&resv_list);
2467 	INIT_LIST_HEAD(&duplicates);
2468 
2469 	/* Get all the page directory BOs that need to be reserved */
2470 	i = 0;
2471 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2472 			    vm_list_node)
2473 		amdgpu_vm_get_pd_bo(peer_vm, &resv_list,
2474 				    &pd_bo_list_entries[i++]);
2475 	/* Add the userptr_inval_list entries to resv_list */
2476 	list_for_each_entry(mem, &process_info->userptr_inval_list,
2477 			    validate_list.head) {
2478 		list_add_tail(&mem->resv_list.head, &resv_list);
2479 		mem->resv_list.bo = mem->validate_list.bo;
2480 		mem->resv_list.num_shared = mem->validate_list.num_shared;
2481 	}
2482 
2483 	/* Reserve all BOs and page tables for validation */
2484 	ret = ttm_eu_reserve_buffers(&ticket, &resv_list, false, &duplicates);
2485 	WARN(!list_empty(&duplicates), "Duplicates should be empty");
2486 	if (ret)
2487 		goto out_free;
2488 
2489 	amdgpu_sync_create(&sync);
2490 
2491 	ret = process_validate_vms(process_info);
2492 	if (ret)
2493 		goto unreserve_out;
2494 
2495 	/* Validate BOs and update GPUVM page tables */
2496 	list_for_each_entry_safe(mem, tmp_mem,
2497 				 &process_info->userptr_inval_list,
2498 				 validate_list.head) {
2499 		struct kfd_mem_attachment *attachment;
2500 
2501 		bo = mem->bo;
2502 
2503 		/* Validate the BO if we got user pages */
2504 		if (bo->tbo.ttm->pages[0]) {
2505 			amdgpu_bo_placement_from_domain(bo, mem->domain);
2506 			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2507 			if (ret) {
2508 				pr_err("%s: failed to validate BO\n", __func__);
2509 				goto unreserve_out;
2510 			}
2511 		}
2512 
2513 		list_move_tail(&mem->validate_list.head,
2514 			       &process_info->userptr_valid_list);
2515 
2516 		/* Update mapping. If the BO was not validated
2517 		 * (because we couldn't get user pages), this will
2518 		 * clear the page table entries, which will result in
2519 		 * VM faults if the GPU tries to access the invalid
2520 		 * memory.
2521 		 */
2522 		list_for_each_entry(attachment, &mem->attachments, list) {
2523 			if (!attachment->is_mapped)
2524 				continue;
2525 
2526 			kfd_mem_dmaunmap_attachment(mem, attachment);
2527 			ret = update_gpuvm_pte(mem, attachment, &sync);
2528 			if (ret) {
2529 				pr_err("%s: update PTE failed\n", __func__);
2530 				/* make sure this gets validated again */
2531 				atomic_inc(&mem->invalid);
2532 				goto unreserve_out;
2533 			}
2534 		}
2535 	}
2536 
2537 	/* Update page directories */
2538 	ret = process_update_pds(process_info, &sync);
2539 
2540 unreserve_out:
2541 	ttm_eu_backoff_reservation(&ticket, &resv_list);
2542 	amdgpu_sync_wait(&sync, false);
2543 	amdgpu_sync_free(&sync);
2544 out_free:
2545 	kfree(pd_bo_list_entries);
2546 out_no_mem:
2547 
2548 	return ret;
2549 }
2550 
2551 /* Worker callback to restore evicted userptr BOs
2552  *
2553  * Tries to update and validate all userptr BOs. If successful and no
2554  * concurrent evictions happened, the queues are restarted. Otherwise,
2555  * reschedule for another attempt later.
2556  */
amdgpu_amdkfd_restore_userptr_worker(struct work_struct * work)2557 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
2558 {
2559 	struct delayed_work *dwork = to_delayed_work(work);
2560 	struct amdkfd_process_info *process_info =
2561 		container_of(dwork, struct amdkfd_process_info,
2562 			     restore_userptr_work);
2563 	struct task_struct *usertask;
2564 	struct mm_struct *mm;
2565 	int evicted_bos;
2566 
2567 	evicted_bos = atomic_read(&process_info->evicted_bos);
2568 	if (!evicted_bos)
2569 		return;
2570 
2571 	/* Reference task and mm in case of concurrent process termination */
2572 	usertask = get_pid_task(process_info->pid, PIDTYPE_PID);
2573 	if (!usertask)
2574 		return;
2575 	mm = get_task_mm(usertask);
2576 	if (!mm) {
2577 		put_task_struct(usertask);
2578 		return;
2579 	}
2580 
2581 	mutex_lock(&process_info->lock);
2582 
2583 	if (update_invalid_user_pages(process_info, mm))
2584 		goto unlock_out;
2585 	/* userptr_inval_list can be empty if all evicted userptr BOs
2586 	 * have been freed. In that case there is nothing to validate
2587 	 * and we can just restart the queues.
2588 	 */
2589 	if (!list_empty(&process_info->userptr_inval_list)) {
2590 		if (atomic_read(&process_info->evicted_bos) != evicted_bos)
2591 			goto unlock_out; /* Concurrent eviction, try again */
2592 
2593 		if (validate_invalid_user_pages(process_info))
2594 			goto unlock_out;
2595 	}
2596 	/* Final check for concurrent evicton and atomic update. If
2597 	 * another eviction happens after successful update, it will
2598 	 * be a first eviction that calls quiesce_mm. The eviction
2599 	 * reference counting inside KFD will handle this case.
2600 	 */
2601 	if (atomic_cmpxchg(&process_info->evicted_bos, evicted_bos, 0) !=
2602 	    evicted_bos)
2603 		goto unlock_out;
2604 	evicted_bos = 0;
2605 	if (kgd2kfd_resume_mm(mm)) {
2606 		pr_err("%s: Failed to resume KFD\n", __func__);
2607 		/* No recovery from this failure. Probably the CP is
2608 		 * hanging. No point trying again.
2609 		 */
2610 	}
2611 
2612 unlock_out:
2613 	mutex_unlock(&process_info->lock);
2614 
2615 	/* If validation failed, reschedule another attempt */
2616 	if (evicted_bos) {
2617 		schedule_delayed_work(&process_info->restore_userptr_work,
2618 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2619 
2620 		kfd_smi_event_queue_restore_rescheduled(mm);
2621 	}
2622 	mmput(mm);
2623 	put_task_struct(usertask);
2624 }
2625 
2626 /** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given
2627  *   KFD process identified by process_info
2628  *
2629  * @process_info: amdkfd_process_info of the KFD process
2630  *
2631  * After memory eviction, restore thread calls this function. The function
2632  * should be called when the Process is still valid. BO restore involves -
2633  *
2634  * 1.  Release old eviction fence and create new one
2635  * 2.  Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.
2636  * 3   Use the second PD list and kfd_bo_list to create a list (ctx.list) of
2637  *     BOs that need to be reserved.
2638  * 4.  Reserve all the BOs
2639  * 5.  Validate of PD and PT BOs.
2640  * 6.  Validate all KFD BOs using kfd_bo_list and Map them and add new fence
2641  * 7.  Add fence to all PD and PT BOs.
2642  * 8.  Unreserve all BOs
2643  */
amdgpu_amdkfd_gpuvm_restore_process_bos(void * info,struct dma_fence ** ef)2644 int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence **ef)
2645 {
2646 	struct amdgpu_bo_list_entry *pd_bo_list;
2647 	struct amdkfd_process_info *process_info = info;
2648 	struct amdgpu_vm *peer_vm;
2649 	struct kgd_mem *mem;
2650 	struct bo_vm_reservation_context ctx;
2651 	struct amdgpu_amdkfd_fence *new_fence;
2652 	int ret = 0, i;
2653 	struct list_head duplicate_save;
2654 	struct amdgpu_sync sync_obj;
2655 	unsigned long failed_size = 0;
2656 	unsigned long total_size = 0;
2657 
2658 	INIT_LIST_HEAD(&duplicate_save);
2659 	INIT_LIST_HEAD(&ctx.list);
2660 	INIT_LIST_HEAD(&ctx.duplicates);
2661 
2662 	pd_bo_list = kcalloc(process_info->n_vms,
2663 			     sizeof(struct amdgpu_bo_list_entry),
2664 			     GFP_KERNEL);
2665 	if (!pd_bo_list)
2666 		return -ENOMEM;
2667 
2668 	i = 0;
2669 	mutex_lock(&process_info->lock);
2670 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2671 			vm_list_node)
2672 		amdgpu_vm_get_pd_bo(peer_vm, &ctx.list, &pd_bo_list[i++]);
2673 
2674 	/* Reserve all BOs and page tables/directory. Add all BOs from
2675 	 * kfd_bo_list to ctx.list
2676 	 */
2677 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2678 			    validate_list.head) {
2679 
2680 		list_add_tail(&mem->resv_list.head, &ctx.list);
2681 		mem->resv_list.bo = mem->validate_list.bo;
2682 		mem->resv_list.num_shared = mem->validate_list.num_shared;
2683 	}
2684 
2685 	ret = ttm_eu_reserve_buffers(&ctx.ticket, &ctx.list,
2686 				     false, &duplicate_save);
2687 	if (ret) {
2688 		pr_debug("Memory eviction: TTM Reserve Failed. Try again\n");
2689 		goto ttm_reserve_fail;
2690 	}
2691 
2692 	amdgpu_sync_create(&sync_obj);
2693 
2694 	/* Validate PDs and PTs */
2695 	ret = process_validate_vms(process_info);
2696 	if (ret)
2697 		goto validate_map_fail;
2698 
2699 	ret = process_sync_pds_resv(process_info, &sync_obj);
2700 	if (ret) {
2701 		pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");
2702 		goto validate_map_fail;
2703 	}
2704 
2705 	/* Validate BOs and map them to GPUVM (update VM page tables). */
2706 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2707 			    validate_list.head) {
2708 
2709 		struct amdgpu_bo *bo = mem->bo;
2710 		uint32_t domain = mem->domain;
2711 		struct kfd_mem_attachment *attachment;
2712 		struct dma_resv_iter cursor;
2713 		struct dma_fence *fence;
2714 
2715 		total_size += amdgpu_bo_size(bo);
2716 
2717 		ret = amdgpu_amdkfd_bo_validate(bo, domain, false);
2718 		if (ret) {
2719 			pr_debug("Memory eviction: Validate BOs failed\n");
2720 			failed_size += amdgpu_bo_size(bo);
2721 			ret = amdgpu_amdkfd_bo_validate(bo,
2722 						AMDGPU_GEM_DOMAIN_GTT, false);
2723 			if (ret) {
2724 				pr_debug("Memory eviction: Try again\n");
2725 				goto validate_map_fail;
2726 			}
2727 		}
2728 		dma_resv_for_each_fence(&cursor, bo->tbo.base.resv,
2729 					DMA_RESV_USAGE_KERNEL, fence) {
2730 			ret = amdgpu_sync_fence(&sync_obj, fence);
2731 			if (ret) {
2732 				pr_debug("Memory eviction: Sync BO fence failed. Try again\n");
2733 				goto validate_map_fail;
2734 			}
2735 		}
2736 		list_for_each_entry(attachment, &mem->attachments, list) {
2737 			if (!attachment->is_mapped)
2738 				continue;
2739 
2740 			if (attachment->bo_va->base.bo->tbo.pin_count)
2741 				continue;
2742 
2743 			kfd_mem_dmaunmap_attachment(mem, attachment);
2744 			ret = update_gpuvm_pte(mem, attachment, &sync_obj);
2745 			if (ret) {
2746 				pr_debug("Memory eviction: update PTE failed. Try again\n");
2747 				goto validate_map_fail;
2748 			}
2749 		}
2750 	}
2751 
2752 	if (failed_size)
2753 		pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size);
2754 
2755 	/* Update page directories */
2756 	ret = process_update_pds(process_info, &sync_obj);
2757 	if (ret) {
2758 		pr_debug("Memory eviction: update PDs failed. Try again\n");
2759 		goto validate_map_fail;
2760 	}
2761 
2762 	/* Wait for validate and PT updates to finish */
2763 	amdgpu_sync_wait(&sync_obj, false);
2764 
2765 	/* Release old eviction fence and create new one, because fence only
2766 	 * goes from unsignaled to signaled, fence cannot be reused.
2767 	 * Use context and mm from the old fence.
2768 	 */
2769 	new_fence = amdgpu_amdkfd_fence_create(
2770 				process_info->eviction_fence->base.context,
2771 				process_info->eviction_fence->mm,
2772 				NULL);
2773 	if (!new_fence) {
2774 		pr_err("Failed to create eviction fence\n");
2775 		ret = -ENOMEM;
2776 		goto validate_map_fail;
2777 	}
2778 	dma_fence_put(&process_info->eviction_fence->base);
2779 	process_info->eviction_fence = new_fence;
2780 	*ef = dma_fence_get(&new_fence->base);
2781 
2782 	/* Attach new eviction fence to all BOs except pinned ones */
2783 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2784 		validate_list.head) {
2785 		if (mem->bo->tbo.pin_count)
2786 			continue;
2787 
2788 		dma_resv_add_fence(mem->bo->tbo.base.resv,
2789 				   &process_info->eviction_fence->base,
2790 				   DMA_RESV_USAGE_BOOKKEEP);
2791 	}
2792 	/* Attach eviction fence to PD / PT BOs */
2793 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2794 			    vm_list_node) {
2795 		struct amdgpu_bo *bo = peer_vm->root.bo;
2796 
2797 		dma_resv_add_fence(bo->tbo.base.resv,
2798 				   &process_info->eviction_fence->base,
2799 				   DMA_RESV_USAGE_BOOKKEEP);
2800 	}
2801 
2802 validate_map_fail:
2803 	ttm_eu_backoff_reservation(&ctx.ticket, &ctx.list);
2804 	amdgpu_sync_free(&sync_obj);
2805 ttm_reserve_fail:
2806 	mutex_unlock(&process_info->lock);
2807 	kfree(pd_bo_list);
2808 	return ret;
2809 }
2810 
amdgpu_amdkfd_add_gws_to_process(void * info,void * gws,struct kgd_mem ** mem)2811 int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem)
2812 {
2813 	struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
2814 	struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws;
2815 	int ret;
2816 
2817 	if (!info || !gws)
2818 		return -EINVAL;
2819 
2820 	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
2821 	if (!*mem)
2822 		return -ENOMEM;
2823 
2824 	mutex_init(&(*mem)->lock);
2825 	INIT_LIST_HEAD(&(*mem)->attachments);
2826 	(*mem)->bo = amdgpu_bo_ref(gws_bo);
2827 	(*mem)->domain = AMDGPU_GEM_DOMAIN_GWS;
2828 	(*mem)->process_info = process_info;
2829 	add_kgd_mem_to_kfd_bo_list(*mem, process_info, false);
2830 	amdgpu_sync_create(&(*mem)->sync);
2831 
2832 
2833 	/* Validate gws bo the first time it is added to process */
2834 	mutex_lock(&(*mem)->process_info->lock);
2835 	ret = amdgpu_bo_reserve(gws_bo, false);
2836 	if (unlikely(ret)) {
2837 		pr_err("Reserve gws bo failed %d\n", ret);
2838 		goto bo_reservation_failure;
2839 	}
2840 
2841 	ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true);
2842 	if (ret) {
2843 		pr_err("GWS BO validate failed %d\n", ret);
2844 		goto bo_validation_failure;
2845 	}
2846 	/* GWS resource is shared b/t amdgpu and amdkfd
2847 	 * Add process eviction fence to bo so they can
2848 	 * evict each other.
2849 	 */
2850 	ret = dma_resv_reserve_fences(gws_bo->tbo.base.resv, 1);
2851 	if (ret)
2852 		goto reserve_shared_fail;
2853 	dma_resv_add_fence(gws_bo->tbo.base.resv,
2854 			   &process_info->eviction_fence->base,
2855 			   DMA_RESV_USAGE_BOOKKEEP);
2856 	amdgpu_bo_unreserve(gws_bo);
2857 	mutex_unlock(&(*mem)->process_info->lock);
2858 
2859 	return ret;
2860 
2861 reserve_shared_fail:
2862 bo_validation_failure:
2863 	amdgpu_bo_unreserve(gws_bo);
2864 bo_reservation_failure:
2865 	mutex_unlock(&(*mem)->process_info->lock);
2866 	amdgpu_sync_free(&(*mem)->sync);
2867 	remove_kgd_mem_from_kfd_bo_list(*mem, process_info);
2868 	amdgpu_bo_unref(&gws_bo);
2869 	mutex_destroy(&(*mem)->lock);
2870 	kfree(*mem);
2871 	*mem = NULL;
2872 	return ret;
2873 }
2874 
amdgpu_amdkfd_remove_gws_from_process(void * info,void * mem)2875 int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem)
2876 {
2877 	int ret;
2878 	struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
2879 	struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;
2880 	struct amdgpu_bo *gws_bo = kgd_mem->bo;
2881 
2882 	/* Remove BO from process's validate list so restore worker won't touch
2883 	 * it anymore
2884 	 */
2885 	remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info);
2886 
2887 	ret = amdgpu_bo_reserve(gws_bo, false);
2888 	if (unlikely(ret)) {
2889 		pr_err("Reserve gws bo failed %d\n", ret);
2890 		//TODO add BO back to validate_list?
2891 		return ret;
2892 	}
2893 	amdgpu_amdkfd_remove_eviction_fence(gws_bo,
2894 			process_info->eviction_fence);
2895 	amdgpu_bo_unreserve(gws_bo);
2896 	amdgpu_sync_free(&kgd_mem->sync);
2897 	amdgpu_bo_unref(&gws_bo);
2898 	mutex_destroy(&kgd_mem->lock);
2899 	kfree(mem);
2900 	return 0;
2901 }
2902 
2903 /* Returns GPU-specific tiling mode information */
amdgpu_amdkfd_get_tile_config(struct amdgpu_device * adev,struct tile_config * config)2904 int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev,
2905 				struct tile_config *config)
2906 {
2907 	config->gb_addr_config = adev->gfx.config.gb_addr_config;
2908 	config->tile_config_ptr = adev->gfx.config.tile_mode_array;
2909 	config->num_tile_configs =
2910 			ARRAY_SIZE(adev->gfx.config.tile_mode_array);
2911 	config->macro_tile_config_ptr =
2912 			adev->gfx.config.macrotile_mode_array;
2913 	config->num_macro_tile_configs =
2914 			ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);
2915 
2916 	/* Those values are not set from GFX9 onwards */
2917 	config->num_banks = adev->gfx.config.num_banks;
2918 	config->num_ranks = adev->gfx.config.num_ranks;
2919 
2920 	return 0;
2921 }
2922 
amdgpu_amdkfd_bo_mapped_to_dev(struct amdgpu_device * adev,struct kgd_mem * mem)2923 bool amdgpu_amdkfd_bo_mapped_to_dev(struct amdgpu_device *adev, struct kgd_mem *mem)
2924 {
2925 	struct kfd_mem_attachment *entry;
2926 
2927 	list_for_each_entry(entry, &mem->attachments, list) {
2928 		if (entry->is_mapped && entry->adev == adev)
2929 			return true;
2930 	}
2931 	return false;
2932 }
2933 
2934 #if defined(CONFIG_DEBUG_FS)
2935 
kfd_debugfs_kfd_mem_limits(struct seq_file * m,void * data)2936 int kfd_debugfs_kfd_mem_limits(struct seq_file *m, void *data)
2937 {
2938 
2939 	spin_lock(&kfd_mem_limit.mem_limit_lock);
2940 	seq_printf(m, "System mem used %lldM out of %lluM\n",
2941 		  (kfd_mem_limit.system_mem_used >> 20),
2942 		  (kfd_mem_limit.max_system_mem_limit >> 20));
2943 	seq_printf(m, "TTM mem used %lldM out of %lluM\n",
2944 		  (kfd_mem_limit.ttm_mem_used >> 20),
2945 		  (kfd_mem_limit.max_ttm_mem_limit >> 20));
2946 	spin_unlock(&kfd_mem_limit.mem_limit_lock);
2947 
2948 	return 0;
2949 }
2950 
2951 #endif
2952