1 // SPDX-License-Identifier: MIT
3 * Copyright 2014-2018 Advanced Micro Devices, Inc.
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
23 #include <linux/dma-buf.h>
24 #include <linux/list.h>
25 #include <linux/pagemap.h>
26 #include <linux/sched/mm.h>
27 #include <linux/sched/task.h>
28 #include <linux/fdtable.h>
29 #include <drm/ttm/ttm_tt.h>
31 #include <drm/drm_exec.h>
33 #include "amdgpu_object.h"
34 #include "amdgpu_gem.h"
35 #include "amdgpu_vm.h"
36 #include "amdgpu_hmm.h"
37 #include "amdgpu_amdkfd.h"
38 #include "amdgpu_dma_buf.h"
39 #include <uapi/linux/kfd_ioctl.h>
40 #include "amdgpu_xgmi.h"
42 #include "kfd_smi_events.h"
44 /* Userptr restore delay, just long enough to allow consecutive VM
45 * changes to accumulate
47 #define AMDGPU_USERPTR_RESTORE_DELAY_MS 1
48 #define AMDGPU_RESERVE_MEM_LIMIT (3UL << 29)
51 * Align VRAM availability to 2MB to avoid fragmentation caused by 4K allocations in the tail 2MB
54 #define VRAM_AVAILABLITY_ALIGN (1 << 21)
56 /* Impose limit on how much memory KFD can use */
58 uint64_t max_system_mem_limit;
59 uint64_t max_ttm_mem_limit;
60 int64_t system_mem_used;
62 spinlock_t mem_limit_lock;
65 static const char * const domain_bit_to_string[] = {
74 #define domain_string(domain) domain_bit_to_string[ffs(domain)-1]
76 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work);
78 static bool kfd_mem_is_attached(struct amdgpu_vm *avm,
81 struct kfd_mem_attachment *entry;
83 list_for_each_entry(entry, &mem->attachments, list)
84 if (entry->bo_va->base.vm == avm)
91 * reuse_dmamap() - Check whether adev can share the original
94 * If both adev and bo_adev are in direct mapping or
95 * in the same iommu group, they can share the original BO.
97 * @adev: Device to which can or cannot share the original BO
98 * @bo_adev: Device to which allocated BO belongs to
100 * Return: returns true if adev can share original userptr BO,
103 static bool reuse_dmamap(struct amdgpu_device *adev, struct amdgpu_device *bo_adev)
105 return (adev->ram_is_direct_mapped && bo_adev->ram_is_direct_mapped) ||
106 (adev->dev->iommu_group == bo_adev->dev->iommu_group);
109 /* Set memory usage limits. Current, limits are
110 * System (TTM + userptr) memory - 15/16th System RAM
111 * TTM memory - 3/8th System RAM
113 void amdgpu_amdkfd_gpuvm_init_mem_limits(void)
118 if (kfd_mem_limit.max_system_mem_limit)
122 mem = si.totalram - si.totalhigh;
125 spin_lock_init(&kfd_mem_limit.mem_limit_lock);
126 kfd_mem_limit.max_system_mem_limit = mem - (mem >> 6);
127 if (kfd_mem_limit.max_system_mem_limit < 2 * AMDGPU_RESERVE_MEM_LIMIT)
128 kfd_mem_limit.max_system_mem_limit >>= 1;
130 kfd_mem_limit.max_system_mem_limit -= AMDGPU_RESERVE_MEM_LIMIT;
132 kfd_mem_limit.max_ttm_mem_limit = ttm_tt_pages_limit() << PAGE_SHIFT;
133 pr_debug("Kernel memory limit %lluM, TTM limit %lluM\n",
134 (kfd_mem_limit.max_system_mem_limit >> 20),
135 (kfd_mem_limit.max_ttm_mem_limit >> 20));
138 void amdgpu_amdkfd_reserve_system_mem(uint64_t size)
140 kfd_mem_limit.system_mem_used += size;
143 /* Estimate page table size needed to represent a given memory size
145 * With 4KB pages, we need one 8 byte PTE for each 4KB of memory
146 * (factor 512, >> 9). With 2MB pages, we need one 8 byte PTE for 2MB
147 * of memory (factor 256K, >> 18). ROCm user mode tries to optimize
148 * for 2MB pages for TLB efficiency. However, small allocations and
149 * fragmented system memory still need some 4KB pages. We choose a
150 * compromise that should work in most cases without reserving too
151 * much memory for page tables unnecessarily (factor 16K, >> 14).
154 #define ESTIMATE_PT_SIZE(mem_size) max(((mem_size) >> 14), AMDGPU_VM_RESERVED_VRAM)
157 * amdgpu_amdkfd_reserve_mem_limit() - Decrease available memory by size
160 * @adev: Device to which allocated BO belongs to
161 * @size: Size of buffer, in bytes, encapsulated by B0. This should be
162 * equivalent to amdgpu_bo_size(BO)
163 * @alloc_flag: Flag used in allocating a BO as noted above
164 * @xcp_id: xcp_id is used to get xcp from xcp manager, one xcp is
165 * managed as one compute node in driver for app
168 * returns -ENOMEM in case of error, ZERO otherwise
170 int amdgpu_amdkfd_reserve_mem_limit(struct amdgpu_device *adev,
171 uint64_t size, u32 alloc_flag, int8_t xcp_id)
173 uint64_t reserved_for_pt =
174 ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);
175 size_t system_mem_needed, ttm_mem_needed, vram_needed;
177 uint64_t vram_size = 0;
179 system_mem_needed = 0;
182 if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
183 system_mem_needed = size;
184 ttm_mem_needed = size;
185 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
187 * Conservatively round up the allocation requirement to 2 MB
188 * to avoid fragmentation caused by 4K allocations in the tail
193 * For GFX 9.4.3, get the VRAM size from XCP structs
195 if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id))
198 vram_size = KFD_XCP_MEMORY_SIZE(adev, xcp_id);
199 if (adev->gmc.is_app_apu || adev->flags & AMD_IS_APU) {
200 system_mem_needed = size;
201 ttm_mem_needed = size;
203 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
204 system_mem_needed = size;
205 } else if (!(alloc_flag &
206 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
207 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {
208 pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
212 spin_lock(&kfd_mem_limit.mem_limit_lock);
214 if (kfd_mem_limit.system_mem_used + system_mem_needed >
215 kfd_mem_limit.max_system_mem_limit)
216 pr_debug("Set no_system_mem_limit=1 if using shared memory\n");
218 if ((kfd_mem_limit.system_mem_used + system_mem_needed >
219 kfd_mem_limit.max_system_mem_limit && !no_system_mem_limit) ||
220 (kfd_mem_limit.ttm_mem_used + ttm_mem_needed >
221 kfd_mem_limit.max_ttm_mem_limit) ||
222 (adev && xcp_id >= 0 && adev->kfd.vram_used[xcp_id] + vram_needed >
223 vram_size - reserved_for_pt - atomic64_read(&adev->vram_pin_size))) {
228 /* Update memory accounting by decreasing available system
229 * memory, TTM memory and GPU memory as computed above
231 WARN_ONCE(vram_needed && !adev,
232 "adev reference can't be null when vram is used");
233 if (adev && xcp_id >= 0) {
234 adev->kfd.vram_used[xcp_id] += vram_needed;
235 adev->kfd.vram_used_aligned[xcp_id] +=
236 (adev->gmc.is_app_apu || adev->flags & AMD_IS_APU) ?
238 ALIGN(vram_needed, VRAM_AVAILABLITY_ALIGN);
240 kfd_mem_limit.system_mem_used += system_mem_needed;
241 kfd_mem_limit.ttm_mem_used += ttm_mem_needed;
244 spin_unlock(&kfd_mem_limit.mem_limit_lock);
248 void amdgpu_amdkfd_unreserve_mem_limit(struct amdgpu_device *adev,
249 uint64_t size, u32 alloc_flag, int8_t xcp_id)
251 spin_lock(&kfd_mem_limit.mem_limit_lock);
253 if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
254 kfd_mem_limit.system_mem_used -= size;
255 kfd_mem_limit.ttm_mem_used -= size;
256 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
258 "adev reference can't be null when alloc mem flags vram is set");
259 if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id))
263 adev->kfd.vram_used[xcp_id] -= size;
264 if (adev->gmc.is_app_apu || adev->flags & AMD_IS_APU) {
265 adev->kfd.vram_used_aligned[xcp_id] -= size;
266 kfd_mem_limit.system_mem_used -= size;
267 kfd_mem_limit.ttm_mem_used -= size;
269 adev->kfd.vram_used_aligned[xcp_id] -=
270 ALIGN(size, VRAM_AVAILABLITY_ALIGN);
273 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
274 kfd_mem_limit.system_mem_used -= size;
275 } else if (!(alloc_flag &
276 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
277 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {
278 pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
281 WARN_ONCE(adev && xcp_id >= 0 && adev->kfd.vram_used[xcp_id] < 0,
282 "KFD VRAM memory accounting unbalanced for xcp: %d", xcp_id);
283 WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0,
284 "KFD TTM memory accounting unbalanced");
285 WARN_ONCE(kfd_mem_limit.system_mem_used < 0,
286 "KFD system memory accounting unbalanced");
289 spin_unlock(&kfd_mem_limit.mem_limit_lock);
292 void amdgpu_amdkfd_release_notify(struct amdgpu_bo *bo)
294 struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
295 u32 alloc_flags = bo->kfd_bo->alloc_flags;
296 u64 size = amdgpu_bo_size(bo);
298 amdgpu_amdkfd_unreserve_mem_limit(adev, size, alloc_flags,
305 * create_dmamap_sg_bo() - Creates a amdgpu_bo object to reflect information
306 * about USERPTR or DOOREBELL or MMIO BO.
308 * @adev: Device for which dmamap BO is being created
309 * @mem: BO of peer device that is being DMA mapped. Provides parameters
310 * in building the dmamap BO
311 * @bo_out: Output parameter updated with handle of dmamap BO
314 create_dmamap_sg_bo(struct amdgpu_device *adev,
315 struct kgd_mem *mem, struct amdgpu_bo **bo_out)
317 struct drm_gem_object *gem_obj;
321 ret = amdgpu_bo_reserve(mem->bo, false);
325 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR)
326 flags |= mem->bo->flags & (AMDGPU_GEM_CREATE_COHERENT |
327 AMDGPU_GEM_CREATE_UNCACHED);
329 ret = amdgpu_gem_object_create(adev, mem->bo->tbo.base.size, 1,
330 AMDGPU_GEM_DOMAIN_CPU, AMDGPU_GEM_CREATE_PREEMPTIBLE | flags,
331 ttm_bo_type_sg, mem->bo->tbo.base.resv, &gem_obj, 0);
333 amdgpu_bo_unreserve(mem->bo);
336 pr_err("Error in creating DMA mappable SG BO on domain: %d\n", ret);
340 *bo_out = gem_to_amdgpu_bo(gem_obj);
341 (*bo_out)->parent = amdgpu_bo_ref(mem->bo);
345 /* amdgpu_amdkfd_remove_eviction_fence - Removes eviction fence from BO's
346 * reservation object.
348 * @bo: [IN] Remove eviction fence(s) from this BO
349 * @ef: [IN] This eviction fence is removed if it
350 * is present in the shared list.
352 * NOTE: Must be called with BO reserved i.e. bo->tbo.resv->lock held.
354 static int amdgpu_amdkfd_remove_eviction_fence(struct amdgpu_bo *bo,
355 struct amdgpu_amdkfd_fence *ef)
357 struct dma_fence *replacement;
362 /* TODO: Instead of block before we should use the fence of the page
363 * table update and TLB flush here directly.
365 replacement = dma_fence_get_stub();
366 dma_resv_replace_fences(bo->tbo.base.resv, ef->base.context,
367 replacement, DMA_RESV_USAGE_BOOKKEEP);
368 dma_fence_put(replacement);
372 int amdgpu_amdkfd_remove_fence_on_pt_pd_bos(struct amdgpu_bo *bo)
374 struct amdgpu_bo *root = bo;
375 struct amdgpu_vm_bo_base *vm_bo;
376 struct amdgpu_vm *vm;
377 struct amdkfd_process_info *info;
378 struct amdgpu_amdkfd_fence *ef;
381 /* we can always get vm_bo from root PD bo.*/
393 info = vm->process_info;
394 if (!info || !info->eviction_fence)
397 ef = container_of(dma_fence_get(&info->eviction_fence->base),
398 struct amdgpu_amdkfd_fence, base);
400 BUG_ON(!dma_resv_trylock(bo->tbo.base.resv));
401 ret = amdgpu_amdkfd_remove_eviction_fence(bo, ef);
402 dma_resv_unlock(bo->tbo.base.resv);
404 dma_fence_put(&ef->base);
408 static int amdgpu_amdkfd_bo_validate(struct amdgpu_bo *bo, uint32_t domain,
411 struct ttm_operation_ctx ctx = { false, false };
414 if (WARN(amdgpu_ttm_tt_get_usermm(bo->tbo.ttm),
415 "Called with userptr BO"))
418 amdgpu_bo_placement_from_domain(bo, domain);
420 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
424 amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
430 int amdgpu_amdkfd_bo_validate_and_fence(struct amdgpu_bo *bo,
432 struct dma_fence *fence)
434 int ret = amdgpu_bo_reserve(bo, false);
439 ret = amdgpu_amdkfd_bo_validate(bo, domain, true);
443 ret = dma_resv_reserve_fences(bo->tbo.base.resv, 1);
447 dma_resv_add_fence(bo->tbo.base.resv, fence,
448 DMA_RESV_USAGE_BOOKKEEP);
451 amdgpu_bo_unreserve(bo);
456 static int amdgpu_amdkfd_validate_vm_bo(void *_unused, struct amdgpu_bo *bo)
458 return amdgpu_amdkfd_bo_validate(bo, bo->allowed_domains, false);
461 /* vm_validate_pt_pd_bos - Validate page table and directory BOs
463 * Page directories are not updated here because huge page handling
464 * during page table updates can invalidate page directory entries
465 * again. Page directories are only updated after updating page
468 static int vm_validate_pt_pd_bos(struct amdgpu_vm *vm,
469 struct ww_acquire_ctx *ticket)
471 struct amdgpu_bo *pd = vm->root.bo;
472 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
475 ret = amdgpu_vm_validate(adev, vm, ticket,
476 amdgpu_amdkfd_validate_vm_bo, NULL);
478 pr_err("failed to validate PT BOs\n");
482 vm->pd_phys_addr = amdgpu_gmc_pd_addr(vm->root.bo);
487 static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync)
489 struct amdgpu_bo *pd = vm->root.bo;
490 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
493 ret = amdgpu_vm_update_pdes(adev, vm, false);
497 return amdgpu_sync_fence(sync, vm->last_update);
500 static uint64_t get_pte_flags(struct amdgpu_device *adev, struct kgd_mem *mem)
502 uint32_t mapping_flags = AMDGPU_VM_PAGE_READABLE |
503 AMDGPU_VM_MTYPE_DEFAULT;
505 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE)
506 mapping_flags |= AMDGPU_VM_PAGE_WRITEABLE;
507 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE)
508 mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE;
510 return amdgpu_gem_va_map_flags(adev, mapping_flags);
514 * create_sg_table() - Create an sg_table for a contiguous DMA addr range
515 * @addr: The starting address to point to
516 * @size: Size of memory area in bytes being pointed to
518 * Allocates an instance of sg_table and initializes it to point to memory
519 * area specified by input parameters. The address used to build is assumed
520 * to be DMA mapped, if needed.
522 * DOORBELL or MMIO BOs use only one scatterlist node in their sg_table
523 * because they are physically contiguous.
525 * Return: Initialized instance of SG Table or NULL
527 static struct sg_table *create_sg_table(uint64_t addr, uint32_t size)
529 struct sg_table *sg = kmalloc(sizeof(*sg), GFP_KERNEL);
533 if (sg_alloc_table(sg, 1, GFP_KERNEL)) {
537 sg_dma_address(sg->sgl) = addr;
538 sg->sgl->length = size;
539 #ifdef CONFIG_NEED_SG_DMA_LENGTH
540 sg->sgl->dma_length = size;
546 kfd_mem_dmamap_userptr(struct kgd_mem *mem,
547 struct kfd_mem_attachment *attachment)
549 enum dma_data_direction direction =
550 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
551 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
552 struct ttm_operation_ctx ctx = {.interruptible = true};
553 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
554 struct amdgpu_device *adev = attachment->adev;
555 struct ttm_tt *src_ttm = mem->bo->tbo.ttm;
556 struct ttm_tt *ttm = bo->tbo.ttm;
559 if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
562 ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL);
563 if (unlikely(!ttm->sg))
566 /* Same sequence as in amdgpu_ttm_tt_pin_userptr */
567 ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages,
569 (u64)ttm->num_pages << PAGE_SHIFT,
574 ret = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
578 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
579 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
586 dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
588 pr_err("DMA map userptr failed: %d\n", ret);
589 sg_free_table(ttm->sg);
597 kfd_mem_dmamap_dmabuf(struct kfd_mem_attachment *attachment)
599 struct ttm_operation_ctx ctx = {.interruptible = true};
600 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
603 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
604 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
608 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
609 return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
613 * kfd_mem_dmamap_sg_bo() - Create DMA mapped sg_table to access DOORBELL or MMIO BO
614 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device
615 * @attachment: Virtual address attachment of the BO on accessing device
617 * An access request from the device that owns DOORBELL does not require DMA mapping.
618 * This is because the request doesn't go through PCIe root complex i.e. it instead
619 * loops back. The need to DMA map arises only when accessing peer device's DOORBELL
621 * In contrast, all access requests for MMIO need to be DMA mapped without regard to
622 * device ownership. This is because access requests for MMIO go through PCIe root
625 * This is accomplished in two steps:
626 * - Obtain DMA mapped address of DOORBELL or MMIO memory that could be used
627 * in updating requesting device's page table
628 * - Signal TTM to mark memory pointed to by requesting device's BO as GPU
629 * accessible. This allows an update of requesting device's page table
630 * with entries associated with DOOREBELL or MMIO memory
632 * This method is invoked in the following contexts:
633 * - Mapping of DOORBELL or MMIO BO of same or peer device
634 * - Validating an evicted DOOREBELL or MMIO BO on device seeking access
636 * Return: ZERO if successful, NON-ZERO otherwise
639 kfd_mem_dmamap_sg_bo(struct kgd_mem *mem,
640 struct kfd_mem_attachment *attachment)
642 struct ttm_operation_ctx ctx = {.interruptible = true};
643 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
644 struct amdgpu_device *adev = attachment->adev;
645 struct ttm_tt *ttm = bo->tbo.ttm;
646 enum dma_data_direction dir;
651 /* Expect SG Table of dmapmap BO to be NULL */
652 mmio = (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP);
653 if (unlikely(ttm->sg)) {
654 pr_err("SG Table of %d BO for peer device is UNEXPECTEDLY NON-NULL", mmio);
658 dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
659 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
660 dma_addr = mem->bo->tbo.sg->sgl->dma_address;
661 pr_debug("%d BO size: %d\n", mmio, mem->bo->tbo.sg->sgl->length);
662 pr_debug("%d BO address before DMA mapping: %llx\n", mmio, dma_addr);
663 dma_addr = dma_map_resource(adev->dev, dma_addr,
664 mem->bo->tbo.sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);
665 ret = dma_mapping_error(adev->dev, dma_addr);
668 pr_debug("%d BO address after DMA mapping: %llx\n", mmio, dma_addr);
670 ttm->sg = create_sg_table(dma_addr, mem->bo->tbo.sg->sgl->length);
671 if (unlikely(!ttm->sg)) {
676 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
677 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
684 sg_free_table(ttm->sg);
688 dma_unmap_resource(adev->dev, dma_addr, mem->bo->tbo.sg->sgl->length,
689 dir, DMA_ATTR_SKIP_CPU_SYNC);
694 kfd_mem_dmamap_attachment(struct kgd_mem *mem,
695 struct kfd_mem_attachment *attachment)
697 switch (attachment->type) {
698 case KFD_MEM_ATT_SHARED:
700 case KFD_MEM_ATT_USERPTR:
701 return kfd_mem_dmamap_userptr(mem, attachment);
702 case KFD_MEM_ATT_DMABUF:
703 return kfd_mem_dmamap_dmabuf(attachment);
705 return kfd_mem_dmamap_sg_bo(mem, attachment);
713 kfd_mem_dmaunmap_userptr(struct kgd_mem *mem,
714 struct kfd_mem_attachment *attachment)
716 enum dma_data_direction direction =
717 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
718 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
719 struct ttm_operation_ctx ctx = {.interruptible = false};
720 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
721 struct amdgpu_device *adev = attachment->adev;
722 struct ttm_tt *ttm = bo->tbo.ttm;
724 if (unlikely(!ttm->sg))
727 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
728 ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
730 dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
731 sg_free_table(ttm->sg);
737 kfd_mem_dmaunmap_dmabuf(struct kfd_mem_attachment *attachment)
739 /* This is a no-op. We don't want to trigger eviction fences when
740 * unmapping DMABufs. Therefore the invalidation (moving to system
741 * domain) is done in kfd_mem_dmamap_dmabuf.
746 * kfd_mem_dmaunmap_sg_bo() - Free DMA mapped sg_table of DOORBELL or MMIO BO
747 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device
748 * @attachment: Virtual address attachment of the BO on accessing device
750 * The method performs following steps:
751 * - Signal TTM to mark memory pointed to by BO as GPU inaccessible
752 * - Free SG Table that is used to encapsulate DMA mapped memory of
753 * peer device's DOORBELL or MMIO memory
755 * This method is invoked in the following contexts:
756 * UNMapping of DOORBELL or MMIO BO on a device having access to its memory
757 * Eviction of DOOREBELL or MMIO BO on device having access to its memory
762 kfd_mem_dmaunmap_sg_bo(struct kgd_mem *mem,
763 struct kfd_mem_attachment *attachment)
765 struct ttm_operation_ctx ctx = {.interruptible = true};
766 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
767 struct amdgpu_device *adev = attachment->adev;
768 struct ttm_tt *ttm = bo->tbo.ttm;
769 enum dma_data_direction dir;
771 if (unlikely(!ttm->sg)) {
772 pr_debug("SG Table of BO is NULL");
776 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
777 ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
779 dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
780 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
781 dma_unmap_resource(adev->dev, ttm->sg->sgl->dma_address,
782 ttm->sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);
783 sg_free_table(ttm->sg);
790 kfd_mem_dmaunmap_attachment(struct kgd_mem *mem,
791 struct kfd_mem_attachment *attachment)
793 switch (attachment->type) {
794 case KFD_MEM_ATT_SHARED:
796 case KFD_MEM_ATT_USERPTR:
797 kfd_mem_dmaunmap_userptr(mem, attachment);
799 case KFD_MEM_ATT_DMABUF:
800 kfd_mem_dmaunmap_dmabuf(attachment);
803 kfd_mem_dmaunmap_sg_bo(mem, attachment);
810 static int kfd_mem_export_dmabuf(struct kgd_mem *mem)
813 struct amdgpu_device *bo_adev;
814 struct dma_buf *dmabuf;
817 bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);
818 r = drm_gem_prime_handle_to_fd(&bo_adev->ddev, bo_adev->kfd.client.file,
820 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
824 dmabuf = dma_buf_get(fd);
826 if (WARN_ON_ONCE(IS_ERR(dmabuf)))
827 return PTR_ERR(dmabuf);
828 mem->dmabuf = dmabuf;
835 kfd_mem_attach_dmabuf(struct amdgpu_device *adev, struct kgd_mem *mem,
836 struct amdgpu_bo **bo)
838 struct drm_gem_object *gobj;
841 ret = kfd_mem_export_dmabuf(mem);
845 gobj = amdgpu_gem_prime_import(adev_to_drm(adev), mem->dmabuf);
847 return PTR_ERR(gobj);
849 *bo = gem_to_amdgpu_bo(gobj);
850 (*bo)->flags |= AMDGPU_GEM_CREATE_PREEMPTIBLE;
855 /* kfd_mem_attach - Add a BO to a VM
857 * Everything that needs to bo done only once when a BO is first added
858 * to a VM. It can later be mapped and unmapped many times without
859 * repeating these steps.
861 * 0. Create BO for DMA mapping, if needed
862 * 1. Allocate and initialize BO VA entry data structure
863 * 2. Add BO to the VM
864 * 3. Determine ASIC-specific PTE flags
865 * 4. Alloc page tables and directories if needed
866 * 4a. Validate new page tables and directories
868 static int kfd_mem_attach(struct amdgpu_device *adev, struct kgd_mem *mem,
869 struct amdgpu_vm *vm, bool is_aql)
871 struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);
872 unsigned long bo_size = mem->bo->tbo.base.size;
873 uint64_t va = mem->va;
874 struct kfd_mem_attachment *attachment[2] = {NULL, NULL};
875 struct amdgpu_bo *bo[2] = {NULL, NULL};
876 struct amdgpu_bo_va *bo_va;
877 bool same_hive = false;
881 pr_err("Invalid VA when adding BO to VM\n");
885 /* Determine access to VRAM, MMIO and DOORBELL BOs of peer devices
887 * The access path of MMIO and DOORBELL BOs of is always over PCIe.
888 * In contrast the access path of VRAM BOs depens upon the type of
889 * link that connects the peer device. Access over PCIe is allowed
890 * if peer device has large BAR. In contrast, access over xGMI is
891 * allowed for both small and large BAR configurations of peer device
893 if ((adev != bo_adev && !(adev->gmc.is_app_apu || adev->flags & AMD_IS_APU)) &&
894 ((mem->domain == AMDGPU_GEM_DOMAIN_VRAM) ||
895 (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) ||
896 (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {
897 if (mem->domain == AMDGPU_GEM_DOMAIN_VRAM)
898 same_hive = amdgpu_xgmi_same_hive(adev, bo_adev);
899 if (!same_hive && !amdgpu_device_is_peer_accessible(bo_adev, adev))
903 for (i = 0; i <= is_aql; i++) {
904 attachment[i] = kzalloc(sizeof(*attachment[i]), GFP_KERNEL);
905 if (unlikely(!attachment[i])) {
910 pr_debug("\t add VA 0x%llx - 0x%llx to vm %p\n", va,
913 if ((adev == bo_adev && !(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) ||
914 (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) && reuse_dmamap(adev, bo_adev)) ||
915 (mem->domain == AMDGPU_GEM_DOMAIN_GTT && reuse_dmamap(adev, bo_adev)) ||
917 /* Mappings on the local GPU, or VRAM mappings in the
918 * local hive, or userptr, or GTT mapping can reuse dma map
919 * address space share the original BO
921 attachment[i]->type = KFD_MEM_ATT_SHARED;
923 drm_gem_object_get(&bo[i]->tbo.base);
925 /* Multiple mappings on the same GPU share the BO */
926 attachment[i]->type = KFD_MEM_ATT_SHARED;
928 drm_gem_object_get(&bo[i]->tbo.base);
929 } else if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {
930 /* Create an SG BO to DMA-map userptrs on other GPUs */
931 attachment[i]->type = KFD_MEM_ATT_USERPTR;
932 ret = create_dmamap_sg_bo(adev, mem, &bo[i]);
935 /* Handle DOORBELL BOs of peer devices and MMIO BOs of local and peer devices */
936 } else if (mem->bo->tbo.type == ttm_bo_type_sg) {
937 WARN_ONCE(!(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL ||
938 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP),
939 "Handing invalid SG BO in ATTACH request");
940 attachment[i]->type = KFD_MEM_ATT_SG;
941 ret = create_dmamap_sg_bo(adev, mem, &bo[i]);
944 /* Enable acces to GTT and VRAM BOs of peer devices */
945 } else if (mem->domain == AMDGPU_GEM_DOMAIN_GTT ||
946 mem->domain == AMDGPU_GEM_DOMAIN_VRAM) {
947 attachment[i]->type = KFD_MEM_ATT_DMABUF;
948 ret = kfd_mem_attach_dmabuf(adev, mem, &bo[i]);
951 pr_debug("Employ DMABUF mechanism to enable peer GPU access\n");
953 WARN_ONCE(true, "Handling invalid ATTACH request");
958 /* Add BO to VM internal data structures */
959 ret = amdgpu_bo_reserve(bo[i], false);
961 pr_debug("Unable to reserve BO during memory attach");
964 bo_va = amdgpu_vm_bo_find(vm, bo[i]);
966 bo_va = amdgpu_vm_bo_add(adev, vm, bo[i]);
969 attachment[i]->bo_va = bo_va;
970 amdgpu_bo_unreserve(bo[i]);
971 if (unlikely(!attachment[i]->bo_va)) {
973 pr_err("Failed to add BO object to VM. ret == %d\n",
977 attachment[i]->va = va;
978 attachment[i]->pte_flags = get_pte_flags(adev, mem);
979 attachment[i]->adev = adev;
980 list_add(&attachment[i]->list, &mem->attachments);
988 for (; i >= 0; i--) {
991 if (attachment[i]->bo_va) {
992 amdgpu_bo_reserve(bo[i], true);
993 if (--attachment[i]->bo_va->ref_count == 0)
994 amdgpu_vm_bo_del(adev, attachment[i]->bo_va);
995 amdgpu_bo_unreserve(bo[i]);
996 list_del(&attachment[i]->list);
999 drm_gem_object_put(&bo[i]->tbo.base);
1000 kfree(attachment[i]);
1005 static void kfd_mem_detach(struct kfd_mem_attachment *attachment)
1007 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
1009 pr_debug("\t remove VA 0x%llx in entry %p\n",
1010 attachment->va, attachment);
1011 if (--attachment->bo_va->ref_count == 0)
1012 amdgpu_vm_bo_del(attachment->adev, attachment->bo_va);
1013 drm_gem_object_put(&bo->tbo.base);
1014 list_del(&attachment->list);
1018 static void add_kgd_mem_to_kfd_bo_list(struct kgd_mem *mem,
1019 struct amdkfd_process_info *process_info,
1022 mutex_lock(&process_info->lock);
1024 list_add_tail(&mem->validate_list,
1025 &process_info->userptr_valid_list);
1027 list_add_tail(&mem->validate_list, &process_info->kfd_bo_list);
1028 mutex_unlock(&process_info->lock);
1031 static void remove_kgd_mem_from_kfd_bo_list(struct kgd_mem *mem,
1032 struct amdkfd_process_info *process_info)
1034 mutex_lock(&process_info->lock);
1035 list_del(&mem->validate_list);
1036 mutex_unlock(&process_info->lock);
1039 /* Initializes user pages. It registers the MMU notifier and validates
1040 * the userptr BO in the GTT domain.
1042 * The BO must already be on the userptr_valid_list. Otherwise an
1043 * eviction and restore may happen that leaves the new BO unmapped
1044 * with the user mode queues running.
1046 * Takes the process_info->lock to protect against concurrent restore
1049 * Returns 0 for success, negative errno for errors.
1051 static int init_user_pages(struct kgd_mem *mem, uint64_t user_addr,
1054 struct amdkfd_process_info *process_info = mem->process_info;
1055 struct amdgpu_bo *bo = mem->bo;
1056 struct ttm_operation_ctx ctx = { true, false };
1057 struct hmm_range *range;
1060 mutex_lock(&process_info->lock);
1062 ret = amdgpu_ttm_tt_set_userptr(&bo->tbo, user_addr, 0);
1064 pr_err("%s: Failed to set userptr: %d\n", __func__, ret);
1068 ret = amdgpu_hmm_register(bo, user_addr);
1070 pr_err("%s: Failed to register MMU notifier: %d\n",
1077 * During a CRIU restore operation, the userptr buffer objects
1078 * will be validated in the restore_userptr_work worker at a
1079 * later stage when it is scheduled by another ioctl called by
1080 * CRIU master process for the target pid for restore.
1082 mutex_lock(&process_info->notifier_lock);
1084 mutex_unlock(&process_info->notifier_lock);
1085 mutex_unlock(&process_info->lock);
1089 ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages, &range);
1091 pr_err("%s: Failed to get user pages: %d\n", __func__, ret);
1092 goto unregister_out;
1095 ret = amdgpu_bo_reserve(bo, true);
1097 pr_err("%s: Failed to reserve BO\n", __func__);
1100 amdgpu_bo_placement_from_domain(bo, mem->domain);
1101 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1103 pr_err("%s: failed to validate BO\n", __func__);
1104 amdgpu_bo_unreserve(bo);
1107 amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm, range);
1110 amdgpu_hmm_unregister(bo);
1112 mutex_unlock(&process_info->lock);
1116 /* Reserving a BO and its page table BOs must happen atomically to
1117 * avoid deadlocks. Some operations update multiple VMs at once. Track
1118 * all the reservation info in a context structure. Optionally a sync
1119 * object can track VM updates.
1121 struct bo_vm_reservation_context {
1122 /* DRM execution context for the reservation */
1123 struct drm_exec exec;
1124 /* Number of VMs reserved */
1126 /* Pointer to sync object */
1127 struct amdgpu_sync *sync;
1131 BO_VM_NOT_MAPPED = 0, /* Match VMs where a BO is not mapped */
1132 BO_VM_MAPPED, /* Match VMs where a BO is mapped */
1133 BO_VM_ALL, /* Match all VMs a BO was added to */
1137 * reserve_bo_and_vm - reserve a BO and a VM unconditionally.
1138 * @mem: KFD BO structure.
1139 * @vm: the VM to reserve.
1140 * @ctx: the struct that will be used in unreserve_bo_and_vms().
1142 static int reserve_bo_and_vm(struct kgd_mem *mem,
1143 struct amdgpu_vm *vm,
1144 struct bo_vm_reservation_context *ctx)
1146 struct amdgpu_bo *bo = mem->bo;
1152 ctx->sync = &mem->sync;
1153 drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT, 0);
1154 drm_exec_until_all_locked(&ctx->exec) {
1155 ret = amdgpu_vm_lock_pd(vm, &ctx->exec, 2);
1156 drm_exec_retry_on_contention(&ctx->exec);
1160 ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1);
1161 drm_exec_retry_on_contention(&ctx->exec);
1168 pr_err("Failed to reserve buffers in ttm.\n");
1169 drm_exec_fini(&ctx->exec);
1174 * reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally
1175 * @mem: KFD BO structure.
1176 * @vm: the VM to reserve. If NULL, then all VMs associated with the BO
1177 * is used. Otherwise, a single VM associated with the BO.
1178 * @map_type: the mapping status that will be used to filter the VMs.
1179 * @ctx: the struct that will be used in unreserve_bo_and_vms().
1181 * Returns 0 for success, negative for failure.
1183 static int reserve_bo_and_cond_vms(struct kgd_mem *mem,
1184 struct amdgpu_vm *vm, enum bo_vm_match map_type,
1185 struct bo_vm_reservation_context *ctx)
1187 struct kfd_mem_attachment *entry;
1188 struct amdgpu_bo *bo = mem->bo;
1191 ctx->sync = &mem->sync;
1192 drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT |
1193 DRM_EXEC_IGNORE_DUPLICATES, 0);
1194 drm_exec_until_all_locked(&ctx->exec) {
1196 list_for_each_entry(entry, &mem->attachments, list) {
1197 if ((vm && vm != entry->bo_va->base.vm) ||
1198 (entry->is_mapped != map_type
1199 && map_type != BO_VM_ALL))
1202 ret = amdgpu_vm_lock_pd(entry->bo_va->base.vm,
1204 drm_exec_retry_on_contention(&ctx->exec);
1210 ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1);
1211 drm_exec_retry_on_contention(&ctx->exec);
1218 pr_err("Failed to reserve buffers in ttm.\n");
1219 drm_exec_fini(&ctx->exec);
1224 * unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context
1225 * @ctx: Reservation context to unreserve
1226 * @wait: Optionally wait for a sync object representing pending VM updates
1227 * @intr: Whether the wait is interruptible
1229 * Also frees any resources allocated in
1230 * reserve_bo_and_(cond_)vm(s). Returns the status from
1233 static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx,
1234 bool wait, bool intr)
1239 ret = amdgpu_sync_wait(ctx->sync, intr);
1241 drm_exec_fini(&ctx->exec);
1246 static void unmap_bo_from_gpuvm(struct kgd_mem *mem,
1247 struct kfd_mem_attachment *entry,
1248 struct amdgpu_sync *sync)
1250 struct amdgpu_bo_va *bo_va = entry->bo_va;
1251 struct amdgpu_device *adev = entry->adev;
1252 struct amdgpu_vm *vm = bo_va->base.vm;
1254 amdgpu_vm_bo_unmap(adev, bo_va, entry->va);
1256 amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update);
1258 amdgpu_sync_fence(sync, bo_va->last_pt_update);
1261 static int update_gpuvm_pte(struct kgd_mem *mem,
1262 struct kfd_mem_attachment *entry,
1263 struct amdgpu_sync *sync)
1265 struct amdgpu_bo_va *bo_va = entry->bo_va;
1266 struct amdgpu_device *adev = entry->adev;
1269 ret = kfd_mem_dmamap_attachment(mem, entry);
1273 /* Update the page tables */
1274 ret = amdgpu_vm_bo_update(adev, bo_va, false);
1276 pr_err("amdgpu_vm_bo_update failed\n");
1280 return amdgpu_sync_fence(sync, bo_va->last_pt_update);
1283 static int map_bo_to_gpuvm(struct kgd_mem *mem,
1284 struct kfd_mem_attachment *entry,
1285 struct amdgpu_sync *sync,
1290 /* Set virtual address for the allocation */
1291 ret = amdgpu_vm_bo_map(entry->adev, entry->bo_va, entry->va, 0,
1292 amdgpu_bo_size(entry->bo_va->base.bo),
1295 pr_err("Failed to map VA 0x%llx in vm. ret %d\n",
1303 ret = update_gpuvm_pte(mem, entry, sync);
1305 pr_err("update_gpuvm_pte() failed\n");
1306 goto update_gpuvm_pte_failed;
1311 update_gpuvm_pte_failed:
1312 unmap_bo_from_gpuvm(mem, entry, sync);
1313 kfd_mem_dmaunmap_attachment(mem, entry);
1317 static int process_validate_vms(struct amdkfd_process_info *process_info,
1318 struct ww_acquire_ctx *ticket)
1320 struct amdgpu_vm *peer_vm;
1323 list_for_each_entry(peer_vm, &process_info->vm_list_head,
1325 ret = vm_validate_pt_pd_bos(peer_vm, ticket);
1333 static int process_sync_pds_resv(struct amdkfd_process_info *process_info,
1334 struct amdgpu_sync *sync)
1336 struct amdgpu_vm *peer_vm;
1339 list_for_each_entry(peer_vm, &process_info->vm_list_head,
1341 struct amdgpu_bo *pd = peer_vm->root.bo;
1343 ret = amdgpu_sync_resv(NULL, sync, pd->tbo.base.resv,
1344 AMDGPU_SYNC_NE_OWNER,
1345 AMDGPU_FENCE_OWNER_KFD);
1353 static int process_update_pds(struct amdkfd_process_info *process_info,
1354 struct amdgpu_sync *sync)
1356 struct amdgpu_vm *peer_vm;
1359 list_for_each_entry(peer_vm, &process_info->vm_list_head,
1361 ret = vm_update_pds(peer_vm, sync);
1369 static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info,
1370 struct dma_fence **ef)
1372 struct amdkfd_process_info *info = NULL;
1375 if (!*process_info) {
1376 info = kzalloc(sizeof(*info), GFP_KERNEL);
1380 mutex_init(&info->lock);
1381 mutex_init(&info->notifier_lock);
1382 INIT_LIST_HEAD(&info->vm_list_head);
1383 INIT_LIST_HEAD(&info->kfd_bo_list);
1384 INIT_LIST_HEAD(&info->userptr_valid_list);
1385 INIT_LIST_HEAD(&info->userptr_inval_list);
1387 info->eviction_fence =
1388 amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),
1391 if (!info->eviction_fence) {
1392 pr_err("Failed to create eviction fence\n");
1394 goto create_evict_fence_fail;
1397 info->pid = get_task_pid(current->group_leader, PIDTYPE_PID);
1398 INIT_DELAYED_WORK(&info->restore_userptr_work,
1399 amdgpu_amdkfd_restore_userptr_worker);
1401 *process_info = info;
1404 vm->process_info = *process_info;
1406 /* Validate page directory and attach eviction fence */
1407 ret = amdgpu_bo_reserve(vm->root.bo, true);
1409 goto reserve_pd_fail;
1410 ret = vm_validate_pt_pd_bos(vm, NULL);
1412 pr_err("validate_pt_pd_bos() failed\n");
1413 goto validate_pd_fail;
1415 ret = amdgpu_bo_sync_wait(vm->root.bo,
1416 AMDGPU_FENCE_OWNER_KFD, false);
1419 ret = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, 1);
1421 goto reserve_shared_fail;
1422 dma_resv_add_fence(vm->root.bo->tbo.base.resv,
1423 &vm->process_info->eviction_fence->base,
1424 DMA_RESV_USAGE_BOOKKEEP);
1425 amdgpu_bo_unreserve(vm->root.bo);
1427 /* Update process info */
1428 mutex_lock(&vm->process_info->lock);
1429 list_add_tail(&vm->vm_list_node,
1430 &(vm->process_info->vm_list_head));
1431 vm->process_info->n_vms++;
1433 *ef = dma_fence_get(&vm->process_info->eviction_fence->base);
1434 mutex_unlock(&vm->process_info->lock);
1438 reserve_shared_fail:
1441 amdgpu_bo_unreserve(vm->root.bo);
1443 vm->process_info = NULL;
1445 dma_fence_put(&info->eviction_fence->base);
1446 *process_info = NULL;
1448 create_evict_fence_fail:
1449 mutex_destroy(&info->lock);
1450 mutex_destroy(&info->notifier_lock);
1457 * amdgpu_amdkfd_gpuvm_pin_bo() - Pins a BO using following criteria
1458 * @bo: Handle of buffer object being pinned
1459 * @domain: Domain into which BO should be pinned
1461 * - USERPTR BOs are UNPINNABLE and will return error
1462 * - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
1463 * PIN count incremented. It is valid to PIN a BO multiple times
1465 * Return: ZERO if successful in pinning, Non-Zero in case of error.
1467 static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain)
1471 ret = amdgpu_bo_reserve(bo, false);
1475 ret = amdgpu_bo_pin_restricted(bo, domain, 0, 0);
1477 pr_err("Error in Pinning BO to domain: %d\n", domain);
1479 amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
1480 amdgpu_bo_unreserve(bo);
1486 * amdgpu_amdkfd_gpuvm_unpin_bo() - Unpins BO using following criteria
1487 * @bo: Handle of buffer object being unpinned
1489 * - Is a illegal request for USERPTR BOs and is ignored
1490 * - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
1491 * PIN count decremented. Calls to UNPIN must balance calls to PIN
1493 static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo)
1497 ret = amdgpu_bo_reserve(bo, false);
1501 amdgpu_bo_unpin(bo);
1502 amdgpu_bo_unreserve(bo);
1505 int amdgpu_amdkfd_gpuvm_set_vm_pasid(struct amdgpu_device *adev,
1506 struct amdgpu_vm *avm, u32 pasid)
1511 /* Free the original amdgpu allocated pasid,
1512 * will be replaced with kfd allocated pasid.
1515 amdgpu_pasid_free(avm->pasid);
1516 amdgpu_vm_set_pasid(adev, avm, 0);
1519 ret = amdgpu_vm_set_pasid(adev, avm, pasid);
1526 int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct amdgpu_device *adev,
1527 struct amdgpu_vm *avm,
1528 void **process_info,
1529 struct dma_fence **ef)
1533 /* Already a compute VM? */
1534 if (avm->process_info)
1537 /* Convert VM into a compute VM */
1538 ret = amdgpu_vm_make_compute(adev, avm);
1542 /* Initialize KFD part of the VM and process info */
1543 ret = init_kfd_vm(avm, process_info, ef);
1547 amdgpu_vm_set_task_info(avm);
1552 void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,
1553 struct amdgpu_vm *vm)
1555 struct amdkfd_process_info *process_info = vm->process_info;
1560 /* Update process info */
1561 mutex_lock(&process_info->lock);
1562 process_info->n_vms--;
1563 list_del(&vm->vm_list_node);
1564 mutex_unlock(&process_info->lock);
1566 vm->process_info = NULL;
1568 /* Release per-process resources when last compute VM is destroyed */
1569 if (!process_info->n_vms) {
1570 WARN_ON(!list_empty(&process_info->kfd_bo_list));
1571 WARN_ON(!list_empty(&process_info->userptr_valid_list));
1572 WARN_ON(!list_empty(&process_info->userptr_inval_list));
1574 dma_fence_put(&process_info->eviction_fence->base);
1575 cancel_delayed_work_sync(&process_info->restore_userptr_work);
1576 put_pid(process_info->pid);
1577 mutex_destroy(&process_info->lock);
1578 mutex_destroy(&process_info->notifier_lock);
1579 kfree(process_info);
1583 void amdgpu_amdkfd_gpuvm_release_process_vm(struct amdgpu_device *adev,
1586 struct amdgpu_vm *avm;
1588 if (WARN_ON(!adev || !drm_priv))
1591 avm = drm_priv_to_vm(drm_priv);
1593 pr_debug("Releasing process vm %p\n", avm);
1595 /* The original pasid of amdgpu vm has already been
1596 * released during making a amdgpu vm to a compute vm
1597 * The current pasid is managed by kfd and will be
1598 * released on kfd process destroy. Set amdgpu pasid
1599 * to 0 to avoid duplicate release.
1601 amdgpu_vm_release_compute(adev, avm);
1604 uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)
1606 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1607 struct amdgpu_bo *pd = avm->root.bo;
1608 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
1610 if (adev->asic_type < CHIP_VEGA10)
1611 return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT;
1612 return avm->pd_phys_addr;
1615 void amdgpu_amdkfd_block_mmu_notifications(void *p)
1617 struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;
1619 mutex_lock(&pinfo->lock);
1620 WRITE_ONCE(pinfo->block_mmu_notifications, true);
1621 mutex_unlock(&pinfo->lock);
1624 int amdgpu_amdkfd_criu_resume(void *p)
1627 struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;
1629 mutex_lock(&pinfo->lock);
1630 pr_debug("scheduling work\n");
1631 mutex_lock(&pinfo->notifier_lock);
1632 pinfo->evicted_bos++;
1633 mutex_unlock(&pinfo->notifier_lock);
1634 if (!READ_ONCE(pinfo->block_mmu_notifications)) {
1638 WRITE_ONCE(pinfo->block_mmu_notifications, false);
1639 queue_delayed_work(system_freezable_wq,
1640 &pinfo->restore_userptr_work, 0);
1643 mutex_unlock(&pinfo->lock);
1647 size_t amdgpu_amdkfd_get_available_memory(struct amdgpu_device *adev,
1650 uint64_t reserved_for_pt =
1651 ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);
1653 uint64_t vram_available, system_mem_available, ttm_mem_available;
1655 spin_lock(&kfd_mem_limit.mem_limit_lock);
1656 vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id)
1657 - adev->kfd.vram_used_aligned[xcp_id]
1658 - atomic64_read(&adev->vram_pin_size)
1661 if (adev->gmc.is_app_apu || adev->flags & AMD_IS_APU) {
1662 system_mem_available = no_system_mem_limit ?
1663 kfd_mem_limit.max_system_mem_limit :
1664 kfd_mem_limit.max_system_mem_limit -
1665 kfd_mem_limit.system_mem_used;
1667 ttm_mem_available = kfd_mem_limit.max_ttm_mem_limit -
1668 kfd_mem_limit.ttm_mem_used;
1670 available = min3(system_mem_available, ttm_mem_available,
1672 available = ALIGN_DOWN(available, PAGE_SIZE);
1674 available = ALIGN_DOWN(vram_available, VRAM_AVAILABLITY_ALIGN);
1677 spin_unlock(&kfd_mem_limit.mem_limit_lock);
1685 int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(
1686 struct amdgpu_device *adev, uint64_t va, uint64_t size,
1687 void *drm_priv, struct kgd_mem **mem,
1688 uint64_t *offset, uint32_t flags, bool criu_resume)
1690 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1691 struct amdgpu_fpriv *fpriv = container_of(avm, struct amdgpu_fpriv, vm);
1692 enum ttm_bo_type bo_type = ttm_bo_type_device;
1693 struct sg_table *sg = NULL;
1694 uint64_t user_addr = 0;
1695 struct amdgpu_bo *bo;
1696 struct drm_gem_object *gobj = NULL;
1697 u32 domain, alloc_domain;
1698 uint64_t aligned_size;
1704 * Check on which domain to allocate BO
1706 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
1707 domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;
1709 if (adev->gmc.is_app_apu || adev->flags & AMD_IS_APU) {
1710 domain = AMDGPU_GEM_DOMAIN_GTT;
1711 alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
1714 alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;
1715 alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ?
1716 AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0;
1718 xcp_id = fpriv->xcp_id == AMDGPU_XCP_NO_PARTITION ?
1720 } else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
1721 domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
1724 domain = AMDGPU_GEM_DOMAIN_GTT;
1725 alloc_domain = AMDGPU_GEM_DOMAIN_CPU;
1726 alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE;
1728 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
1729 if (!offset || !*offset)
1731 user_addr = untagged_addr(*offset);
1732 } else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1733 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1734 bo_type = ttm_bo_type_sg;
1735 if (size > UINT_MAX)
1737 sg = create_sg_table(*offset, size);
1745 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_COHERENT)
1746 alloc_flags |= AMDGPU_GEM_CREATE_COHERENT;
1747 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_EXT_COHERENT)
1748 alloc_flags |= AMDGPU_GEM_CREATE_EXT_COHERENT;
1749 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED)
1750 alloc_flags |= AMDGPU_GEM_CREATE_UNCACHED;
1752 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
1757 INIT_LIST_HEAD(&(*mem)->attachments);
1758 mutex_init(&(*mem)->lock);
1759 (*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);
1761 /* Workaround for AQL queue wraparound bug. Map the same
1762 * memory twice. That means we only actually allocate half
1765 if ((*mem)->aql_queue)
1767 aligned_size = PAGE_ALIGN(size);
1769 (*mem)->alloc_flags = flags;
1771 amdgpu_sync_create(&(*mem)->sync);
1773 ret = amdgpu_amdkfd_reserve_mem_limit(adev, aligned_size, flags,
1776 pr_debug("Insufficient memory\n");
1777 goto err_reserve_limit;
1780 pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s xcp_id %d\n",
1781 va, (*mem)->aql_queue ? size << 1 : size,
1782 domain_string(alloc_domain), xcp_id);
1784 ret = amdgpu_gem_object_create(adev, aligned_size, 1, alloc_domain, alloc_flags,
1785 bo_type, NULL, &gobj, xcp_id + 1);
1787 pr_debug("Failed to create BO on domain %s. ret %d\n",
1788 domain_string(alloc_domain), ret);
1791 ret = drm_vma_node_allow(&gobj->vma_node, drm_priv);
1793 pr_debug("Failed to allow vma node access. ret %d\n", ret);
1794 goto err_node_allow;
1796 ret = drm_gem_handle_create(adev->kfd.client.file, gobj, &(*mem)->gem_handle);
1798 goto err_gem_handle_create;
1799 bo = gem_to_amdgpu_bo(gobj);
1800 if (bo_type == ttm_bo_type_sg) {
1802 bo->tbo.ttm->sg = sg;
1807 bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO;
1810 (*mem)->domain = domain;
1811 (*mem)->mapped_to_gpu_memory = 0;
1812 (*mem)->process_info = avm->process_info;
1814 add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);
1817 pr_debug("creating userptr BO for user_addr = %llx\n", user_addr);
1818 ret = init_user_pages(*mem, user_addr, criu_resume);
1820 goto allocate_init_user_pages_failed;
1821 } else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1822 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1823 ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT);
1825 pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n");
1828 bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
1829 bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
1831 mutex_lock(&avm->process_info->lock);
1832 if (avm->process_info->eviction_fence &&
1833 !dma_fence_is_signaled(&avm->process_info->eviction_fence->base))
1834 ret = amdgpu_amdkfd_bo_validate_and_fence(bo, domain,
1835 &avm->process_info->eviction_fence->base);
1836 mutex_unlock(&avm->process_info->lock);
1838 goto err_validate_bo;
1842 *offset = amdgpu_bo_mmap_offset(bo);
1846 allocate_init_user_pages_failed:
1849 remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);
1850 drm_gem_handle_delete(adev->kfd.client.file, (*mem)->gem_handle);
1851 err_gem_handle_create:
1852 drm_vma_node_revoke(&gobj->vma_node, drm_priv);
1854 /* Don't unreserve system mem limit twice */
1855 goto err_reserve_limit;
1857 amdgpu_amdkfd_unreserve_mem_limit(adev, aligned_size, flags, xcp_id);
1859 amdgpu_sync_free(&(*mem)->sync);
1860 mutex_destroy(&(*mem)->lock);
1862 drm_gem_object_put(gobj);
1873 int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(
1874 struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv,
1877 struct amdkfd_process_info *process_info = mem->process_info;
1878 unsigned long bo_size = mem->bo->tbo.base.size;
1879 bool use_release_notifier = (mem->bo->kfd_bo == mem);
1880 struct kfd_mem_attachment *entry, *tmp;
1881 struct bo_vm_reservation_context ctx;
1882 unsigned int mapped_to_gpu_memory;
1884 bool is_imported = false;
1886 mutex_lock(&mem->lock);
1888 /* Unpin MMIO/DOORBELL BO's that were pinned during allocation */
1889 if (mem->alloc_flags &
1890 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1891 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1892 amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo);
1895 mapped_to_gpu_memory = mem->mapped_to_gpu_memory;
1896 is_imported = mem->is_imported;
1897 mutex_unlock(&mem->lock);
1898 /* lock is not needed after this, since mem is unused and will
1902 if (mapped_to_gpu_memory > 0) {
1903 pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",
1908 /* Make sure restore workers don't access the BO any more */
1909 mutex_lock(&process_info->lock);
1910 list_del(&mem->validate_list);
1911 mutex_unlock(&process_info->lock);
1913 /* Cleanup user pages and MMU notifiers */
1914 if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {
1915 amdgpu_hmm_unregister(mem->bo);
1916 mutex_lock(&process_info->notifier_lock);
1917 amdgpu_ttm_tt_discard_user_pages(mem->bo->tbo.ttm, mem->range);
1918 mutex_unlock(&process_info->notifier_lock);
1921 ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);
1925 amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1926 process_info->eviction_fence);
1927 pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,
1928 mem->va + bo_size * (1 + mem->aql_queue));
1930 /* Remove from VM internal data structures */
1931 list_for_each_entry_safe(entry, tmp, &mem->attachments, list) {
1932 kfd_mem_dmaunmap_attachment(mem, entry);
1933 kfd_mem_detach(entry);
1936 ret = unreserve_bo_and_vms(&ctx, false, false);
1938 /* Free the sync object */
1939 amdgpu_sync_free(&mem->sync);
1941 /* If the SG is not NULL, it's one we created for a doorbell or mmio
1942 * remap BO. We need to free it.
1944 if (mem->bo->tbo.sg) {
1945 sg_free_table(mem->bo->tbo.sg);
1946 kfree(mem->bo->tbo.sg);
1949 /* Update the size of the BO being freed if it was allocated from
1950 * VRAM and is not imported. For APP APU VRAM allocations are done
1955 (mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_VRAM ||
1956 ((adev->gmc.is_app_apu || adev->flags & AMD_IS_APU) &&
1957 mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_GTT)))
1964 drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv);
1965 drm_gem_handle_delete(adev->kfd.client.file, mem->gem_handle);
1967 dma_buf_put(mem->dmabuf);
1970 mutex_destroy(&mem->lock);
1972 /* If this releases the last reference, it will end up calling
1973 * amdgpu_amdkfd_release_notify and kfree the mem struct. That's why
1974 * this needs to be the last call here.
1976 drm_gem_object_put(&mem->bo->tbo.base);
1979 * For kgd_mem allocated in amdgpu_amdkfd_gpuvm_import_dmabuf(),
1980 * explicitly free it here.
1982 if (!use_release_notifier)
1988 int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1989 struct amdgpu_device *adev, struct kgd_mem *mem,
1992 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1994 struct amdgpu_bo *bo;
1996 struct kfd_mem_attachment *entry;
1997 struct bo_vm_reservation_context ctx;
1998 unsigned long bo_size;
1999 bool is_invalid_userptr = false;
2003 pr_err("Invalid BO when mapping memory to GPU\n");
2007 /* Make sure restore is not running concurrently. Since we
2008 * don't map invalid userptr BOs, we rely on the next restore
2009 * worker to do the mapping
2011 mutex_lock(&mem->process_info->lock);
2013 /* Lock notifier lock. If we find an invalid userptr BO, we can be
2014 * sure that the MMU notifier is no longer running
2015 * concurrently and the queues are actually stopped
2017 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
2018 mutex_lock(&mem->process_info->notifier_lock);
2019 is_invalid_userptr = !!mem->invalid;
2020 mutex_unlock(&mem->process_info->notifier_lock);
2023 mutex_lock(&mem->lock);
2025 domain = mem->domain;
2026 bo_size = bo->tbo.base.size;
2028 pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",
2030 mem->va + bo_size * (1 + mem->aql_queue),
2031 avm, domain_string(domain));
2033 if (!kfd_mem_is_attached(avm, mem)) {
2034 ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue);
2039 ret = reserve_bo_and_vm(mem, avm, &ctx);
2043 /* Userptr can be marked as "not invalid", but not actually be
2044 * validated yet (still in the system domain). In that case
2045 * the queues are still stopped and we can leave mapping for
2046 * the next restore worker
2048 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&
2049 bo->tbo.resource->mem_type == TTM_PL_SYSTEM)
2050 is_invalid_userptr = true;
2052 ret = vm_validate_pt_pd_bos(avm, NULL);
2056 list_for_each_entry(entry, &mem->attachments, list) {
2057 if (entry->bo_va->base.vm != avm || entry->is_mapped)
2060 pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",
2061 entry->va, entry->va + bo_size, entry);
2063 ret = map_bo_to_gpuvm(mem, entry, ctx.sync,
2064 is_invalid_userptr);
2066 pr_err("Failed to map bo to gpuvm\n");
2070 ret = vm_update_pds(avm, ctx.sync);
2072 pr_err("Failed to update page directories\n");
2076 entry->is_mapped = true;
2077 mem->mapped_to_gpu_memory++;
2078 pr_debug("\t INC mapping count %d\n",
2079 mem->mapped_to_gpu_memory);
2082 ret = unreserve_bo_and_vms(&ctx, false, false);
2087 unreserve_bo_and_vms(&ctx, false, false);
2089 mutex_unlock(&mem->process_info->lock);
2090 mutex_unlock(&mem->lock);
2094 int amdgpu_amdkfd_gpuvm_dmaunmap_mem(struct kgd_mem *mem, void *drm_priv)
2096 struct kfd_mem_attachment *entry;
2097 struct amdgpu_vm *vm;
2100 vm = drm_priv_to_vm(drm_priv);
2102 mutex_lock(&mem->lock);
2104 ret = amdgpu_bo_reserve(mem->bo, true);
2108 list_for_each_entry(entry, &mem->attachments, list) {
2109 if (entry->bo_va->base.vm != vm)
2111 if (entry->bo_va->base.bo->tbo.ttm &&
2112 !entry->bo_va->base.bo->tbo.ttm->sg)
2115 kfd_mem_dmaunmap_attachment(mem, entry);
2118 amdgpu_bo_unreserve(mem->bo);
2120 mutex_unlock(&mem->lock);
2125 int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
2126 struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv)
2128 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
2129 unsigned long bo_size = mem->bo->tbo.base.size;
2130 struct kfd_mem_attachment *entry;
2131 struct bo_vm_reservation_context ctx;
2134 mutex_lock(&mem->lock);
2136 ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx);
2139 /* If no VMs were reserved, it means the BO wasn't actually mapped */
2140 if (ctx.n_vms == 0) {
2145 ret = vm_validate_pt_pd_bos(avm, NULL);
2149 pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",
2151 mem->va + bo_size * (1 + mem->aql_queue),
2154 list_for_each_entry(entry, &mem->attachments, list) {
2155 if (entry->bo_va->base.vm != avm || !entry->is_mapped)
2158 pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",
2159 entry->va, entry->va + bo_size, entry);
2161 unmap_bo_from_gpuvm(mem, entry, ctx.sync);
2162 entry->is_mapped = false;
2164 mem->mapped_to_gpu_memory--;
2165 pr_debug("\t DEC mapping count %d\n",
2166 mem->mapped_to_gpu_memory);
2170 unreserve_bo_and_vms(&ctx, false, false);
2172 mutex_unlock(&mem->lock);
2176 int amdgpu_amdkfd_gpuvm_sync_memory(
2177 struct amdgpu_device *adev, struct kgd_mem *mem, bool intr)
2179 struct amdgpu_sync sync;
2182 amdgpu_sync_create(&sync);
2184 mutex_lock(&mem->lock);
2185 amdgpu_sync_clone(&mem->sync, &sync);
2186 mutex_unlock(&mem->lock);
2188 ret = amdgpu_sync_wait(&sync, intr);
2189 amdgpu_sync_free(&sync);
2194 * amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count
2195 * @bo: Buffer object to be mapped
2197 * Before return, bo reference count is incremented. To release the reference and unpin/
2198 * unmap the BO, call amdgpu_amdkfd_free_gtt_mem.
2200 int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_bo *bo)
2204 ret = amdgpu_bo_reserve(bo, true);
2206 pr_err("Failed to reserve bo. ret %d\n", ret);
2207 goto err_reserve_bo_failed;
2210 ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
2212 pr_err("Failed to pin bo. ret %d\n", ret);
2213 goto err_pin_bo_failed;
2216 ret = amdgpu_ttm_alloc_gart(&bo->tbo);
2218 pr_err("Failed to bind bo to GART. ret %d\n", ret);
2219 goto err_map_bo_gart_failed;
2222 amdgpu_amdkfd_remove_eviction_fence(
2223 bo, bo->vm_bo->vm->process_info->eviction_fence);
2225 amdgpu_bo_unreserve(bo);
2227 bo = amdgpu_bo_ref(bo);
2231 err_map_bo_gart_failed:
2232 amdgpu_bo_unpin(bo);
2234 amdgpu_bo_unreserve(bo);
2235 err_reserve_bo_failed:
2240 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Map a GTT BO for kernel CPU access
2242 * @mem: Buffer object to be mapped for CPU access
2243 * @kptr[out]: pointer in kernel CPU address space
2244 * @size[out]: size of the buffer
2246 * Pins the BO and maps it for kernel CPU access. The eviction fence is removed
2247 * from the BO, since pinned BOs cannot be evicted. The bo must remain on the
2248 * validate_list, so the GPU mapping can be restored after a page table was
2251 * Return: 0 on success, error code on failure
2253 int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem,
2254 void **kptr, uint64_t *size)
2257 struct amdgpu_bo *bo = mem->bo;
2259 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
2260 pr_err("userptr can't be mapped to kernel\n");
2264 mutex_lock(&mem->process_info->lock);
2266 ret = amdgpu_bo_reserve(bo, true);
2268 pr_err("Failed to reserve bo. ret %d\n", ret);
2269 goto bo_reserve_failed;
2272 ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
2274 pr_err("Failed to pin bo. ret %d\n", ret);
2278 ret = amdgpu_bo_kmap(bo, kptr);
2280 pr_err("Failed to map bo to kernel. ret %d\n", ret);
2284 amdgpu_amdkfd_remove_eviction_fence(
2285 bo, mem->process_info->eviction_fence);
2288 *size = amdgpu_bo_size(bo);
2290 amdgpu_bo_unreserve(bo);
2292 mutex_unlock(&mem->process_info->lock);
2296 amdgpu_bo_unpin(bo);
2298 amdgpu_bo_unreserve(bo);
2300 mutex_unlock(&mem->process_info->lock);
2305 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Unmap a GTT BO for kernel CPU access
2307 * @mem: Buffer object to be unmapped for CPU access
2309 * Removes the kernel CPU mapping and unpins the BO. It does not restore the
2310 * eviction fence, so this function should only be used for cleanup before the
2313 void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem *mem)
2315 struct amdgpu_bo *bo = mem->bo;
2317 amdgpu_bo_reserve(bo, true);
2318 amdgpu_bo_kunmap(bo);
2319 amdgpu_bo_unpin(bo);
2320 amdgpu_bo_unreserve(bo);
2323 int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev,
2324 struct kfd_vm_fault_info *mem)
2326 if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) {
2327 *mem = *adev->gmc.vm_fault_info;
2328 mb(); /* make sure read happened */
2329 atomic_set(&adev->gmc.vm_fault_info_updated, 0);
2334 static int import_obj_create(struct amdgpu_device *adev,
2335 struct dma_buf *dma_buf,
2336 struct drm_gem_object *obj,
2337 uint64_t va, void *drm_priv,
2338 struct kgd_mem **mem, uint64_t *size,
2339 uint64_t *mmap_offset)
2341 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
2342 struct amdgpu_bo *bo;
2345 bo = gem_to_amdgpu_bo(obj);
2346 if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM |
2347 AMDGPU_GEM_DOMAIN_GTT)))
2348 /* Only VRAM and GTT BOs are supported */
2351 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
2355 ret = drm_vma_node_allow(&obj->vma_node, drm_priv);
2360 *size = amdgpu_bo_size(bo);
2363 *mmap_offset = amdgpu_bo_mmap_offset(bo);
2365 INIT_LIST_HEAD(&(*mem)->attachments);
2366 mutex_init(&(*mem)->lock);
2368 (*mem)->alloc_flags =
2369 ((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
2370 KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT)
2371 | KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE
2372 | KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;
2374 get_dma_buf(dma_buf);
2375 (*mem)->dmabuf = dma_buf;
2378 (*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) &&
2379 !(adev->gmc.is_app_apu || adev->flags & AMD_IS_APU) ?
2380 AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT;
2382 (*mem)->mapped_to_gpu_memory = 0;
2383 (*mem)->process_info = avm->process_info;
2384 add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false);
2385 amdgpu_sync_create(&(*mem)->sync);
2386 (*mem)->is_imported = true;
2388 mutex_lock(&avm->process_info->lock);
2389 if (avm->process_info->eviction_fence &&
2390 !dma_fence_is_signaled(&avm->process_info->eviction_fence->base))
2391 ret = amdgpu_amdkfd_bo_validate_and_fence(bo, (*mem)->domain,
2392 &avm->process_info->eviction_fence->base);
2393 mutex_unlock(&avm->process_info->lock);
2395 goto err_remove_mem;
2400 remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);
2401 drm_vma_node_revoke(&obj->vma_node, drm_priv);
2407 int amdgpu_amdkfd_gpuvm_import_dmabuf_fd(struct amdgpu_device *adev, int fd,
2408 uint64_t va, void *drm_priv,
2409 struct kgd_mem **mem, uint64_t *size,
2410 uint64_t *mmap_offset)
2412 struct drm_gem_object *obj;
2416 ret = drm_gem_prime_fd_to_handle(&adev->ddev, adev->kfd.client.file, fd,
2420 obj = drm_gem_object_lookup(adev->kfd.client.file, handle);
2423 goto err_release_handle;
2426 ret = import_obj_create(adev, obj->dma_buf, obj, va, drm_priv, mem, size,
2431 (*mem)->gem_handle = handle;
2436 drm_gem_object_put(obj);
2438 drm_gem_handle_delete(adev->kfd.client.file, handle);
2442 int amdgpu_amdkfd_gpuvm_export_dmabuf(struct kgd_mem *mem,
2443 struct dma_buf **dma_buf)
2447 mutex_lock(&mem->lock);
2448 ret = kfd_mem_export_dmabuf(mem);
2452 get_dma_buf(mem->dmabuf);
2453 *dma_buf = mem->dmabuf;
2455 mutex_unlock(&mem->lock);
2459 /* Evict a userptr BO by stopping the queues if necessary
2461 * Runs in MMU notifier, may be in RECLAIM_FS context. This means it
2462 * cannot do any memory allocations, and cannot take any locks that
2463 * are held elsewhere while allocating memory.
2465 * It doesn't do anything to the BO itself. The real work happens in
2466 * restore, where we get updated page addresses. This function only
2467 * ensures that GPU access to the BO is stopped.
2469 int amdgpu_amdkfd_evict_userptr(struct mmu_interval_notifier *mni,
2470 unsigned long cur_seq, struct kgd_mem *mem)
2472 struct amdkfd_process_info *process_info = mem->process_info;
2475 /* Do not process MMU notifications during CRIU restore until
2476 * KFD_CRIU_OP_RESUME IOCTL is received
2478 if (READ_ONCE(process_info->block_mmu_notifications))
2481 mutex_lock(&process_info->notifier_lock);
2482 mmu_interval_set_seq(mni, cur_seq);
2485 if (++process_info->evicted_bos == 1) {
2486 /* First eviction, stop the queues */
2487 r = kgd2kfd_quiesce_mm(mni->mm,
2488 KFD_QUEUE_EVICTION_TRIGGER_USERPTR);
2490 pr_err("Failed to quiesce KFD\n");
2491 queue_delayed_work(system_freezable_wq,
2492 &process_info->restore_userptr_work,
2493 msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2495 mutex_unlock(&process_info->notifier_lock);
2500 /* Update invalid userptr BOs
2502 * Moves invalidated (evicted) userptr BOs from userptr_valid_list to
2503 * userptr_inval_list and updates user pages for all BOs that have
2504 * been invalidated since their last update.
2506 static int update_invalid_user_pages(struct amdkfd_process_info *process_info,
2507 struct mm_struct *mm)
2509 struct kgd_mem *mem, *tmp_mem;
2510 struct amdgpu_bo *bo;
2511 struct ttm_operation_ctx ctx = { false, false };
2515 mutex_lock(&process_info->notifier_lock);
2517 /* Move all invalidated BOs to the userptr_inval_list */
2518 list_for_each_entry_safe(mem, tmp_mem,
2519 &process_info->userptr_valid_list,
2522 list_move_tail(&mem->validate_list,
2523 &process_info->userptr_inval_list);
2525 /* Go through userptr_inval_list and update any invalid user_pages */
2526 list_for_each_entry(mem, &process_info->userptr_inval_list,
2528 invalid = mem->invalid;
2530 /* BO hasn't been invalidated since the last
2531 * revalidation attempt. Keep its page list.
2537 amdgpu_ttm_tt_discard_user_pages(bo->tbo.ttm, mem->range);
2540 /* BO reservations and getting user pages (hmm_range_fault)
2541 * must happen outside the notifier lock
2543 mutex_unlock(&process_info->notifier_lock);
2545 /* Move the BO to system (CPU) domain if necessary to unmap
2546 * and free the SG table
2548 if (bo->tbo.resource->mem_type != TTM_PL_SYSTEM) {
2549 if (amdgpu_bo_reserve(bo, true))
2551 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
2552 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2553 amdgpu_bo_unreserve(bo);
2555 pr_err("%s: Failed to invalidate userptr BO\n",
2561 /* Get updated user pages */
2562 ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages,
2565 pr_debug("Failed %d to get user pages\n", ret);
2567 /* Return -EFAULT bad address error as success. It will
2568 * fail later with a VM fault if the GPU tries to access
2569 * it. Better than hanging indefinitely with stalled
2572 * Return other error -EBUSY or -ENOMEM to retry restore
2580 mutex_lock(&process_info->notifier_lock);
2582 /* Mark the BO as valid unless it was invalidated
2583 * again concurrently.
2585 if (mem->invalid != invalid) {
2589 /* set mem valid if mem has hmm range associated */
2595 mutex_unlock(&process_info->notifier_lock);
2600 /* Validate invalid userptr BOs
2602 * Validates BOs on the userptr_inval_list. Also updates GPUVM page tables
2603 * with new page addresses and waits for the page table updates to complete.
2605 static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)
2607 struct ttm_operation_ctx ctx = { false, false };
2608 struct amdgpu_sync sync;
2609 struct drm_exec exec;
2611 struct amdgpu_vm *peer_vm;
2612 struct kgd_mem *mem, *tmp_mem;
2613 struct amdgpu_bo *bo;
2616 amdgpu_sync_create(&sync);
2618 drm_exec_init(&exec, 0, 0);
2619 /* Reserve all BOs and page tables for validation */
2620 drm_exec_until_all_locked(&exec) {
2621 /* Reserve all the page directories */
2622 list_for_each_entry(peer_vm, &process_info->vm_list_head,
2624 ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2);
2625 drm_exec_retry_on_contention(&exec);
2630 /* Reserve the userptr_inval_list entries to resv_list */
2631 list_for_each_entry(mem, &process_info->userptr_inval_list,
2633 struct drm_gem_object *gobj;
2635 gobj = &mem->bo->tbo.base;
2636 ret = drm_exec_prepare_obj(&exec, gobj, 1);
2637 drm_exec_retry_on_contention(&exec);
2643 ret = process_validate_vms(process_info, NULL);
2647 /* Validate BOs and update GPUVM page tables */
2648 list_for_each_entry_safe(mem, tmp_mem,
2649 &process_info->userptr_inval_list,
2651 struct kfd_mem_attachment *attachment;
2655 /* Validate the BO if we got user pages */
2656 if (bo->tbo.ttm->pages[0]) {
2657 amdgpu_bo_placement_from_domain(bo, mem->domain);
2658 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2660 pr_err("%s: failed to validate BO\n", __func__);
2665 /* Update mapping. If the BO was not validated
2666 * (because we couldn't get user pages), this will
2667 * clear the page table entries, which will result in
2668 * VM faults if the GPU tries to access the invalid
2671 list_for_each_entry(attachment, &mem->attachments, list) {
2672 if (!attachment->is_mapped)
2675 kfd_mem_dmaunmap_attachment(mem, attachment);
2676 ret = update_gpuvm_pte(mem, attachment, &sync);
2678 pr_err("%s: update PTE failed\n", __func__);
2679 /* make sure this gets validated again */
2680 mutex_lock(&process_info->notifier_lock);
2682 mutex_unlock(&process_info->notifier_lock);
2688 /* Update page directories */
2689 ret = process_update_pds(process_info, &sync);
2692 drm_exec_fini(&exec);
2693 amdgpu_sync_wait(&sync, false);
2694 amdgpu_sync_free(&sync);
2699 /* Confirm that all user pages are valid while holding the notifier lock
2701 * Moves valid BOs from the userptr_inval_list back to userptr_val_list.
2703 static int confirm_valid_user_pages_locked(struct amdkfd_process_info *process_info)
2705 struct kgd_mem *mem, *tmp_mem;
2708 list_for_each_entry_safe(mem, tmp_mem,
2709 &process_info->userptr_inval_list,
2713 /* keep mem without hmm range at userptr_inval_list */
2717 /* Only check mem with hmm range associated */
2718 valid = amdgpu_ttm_tt_get_user_pages_done(
2719 mem->bo->tbo.ttm, mem->range);
2723 WARN(!mem->invalid, "Invalid BO not marked invalid");
2729 WARN(1, "Valid BO is marked invalid");
2734 list_move_tail(&mem->validate_list,
2735 &process_info->userptr_valid_list);
2741 /* Worker callback to restore evicted userptr BOs
2743 * Tries to update and validate all userptr BOs. If successful and no
2744 * concurrent evictions happened, the queues are restarted. Otherwise,
2745 * reschedule for another attempt later.
2747 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
2749 struct delayed_work *dwork = to_delayed_work(work);
2750 struct amdkfd_process_info *process_info =
2751 container_of(dwork, struct amdkfd_process_info,
2752 restore_userptr_work);
2753 struct task_struct *usertask;
2754 struct mm_struct *mm;
2755 uint32_t evicted_bos;
2757 mutex_lock(&process_info->notifier_lock);
2758 evicted_bos = process_info->evicted_bos;
2759 mutex_unlock(&process_info->notifier_lock);
2763 /* Reference task and mm in case of concurrent process termination */
2764 usertask = get_pid_task(process_info->pid, PIDTYPE_PID);
2767 mm = get_task_mm(usertask);
2769 put_task_struct(usertask);
2773 mutex_lock(&process_info->lock);
2775 if (update_invalid_user_pages(process_info, mm))
2777 /* userptr_inval_list can be empty if all evicted userptr BOs
2778 * have been freed. In that case there is nothing to validate
2779 * and we can just restart the queues.
2781 if (!list_empty(&process_info->userptr_inval_list)) {
2782 if (validate_invalid_user_pages(process_info))
2785 /* Final check for concurrent evicton and atomic update. If
2786 * another eviction happens after successful update, it will
2787 * be a first eviction that calls quiesce_mm. The eviction
2788 * reference counting inside KFD will handle this case.
2790 mutex_lock(&process_info->notifier_lock);
2791 if (process_info->evicted_bos != evicted_bos)
2792 goto unlock_notifier_out;
2794 if (confirm_valid_user_pages_locked(process_info)) {
2795 WARN(1, "User pages unexpectedly invalid");
2796 goto unlock_notifier_out;
2799 process_info->evicted_bos = evicted_bos = 0;
2801 if (kgd2kfd_resume_mm(mm)) {
2802 pr_err("%s: Failed to resume KFD\n", __func__);
2803 /* No recovery from this failure. Probably the CP is
2804 * hanging. No point trying again.
2808 unlock_notifier_out:
2809 mutex_unlock(&process_info->notifier_lock);
2811 mutex_unlock(&process_info->lock);
2813 /* If validation failed, reschedule another attempt */
2815 queue_delayed_work(system_freezable_wq,
2816 &process_info->restore_userptr_work,
2817 msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2819 kfd_smi_event_queue_restore_rescheduled(mm);
2822 put_task_struct(usertask);
2825 static void replace_eviction_fence(struct dma_fence __rcu **ef,
2826 struct dma_fence *new_ef)
2828 struct dma_fence *old_ef = rcu_replace_pointer(*ef, new_ef, true
2829 /* protected by process_info->lock */);
2831 /* If we're replacing an unsignaled eviction fence, that fence will
2832 * never be signaled, and if anyone is still waiting on that fence,
2833 * they will hang forever. This should never happen. We should only
2834 * replace the fence in restore_work that only gets scheduled after
2835 * eviction work signaled the fence.
2837 WARN_ONCE(!dma_fence_is_signaled(old_ef),
2838 "Replacing unsignaled eviction fence");
2839 dma_fence_put(old_ef);
2842 /** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given
2843 * KFD process identified by process_info
2845 * @process_info: amdkfd_process_info of the KFD process
2847 * After memory eviction, restore thread calls this function. The function
2848 * should be called when the Process is still valid. BO restore involves -
2850 * 1. Release old eviction fence and create new one
2851 * 2. Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.
2852 * 3 Use the second PD list and kfd_bo_list to create a list (ctx.list) of
2853 * BOs that need to be reserved.
2854 * 4. Reserve all the BOs
2855 * 5. Validate of PD and PT BOs.
2856 * 6. Validate all KFD BOs using kfd_bo_list and Map them and add new fence
2857 * 7. Add fence to all PD and PT BOs.
2858 * 8. Unreserve all BOs
2860 int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence __rcu **ef)
2862 struct amdkfd_process_info *process_info = info;
2863 struct amdgpu_vm *peer_vm;
2864 struct kgd_mem *mem;
2865 struct list_head duplicate_save;
2866 struct amdgpu_sync sync_obj;
2867 unsigned long failed_size = 0;
2868 unsigned long total_size = 0;
2869 struct drm_exec exec;
2872 INIT_LIST_HEAD(&duplicate_save);
2874 mutex_lock(&process_info->lock);
2876 drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);
2877 drm_exec_until_all_locked(&exec) {
2878 list_for_each_entry(peer_vm, &process_info->vm_list_head,
2880 ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2);
2881 drm_exec_retry_on_contention(&exec);
2882 if (unlikely(ret)) {
2883 pr_err("Locking VM PD failed, ret: %d\n", ret);
2884 goto ttm_reserve_fail;
2888 /* Reserve all BOs and page tables/directory. Add all BOs from
2889 * kfd_bo_list to ctx.list
2891 list_for_each_entry(mem, &process_info->kfd_bo_list,
2893 struct drm_gem_object *gobj;
2895 gobj = &mem->bo->tbo.base;
2896 ret = drm_exec_prepare_obj(&exec, gobj, 1);
2897 drm_exec_retry_on_contention(&exec);
2898 if (unlikely(ret)) {
2899 pr_err("drm_exec_prepare_obj failed, ret: %d\n", ret);
2900 goto ttm_reserve_fail;
2905 amdgpu_sync_create(&sync_obj);
2907 /* Validate BOs managed by KFD */
2908 list_for_each_entry(mem, &process_info->kfd_bo_list,
2911 struct amdgpu_bo *bo = mem->bo;
2912 uint32_t domain = mem->domain;
2913 struct dma_resv_iter cursor;
2914 struct dma_fence *fence;
2916 total_size += amdgpu_bo_size(bo);
2918 ret = amdgpu_amdkfd_bo_validate(bo, domain, false);
2920 pr_debug("Memory eviction: Validate BOs failed\n");
2921 failed_size += amdgpu_bo_size(bo);
2922 ret = amdgpu_amdkfd_bo_validate(bo,
2923 AMDGPU_GEM_DOMAIN_GTT, false);
2925 pr_debug("Memory eviction: Try again\n");
2926 goto validate_map_fail;
2929 dma_resv_for_each_fence(&cursor, bo->tbo.base.resv,
2930 DMA_RESV_USAGE_KERNEL, fence) {
2931 ret = amdgpu_sync_fence(&sync_obj, fence);
2933 pr_debug("Memory eviction: Sync BO fence failed. Try again\n");
2934 goto validate_map_fail;
2940 pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size);
2942 /* Validate PDs, PTs and evicted DMABuf imports last. Otherwise BO
2943 * validations above would invalidate DMABuf imports again.
2945 ret = process_validate_vms(process_info, &exec.ticket);
2947 pr_debug("Validating VMs failed, ret: %d\n", ret);
2948 goto validate_map_fail;
2951 /* Update mappings managed by KFD. */
2952 list_for_each_entry(mem, &process_info->kfd_bo_list,
2954 struct kfd_mem_attachment *attachment;
2956 list_for_each_entry(attachment, &mem->attachments, list) {
2957 if (!attachment->is_mapped)
2960 if (attachment->bo_va->base.bo->tbo.pin_count)
2963 kfd_mem_dmaunmap_attachment(mem, attachment);
2964 ret = update_gpuvm_pte(mem, attachment, &sync_obj);
2966 pr_debug("Memory eviction: update PTE failed. Try again\n");
2967 goto validate_map_fail;
2972 /* Update mappings not managed by KFD */
2973 list_for_each_entry(peer_vm, &process_info->vm_list_head,
2975 struct amdgpu_device *adev = amdgpu_ttm_adev(
2976 peer_vm->root.bo->tbo.bdev);
2978 ret = amdgpu_vm_handle_moved(adev, peer_vm, &exec.ticket);
2980 pr_debug("Memory eviction: handle moved failed. Try again\n");
2981 goto validate_map_fail;
2985 /* Update page directories */
2986 ret = process_update_pds(process_info, &sync_obj);
2988 pr_debug("Memory eviction: update PDs failed. Try again\n");
2989 goto validate_map_fail;
2992 /* Sync with fences on all the page tables. They implicitly depend on any
2993 * move fences from amdgpu_vm_handle_moved above.
2995 ret = process_sync_pds_resv(process_info, &sync_obj);
2997 pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");
2998 goto validate_map_fail;
3001 /* Wait for validate and PT updates to finish */
3002 amdgpu_sync_wait(&sync_obj, false);
3004 /* The old eviction fence may be unsignaled if restore happens
3005 * after a GPU reset or suspend/resume. Keep the old fence in that
3006 * case. Otherwise release the old eviction fence and create new
3007 * one, because fence only goes from unsignaled to signaled once
3008 * and cannot be reused. Use context and mm from the old fence.
3010 * If an old eviction fence signals after this check, that's OK.
3011 * Anyone signaling an eviction fence must stop the queues first
3012 * and schedule another restore worker.
3014 if (dma_fence_is_signaled(&process_info->eviction_fence->base)) {
3015 struct amdgpu_amdkfd_fence *new_fence =
3016 amdgpu_amdkfd_fence_create(
3017 process_info->eviction_fence->base.context,
3018 process_info->eviction_fence->mm,
3022 pr_err("Failed to create eviction fence\n");
3024 goto validate_map_fail;
3026 dma_fence_put(&process_info->eviction_fence->base);
3027 process_info->eviction_fence = new_fence;
3028 replace_eviction_fence(ef, dma_fence_get(&new_fence->base));
3030 WARN_ONCE(*ef != &process_info->eviction_fence->base,
3031 "KFD eviction fence doesn't match KGD process_info");
3034 /* Attach new eviction fence to all BOs except pinned ones */
3035 list_for_each_entry(mem, &process_info->kfd_bo_list, validate_list) {
3036 if (mem->bo->tbo.pin_count)
3039 dma_resv_add_fence(mem->bo->tbo.base.resv,
3040 &process_info->eviction_fence->base,
3041 DMA_RESV_USAGE_BOOKKEEP);
3043 /* Attach eviction fence to PD / PT BOs and DMABuf imports */
3044 list_for_each_entry(peer_vm, &process_info->vm_list_head,
3046 struct amdgpu_bo *bo = peer_vm->root.bo;
3048 dma_resv_add_fence(bo->tbo.base.resv,
3049 &process_info->eviction_fence->base,
3050 DMA_RESV_USAGE_BOOKKEEP);
3054 amdgpu_sync_free(&sync_obj);
3056 drm_exec_fini(&exec);
3057 mutex_unlock(&process_info->lock);
3061 int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem)
3063 struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
3064 struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws;
3070 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
3074 mutex_init(&(*mem)->lock);
3075 INIT_LIST_HEAD(&(*mem)->attachments);
3076 (*mem)->bo = amdgpu_bo_ref(gws_bo);
3077 (*mem)->domain = AMDGPU_GEM_DOMAIN_GWS;
3078 (*mem)->process_info = process_info;
3079 add_kgd_mem_to_kfd_bo_list(*mem, process_info, false);
3080 amdgpu_sync_create(&(*mem)->sync);
3083 /* Validate gws bo the first time it is added to process */
3084 mutex_lock(&(*mem)->process_info->lock);
3085 ret = amdgpu_bo_reserve(gws_bo, false);
3086 if (unlikely(ret)) {
3087 pr_err("Reserve gws bo failed %d\n", ret);
3088 goto bo_reservation_failure;
3091 ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true);
3093 pr_err("GWS BO validate failed %d\n", ret);
3094 goto bo_validation_failure;
3096 /* GWS resource is shared b/t amdgpu and amdkfd
3097 * Add process eviction fence to bo so they can
3100 ret = dma_resv_reserve_fences(gws_bo->tbo.base.resv, 1);
3102 goto reserve_shared_fail;
3103 dma_resv_add_fence(gws_bo->tbo.base.resv,
3104 &process_info->eviction_fence->base,
3105 DMA_RESV_USAGE_BOOKKEEP);
3106 amdgpu_bo_unreserve(gws_bo);
3107 mutex_unlock(&(*mem)->process_info->lock);
3111 reserve_shared_fail:
3112 bo_validation_failure:
3113 amdgpu_bo_unreserve(gws_bo);
3114 bo_reservation_failure:
3115 mutex_unlock(&(*mem)->process_info->lock);
3116 amdgpu_sync_free(&(*mem)->sync);
3117 remove_kgd_mem_from_kfd_bo_list(*mem, process_info);
3118 amdgpu_bo_unref(&gws_bo);
3119 mutex_destroy(&(*mem)->lock);
3125 int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem)
3128 struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
3129 struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;
3130 struct amdgpu_bo *gws_bo = kgd_mem->bo;
3132 /* Remove BO from process's validate list so restore worker won't touch
3135 remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info);
3137 ret = amdgpu_bo_reserve(gws_bo, false);
3138 if (unlikely(ret)) {
3139 pr_err("Reserve gws bo failed %d\n", ret);
3140 //TODO add BO back to validate_list?
3143 amdgpu_amdkfd_remove_eviction_fence(gws_bo,
3144 process_info->eviction_fence);
3145 amdgpu_bo_unreserve(gws_bo);
3146 amdgpu_sync_free(&kgd_mem->sync);
3147 amdgpu_bo_unref(&gws_bo);
3148 mutex_destroy(&kgd_mem->lock);
3153 /* Returns GPU-specific tiling mode information */
3154 int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev,
3155 struct tile_config *config)
3157 config->gb_addr_config = adev->gfx.config.gb_addr_config;
3158 config->tile_config_ptr = adev->gfx.config.tile_mode_array;
3159 config->num_tile_configs =
3160 ARRAY_SIZE(adev->gfx.config.tile_mode_array);
3161 config->macro_tile_config_ptr =
3162 adev->gfx.config.macrotile_mode_array;
3163 config->num_macro_tile_configs =
3164 ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);
3166 /* Those values are not set from GFX9 onwards */
3167 config->num_banks = adev->gfx.config.num_banks;
3168 config->num_ranks = adev->gfx.config.num_ranks;
3173 bool amdgpu_amdkfd_bo_mapped_to_dev(struct amdgpu_device *adev, struct kgd_mem *mem)
3175 struct kfd_mem_attachment *entry;
3177 list_for_each_entry(entry, &mem->attachments, list) {
3178 if (entry->is_mapped && entry->adev == adev)
3184 #if defined(CONFIG_DEBUG_FS)
3186 int kfd_debugfs_kfd_mem_limits(struct seq_file *m, void *data)
3189 spin_lock(&kfd_mem_limit.mem_limit_lock);
3190 seq_printf(m, "System mem used %lldM out of %lluM\n",
3191 (kfd_mem_limit.system_mem_used >> 20),
3192 (kfd_mem_limit.max_system_mem_limit >> 20));
3193 seq_printf(m, "TTM mem used %lldM out of %lluM\n",
3194 (kfd_mem_limit.ttm_mem_used >> 20),
3195 (kfd_mem_limit.max_ttm_mem_limit >> 20));
3196 spin_unlock(&kfd_mem_limit.mem_limit_lock);