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