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