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