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