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 <drm/ttm/ttm_tt.h>
30 #include "amdgpu_object.h"
31 #include "amdgpu_gem.h"
32 #include "amdgpu_vm.h"
33 #include "amdgpu_hmm.h"
34 #include "amdgpu_amdkfd.h"
35 #include "amdgpu_dma_buf.h"
36 #include <uapi/linux/kfd_ioctl.h>
37 #include "amdgpu_xgmi.h"
39 #include "kfd_smi_events.h"
40 #include <drm/ttm/ttm_tt.h>
42 /* Userptr restore delay, just long enough to allow consecutive VM
43 * changes to accumulate
45 #define AMDGPU_USERPTR_RESTORE_DELAY_MS 1
48 * Align VRAM availability to 2MB to avoid fragmentation caused by 4K allocations in the tail 2MB
51 #define VRAM_AVAILABLITY_ALIGN (1 << 21)
53 /* Impose limit on how much memory KFD can use */
55 uint64_t max_system_mem_limit;
56 uint64_t max_ttm_mem_limit;
57 int64_t system_mem_used;
59 spinlock_t mem_limit_lock;
62 static const char * const domain_bit_to_string[] = {
71 #define domain_string(domain) domain_bit_to_string[ffs(domain)-1]
73 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work);
75 static bool kfd_mem_is_attached(struct amdgpu_vm *avm,
78 struct kfd_mem_attachment *entry;
80 list_for_each_entry(entry, &mem->attachments, list)
81 if (entry->bo_va->base.vm == avm)
88 * reuse_dmamap() - Check whether adev can share the original
91 * If both adev and bo_adev are in direct mapping or
92 * in the same iommu group, they can share the original BO.
94 * @adev: Device to which can or cannot share the original BO
95 * @bo_adev: Device to which allocated BO belongs to
97 * Return: returns true if adev can share original userptr BO,
100 static bool reuse_dmamap(struct amdgpu_device *adev, struct amdgpu_device *bo_adev)
102 return (adev->ram_is_direct_mapped && bo_adev->ram_is_direct_mapped) ||
103 (adev->dev->iommu_group == bo_adev->dev->iommu_group);
106 /* Set memory usage limits. Current, limits are
107 * System (TTM + userptr) memory - 15/16th System RAM
108 * TTM memory - 3/8th System RAM
110 void amdgpu_amdkfd_gpuvm_init_mem_limits(void)
115 if (kfd_mem_limit.max_system_mem_limit)
119 mem = si.freeram - si.freehigh;
122 spin_lock_init(&kfd_mem_limit.mem_limit_lock);
123 kfd_mem_limit.max_system_mem_limit = mem - (mem >> 4);
124 kfd_mem_limit.max_ttm_mem_limit = ttm_tt_pages_limit() << PAGE_SHIFT;
125 pr_debug("Kernel memory limit %lluM, TTM limit %lluM\n",
126 (kfd_mem_limit.max_system_mem_limit >> 20),
127 (kfd_mem_limit.max_ttm_mem_limit >> 20));
130 void amdgpu_amdkfd_reserve_system_mem(uint64_t size)
132 kfd_mem_limit.system_mem_used += size;
135 /* Estimate page table size needed to represent a given memory size
137 * With 4KB pages, we need one 8 byte PTE for each 4KB of memory
138 * (factor 512, >> 9). With 2MB pages, we need one 8 byte PTE for 2MB
139 * of memory (factor 256K, >> 18). ROCm user mode tries to optimize
140 * for 2MB pages for TLB efficiency. However, small allocations and
141 * fragmented system memory still need some 4KB pages. We choose a
142 * compromise that should work in most cases without reserving too
143 * much memory for page tables unnecessarily (factor 16K, >> 14).
146 #define ESTIMATE_PT_SIZE(mem_size) max(((mem_size) >> 14), AMDGPU_VM_RESERVED_VRAM)
149 * amdgpu_amdkfd_reserve_mem_limit() - Decrease available memory by size
152 * @adev: Device to which allocated BO belongs to
153 * @size: Size of buffer, in bytes, encapsulated by B0. This should be
154 * equivalent to amdgpu_bo_size(BO)
155 * @alloc_flag: Flag used in allocating a BO as noted above
156 * @xcp_id: xcp_id is used to get xcp from xcp manager, one xcp is
157 * managed as one compute node in driver for app
160 * returns -ENOMEM in case of error, ZERO otherwise
162 int amdgpu_amdkfd_reserve_mem_limit(struct amdgpu_device *adev,
163 uint64_t size, u32 alloc_flag, int8_t xcp_id)
165 uint64_t reserved_for_pt =
166 ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);
167 size_t system_mem_needed, ttm_mem_needed, vram_needed;
169 uint64_t vram_size = 0;
171 system_mem_needed = 0;
174 if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
175 system_mem_needed = size;
176 ttm_mem_needed = size;
177 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
179 * Conservatively round up the allocation requirement to 2 MB
180 * to avoid fragmentation caused by 4K allocations in the tail
185 * For GFX 9.4.3, get the VRAM size from XCP structs
187 if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id))
190 vram_size = KFD_XCP_MEMORY_SIZE(adev, xcp_id);
191 if (adev->gmc.is_app_apu) {
192 system_mem_needed = size;
193 ttm_mem_needed = size;
195 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
196 system_mem_needed = size;
197 } else if (!(alloc_flag &
198 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
199 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {
200 pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
204 spin_lock(&kfd_mem_limit.mem_limit_lock);
206 if (kfd_mem_limit.system_mem_used + system_mem_needed >
207 kfd_mem_limit.max_system_mem_limit)
208 pr_debug("Set no_system_mem_limit=1 if using shared memory\n");
210 if ((kfd_mem_limit.system_mem_used + system_mem_needed >
211 kfd_mem_limit.max_system_mem_limit && !no_system_mem_limit) ||
212 (kfd_mem_limit.ttm_mem_used + ttm_mem_needed >
213 kfd_mem_limit.max_ttm_mem_limit) ||
214 (adev && xcp_id >= 0 && adev->kfd.vram_used[xcp_id] + vram_needed >
215 vram_size - reserved_for_pt)) {
220 /* Update memory accounting by decreasing available system
221 * memory, TTM memory and GPU memory as computed above
223 WARN_ONCE(vram_needed && !adev,
224 "adev reference can't be null when vram is used");
225 if (adev && xcp_id >= 0) {
226 adev->kfd.vram_used[xcp_id] += vram_needed;
227 adev->kfd.vram_used_aligned[xcp_id] += adev->gmc.is_app_apu ?
229 ALIGN(vram_needed, VRAM_AVAILABLITY_ALIGN);
231 kfd_mem_limit.system_mem_used += system_mem_needed;
232 kfd_mem_limit.ttm_mem_used += ttm_mem_needed;
235 spin_unlock(&kfd_mem_limit.mem_limit_lock);
239 void amdgpu_amdkfd_unreserve_mem_limit(struct amdgpu_device *adev,
240 uint64_t size, u32 alloc_flag, int8_t xcp_id)
242 spin_lock(&kfd_mem_limit.mem_limit_lock);
244 if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
245 kfd_mem_limit.system_mem_used -= size;
246 kfd_mem_limit.ttm_mem_used -= size;
247 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
249 "adev reference can't be null when alloc mem flags vram is set");
250 if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id))
254 adev->kfd.vram_used[xcp_id] -= size;
255 if (adev->gmc.is_app_apu) {
256 adev->kfd.vram_used_aligned[xcp_id] -= size;
257 kfd_mem_limit.system_mem_used -= size;
258 kfd_mem_limit.ttm_mem_used -= size;
260 adev->kfd.vram_used_aligned[xcp_id] -=
261 ALIGN(size, VRAM_AVAILABLITY_ALIGN);
264 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
265 kfd_mem_limit.system_mem_used -= size;
266 } else if (!(alloc_flag &
267 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
268 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {
269 pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
272 WARN_ONCE(adev && xcp_id >= 0 && adev->kfd.vram_used[xcp_id] < 0,
273 "KFD VRAM memory accounting unbalanced for xcp: %d", xcp_id);
274 WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0,
275 "KFD TTM memory accounting unbalanced");
276 WARN_ONCE(kfd_mem_limit.system_mem_used < 0,
277 "KFD system memory accounting unbalanced");
280 spin_unlock(&kfd_mem_limit.mem_limit_lock);
283 void amdgpu_amdkfd_release_notify(struct amdgpu_bo *bo)
285 struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
286 u32 alloc_flags = bo->kfd_bo->alloc_flags;
287 u64 size = amdgpu_bo_size(bo);
289 amdgpu_amdkfd_unreserve_mem_limit(adev, size, alloc_flags,
296 * create_dmamap_sg_bo() - Creates a amdgpu_bo object to reflect information
297 * about USERPTR or DOOREBELL or MMIO BO.
299 * @adev: Device for which dmamap BO is being created
300 * @mem: BO of peer device that is being DMA mapped. Provides parameters
301 * in building the dmamap BO
302 * @bo_out: Output parameter updated with handle of dmamap BO
305 create_dmamap_sg_bo(struct amdgpu_device *adev,
306 struct kgd_mem *mem, struct amdgpu_bo **bo_out)
308 struct drm_gem_object *gem_obj;
312 ret = amdgpu_bo_reserve(mem->bo, false);
316 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR)
317 flags |= mem->bo->flags & (AMDGPU_GEM_CREATE_COHERENT |
318 AMDGPU_GEM_CREATE_UNCACHED);
320 ret = amdgpu_gem_object_create(adev, mem->bo->tbo.base.size, 1,
321 AMDGPU_GEM_DOMAIN_CPU, AMDGPU_GEM_CREATE_PREEMPTIBLE | flags,
322 ttm_bo_type_sg, mem->bo->tbo.base.resv, &gem_obj, 0);
324 amdgpu_bo_unreserve(mem->bo);
327 pr_err("Error in creating DMA mappable SG BO on domain: %d\n", ret);
331 *bo_out = gem_to_amdgpu_bo(gem_obj);
332 (*bo_out)->parent = amdgpu_bo_ref(mem->bo);
336 /* amdgpu_amdkfd_remove_eviction_fence - Removes eviction fence from BO's
337 * reservation object.
339 * @bo: [IN] Remove eviction fence(s) from this BO
340 * @ef: [IN] This eviction fence is removed if it
341 * is present in the shared list.
343 * NOTE: Must be called with BO reserved i.e. bo->tbo.resv->lock held.
345 static int amdgpu_amdkfd_remove_eviction_fence(struct amdgpu_bo *bo,
346 struct amdgpu_amdkfd_fence *ef)
348 struct dma_fence *replacement;
353 /* TODO: Instead of block before we should use the fence of the page
354 * table update and TLB flush here directly.
356 replacement = dma_fence_get_stub();
357 dma_resv_replace_fences(bo->tbo.base.resv, ef->base.context,
358 replacement, DMA_RESV_USAGE_BOOKKEEP);
359 dma_fence_put(replacement);
363 int amdgpu_amdkfd_remove_fence_on_pt_pd_bos(struct amdgpu_bo *bo)
365 struct amdgpu_bo *root = bo;
366 struct amdgpu_vm_bo_base *vm_bo;
367 struct amdgpu_vm *vm;
368 struct amdkfd_process_info *info;
369 struct amdgpu_amdkfd_fence *ef;
372 /* we can always get vm_bo from root PD bo.*/
384 info = vm->process_info;
385 if (!info || !info->eviction_fence)
388 ef = container_of(dma_fence_get(&info->eviction_fence->base),
389 struct amdgpu_amdkfd_fence, base);
391 BUG_ON(!dma_resv_trylock(bo->tbo.base.resv));
392 ret = amdgpu_amdkfd_remove_eviction_fence(bo, ef);
393 dma_resv_unlock(bo->tbo.base.resv);
395 dma_fence_put(&ef->base);
399 static int amdgpu_amdkfd_bo_validate(struct amdgpu_bo *bo, uint32_t domain,
402 struct ttm_operation_ctx ctx = { false, false };
405 if (WARN(amdgpu_ttm_tt_get_usermm(bo->tbo.ttm),
406 "Called with userptr BO"))
409 amdgpu_bo_placement_from_domain(bo, domain);
411 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
415 amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
421 static int amdgpu_amdkfd_validate_vm_bo(void *_unused, struct amdgpu_bo *bo)
423 return amdgpu_amdkfd_bo_validate(bo, bo->allowed_domains, false);
426 /* vm_validate_pt_pd_bos - Validate page table and directory BOs
428 * Page directories are not updated here because huge page handling
429 * during page table updates can invalidate page directory entries
430 * again. Page directories are only updated after updating page
433 static int vm_validate_pt_pd_bos(struct amdgpu_vm *vm)
435 struct amdgpu_bo *pd = vm->root.bo;
436 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
439 ret = amdgpu_vm_validate_pt_bos(adev, vm, amdgpu_amdkfd_validate_vm_bo, NULL);
441 pr_err("failed to validate PT BOs\n");
445 vm->pd_phys_addr = amdgpu_gmc_pd_addr(vm->root.bo);
450 static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync)
452 struct amdgpu_bo *pd = vm->root.bo;
453 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
456 ret = amdgpu_vm_update_pdes(adev, vm, false);
460 return amdgpu_sync_fence(sync, vm->last_update);
463 static uint64_t get_pte_flags(struct amdgpu_device *adev, struct kgd_mem *mem)
465 uint32_t mapping_flags = AMDGPU_VM_PAGE_READABLE |
466 AMDGPU_VM_MTYPE_DEFAULT;
468 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE)
469 mapping_flags |= AMDGPU_VM_PAGE_WRITEABLE;
470 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE)
471 mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE;
473 return amdgpu_gem_va_map_flags(adev, mapping_flags);
477 * create_sg_table() - Create an sg_table for a contiguous DMA addr range
478 * @addr: The starting address to point to
479 * @size: Size of memory area in bytes being pointed to
481 * Allocates an instance of sg_table and initializes it to point to memory
482 * area specified by input parameters. The address used to build is assumed
483 * to be DMA mapped, if needed.
485 * DOORBELL or MMIO BOs use only one scatterlist node in their sg_table
486 * because they are physically contiguous.
488 * Return: Initialized instance of SG Table or NULL
490 static struct sg_table *create_sg_table(uint64_t addr, uint32_t size)
492 struct sg_table *sg = kmalloc(sizeof(*sg), GFP_KERNEL);
496 if (sg_alloc_table(sg, 1, GFP_KERNEL)) {
500 sg_dma_address(sg->sgl) = addr;
501 sg->sgl->length = size;
502 #ifdef CONFIG_NEED_SG_DMA_LENGTH
503 sg->sgl->dma_length = size;
509 kfd_mem_dmamap_userptr(struct kgd_mem *mem,
510 struct kfd_mem_attachment *attachment)
512 enum dma_data_direction direction =
513 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
514 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
515 struct ttm_operation_ctx ctx = {.interruptible = true};
516 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
517 struct amdgpu_device *adev = attachment->adev;
518 struct ttm_tt *src_ttm = mem->bo->tbo.ttm;
519 struct ttm_tt *ttm = bo->tbo.ttm;
522 if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
525 ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL);
526 if (unlikely(!ttm->sg))
529 /* Same sequence as in amdgpu_ttm_tt_pin_userptr */
530 ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages,
532 (u64)ttm->num_pages << PAGE_SHIFT,
537 ret = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
541 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
542 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
549 dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
551 pr_err("DMA map userptr failed: %d\n", ret);
552 sg_free_table(ttm->sg);
560 kfd_mem_dmamap_dmabuf(struct kfd_mem_attachment *attachment)
562 struct ttm_operation_ctx ctx = {.interruptible = true};
563 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
566 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
567 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
571 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
572 return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
576 * kfd_mem_dmamap_sg_bo() - Create DMA mapped sg_table to access DOORBELL or MMIO BO
577 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device
578 * @attachment: Virtual address attachment of the BO on accessing device
580 * An access request from the device that owns DOORBELL does not require DMA mapping.
581 * This is because the request doesn't go through PCIe root complex i.e. it instead
582 * loops back. The need to DMA map arises only when accessing peer device's DOORBELL
584 * In contrast, all access requests for MMIO need to be DMA mapped without regard to
585 * device ownership. This is because access requests for MMIO go through PCIe root
588 * This is accomplished in two steps:
589 * - Obtain DMA mapped address of DOORBELL or MMIO memory that could be used
590 * in updating requesting device's page table
591 * - Signal TTM to mark memory pointed to by requesting device's BO as GPU
592 * accessible. This allows an update of requesting device's page table
593 * with entries associated with DOOREBELL or MMIO memory
595 * This method is invoked in the following contexts:
596 * - Mapping of DOORBELL or MMIO BO of same or peer device
597 * - Validating an evicted DOOREBELL or MMIO BO on device seeking access
599 * Return: ZERO if successful, NON-ZERO otherwise
602 kfd_mem_dmamap_sg_bo(struct kgd_mem *mem,
603 struct kfd_mem_attachment *attachment)
605 struct ttm_operation_ctx ctx = {.interruptible = true};
606 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
607 struct amdgpu_device *adev = attachment->adev;
608 struct ttm_tt *ttm = bo->tbo.ttm;
609 enum dma_data_direction dir;
614 /* Expect SG Table of dmapmap BO to be NULL */
615 mmio = (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP);
616 if (unlikely(ttm->sg)) {
617 pr_err("SG Table of %d BO for peer device is UNEXPECTEDLY NON-NULL", mmio);
621 dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
622 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
623 dma_addr = mem->bo->tbo.sg->sgl->dma_address;
624 pr_debug("%d BO size: %d\n", mmio, mem->bo->tbo.sg->sgl->length);
625 pr_debug("%d BO address before DMA mapping: %llx\n", mmio, dma_addr);
626 dma_addr = dma_map_resource(adev->dev, dma_addr,
627 mem->bo->tbo.sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);
628 ret = dma_mapping_error(adev->dev, dma_addr);
631 pr_debug("%d BO address after DMA mapping: %llx\n", mmio, dma_addr);
633 ttm->sg = create_sg_table(dma_addr, mem->bo->tbo.sg->sgl->length);
634 if (unlikely(!ttm->sg)) {
639 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
640 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
647 sg_free_table(ttm->sg);
651 dma_unmap_resource(adev->dev, dma_addr, mem->bo->tbo.sg->sgl->length,
652 dir, DMA_ATTR_SKIP_CPU_SYNC);
657 kfd_mem_dmamap_attachment(struct kgd_mem *mem,
658 struct kfd_mem_attachment *attachment)
660 switch (attachment->type) {
661 case KFD_MEM_ATT_SHARED:
663 case KFD_MEM_ATT_USERPTR:
664 return kfd_mem_dmamap_userptr(mem, attachment);
665 case KFD_MEM_ATT_DMABUF:
666 return kfd_mem_dmamap_dmabuf(attachment);
668 return kfd_mem_dmamap_sg_bo(mem, attachment);
676 kfd_mem_dmaunmap_userptr(struct kgd_mem *mem,
677 struct kfd_mem_attachment *attachment)
679 enum dma_data_direction direction =
680 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
681 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
682 struct ttm_operation_ctx ctx = {.interruptible = false};
683 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
684 struct amdgpu_device *adev = attachment->adev;
685 struct ttm_tt *ttm = bo->tbo.ttm;
687 if (unlikely(!ttm->sg))
690 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
691 ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
693 dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
694 sg_free_table(ttm->sg);
700 kfd_mem_dmaunmap_dmabuf(struct kfd_mem_attachment *attachment)
702 /* This is a no-op. We don't want to trigger eviction fences when
703 * unmapping DMABufs. Therefore the invalidation (moving to system
704 * domain) is done in kfd_mem_dmamap_dmabuf.
709 * kfd_mem_dmaunmap_sg_bo() - Free DMA mapped sg_table of DOORBELL or MMIO BO
710 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device
711 * @attachment: Virtual address attachment of the BO on accessing device
713 * The method performs following steps:
714 * - Signal TTM to mark memory pointed to by BO as GPU inaccessible
715 * - Free SG Table that is used to encapsulate DMA mapped memory of
716 * peer device's DOORBELL or MMIO memory
718 * This method is invoked in the following contexts:
719 * UNMapping of DOORBELL or MMIO BO on a device having access to its memory
720 * Eviction of DOOREBELL or MMIO BO on device having access to its memory
725 kfd_mem_dmaunmap_sg_bo(struct kgd_mem *mem,
726 struct kfd_mem_attachment *attachment)
728 struct ttm_operation_ctx ctx = {.interruptible = true};
729 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
730 struct amdgpu_device *adev = attachment->adev;
731 struct ttm_tt *ttm = bo->tbo.ttm;
732 enum dma_data_direction dir;
734 if (unlikely(!ttm->sg)) {
735 pr_err("SG Table of BO is UNEXPECTEDLY NULL");
739 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
740 ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
742 dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
743 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
744 dma_unmap_resource(adev->dev, ttm->sg->sgl->dma_address,
745 ttm->sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);
746 sg_free_table(ttm->sg);
753 kfd_mem_dmaunmap_attachment(struct kgd_mem *mem,
754 struct kfd_mem_attachment *attachment)
756 switch (attachment->type) {
757 case KFD_MEM_ATT_SHARED:
759 case KFD_MEM_ATT_USERPTR:
760 kfd_mem_dmaunmap_userptr(mem, attachment);
762 case KFD_MEM_ATT_DMABUF:
763 kfd_mem_dmaunmap_dmabuf(attachment);
766 kfd_mem_dmaunmap_sg_bo(mem, attachment);
773 static int kfd_mem_export_dmabuf(struct kgd_mem *mem)
776 struct dma_buf *ret = amdgpu_gem_prime_export(
778 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
789 kfd_mem_attach_dmabuf(struct amdgpu_device *adev, struct kgd_mem *mem,
790 struct amdgpu_bo **bo)
792 struct drm_gem_object *gobj;
795 ret = kfd_mem_export_dmabuf(mem);
799 gobj = amdgpu_gem_prime_import(adev_to_drm(adev), mem->dmabuf);
801 return PTR_ERR(gobj);
803 *bo = gem_to_amdgpu_bo(gobj);
804 (*bo)->flags |= AMDGPU_GEM_CREATE_PREEMPTIBLE;
809 /* kfd_mem_attach - Add a BO to a VM
811 * Everything that needs to bo done only once when a BO is first added
812 * to a VM. It can later be mapped and unmapped many times without
813 * repeating these steps.
815 * 0. Create BO for DMA mapping, if needed
816 * 1. Allocate and initialize BO VA entry data structure
817 * 2. Add BO to the VM
818 * 3. Determine ASIC-specific PTE flags
819 * 4. Alloc page tables and directories if needed
820 * 4a. Validate new page tables and directories
822 static int kfd_mem_attach(struct amdgpu_device *adev, struct kgd_mem *mem,
823 struct amdgpu_vm *vm, bool is_aql)
825 struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);
826 unsigned long bo_size = mem->bo->tbo.base.size;
827 uint64_t va = mem->va;
828 struct kfd_mem_attachment *attachment[2] = {NULL, NULL};
829 struct amdgpu_bo *bo[2] = {NULL, NULL};
830 bool same_hive = false;
834 pr_err("Invalid VA when adding BO to VM\n");
838 /* Determine access to VRAM, MMIO and DOORBELL BOs of peer devices
840 * The access path of MMIO and DOORBELL BOs of is always over PCIe.
841 * In contrast the access path of VRAM BOs depens upon the type of
842 * link that connects the peer device. Access over PCIe is allowed
843 * if peer device has large BAR. In contrast, access over xGMI is
844 * allowed for both small and large BAR configurations of peer device
846 if ((adev != bo_adev && !adev->gmc.is_app_apu) &&
847 ((mem->domain == AMDGPU_GEM_DOMAIN_VRAM) ||
848 (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) ||
849 (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {
850 if (mem->domain == AMDGPU_GEM_DOMAIN_VRAM)
851 same_hive = amdgpu_xgmi_same_hive(adev, bo_adev);
852 if (!same_hive && !amdgpu_device_is_peer_accessible(bo_adev, adev))
856 for (i = 0; i <= is_aql; i++) {
857 attachment[i] = kzalloc(sizeof(*attachment[i]), GFP_KERNEL);
858 if (unlikely(!attachment[i])) {
863 pr_debug("\t add VA 0x%llx - 0x%llx to vm %p\n", va,
866 if ((adev == bo_adev && !(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) ||
867 (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) && reuse_dmamap(adev, bo_adev)) ||
869 /* Mappings on the local GPU, or VRAM mappings in the
870 * local hive, or userptr mapping can reuse dma map
871 * address space share the original BO
873 attachment[i]->type = KFD_MEM_ATT_SHARED;
875 drm_gem_object_get(&bo[i]->tbo.base);
877 /* Multiple mappings on the same GPU share the BO */
878 attachment[i]->type = KFD_MEM_ATT_SHARED;
880 drm_gem_object_get(&bo[i]->tbo.base);
881 } else if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {
882 /* Create an SG BO to DMA-map userptrs on other GPUs */
883 attachment[i]->type = KFD_MEM_ATT_USERPTR;
884 ret = create_dmamap_sg_bo(adev, mem, &bo[i]);
887 /* Handle DOORBELL BOs of peer devices and MMIO BOs of local and peer devices */
888 } else if (mem->bo->tbo.type == ttm_bo_type_sg) {
889 WARN_ONCE(!(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL ||
890 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP),
891 "Handing invalid SG BO in ATTACH request");
892 attachment[i]->type = KFD_MEM_ATT_SG;
893 ret = create_dmamap_sg_bo(adev, mem, &bo[i]);
896 /* Enable acces to GTT and VRAM BOs of peer devices */
897 } else if (mem->domain == AMDGPU_GEM_DOMAIN_GTT ||
898 mem->domain == AMDGPU_GEM_DOMAIN_VRAM) {
899 attachment[i]->type = KFD_MEM_ATT_DMABUF;
900 ret = kfd_mem_attach_dmabuf(adev, mem, &bo[i]);
903 pr_debug("Employ DMABUF mechanism to enable peer GPU access\n");
905 WARN_ONCE(true, "Handling invalid ATTACH request");
910 /* Add BO to VM internal data structures */
911 ret = amdgpu_bo_reserve(bo[i], false);
913 pr_debug("Unable to reserve BO during memory attach");
916 attachment[i]->bo_va = amdgpu_vm_bo_add(adev, vm, bo[i]);
917 amdgpu_bo_unreserve(bo[i]);
918 if (unlikely(!attachment[i]->bo_va)) {
920 pr_err("Failed to add BO object to VM. ret == %d\n",
924 attachment[i]->va = va;
925 attachment[i]->pte_flags = get_pte_flags(adev, mem);
926 attachment[i]->adev = adev;
927 list_add(&attachment[i]->list, &mem->attachments);
935 for (; i >= 0; i--) {
938 if (attachment[i]->bo_va) {
939 amdgpu_bo_reserve(bo[i], true);
940 amdgpu_vm_bo_del(adev, attachment[i]->bo_va);
941 amdgpu_bo_unreserve(bo[i]);
942 list_del(&attachment[i]->list);
945 drm_gem_object_put(&bo[i]->tbo.base);
946 kfree(attachment[i]);
951 static void kfd_mem_detach(struct kfd_mem_attachment *attachment)
953 struct amdgpu_bo *bo = attachment->bo_va->base.bo;
955 pr_debug("\t remove VA 0x%llx in entry %p\n",
956 attachment->va, attachment);
957 amdgpu_vm_bo_del(attachment->adev, attachment->bo_va);
958 drm_gem_object_put(&bo->tbo.base);
959 list_del(&attachment->list);
963 static void add_kgd_mem_to_kfd_bo_list(struct kgd_mem *mem,
964 struct amdkfd_process_info *process_info,
967 struct ttm_validate_buffer *entry = &mem->validate_list;
968 struct amdgpu_bo *bo = mem->bo;
970 INIT_LIST_HEAD(&entry->head);
971 entry->num_shared = 1;
972 entry->bo = &bo->tbo;
973 mutex_lock(&process_info->lock);
975 list_add_tail(&entry->head, &process_info->userptr_valid_list);
977 list_add_tail(&entry->head, &process_info->kfd_bo_list);
978 mutex_unlock(&process_info->lock);
981 static void remove_kgd_mem_from_kfd_bo_list(struct kgd_mem *mem,
982 struct amdkfd_process_info *process_info)
984 struct ttm_validate_buffer *bo_list_entry;
986 bo_list_entry = &mem->validate_list;
987 mutex_lock(&process_info->lock);
988 list_del(&bo_list_entry->head);
989 mutex_unlock(&process_info->lock);
992 /* Initializes user pages. It registers the MMU notifier and validates
993 * the userptr BO in the GTT domain.
995 * The BO must already be on the userptr_valid_list. Otherwise an
996 * eviction and restore may happen that leaves the new BO unmapped
997 * with the user mode queues running.
999 * Takes the process_info->lock to protect against concurrent restore
1002 * Returns 0 for success, negative errno for errors.
1004 static int init_user_pages(struct kgd_mem *mem, uint64_t user_addr,
1007 struct amdkfd_process_info *process_info = mem->process_info;
1008 struct amdgpu_bo *bo = mem->bo;
1009 struct ttm_operation_ctx ctx = { true, false };
1010 struct hmm_range *range;
1013 mutex_lock(&process_info->lock);
1015 ret = amdgpu_ttm_tt_set_userptr(&bo->tbo, user_addr, 0);
1017 pr_err("%s: Failed to set userptr: %d\n", __func__, ret);
1021 ret = amdgpu_hmm_register(bo, user_addr);
1023 pr_err("%s: Failed to register MMU notifier: %d\n",
1030 * During a CRIU restore operation, the userptr buffer objects
1031 * will be validated in the restore_userptr_work worker at a
1032 * later stage when it is scheduled by another ioctl called by
1033 * CRIU master process for the target pid for restore.
1035 mutex_lock(&process_info->notifier_lock);
1037 mutex_unlock(&process_info->notifier_lock);
1038 mutex_unlock(&process_info->lock);
1042 ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages, &range);
1044 pr_err("%s: Failed to get user pages: %d\n", __func__, ret);
1045 goto unregister_out;
1048 ret = amdgpu_bo_reserve(bo, true);
1050 pr_err("%s: Failed to reserve BO\n", __func__);
1053 amdgpu_bo_placement_from_domain(bo, mem->domain);
1054 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1056 pr_err("%s: failed to validate BO\n", __func__);
1057 amdgpu_bo_unreserve(bo);
1060 amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm, range);
1063 amdgpu_hmm_unregister(bo);
1065 mutex_unlock(&process_info->lock);
1069 /* Reserving a BO and its page table BOs must happen atomically to
1070 * avoid deadlocks. Some operations update multiple VMs at once. Track
1071 * all the reservation info in a context structure. Optionally a sync
1072 * object can track VM updates.
1074 struct bo_vm_reservation_context {
1075 struct amdgpu_bo_list_entry kfd_bo; /* BO list entry for the KFD BO */
1076 unsigned int n_vms; /* Number of VMs reserved */
1077 struct amdgpu_bo_list_entry *vm_pd; /* Array of VM BO list entries */
1078 struct ww_acquire_ctx ticket; /* Reservation ticket */
1079 struct list_head list, duplicates; /* BO lists */
1080 struct amdgpu_sync *sync; /* Pointer to sync object */
1081 bool reserved; /* Whether BOs are reserved */
1085 BO_VM_NOT_MAPPED = 0, /* Match VMs where a BO is not mapped */
1086 BO_VM_MAPPED, /* Match VMs where a BO is mapped */
1087 BO_VM_ALL, /* Match all VMs a BO was added to */
1091 * reserve_bo_and_vm - reserve a BO and a VM unconditionally.
1092 * @mem: KFD BO structure.
1093 * @vm: the VM to reserve.
1094 * @ctx: the struct that will be used in unreserve_bo_and_vms().
1096 static int reserve_bo_and_vm(struct kgd_mem *mem,
1097 struct amdgpu_vm *vm,
1098 struct bo_vm_reservation_context *ctx)
1100 struct amdgpu_bo *bo = mem->bo;
1105 ctx->reserved = false;
1107 ctx->sync = &mem->sync;
1109 INIT_LIST_HEAD(&ctx->list);
1110 INIT_LIST_HEAD(&ctx->duplicates);
1112 ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd), GFP_KERNEL);
1116 ctx->kfd_bo.priority = 0;
1117 ctx->kfd_bo.tv.bo = &bo->tbo;
1118 ctx->kfd_bo.tv.num_shared = 1;
1119 list_add(&ctx->kfd_bo.tv.head, &ctx->list);
1121 amdgpu_vm_get_pd_bo(vm, &ctx->list, &ctx->vm_pd[0]);
1123 ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
1124 false, &ctx->duplicates);
1126 pr_err("Failed to reserve buffers in ttm.\n");
1132 ctx->reserved = true;
1137 * reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally
1138 * @mem: KFD BO structure.
1139 * @vm: the VM to reserve. If NULL, then all VMs associated with the BO
1140 * is used. Otherwise, a single VM associated with the BO.
1141 * @map_type: the mapping status that will be used to filter the VMs.
1142 * @ctx: the struct that will be used in unreserve_bo_and_vms().
1144 * Returns 0 for success, negative for failure.
1146 static int reserve_bo_and_cond_vms(struct kgd_mem *mem,
1147 struct amdgpu_vm *vm, enum bo_vm_match map_type,
1148 struct bo_vm_reservation_context *ctx)
1150 struct amdgpu_bo *bo = mem->bo;
1151 struct kfd_mem_attachment *entry;
1155 ctx->reserved = false;
1158 ctx->sync = &mem->sync;
1160 INIT_LIST_HEAD(&ctx->list);
1161 INIT_LIST_HEAD(&ctx->duplicates);
1163 list_for_each_entry(entry, &mem->attachments, list) {
1164 if ((vm && vm != entry->bo_va->base.vm) ||
1165 (entry->is_mapped != map_type
1166 && map_type != BO_VM_ALL))
1172 if (ctx->n_vms != 0) {
1173 ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd),
1179 ctx->kfd_bo.priority = 0;
1180 ctx->kfd_bo.tv.bo = &bo->tbo;
1181 ctx->kfd_bo.tv.num_shared = 1;
1182 list_add(&ctx->kfd_bo.tv.head, &ctx->list);
1185 list_for_each_entry(entry, &mem->attachments, list) {
1186 if ((vm && vm != entry->bo_va->base.vm) ||
1187 (entry->is_mapped != map_type
1188 && map_type != BO_VM_ALL))
1191 amdgpu_vm_get_pd_bo(entry->bo_va->base.vm, &ctx->list,
1196 ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
1197 false, &ctx->duplicates);
1199 pr_err("Failed to reserve buffers in ttm.\n");
1205 ctx->reserved = true;
1210 * unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context
1211 * @ctx: Reservation context to unreserve
1212 * @wait: Optionally wait for a sync object representing pending VM updates
1213 * @intr: Whether the wait is interruptible
1215 * Also frees any resources allocated in
1216 * reserve_bo_and_(cond_)vm(s). Returns the status from
1219 static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx,
1220 bool wait, bool intr)
1225 ret = amdgpu_sync_wait(ctx->sync, intr);
1228 ttm_eu_backoff_reservation(&ctx->ticket, &ctx->list);
1233 ctx->reserved = false;
1239 static void unmap_bo_from_gpuvm(struct kgd_mem *mem,
1240 struct kfd_mem_attachment *entry,
1241 struct amdgpu_sync *sync)
1243 struct amdgpu_bo_va *bo_va = entry->bo_va;
1244 struct amdgpu_device *adev = entry->adev;
1245 struct amdgpu_vm *vm = bo_va->base.vm;
1247 amdgpu_vm_bo_unmap(adev, bo_va, entry->va);
1249 amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update);
1251 amdgpu_sync_fence(sync, bo_va->last_pt_update);
1253 kfd_mem_dmaunmap_attachment(mem, entry);
1256 static int update_gpuvm_pte(struct kgd_mem *mem,
1257 struct kfd_mem_attachment *entry,
1258 struct amdgpu_sync *sync)
1260 struct amdgpu_bo_va *bo_va = entry->bo_va;
1261 struct amdgpu_device *adev = entry->adev;
1264 ret = kfd_mem_dmamap_attachment(mem, entry);
1268 /* Update the page tables */
1269 ret = amdgpu_vm_bo_update(adev, bo_va, false);
1271 pr_err("amdgpu_vm_bo_update failed\n");
1275 return amdgpu_sync_fence(sync, bo_va->last_pt_update);
1278 static int map_bo_to_gpuvm(struct kgd_mem *mem,
1279 struct kfd_mem_attachment *entry,
1280 struct amdgpu_sync *sync,
1285 /* Set virtual address for the allocation */
1286 ret = amdgpu_vm_bo_map(entry->adev, entry->bo_va, entry->va, 0,
1287 amdgpu_bo_size(entry->bo_va->base.bo),
1290 pr_err("Failed to map VA 0x%llx in vm. ret %d\n",
1298 ret = update_gpuvm_pte(mem, entry, sync);
1300 pr_err("update_gpuvm_pte() failed\n");
1301 goto update_gpuvm_pte_failed;
1306 update_gpuvm_pte_failed:
1307 unmap_bo_from_gpuvm(mem, entry, sync);
1311 static int process_validate_vms(struct amdkfd_process_info *process_info)
1313 struct amdgpu_vm *peer_vm;
1316 list_for_each_entry(peer_vm, &process_info->vm_list_head,
1318 ret = vm_validate_pt_pd_bos(peer_vm);
1326 static int process_sync_pds_resv(struct amdkfd_process_info *process_info,
1327 struct amdgpu_sync *sync)
1329 struct amdgpu_vm *peer_vm;
1332 list_for_each_entry(peer_vm, &process_info->vm_list_head,
1334 struct amdgpu_bo *pd = peer_vm->root.bo;
1336 ret = amdgpu_sync_resv(NULL, sync, pd->tbo.base.resv,
1337 AMDGPU_SYNC_NE_OWNER,
1338 AMDGPU_FENCE_OWNER_KFD);
1346 static int process_update_pds(struct amdkfd_process_info *process_info,
1347 struct amdgpu_sync *sync)
1349 struct amdgpu_vm *peer_vm;
1352 list_for_each_entry(peer_vm, &process_info->vm_list_head,
1354 ret = vm_update_pds(peer_vm, sync);
1362 static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info,
1363 struct dma_fence **ef)
1365 struct amdkfd_process_info *info = NULL;
1368 if (!*process_info) {
1369 info = kzalloc(sizeof(*info), GFP_KERNEL);
1373 mutex_init(&info->lock);
1374 mutex_init(&info->notifier_lock);
1375 INIT_LIST_HEAD(&info->vm_list_head);
1376 INIT_LIST_HEAD(&info->kfd_bo_list);
1377 INIT_LIST_HEAD(&info->userptr_valid_list);
1378 INIT_LIST_HEAD(&info->userptr_inval_list);
1380 info->eviction_fence =
1381 amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),
1384 if (!info->eviction_fence) {
1385 pr_err("Failed to create eviction fence\n");
1387 goto create_evict_fence_fail;
1390 info->pid = get_task_pid(current->group_leader, PIDTYPE_PID);
1391 INIT_DELAYED_WORK(&info->restore_userptr_work,
1392 amdgpu_amdkfd_restore_userptr_worker);
1394 *process_info = info;
1395 *ef = dma_fence_get(&info->eviction_fence->base);
1398 vm->process_info = *process_info;
1400 /* Validate page directory and attach eviction fence */
1401 ret = amdgpu_bo_reserve(vm->root.bo, true);
1403 goto reserve_pd_fail;
1404 ret = vm_validate_pt_pd_bos(vm);
1406 pr_err("validate_pt_pd_bos() failed\n");
1407 goto validate_pd_fail;
1409 ret = amdgpu_bo_sync_wait(vm->root.bo,
1410 AMDGPU_FENCE_OWNER_KFD, false);
1413 ret = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, 1);
1415 goto reserve_shared_fail;
1416 dma_resv_add_fence(vm->root.bo->tbo.base.resv,
1417 &vm->process_info->eviction_fence->base,
1418 DMA_RESV_USAGE_BOOKKEEP);
1419 amdgpu_bo_unreserve(vm->root.bo);
1421 /* Update process info */
1422 mutex_lock(&vm->process_info->lock);
1423 list_add_tail(&vm->vm_list_node,
1424 &(vm->process_info->vm_list_head));
1425 vm->process_info->n_vms++;
1426 mutex_unlock(&vm->process_info->lock);
1430 reserve_shared_fail:
1433 amdgpu_bo_unreserve(vm->root.bo);
1435 vm->process_info = NULL;
1437 /* Two fence references: one in info and one in *ef */
1438 dma_fence_put(&info->eviction_fence->base);
1441 *process_info = NULL;
1443 create_evict_fence_fail:
1444 mutex_destroy(&info->lock);
1445 mutex_destroy(&info->notifier_lock);
1452 * amdgpu_amdkfd_gpuvm_pin_bo() - Pins a BO using following criteria
1453 * @bo: Handle of buffer object being pinned
1454 * @domain: Domain into which BO should be pinned
1456 * - USERPTR BOs are UNPINNABLE and will return error
1457 * - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
1458 * PIN count incremented. It is valid to PIN a BO multiple times
1460 * Return: ZERO if successful in pinning, Non-Zero in case of error.
1462 static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain)
1466 ret = amdgpu_bo_reserve(bo, false);
1470 ret = amdgpu_bo_pin_restricted(bo, domain, 0, 0);
1472 pr_err("Error in Pinning BO to domain: %d\n", domain);
1474 amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
1475 amdgpu_bo_unreserve(bo);
1481 * amdgpu_amdkfd_gpuvm_unpin_bo() - Unpins BO using following criteria
1482 * @bo: Handle of buffer object being unpinned
1484 * - Is a illegal request for USERPTR BOs and is ignored
1485 * - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
1486 * PIN count decremented. Calls to UNPIN must balance calls to PIN
1488 static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo)
1492 ret = amdgpu_bo_reserve(bo, false);
1496 amdgpu_bo_unpin(bo);
1497 amdgpu_bo_unreserve(bo);
1500 int amdgpu_amdkfd_gpuvm_set_vm_pasid(struct amdgpu_device *adev,
1501 struct amdgpu_vm *avm, u32 pasid)
1506 /* Free the original amdgpu allocated pasid,
1507 * will be replaced with kfd allocated pasid.
1510 amdgpu_pasid_free(avm->pasid);
1511 amdgpu_vm_set_pasid(adev, avm, 0);
1514 ret = amdgpu_vm_set_pasid(adev, avm, pasid);
1521 int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct amdgpu_device *adev,
1522 struct amdgpu_vm *avm,
1523 void **process_info,
1524 struct dma_fence **ef)
1528 /* Already a compute VM? */
1529 if (avm->process_info)
1532 /* Convert VM into a compute VM */
1533 ret = amdgpu_vm_make_compute(adev, avm);
1537 /* Initialize KFD part of the VM and process info */
1538 ret = init_kfd_vm(avm, process_info, ef);
1542 amdgpu_vm_set_task_info(avm);
1547 void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,
1548 struct amdgpu_vm *vm)
1550 struct amdkfd_process_info *process_info = vm->process_info;
1555 /* Update process info */
1556 mutex_lock(&process_info->lock);
1557 process_info->n_vms--;
1558 list_del(&vm->vm_list_node);
1559 mutex_unlock(&process_info->lock);
1561 vm->process_info = NULL;
1563 /* Release per-process resources when last compute VM is destroyed */
1564 if (!process_info->n_vms) {
1565 WARN_ON(!list_empty(&process_info->kfd_bo_list));
1566 WARN_ON(!list_empty(&process_info->userptr_valid_list));
1567 WARN_ON(!list_empty(&process_info->userptr_inval_list));
1569 dma_fence_put(&process_info->eviction_fence->base);
1570 cancel_delayed_work_sync(&process_info->restore_userptr_work);
1571 put_pid(process_info->pid);
1572 mutex_destroy(&process_info->lock);
1573 mutex_destroy(&process_info->notifier_lock);
1574 kfree(process_info);
1578 void amdgpu_amdkfd_gpuvm_release_process_vm(struct amdgpu_device *adev,
1581 struct amdgpu_vm *avm;
1583 if (WARN_ON(!adev || !drm_priv))
1586 avm = drm_priv_to_vm(drm_priv);
1588 pr_debug("Releasing process vm %p\n", avm);
1590 /* The original pasid of amdgpu vm has already been
1591 * released during making a amdgpu vm to a compute vm
1592 * The current pasid is managed by kfd and will be
1593 * released on kfd process destroy. Set amdgpu pasid
1594 * to 0 to avoid duplicate release.
1596 amdgpu_vm_release_compute(adev, avm);
1599 uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)
1601 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1602 struct amdgpu_bo *pd = avm->root.bo;
1603 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
1605 if (adev->asic_type < CHIP_VEGA10)
1606 return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT;
1607 return avm->pd_phys_addr;
1610 void amdgpu_amdkfd_block_mmu_notifications(void *p)
1612 struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;
1614 mutex_lock(&pinfo->lock);
1615 WRITE_ONCE(pinfo->block_mmu_notifications, true);
1616 mutex_unlock(&pinfo->lock);
1619 int amdgpu_amdkfd_criu_resume(void *p)
1622 struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;
1624 mutex_lock(&pinfo->lock);
1625 pr_debug("scheduling work\n");
1626 mutex_lock(&pinfo->notifier_lock);
1627 pinfo->evicted_bos++;
1628 mutex_unlock(&pinfo->notifier_lock);
1629 if (!READ_ONCE(pinfo->block_mmu_notifications)) {
1633 WRITE_ONCE(pinfo->block_mmu_notifications, false);
1634 schedule_delayed_work(&pinfo->restore_userptr_work, 0);
1637 mutex_unlock(&pinfo->lock);
1641 size_t amdgpu_amdkfd_get_available_memory(struct amdgpu_device *adev,
1644 uint64_t reserved_for_pt =
1645 ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);
1647 uint64_t vram_available, system_mem_available, ttm_mem_available;
1649 spin_lock(&kfd_mem_limit.mem_limit_lock);
1650 vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id)
1651 - adev->kfd.vram_used_aligned[xcp_id]
1652 - atomic64_read(&adev->vram_pin_size)
1655 if (adev->gmc.is_app_apu) {
1656 system_mem_available = no_system_mem_limit ?
1657 kfd_mem_limit.max_system_mem_limit :
1658 kfd_mem_limit.max_system_mem_limit -
1659 kfd_mem_limit.system_mem_used;
1661 ttm_mem_available = kfd_mem_limit.max_ttm_mem_limit -
1662 kfd_mem_limit.ttm_mem_used;
1664 available = min3(system_mem_available, ttm_mem_available,
1666 available = ALIGN_DOWN(available, PAGE_SIZE);
1668 available = ALIGN_DOWN(vram_available, VRAM_AVAILABLITY_ALIGN);
1671 spin_unlock(&kfd_mem_limit.mem_limit_lock);
1679 int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(
1680 struct amdgpu_device *adev, uint64_t va, uint64_t size,
1681 void *drm_priv, struct kgd_mem **mem,
1682 uint64_t *offset, uint32_t flags, bool criu_resume)
1684 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1685 struct amdgpu_fpriv *fpriv = container_of(avm, struct amdgpu_fpriv, vm);
1686 enum ttm_bo_type bo_type = ttm_bo_type_device;
1687 struct sg_table *sg = NULL;
1688 uint64_t user_addr = 0;
1689 struct amdgpu_bo *bo;
1690 struct drm_gem_object *gobj = NULL;
1691 u32 domain, alloc_domain;
1692 uint64_t aligned_size;
1698 * Check on which domain to allocate BO
1700 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
1701 domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;
1703 if (adev->gmc.is_app_apu) {
1704 domain = AMDGPU_GEM_DOMAIN_GTT;
1705 alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
1708 alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;
1709 alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ?
1710 AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0;
1712 xcp_id = fpriv->xcp_id == ~0 ? 0 : fpriv->xcp_id;
1713 } else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
1714 domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
1717 domain = AMDGPU_GEM_DOMAIN_GTT;
1718 alloc_domain = AMDGPU_GEM_DOMAIN_CPU;
1719 alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE;
1721 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
1722 if (!offset || !*offset)
1724 user_addr = untagged_addr(*offset);
1725 } else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1726 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1727 bo_type = ttm_bo_type_sg;
1728 if (size > UINT_MAX)
1730 sg = create_sg_table(*offset, size);
1738 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_COHERENT)
1739 alloc_flags |= AMDGPU_GEM_CREATE_COHERENT;
1740 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED)
1741 alloc_flags |= AMDGPU_GEM_CREATE_UNCACHED;
1743 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
1748 INIT_LIST_HEAD(&(*mem)->attachments);
1749 mutex_init(&(*mem)->lock);
1750 (*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);
1752 /* Workaround for AQL queue wraparound bug. Map the same
1753 * memory twice. That means we only actually allocate half
1756 if ((*mem)->aql_queue)
1758 aligned_size = PAGE_ALIGN(size);
1760 (*mem)->alloc_flags = flags;
1762 amdgpu_sync_create(&(*mem)->sync);
1764 ret = amdgpu_amdkfd_reserve_mem_limit(adev, aligned_size, flags,
1767 pr_debug("Insufficient memory\n");
1768 goto err_reserve_limit;
1771 pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s xcp_id %d\n",
1772 va, (*mem)->aql_queue ? size << 1 : size,
1773 domain_string(alloc_domain), xcp_id);
1775 ret = amdgpu_gem_object_create(adev, aligned_size, 1, alloc_domain, alloc_flags,
1776 bo_type, NULL, &gobj, xcp_id + 1);
1778 pr_debug("Failed to create BO on domain %s. ret %d\n",
1779 domain_string(alloc_domain), ret);
1782 ret = drm_vma_node_allow(&gobj->vma_node, drm_priv);
1784 pr_debug("Failed to allow vma node access. ret %d\n", ret);
1785 goto err_node_allow;
1787 bo = gem_to_amdgpu_bo(gobj);
1788 if (bo_type == ttm_bo_type_sg) {
1790 bo->tbo.ttm->sg = sg;
1795 bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO;
1798 (*mem)->domain = domain;
1799 (*mem)->mapped_to_gpu_memory = 0;
1800 (*mem)->process_info = avm->process_info;
1802 add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);
1805 pr_debug("creating userptr BO for user_addr = %llx\n", user_addr);
1806 ret = init_user_pages(*mem, user_addr, criu_resume);
1808 goto allocate_init_user_pages_failed;
1809 } else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1810 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1811 ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT);
1813 pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n");
1816 bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
1817 bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
1821 *offset = amdgpu_bo_mmap_offset(bo);
1825 allocate_init_user_pages_failed:
1827 remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);
1828 drm_vma_node_revoke(&gobj->vma_node, drm_priv);
1830 /* Don't unreserve system mem limit twice */
1831 goto err_reserve_limit;
1833 amdgpu_amdkfd_unreserve_mem_limit(adev, aligned_size, flags, xcp_id);
1835 mutex_destroy(&(*mem)->lock);
1837 drm_gem_object_put(gobj);
1848 int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(
1849 struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv,
1852 struct amdkfd_process_info *process_info = mem->process_info;
1853 unsigned long bo_size = mem->bo->tbo.base.size;
1854 bool use_release_notifier = (mem->bo->kfd_bo == mem);
1855 struct kfd_mem_attachment *entry, *tmp;
1856 struct bo_vm_reservation_context ctx;
1857 struct ttm_validate_buffer *bo_list_entry;
1858 unsigned int mapped_to_gpu_memory;
1860 bool is_imported = false;
1862 mutex_lock(&mem->lock);
1864 /* Unpin MMIO/DOORBELL BO's that were pinned during allocation */
1865 if (mem->alloc_flags &
1866 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
1867 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1868 amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo);
1871 mapped_to_gpu_memory = mem->mapped_to_gpu_memory;
1872 is_imported = mem->is_imported;
1873 mutex_unlock(&mem->lock);
1874 /* lock is not needed after this, since mem is unused and will
1878 if (mapped_to_gpu_memory > 0) {
1879 pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",
1884 /* Make sure restore workers don't access the BO any more */
1885 bo_list_entry = &mem->validate_list;
1886 mutex_lock(&process_info->lock);
1887 list_del(&bo_list_entry->head);
1888 mutex_unlock(&process_info->lock);
1890 /* Cleanup user pages and MMU notifiers */
1891 if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {
1892 amdgpu_hmm_unregister(mem->bo);
1893 mutex_lock(&process_info->notifier_lock);
1894 amdgpu_ttm_tt_discard_user_pages(mem->bo->tbo.ttm, mem->range);
1895 mutex_unlock(&process_info->notifier_lock);
1898 ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);
1902 /* The eviction fence should be removed by the last unmap.
1903 * TODO: Log an error condition if the bo still has the eviction fence
1906 amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1907 process_info->eviction_fence);
1908 pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,
1909 mem->va + bo_size * (1 + mem->aql_queue));
1911 /* Remove from VM internal data structures */
1912 list_for_each_entry_safe(entry, tmp, &mem->attachments, list)
1913 kfd_mem_detach(entry);
1915 ret = unreserve_bo_and_vms(&ctx, false, false);
1917 /* Free the sync object */
1918 amdgpu_sync_free(&mem->sync);
1920 /* If the SG is not NULL, it's one we created for a doorbell or mmio
1921 * remap BO. We need to free it.
1923 if (mem->bo->tbo.sg) {
1924 sg_free_table(mem->bo->tbo.sg);
1925 kfree(mem->bo->tbo.sg);
1928 /* Update the size of the BO being freed if it was allocated from
1929 * VRAM and is not imported. For APP APU VRAM allocations are done
1934 (mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_VRAM ||
1935 (adev->gmc.is_app_apu &&
1936 mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_GTT)))
1943 drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv);
1945 dma_buf_put(mem->dmabuf);
1946 mutex_destroy(&mem->lock);
1948 /* If this releases the last reference, it will end up calling
1949 * amdgpu_amdkfd_release_notify and kfree the mem struct. That's why
1950 * this needs to be the last call here.
1952 drm_gem_object_put(&mem->bo->tbo.base);
1955 * For kgd_mem allocated in amdgpu_amdkfd_gpuvm_import_dmabuf(),
1956 * explicitly free it here.
1958 if (!use_release_notifier)
1964 int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1965 struct amdgpu_device *adev, struct kgd_mem *mem,
1968 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1970 struct amdgpu_bo *bo;
1972 struct kfd_mem_attachment *entry;
1973 struct bo_vm_reservation_context ctx;
1974 unsigned long bo_size;
1975 bool is_invalid_userptr = false;
1979 pr_err("Invalid BO when mapping memory to GPU\n");
1983 /* Make sure restore is not running concurrently. Since we
1984 * don't map invalid userptr BOs, we rely on the next restore
1985 * worker to do the mapping
1987 mutex_lock(&mem->process_info->lock);
1989 /* Lock notifier lock. If we find an invalid userptr BO, we can be
1990 * sure that the MMU notifier is no longer running
1991 * concurrently and the queues are actually stopped
1993 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1994 mutex_lock(&mem->process_info->notifier_lock);
1995 is_invalid_userptr = !!mem->invalid;
1996 mutex_unlock(&mem->process_info->notifier_lock);
1999 mutex_lock(&mem->lock);
2001 domain = mem->domain;
2002 bo_size = bo->tbo.base.size;
2004 pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",
2006 mem->va + bo_size * (1 + mem->aql_queue),
2007 avm, domain_string(domain));
2009 if (!kfd_mem_is_attached(avm, mem)) {
2010 ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue);
2015 ret = reserve_bo_and_vm(mem, avm, &ctx);
2019 /* Userptr can be marked as "not invalid", but not actually be
2020 * validated yet (still in the system domain). In that case
2021 * the queues are still stopped and we can leave mapping for
2022 * the next restore worker
2024 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&
2025 bo->tbo.resource->mem_type == TTM_PL_SYSTEM)
2026 is_invalid_userptr = true;
2028 ret = vm_validate_pt_pd_bos(avm);
2032 if (mem->mapped_to_gpu_memory == 0 &&
2033 !amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
2034 /* Validate BO only once. The eviction fence gets added to BO
2035 * the first time it is mapped. Validate will wait for all
2036 * background evictions to complete.
2038 ret = amdgpu_amdkfd_bo_validate(bo, domain, true);
2040 pr_debug("Validate failed\n");
2045 list_for_each_entry(entry, &mem->attachments, list) {
2046 if (entry->bo_va->base.vm != avm || entry->is_mapped)
2049 pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",
2050 entry->va, entry->va + bo_size, entry);
2052 ret = map_bo_to_gpuvm(mem, entry, ctx.sync,
2053 is_invalid_userptr);
2055 pr_err("Failed to map bo to gpuvm\n");
2059 ret = vm_update_pds(avm, ctx.sync);
2061 pr_err("Failed to update page directories\n");
2065 entry->is_mapped = true;
2066 mem->mapped_to_gpu_memory++;
2067 pr_debug("\t INC mapping count %d\n",
2068 mem->mapped_to_gpu_memory);
2071 if (!amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) && !bo->tbo.pin_count)
2072 dma_resv_add_fence(bo->tbo.base.resv,
2073 &avm->process_info->eviction_fence->base,
2074 DMA_RESV_USAGE_BOOKKEEP);
2075 ret = unreserve_bo_and_vms(&ctx, false, false);
2080 unreserve_bo_and_vms(&ctx, false, false);
2082 mutex_unlock(&mem->process_info->lock);
2083 mutex_unlock(&mem->lock);
2087 int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
2088 struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv)
2090 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
2091 struct amdkfd_process_info *process_info = avm->process_info;
2092 unsigned long bo_size = mem->bo->tbo.base.size;
2093 struct kfd_mem_attachment *entry;
2094 struct bo_vm_reservation_context ctx;
2097 mutex_lock(&mem->lock);
2099 ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx);
2102 /* If no VMs were reserved, it means the BO wasn't actually mapped */
2103 if (ctx.n_vms == 0) {
2108 ret = vm_validate_pt_pd_bos(avm);
2112 pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",
2114 mem->va + bo_size * (1 + mem->aql_queue),
2117 list_for_each_entry(entry, &mem->attachments, list) {
2118 if (entry->bo_va->base.vm != avm || !entry->is_mapped)
2121 pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",
2122 entry->va, entry->va + bo_size, entry);
2124 unmap_bo_from_gpuvm(mem, entry, ctx.sync);
2125 entry->is_mapped = false;
2127 mem->mapped_to_gpu_memory--;
2128 pr_debug("\t DEC mapping count %d\n",
2129 mem->mapped_to_gpu_memory);
2132 /* If BO is unmapped from all VMs, unfence it. It can be evicted if
2135 if (mem->mapped_to_gpu_memory == 0 &&
2136 !amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) &&
2137 !mem->bo->tbo.pin_count)
2138 amdgpu_amdkfd_remove_eviction_fence(mem->bo,
2139 process_info->eviction_fence);
2142 unreserve_bo_and_vms(&ctx, false, false);
2144 mutex_unlock(&mem->lock);
2148 int amdgpu_amdkfd_gpuvm_sync_memory(
2149 struct amdgpu_device *adev, struct kgd_mem *mem, bool intr)
2151 struct amdgpu_sync sync;
2154 amdgpu_sync_create(&sync);
2156 mutex_lock(&mem->lock);
2157 amdgpu_sync_clone(&mem->sync, &sync);
2158 mutex_unlock(&mem->lock);
2160 ret = amdgpu_sync_wait(&sync, intr);
2161 amdgpu_sync_free(&sync);
2166 * amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count
2167 * @adev: Device to which allocated BO belongs
2168 * @bo: Buffer object to be mapped
2170 * Before return, bo reference count is incremented. To release the reference and unpin/
2171 * unmap the BO, call amdgpu_amdkfd_free_gtt_mem.
2173 int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_device *adev, struct amdgpu_bo *bo)
2177 ret = amdgpu_bo_reserve(bo, true);
2179 pr_err("Failed to reserve bo. ret %d\n", ret);
2180 goto err_reserve_bo_failed;
2183 ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
2185 pr_err("Failed to pin bo. ret %d\n", ret);
2186 goto err_pin_bo_failed;
2189 ret = amdgpu_ttm_alloc_gart(&bo->tbo);
2191 pr_err("Failed to bind bo to GART. ret %d\n", ret);
2192 goto err_map_bo_gart_failed;
2195 amdgpu_amdkfd_remove_eviction_fence(
2196 bo, bo->vm_bo->vm->process_info->eviction_fence);
2198 amdgpu_bo_unreserve(bo);
2200 bo = amdgpu_bo_ref(bo);
2204 err_map_bo_gart_failed:
2205 amdgpu_bo_unpin(bo);
2207 amdgpu_bo_unreserve(bo);
2208 err_reserve_bo_failed:
2213 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Map a GTT BO for kernel CPU access
2215 * @mem: Buffer object to be mapped for CPU access
2216 * @kptr[out]: pointer in kernel CPU address space
2217 * @size[out]: size of the buffer
2219 * Pins the BO and maps it for kernel CPU access. The eviction fence is removed
2220 * from the BO, since pinned BOs cannot be evicted. The bo must remain on the
2221 * validate_list, so the GPU mapping can be restored after a page table was
2224 * Return: 0 on success, error code on failure
2226 int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem,
2227 void **kptr, uint64_t *size)
2230 struct amdgpu_bo *bo = mem->bo;
2232 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
2233 pr_err("userptr can't be mapped to kernel\n");
2237 mutex_lock(&mem->process_info->lock);
2239 ret = amdgpu_bo_reserve(bo, true);
2241 pr_err("Failed to reserve bo. ret %d\n", ret);
2242 goto bo_reserve_failed;
2245 ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
2247 pr_err("Failed to pin bo. ret %d\n", ret);
2251 ret = amdgpu_bo_kmap(bo, kptr);
2253 pr_err("Failed to map bo to kernel. ret %d\n", ret);
2257 amdgpu_amdkfd_remove_eviction_fence(
2258 bo, mem->process_info->eviction_fence);
2261 *size = amdgpu_bo_size(bo);
2263 amdgpu_bo_unreserve(bo);
2265 mutex_unlock(&mem->process_info->lock);
2269 amdgpu_bo_unpin(bo);
2271 amdgpu_bo_unreserve(bo);
2273 mutex_unlock(&mem->process_info->lock);
2278 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Unmap a GTT BO for kernel CPU access
2280 * @mem: Buffer object to be unmapped for CPU access
2282 * Removes the kernel CPU mapping and unpins the BO. It does not restore the
2283 * eviction fence, so this function should only be used for cleanup before the
2286 void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem *mem)
2288 struct amdgpu_bo *bo = mem->bo;
2290 amdgpu_bo_reserve(bo, true);
2291 amdgpu_bo_kunmap(bo);
2292 amdgpu_bo_unpin(bo);
2293 amdgpu_bo_unreserve(bo);
2296 int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev,
2297 struct kfd_vm_fault_info *mem)
2299 if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) {
2300 *mem = *adev->gmc.vm_fault_info;
2301 mb(); /* make sure read happened */
2302 atomic_set(&adev->gmc.vm_fault_info_updated, 0);
2307 int amdgpu_amdkfd_gpuvm_import_dmabuf(struct amdgpu_device *adev,
2308 struct dma_buf *dma_buf,
2309 uint64_t va, void *drm_priv,
2310 struct kgd_mem **mem, uint64_t *size,
2311 uint64_t *mmap_offset)
2313 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
2314 struct drm_gem_object *obj;
2315 struct amdgpu_bo *bo;
2318 obj = amdgpu_gem_prime_import(adev_to_drm(adev), dma_buf);
2320 return PTR_ERR(obj);
2322 bo = gem_to_amdgpu_bo(obj);
2323 if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM |
2324 AMDGPU_GEM_DOMAIN_GTT))) {
2325 /* Only VRAM and GTT BOs are supported */
2330 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
2336 ret = drm_vma_node_allow(&obj->vma_node, drm_priv);
2341 *size = amdgpu_bo_size(bo);
2344 *mmap_offset = amdgpu_bo_mmap_offset(bo);
2346 INIT_LIST_HEAD(&(*mem)->attachments);
2347 mutex_init(&(*mem)->lock);
2349 (*mem)->alloc_flags =
2350 ((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
2351 KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT)
2352 | KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE
2353 | KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;
2355 get_dma_buf(dma_buf);
2356 (*mem)->dmabuf = dma_buf;
2359 (*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) && !adev->gmc.is_app_apu ?
2360 AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT;
2362 (*mem)->mapped_to_gpu_memory = 0;
2363 (*mem)->process_info = avm->process_info;
2364 add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false);
2365 amdgpu_sync_create(&(*mem)->sync);
2366 (*mem)->is_imported = true;
2373 drm_gem_object_put(obj);
2377 int amdgpu_amdkfd_gpuvm_export_dmabuf(struct kgd_mem *mem,
2378 struct dma_buf **dma_buf)
2382 mutex_lock(&mem->lock);
2383 ret = kfd_mem_export_dmabuf(mem);
2387 get_dma_buf(mem->dmabuf);
2388 *dma_buf = mem->dmabuf;
2390 mutex_unlock(&mem->lock);
2394 /* Evict a userptr BO by stopping the queues if necessary
2396 * Runs in MMU notifier, may be in RECLAIM_FS context. This means it
2397 * cannot do any memory allocations, and cannot take any locks that
2398 * are held elsewhere while allocating memory.
2400 * It doesn't do anything to the BO itself. The real work happens in
2401 * restore, where we get updated page addresses. This function only
2402 * ensures that GPU access to the BO is stopped.
2404 int amdgpu_amdkfd_evict_userptr(struct mmu_interval_notifier *mni,
2405 unsigned long cur_seq, struct kgd_mem *mem)
2407 struct amdkfd_process_info *process_info = mem->process_info;
2410 /* Do not process MMU notifications during CRIU restore until
2411 * KFD_CRIU_OP_RESUME IOCTL is received
2413 if (READ_ONCE(process_info->block_mmu_notifications))
2416 mutex_lock(&process_info->notifier_lock);
2417 mmu_interval_set_seq(mni, cur_seq);
2420 if (++process_info->evicted_bos == 1) {
2421 /* First eviction, stop the queues */
2422 r = kgd2kfd_quiesce_mm(mni->mm,
2423 KFD_QUEUE_EVICTION_TRIGGER_USERPTR);
2425 pr_err("Failed to quiesce KFD\n");
2426 schedule_delayed_work(&process_info->restore_userptr_work,
2427 msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2429 mutex_unlock(&process_info->notifier_lock);
2434 /* Update invalid userptr BOs
2436 * Moves invalidated (evicted) userptr BOs from userptr_valid_list to
2437 * userptr_inval_list and updates user pages for all BOs that have
2438 * been invalidated since their last update.
2440 static int update_invalid_user_pages(struct amdkfd_process_info *process_info,
2441 struct mm_struct *mm)
2443 struct kgd_mem *mem, *tmp_mem;
2444 struct amdgpu_bo *bo;
2445 struct ttm_operation_ctx ctx = { false, false };
2449 mutex_lock(&process_info->notifier_lock);
2451 /* Move all invalidated BOs to the userptr_inval_list */
2452 list_for_each_entry_safe(mem, tmp_mem,
2453 &process_info->userptr_valid_list,
2456 list_move_tail(&mem->validate_list.head,
2457 &process_info->userptr_inval_list);
2459 /* Go through userptr_inval_list and update any invalid user_pages */
2460 list_for_each_entry(mem, &process_info->userptr_inval_list,
2461 validate_list.head) {
2462 invalid = mem->invalid;
2464 /* BO hasn't been invalidated since the last
2465 * revalidation attempt. Keep its page list.
2471 amdgpu_ttm_tt_discard_user_pages(bo->tbo.ttm, mem->range);
2474 /* BO reservations and getting user pages (hmm_range_fault)
2475 * must happen outside the notifier lock
2477 mutex_unlock(&process_info->notifier_lock);
2479 /* Move the BO to system (CPU) domain if necessary to unmap
2480 * and free the SG table
2482 if (bo->tbo.resource->mem_type != TTM_PL_SYSTEM) {
2483 if (amdgpu_bo_reserve(bo, true))
2485 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
2486 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2487 amdgpu_bo_unreserve(bo);
2489 pr_err("%s: Failed to invalidate userptr BO\n",
2495 /* Get updated user pages */
2496 ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages,
2499 pr_debug("Failed %d to get user pages\n", ret);
2501 /* Return -EFAULT bad address error as success. It will
2502 * fail later with a VM fault if the GPU tries to access
2503 * it. Better than hanging indefinitely with stalled
2506 * Return other error -EBUSY or -ENOMEM to retry restore
2514 mutex_lock(&process_info->notifier_lock);
2516 /* Mark the BO as valid unless it was invalidated
2517 * again concurrently.
2519 if (mem->invalid != invalid) {
2523 /* set mem valid if mem has hmm range associated */
2529 mutex_unlock(&process_info->notifier_lock);
2534 /* Validate invalid userptr BOs
2536 * Validates BOs on the userptr_inval_list. Also updates GPUVM page tables
2537 * with new page addresses and waits for the page table updates to complete.
2539 static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)
2541 struct amdgpu_bo_list_entry *pd_bo_list_entries;
2542 struct list_head resv_list, duplicates;
2543 struct ww_acquire_ctx ticket;
2544 struct amdgpu_sync sync;
2546 struct amdgpu_vm *peer_vm;
2547 struct kgd_mem *mem, *tmp_mem;
2548 struct amdgpu_bo *bo;
2549 struct ttm_operation_ctx ctx = { false, false };
2552 pd_bo_list_entries = kcalloc(process_info->n_vms,
2553 sizeof(struct amdgpu_bo_list_entry),
2555 if (!pd_bo_list_entries) {
2556 pr_err("%s: Failed to allocate PD BO list entries\n", __func__);
2561 INIT_LIST_HEAD(&resv_list);
2562 INIT_LIST_HEAD(&duplicates);
2564 /* Get all the page directory BOs that need to be reserved */
2566 list_for_each_entry(peer_vm, &process_info->vm_list_head,
2568 amdgpu_vm_get_pd_bo(peer_vm, &resv_list,
2569 &pd_bo_list_entries[i++]);
2570 /* Add the userptr_inval_list entries to resv_list */
2571 list_for_each_entry(mem, &process_info->userptr_inval_list,
2572 validate_list.head) {
2573 list_add_tail(&mem->resv_list.head, &resv_list);
2574 mem->resv_list.bo = mem->validate_list.bo;
2575 mem->resv_list.num_shared = mem->validate_list.num_shared;
2578 /* Reserve all BOs and page tables for validation */
2579 ret = ttm_eu_reserve_buffers(&ticket, &resv_list, false, &duplicates);
2580 WARN(!list_empty(&duplicates), "Duplicates should be empty");
2584 amdgpu_sync_create(&sync);
2586 ret = process_validate_vms(process_info);
2590 /* Validate BOs and update GPUVM page tables */
2591 list_for_each_entry_safe(mem, tmp_mem,
2592 &process_info->userptr_inval_list,
2593 validate_list.head) {
2594 struct kfd_mem_attachment *attachment;
2598 /* Validate the BO if we got user pages */
2599 if (bo->tbo.ttm->pages[0]) {
2600 amdgpu_bo_placement_from_domain(bo, mem->domain);
2601 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
2603 pr_err("%s: failed to validate BO\n", __func__);
2608 /* Update mapping. If the BO was not validated
2609 * (because we couldn't get user pages), this will
2610 * clear the page table entries, which will result in
2611 * VM faults if the GPU tries to access the invalid
2614 list_for_each_entry(attachment, &mem->attachments, list) {
2615 if (!attachment->is_mapped)
2618 kfd_mem_dmaunmap_attachment(mem, attachment);
2619 ret = update_gpuvm_pte(mem, attachment, &sync);
2621 pr_err("%s: update PTE failed\n", __func__);
2622 /* make sure this gets validated again */
2623 mutex_lock(&process_info->notifier_lock);
2625 mutex_unlock(&process_info->notifier_lock);
2631 /* Update page directories */
2632 ret = process_update_pds(process_info, &sync);
2635 ttm_eu_backoff_reservation(&ticket, &resv_list);
2636 amdgpu_sync_wait(&sync, false);
2637 amdgpu_sync_free(&sync);
2639 kfree(pd_bo_list_entries);
2645 /* Confirm that all user pages are valid while holding the notifier lock
2647 * Moves valid BOs from the userptr_inval_list back to userptr_val_list.
2649 static int confirm_valid_user_pages_locked(struct amdkfd_process_info *process_info)
2651 struct kgd_mem *mem, *tmp_mem;
2654 list_for_each_entry_safe(mem, tmp_mem,
2655 &process_info->userptr_inval_list,
2656 validate_list.head) {
2659 /* keep mem without hmm range at userptr_inval_list */
2663 /* Only check mem with hmm range associated */
2664 valid = amdgpu_ttm_tt_get_user_pages_done(
2665 mem->bo->tbo.ttm, mem->range);
2669 WARN(!mem->invalid, "Invalid BO not marked invalid");
2675 WARN(1, "Valid BO is marked invalid");
2680 list_move_tail(&mem->validate_list.head,
2681 &process_info->userptr_valid_list);
2687 /* Worker callback to restore evicted userptr BOs
2689 * Tries to update and validate all userptr BOs. If successful and no
2690 * concurrent evictions happened, the queues are restarted. Otherwise,
2691 * reschedule for another attempt later.
2693 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
2695 struct delayed_work *dwork = to_delayed_work(work);
2696 struct amdkfd_process_info *process_info =
2697 container_of(dwork, struct amdkfd_process_info,
2698 restore_userptr_work);
2699 struct task_struct *usertask;
2700 struct mm_struct *mm;
2701 uint32_t evicted_bos;
2703 mutex_lock(&process_info->notifier_lock);
2704 evicted_bos = process_info->evicted_bos;
2705 mutex_unlock(&process_info->notifier_lock);
2709 /* Reference task and mm in case of concurrent process termination */
2710 usertask = get_pid_task(process_info->pid, PIDTYPE_PID);
2713 mm = get_task_mm(usertask);
2715 put_task_struct(usertask);
2719 mutex_lock(&process_info->lock);
2721 if (update_invalid_user_pages(process_info, mm))
2723 /* userptr_inval_list can be empty if all evicted userptr BOs
2724 * have been freed. In that case there is nothing to validate
2725 * and we can just restart the queues.
2727 if (!list_empty(&process_info->userptr_inval_list)) {
2728 if (validate_invalid_user_pages(process_info))
2731 /* Final check for concurrent evicton and atomic update. If
2732 * another eviction happens after successful update, it will
2733 * be a first eviction that calls quiesce_mm. The eviction
2734 * reference counting inside KFD will handle this case.
2736 mutex_lock(&process_info->notifier_lock);
2737 if (process_info->evicted_bos != evicted_bos)
2738 goto unlock_notifier_out;
2740 if (confirm_valid_user_pages_locked(process_info)) {
2741 WARN(1, "User pages unexpectedly invalid");
2742 goto unlock_notifier_out;
2745 process_info->evicted_bos = evicted_bos = 0;
2747 if (kgd2kfd_resume_mm(mm)) {
2748 pr_err("%s: Failed to resume KFD\n", __func__);
2749 /* No recovery from this failure. Probably the CP is
2750 * hanging. No point trying again.
2754 unlock_notifier_out:
2755 mutex_unlock(&process_info->notifier_lock);
2757 mutex_unlock(&process_info->lock);
2759 /* If validation failed, reschedule another attempt */
2761 schedule_delayed_work(&process_info->restore_userptr_work,
2762 msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2764 kfd_smi_event_queue_restore_rescheduled(mm);
2767 put_task_struct(usertask);
2770 /** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given
2771 * KFD process identified by process_info
2773 * @process_info: amdkfd_process_info of the KFD process
2775 * After memory eviction, restore thread calls this function. The function
2776 * should be called when the Process is still valid. BO restore involves -
2778 * 1. Release old eviction fence and create new one
2779 * 2. Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.
2780 * 3 Use the second PD list and kfd_bo_list to create a list (ctx.list) of
2781 * BOs that need to be reserved.
2782 * 4. Reserve all the BOs
2783 * 5. Validate of PD and PT BOs.
2784 * 6. Validate all KFD BOs using kfd_bo_list and Map them and add new fence
2785 * 7. Add fence to all PD and PT BOs.
2786 * 8. Unreserve all BOs
2788 int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence **ef)
2790 struct amdgpu_bo_list_entry *pd_bo_list;
2791 struct amdkfd_process_info *process_info = info;
2792 struct amdgpu_vm *peer_vm;
2793 struct kgd_mem *mem;
2794 struct bo_vm_reservation_context ctx;
2795 struct amdgpu_amdkfd_fence *new_fence;
2797 struct list_head duplicate_save;
2798 struct amdgpu_sync sync_obj;
2799 unsigned long failed_size = 0;
2800 unsigned long total_size = 0;
2802 INIT_LIST_HEAD(&duplicate_save);
2803 INIT_LIST_HEAD(&ctx.list);
2804 INIT_LIST_HEAD(&ctx.duplicates);
2806 pd_bo_list = kcalloc(process_info->n_vms,
2807 sizeof(struct amdgpu_bo_list_entry),
2813 mutex_lock(&process_info->lock);
2814 list_for_each_entry(peer_vm, &process_info->vm_list_head,
2816 amdgpu_vm_get_pd_bo(peer_vm, &ctx.list, &pd_bo_list[i++]);
2818 /* Reserve all BOs and page tables/directory. Add all BOs from
2819 * kfd_bo_list to ctx.list
2821 list_for_each_entry(mem, &process_info->kfd_bo_list,
2822 validate_list.head) {
2824 list_add_tail(&mem->resv_list.head, &ctx.list);
2825 mem->resv_list.bo = mem->validate_list.bo;
2826 mem->resv_list.num_shared = mem->validate_list.num_shared;
2829 ret = ttm_eu_reserve_buffers(&ctx.ticket, &ctx.list,
2830 false, &duplicate_save);
2832 pr_debug("Memory eviction: TTM Reserve Failed. Try again\n");
2833 goto ttm_reserve_fail;
2836 amdgpu_sync_create(&sync_obj);
2838 /* Validate PDs and PTs */
2839 ret = process_validate_vms(process_info);
2841 goto validate_map_fail;
2843 ret = process_sync_pds_resv(process_info, &sync_obj);
2845 pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");
2846 goto validate_map_fail;
2849 /* Validate BOs and map them to GPUVM (update VM page tables). */
2850 list_for_each_entry(mem, &process_info->kfd_bo_list,
2851 validate_list.head) {
2853 struct amdgpu_bo *bo = mem->bo;
2854 uint32_t domain = mem->domain;
2855 struct kfd_mem_attachment *attachment;
2856 struct dma_resv_iter cursor;
2857 struct dma_fence *fence;
2859 total_size += amdgpu_bo_size(bo);
2861 ret = amdgpu_amdkfd_bo_validate(bo, domain, false);
2863 pr_debug("Memory eviction: Validate BOs failed\n");
2864 failed_size += amdgpu_bo_size(bo);
2865 ret = amdgpu_amdkfd_bo_validate(bo,
2866 AMDGPU_GEM_DOMAIN_GTT, false);
2868 pr_debug("Memory eviction: Try again\n");
2869 goto validate_map_fail;
2872 dma_resv_for_each_fence(&cursor, bo->tbo.base.resv,
2873 DMA_RESV_USAGE_KERNEL, fence) {
2874 ret = amdgpu_sync_fence(&sync_obj, fence);
2876 pr_debug("Memory eviction: Sync BO fence failed. Try again\n");
2877 goto validate_map_fail;
2880 list_for_each_entry(attachment, &mem->attachments, list) {
2881 if (!attachment->is_mapped)
2884 kfd_mem_dmaunmap_attachment(mem, attachment);
2885 ret = update_gpuvm_pte(mem, attachment, &sync_obj);
2887 pr_debug("Memory eviction: update PTE failed. Try again\n");
2888 goto validate_map_fail;
2894 pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size);
2896 /* Update page directories */
2897 ret = process_update_pds(process_info, &sync_obj);
2899 pr_debug("Memory eviction: update PDs failed. Try again\n");
2900 goto validate_map_fail;
2903 /* Wait for validate and PT updates to finish */
2904 amdgpu_sync_wait(&sync_obj, false);
2906 /* Release old eviction fence and create new one, because fence only
2907 * goes from unsignaled to signaled, fence cannot be reused.
2908 * Use context and mm from the old fence.
2910 new_fence = amdgpu_amdkfd_fence_create(
2911 process_info->eviction_fence->base.context,
2912 process_info->eviction_fence->mm,
2915 pr_err("Failed to create eviction fence\n");
2917 goto validate_map_fail;
2919 dma_fence_put(&process_info->eviction_fence->base);
2920 process_info->eviction_fence = new_fence;
2921 *ef = dma_fence_get(&new_fence->base);
2923 /* Attach new eviction fence to all BOs except pinned ones */
2924 list_for_each_entry(mem, &process_info->kfd_bo_list,
2925 validate_list.head) {
2926 if (mem->bo->tbo.pin_count)
2929 dma_resv_add_fence(mem->bo->tbo.base.resv,
2930 &process_info->eviction_fence->base,
2931 DMA_RESV_USAGE_BOOKKEEP);
2933 /* Attach eviction fence to PD / PT BOs */
2934 list_for_each_entry(peer_vm, &process_info->vm_list_head,
2936 struct amdgpu_bo *bo = peer_vm->root.bo;
2938 dma_resv_add_fence(bo->tbo.base.resv,
2939 &process_info->eviction_fence->base,
2940 DMA_RESV_USAGE_BOOKKEEP);
2944 ttm_eu_backoff_reservation(&ctx.ticket, &ctx.list);
2945 amdgpu_sync_free(&sync_obj);
2947 mutex_unlock(&process_info->lock);
2952 int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem)
2954 struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
2955 struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws;
2961 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
2965 mutex_init(&(*mem)->lock);
2966 INIT_LIST_HEAD(&(*mem)->attachments);
2967 (*mem)->bo = amdgpu_bo_ref(gws_bo);
2968 (*mem)->domain = AMDGPU_GEM_DOMAIN_GWS;
2969 (*mem)->process_info = process_info;
2970 add_kgd_mem_to_kfd_bo_list(*mem, process_info, false);
2971 amdgpu_sync_create(&(*mem)->sync);
2974 /* Validate gws bo the first time it is added to process */
2975 mutex_lock(&(*mem)->process_info->lock);
2976 ret = amdgpu_bo_reserve(gws_bo, false);
2977 if (unlikely(ret)) {
2978 pr_err("Reserve gws bo failed %d\n", ret);
2979 goto bo_reservation_failure;
2982 ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true);
2984 pr_err("GWS BO validate failed %d\n", ret);
2985 goto bo_validation_failure;
2987 /* GWS resource is shared b/t amdgpu and amdkfd
2988 * Add process eviction fence to bo so they can
2991 ret = dma_resv_reserve_fences(gws_bo->tbo.base.resv, 1);
2993 goto reserve_shared_fail;
2994 dma_resv_add_fence(gws_bo->tbo.base.resv,
2995 &process_info->eviction_fence->base,
2996 DMA_RESV_USAGE_BOOKKEEP);
2997 amdgpu_bo_unreserve(gws_bo);
2998 mutex_unlock(&(*mem)->process_info->lock);
3002 reserve_shared_fail:
3003 bo_validation_failure:
3004 amdgpu_bo_unreserve(gws_bo);
3005 bo_reservation_failure:
3006 mutex_unlock(&(*mem)->process_info->lock);
3007 amdgpu_sync_free(&(*mem)->sync);
3008 remove_kgd_mem_from_kfd_bo_list(*mem, process_info);
3009 amdgpu_bo_unref(&gws_bo);
3010 mutex_destroy(&(*mem)->lock);
3016 int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem)
3019 struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
3020 struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;
3021 struct amdgpu_bo *gws_bo = kgd_mem->bo;
3023 /* Remove BO from process's validate list so restore worker won't touch
3026 remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info);
3028 ret = amdgpu_bo_reserve(gws_bo, false);
3029 if (unlikely(ret)) {
3030 pr_err("Reserve gws bo failed %d\n", ret);
3031 //TODO add BO back to validate_list?
3034 amdgpu_amdkfd_remove_eviction_fence(gws_bo,
3035 process_info->eviction_fence);
3036 amdgpu_bo_unreserve(gws_bo);
3037 amdgpu_sync_free(&kgd_mem->sync);
3038 amdgpu_bo_unref(&gws_bo);
3039 mutex_destroy(&kgd_mem->lock);
3044 /* Returns GPU-specific tiling mode information */
3045 int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev,
3046 struct tile_config *config)
3048 config->gb_addr_config = adev->gfx.config.gb_addr_config;
3049 config->tile_config_ptr = adev->gfx.config.tile_mode_array;
3050 config->num_tile_configs =
3051 ARRAY_SIZE(adev->gfx.config.tile_mode_array);
3052 config->macro_tile_config_ptr =
3053 adev->gfx.config.macrotile_mode_array;
3054 config->num_macro_tile_configs =
3055 ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);
3057 /* Those values are not set from GFX9 onwards */
3058 config->num_banks = adev->gfx.config.num_banks;
3059 config->num_ranks = adev->gfx.config.num_ranks;
3064 bool amdgpu_amdkfd_bo_mapped_to_dev(struct amdgpu_device *adev, struct kgd_mem *mem)
3066 struct kfd_mem_attachment *entry;
3068 list_for_each_entry(entry, &mem->attachments, list) {
3069 if (entry->is_mapped && entry->adev == adev)
3075 #if defined(CONFIG_DEBUG_FS)
3077 int kfd_debugfs_kfd_mem_limits(struct seq_file *m, void *data)
3080 spin_lock(&kfd_mem_limit.mem_limit_lock);
3081 seq_printf(m, "System mem used %lldM out of %lluM\n",
3082 (kfd_mem_limit.system_mem_used >> 20),
3083 (kfd_mem_limit.max_system_mem_limit >> 20));
3084 seq_printf(m, "TTM mem used %lldM out of %lluM\n",
3085 (kfd_mem_limit.ttm_mem_used >> 20),
3086 (kfd_mem_limit.max_ttm_mem_limit >> 20));
3087 spin_unlock(&kfd_mem_limit.mem_limit_lock);