Path: blob/master/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c
29285 views
// SPDX-License-Identifier: MIT1/*2* Copyright 2014-2018 Advanced Micro Devices, Inc.3*4* Permission is hereby granted, free of charge, to any person obtaining a5* copy of this software and associated documentation files (the "Software"),6* to deal in the Software without restriction, including without limitation7* the rights to use, copy, modify, merge, publish, distribute, sublicense,8* and/or sell copies of the Software, and to permit persons to whom the9* Software is furnished to do so, subject to the following conditions:10*11* The above copyright notice and this permission notice shall be included in12* all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR18* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,19* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR20* OTHER DEALINGS IN THE SOFTWARE.21*/22#include <linux/dma-buf.h>23#include <linux/list.h>24#include <linux/pagemap.h>25#include <linux/sched/mm.h>26#include <linux/sched/task.h>27#include <drm/ttm/ttm_tt.h>2829#include <drm/drm_exec.h>3031#include "amdgpu_object.h"32#include "amdgpu_gem.h"33#include "amdgpu_vm.h"34#include "amdgpu_hmm.h"35#include "amdgpu_amdkfd.h"36#include "amdgpu_dma_buf.h"37#include <uapi/linux/kfd_ioctl.h>38#include "amdgpu_xgmi.h"39#include "kfd_priv.h"40#include "kfd_smi_events.h"4142/* Userptr restore delay, just long enough to allow consecutive VM43* changes to accumulate44*/45#define AMDGPU_USERPTR_RESTORE_DELAY_MS 146#define AMDGPU_RESERVE_MEM_LIMIT (3UL << 29)4748/*49* Align VRAM availability to 2MB to avoid fragmentation caused by 4K allocations in the tail 2MB50* BO chunk51*/52#define VRAM_AVAILABLITY_ALIGN (1 << 21)5354/* Impose limit on how much memory KFD can use */55static struct {56uint64_t max_system_mem_limit;57uint64_t max_ttm_mem_limit;58int64_t system_mem_used;59int64_t ttm_mem_used;60spinlock_t mem_limit_lock;61} kfd_mem_limit;6263static const char * const domain_bit_to_string[] = {64"CPU",65"GTT",66"VRAM",67"GDS",68"GWS",69"OA"70};7172#define domain_string(domain) domain_bit_to_string[ffs(domain)-1]7374static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work);7576static bool kfd_mem_is_attached(struct amdgpu_vm *avm,77struct kgd_mem *mem)78{79struct kfd_mem_attachment *entry;8081list_for_each_entry(entry, &mem->attachments, list)82if (entry->bo_va->base.vm == avm)83return true;8485return false;86}8788/**89* reuse_dmamap() - Check whether adev can share the original90* userptr BO91*92* If both adev and bo_adev are in direct mapping or93* in the same iommu group, they can share the original BO.94*95* @adev: Device to which can or cannot share the original BO96* @bo_adev: Device to which allocated BO belongs to97*98* Return: returns true if adev can share original userptr BO,99* false otherwise.100*/101static bool reuse_dmamap(struct amdgpu_device *adev, struct amdgpu_device *bo_adev)102{103return (adev->ram_is_direct_mapped && bo_adev->ram_is_direct_mapped) ||104(adev->dev->iommu_group == bo_adev->dev->iommu_group);105}106107/* Set memory usage limits. Current, limits are108* System (TTM + userptr) memory - 15/16th System RAM109* TTM memory - 3/8th System RAM110*/111void amdgpu_amdkfd_gpuvm_init_mem_limits(void)112{113struct sysinfo si;114uint64_t mem;115116if (kfd_mem_limit.max_system_mem_limit)117return;118119si_meminfo(&si);120mem = si.totalram - si.totalhigh;121mem *= si.mem_unit;122123spin_lock_init(&kfd_mem_limit.mem_limit_lock);124kfd_mem_limit.max_system_mem_limit = mem - (mem >> 6);125if (kfd_mem_limit.max_system_mem_limit < 2 * AMDGPU_RESERVE_MEM_LIMIT)126kfd_mem_limit.max_system_mem_limit >>= 1;127else128kfd_mem_limit.max_system_mem_limit -= AMDGPU_RESERVE_MEM_LIMIT;129130kfd_mem_limit.max_ttm_mem_limit = ttm_tt_pages_limit() << PAGE_SHIFT;131pr_debug("Kernel memory limit %lluM, TTM limit %lluM\n",132(kfd_mem_limit.max_system_mem_limit >> 20),133(kfd_mem_limit.max_ttm_mem_limit >> 20));134}135136void amdgpu_amdkfd_reserve_system_mem(uint64_t size)137{138kfd_mem_limit.system_mem_used += size;139}140141/* Estimate page table size needed to represent a given memory size142*143* With 4KB pages, we need one 8 byte PTE for each 4KB of memory144* (factor 512, >> 9). With 2MB pages, we need one 8 byte PTE for 2MB145* of memory (factor 256K, >> 18). ROCm user mode tries to optimize146* for 2MB pages for TLB efficiency. However, small allocations and147* fragmented system memory still need some 4KB pages. We choose a148* compromise that should work in most cases without reserving too149* much memory for page tables unnecessarily (factor 16K, >> 14).150*/151152#define ESTIMATE_PT_SIZE(mem_size) max(((mem_size) >> 14), AMDGPU_VM_RESERVED_VRAM)153154/**155* amdgpu_amdkfd_reserve_mem_limit() - Decrease available memory by size156* of buffer.157*158* @adev: Device to which allocated BO belongs to159* @size: Size of buffer, in bytes, encapsulated by B0. This should be160* equivalent to amdgpu_bo_size(BO)161* @alloc_flag: Flag used in allocating a BO as noted above162* @xcp_id: xcp_id is used to get xcp from xcp manager, one xcp is163* managed as one compute node in driver for app164*165* Return:166* returns -ENOMEM in case of error, ZERO otherwise167*/168int amdgpu_amdkfd_reserve_mem_limit(struct amdgpu_device *adev,169uint64_t size, u32 alloc_flag, int8_t xcp_id)170{171uint64_t reserved_for_pt =172ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);173struct amdgpu_ras *con = amdgpu_ras_get_context(adev);174uint64_t reserved_for_ras = (con ? con->reserved_pages_in_bytes : 0);175size_t system_mem_needed, ttm_mem_needed, vram_needed;176int ret = 0;177uint64_t vram_size = 0;178179system_mem_needed = 0;180ttm_mem_needed = 0;181vram_needed = 0;182if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {183system_mem_needed = size;184ttm_mem_needed = size;185} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {186/*187* Conservatively round up the allocation requirement to 2 MB188* to avoid fragmentation caused by 4K allocations in the tail189* 2M BO chunk.190*/191vram_needed = size;192/*193* For GFX 9.4.3, get the VRAM size from XCP structs194*/195if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id))196return -EINVAL;197198vram_size = KFD_XCP_MEMORY_SIZE(adev, xcp_id);199if (adev->apu_prefer_gtt) {200system_mem_needed = size;201ttm_mem_needed = size;202}203} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {204system_mem_needed = size;205} else if (!(alloc_flag &206(KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |207KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {208pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);209return -ENOMEM;210}211212spin_lock(&kfd_mem_limit.mem_limit_lock);213214if (kfd_mem_limit.system_mem_used + system_mem_needed >215kfd_mem_limit.max_system_mem_limit) {216pr_debug("Set no_system_mem_limit=1 if using shared memory\n");217if (!no_system_mem_limit) {218ret = -ENOMEM;219goto release;220}221}222223if (kfd_mem_limit.ttm_mem_used + ttm_mem_needed >224kfd_mem_limit.max_ttm_mem_limit) {225ret = -ENOMEM;226goto release;227}228229/*if is_app_apu is false and apu_prefer_gtt is true, it is an APU with230* carve out < gtt. In that case, VRAM allocation will go to gtt domain, skip231* VRAM check since ttm_mem_limit check already cover this allocation232*/233234if (adev && xcp_id >= 0 && (!adev->apu_prefer_gtt || adev->gmc.is_app_apu)) {235uint64_t vram_available =236vram_size - reserved_for_pt - reserved_for_ras -237atomic64_read(&adev->vram_pin_size);238if (adev->kfd.vram_used[xcp_id] + vram_needed > vram_available) {239ret = -ENOMEM;240goto release;241}242}243244/* Update memory accounting by decreasing available system245* memory, TTM memory and GPU memory as computed above246*/247WARN_ONCE(vram_needed && !adev,248"adev reference can't be null when vram is used");249if (adev && xcp_id >= 0) {250adev->kfd.vram_used[xcp_id] += vram_needed;251adev->kfd.vram_used_aligned[xcp_id] +=252adev->apu_prefer_gtt ?253vram_needed :254ALIGN(vram_needed, VRAM_AVAILABLITY_ALIGN);255}256kfd_mem_limit.system_mem_used += system_mem_needed;257kfd_mem_limit.ttm_mem_used += ttm_mem_needed;258259release:260spin_unlock(&kfd_mem_limit.mem_limit_lock);261return ret;262}263264void amdgpu_amdkfd_unreserve_mem_limit(struct amdgpu_device *adev,265uint64_t size, u32 alloc_flag, int8_t xcp_id)266{267spin_lock(&kfd_mem_limit.mem_limit_lock);268269if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {270kfd_mem_limit.system_mem_used -= size;271kfd_mem_limit.ttm_mem_used -= size;272} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {273WARN_ONCE(!adev,274"adev reference can't be null when alloc mem flags vram is set");275if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id))276goto release;277278if (adev) {279adev->kfd.vram_used[xcp_id] -= size;280if (adev->apu_prefer_gtt) {281adev->kfd.vram_used_aligned[xcp_id] -= size;282kfd_mem_limit.system_mem_used -= size;283kfd_mem_limit.ttm_mem_used -= size;284} else {285adev->kfd.vram_used_aligned[xcp_id] -=286ALIGN(size, VRAM_AVAILABLITY_ALIGN);287}288}289} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {290kfd_mem_limit.system_mem_used -= size;291} else if (!(alloc_flag &292(KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |293KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {294pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);295goto release;296}297WARN_ONCE(adev && xcp_id >= 0 && adev->kfd.vram_used[xcp_id] < 0,298"KFD VRAM memory accounting unbalanced for xcp: %d", xcp_id);299WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0,300"KFD TTM memory accounting unbalanced");301WARN_ONCE(kfd_mem_limit.system_mem_used < 0,302"KFD system memory accounting unbalanced");303304release:305spin_unlock(&kfd_mem_limit.mem_limit_lock);306}307308void amdgpu_amdkfd_release_notify(struct amdgpu_bo *bo)309{310struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);311u32 alloc_flags = bo->kfd_bo->alloc_flags;312u64 size = amdgpu_bo_size(bo);313314amdgpu_amdkfd_unreserve_mem_limit(adev, size, alloc_flags,315bo->xcp_id);316317kfree(bo->kfd_bo);318}319320/**321* create_dmamap_sg_bo() - Creates a amdgpu_bo object to reflect information322* about USERPTR or DOOREBELL or MMIO BO.323*324* @adev: Device for which dmamap BO is being created325* @mem: BO of peer device that is being DMA mapped. Provides parameters326* in building the dmamap BO327* @bo_out: Output parameter updated with handle of dmamap BO328*/329static int330create_dmamap_sg_bo(struct amdgpu_device *adev,331struct kgd_mem *mem, struct amdgpu_bo **bo_out)332{333struct drm_gem_object *gem_obj;334int ret;335uint64_t flags = 0;336337ret = amdgpu_bo_reserve(mem->bo, false);338if (ret)339return ret;340341if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR)342flags |= mem->bo->flags & (AMDGPU_GEM_CREATE_COHERENT |343AMDGPU_GEM_CREATE_UNCACHED);344345ret = amdgpu_gem_object_create(adev, mem->bo->tbo.base.size, 1,346AMDGPU_GEM_DOMAIN_CPU, AMDGPU_GEM_CREATE_PREEMPTIBLE | flags,347ttm_bo_type_sg, mem->bo->tbo.base.resv, &gem_obj, 0);348349amdgpu_bo_unreserve(mem->bo);350351if (ret) {352pr_err("Error in creating DMA mappable SG BO on domain: %d\n", ret);353return -EINVAL;354}355356*bo_out = gem_to_amdgpu_bo(gem_obj);357(*bo_out)->parent = amdgpu_bo_ref(mem->bo);358return ret;359}360361/* amdgpu_amdkfd_remove_eviction_fence - Removes eviction fence from BO's362* reservation object.363*364* @bo: [IN] Remove eviction fence(s) from this BO365* @ef: [IN] This eviction fence is removed if it366* is present in the shared list.367*368* NOTE: Must be called with BO reserved i.e. bo->tbo.resv->lock held.369*/370static int amdgpu_amdkfd_remove_eviction_fence(struct amdgpu_bo *bo,371struct amdgpu_amdkfd_fence *ef)372{373struct dma_fence *replacement;374375if (!ef)376return -EINVAL;377378/* TODO: Instead of block before we should use the fence of the page379* table update and TLB flush here directly.380*/381replacement = dma_fence_get_stub();382dma_resv_replace_fences(bo->tbo.base.resv, ef->base.context,383replacement, DMA_RESV_USAGE_BOOKKEEP);384dma_fence_put(replacement);385return 0;386}387388/**389* amdgpu_amdkfd_remove_all_eviction_fences - Remove all eviction fences390* @bo: the BO where to remove the evictions fences from.391*392* This functions should only be used on release when all references to the BO393* are already dropped. We remove the eviction fence from the private copy of394* the dma_resv object here since that is what is used during release to395* determine of the BO is idle or not.396*/397void amdgpu_amdkfd_remove_all_eviction_fences(struct amdgpu_bo *bo)398{399struct dma_resv *resv = &bo->tbo.base._resv;400struct dma_fence *fence, *stub;401struct dma_resv_iter cursor;402403dma_resv_assert_held(resv);404405stub = dma_fence_get_stub();406dma_resv_for_each_fence(&cursor, resv, DMA_RESV_USAGE_BOOKKEEP, fence) {407if (!to_amdgpu_amdkfd_fence(fence))408continue;409410dma_resv_replace_fences(resv, fence->context, stub,411DMA_RESV_USAGE_BOOKKEEP);412}413dma_fence_put(stub);414}415416static int amdgpu_amdkfd_bo_validate(struct amdgpu_bo *bo, uint32_t domain,417bool wait)418{419struct ttm_operation_ctx ctx = { false, false };420int ret;421422if (WARN(amdgpu_ttm_tt_get_usermm(bo->tbo.ttm),423"Called with userptr BO"))424return -EINVAL;425426/* bo has been pinned, not need validate it */427if (bo->tbo.pin_count)428return 0;429430amdgpu_bo_placement_from_domain(bo, domain);431432ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);433if (ret)434goto validate_fail;435if (wait)436amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);437438validate_fail:439return ret;440}441442int amdgpu_amdkfd_bo_validate_and_fence(struct amdgpu_bo *bo,443uint32_t domain,444struct dma_fence *fence)445{446int ret = amdgpu_bo_reserve(bo, false);447448if (ret)449return ret;450451ret = amdgpu_amdkfd_bo_validate(bo, domain, true);452if (ret)453goto unreserve_out;454455ret = dma_resv_reserve_fences(bo->tbo.base.resv, 1);456if (ret)457goto unreserve_out;458459dma_resv_add_fence(bo->tbo.base.resv, fence,460DMA_RESV_USAGE_BOOKKEEP);461462unreserve_out:463amdgpu_bo_unreserve(bo);464465return ret;466}467468static int amdgpu_amdkfd_validate_vm_bo(void *_unused, struct amdgpu_bo *bo)469{470return amdgpu_amdkfd_bo_validate(bo, bo->allowed_domains, false);471}472473/* vm_validate_pt_pd_bos - Validate page table and directory BOs474*475* Page directories are not updated here because huge page handling476* during page table updates can invalidate page directory entries477* again. Page directories are only updated after updating page478* tables.479*/480static int vm_validate_pt_pd_bos(struct amdgpu_vm *vm,481struct ww_acquire_ctx *ticket)482{483struct amdgpu_bo *pd = vm->root.bo;484struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);485int ret;486487ret = amdgpu_vm_validate(adev, vm, ticket,488amdgpu_amdkfd_validate_vm_bo, NULL);489if (ret) {490pr_err("failed to validate PT BOs\n");491return ret;492}493494vm->pd_phys_addr = amdgpu_gmc_pd_addr(vm->root.bo);495496return 0;497}498499static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync)500{501struct amdgpu_bo *pd = vm->root.bo;502struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);503int ret;504505ret = amdgpu_vm_update_pdes(adev, vm, false);506if (ret)507return ret;508509return amdgpu_sync_fence(sync, vm->last_update, GFP_KERNEL);510}511512static uint64_t get_pte_flags(struct amdgpu_device *adev, struct amdgpu_vm *vm,513struct kgd_mem *mem)514{515uint32_t mapping_flags = AMDGPU_VM_PAGE_READABLE |516AMDGPU_VM_MTYPE_DEFAULT;517518if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE)519mapping_flags |= AMDGPU_VM_PAGE_WRITEABLE;520if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE)521mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE;522523return mapping_flags;524}525526/**527* create_sg_table() - Create an sg_table for a contiguous DMA addr range528* @addr: The starting address to point to529* @size: Size of memory area in bytes being pointed to530*531* Allocates an instance of sg_table and initializes it to point to memory532* area specified by input parameters. The address used to build is assumed533* to be DMA mapped, if needed.534*535* DOORBELL or MMIO BOs use only one scatterlist node in their sg_table536* because they are physically contiguous.537*538* Return: Initialized instance of SG Table or NULL539*/540static struct sg_table *create_sg_table(uint64_t addr, uint32_t size)541{542struct sg_table *sg = kmalloc(sizeof(*sg), GFP_KERNEL);543544if (!sg)545return NULL;546if (sg_alloc_table(sg, 1, GFP_KERNEL)) {547kfree(sg);548return NULL;549}550sg_dma_address(sg->sgl) = addr;551sg->sgl->length = size;552#ifdef CONFIG_NEED_SG_DMA_LENGTH553sg->sgl->dma_length = size;554#endif555return sg;556}557558static int559kfd_mem_dmamap_userptr(struct kgd_mem *mem,560struct kfd_mem_attachment *attachment)561{562enum dma_data_direction direction =563mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?564DMA_BIDIRECTIONAL : DMA_TO_DEVICE;565struct ttm_operation_ctx ctx = {.interruptible = true};566struct amdgpu_bo *bo = attachment->bo_va->base.bo;567struct amdgpu_device *adev = attachment->adev;568struct ttm_tt *src_ttm = mem->bo->tbo.ttm;569struct ttm_tt *ttm = bo->tbo.ttm;570int ret;571572if (WARN_ON(ttm->num_pages != src_ttm->num_pages))573return -EINVAL;574575ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL);576if (unlikely(!ttm->sg))577return -ENOMEM;578579/* Same sequence as in amdgpu_ttm_tt_pin_userptr */580ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages,581ttm->num_pages, 0,582(u64)ttm->num_pages << PAGE_SHIFT,583GFP_KERNEL);584if (unlikely(ret))585goto free_sg;586587ret = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);588if (unlikely(ret))589goto release_sg;590591amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);592ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);593if (ret)594goto unmap_sg;595596return 0;597598unmap_sg:599dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);600release_sg:601pr_err("DMA map userptr failed: %d\n", ret);602sg_free_table(ttm->sg);603free_sg:604kfree(ttm->sg);605ttm->sg = NULL;606return ret;607}608609static int610kfd_mem_dmamap_dmabuf(struct kfd_mem_attachment *attachment)611{612struct ttm_operation_ctx ctx = {.interruptible = true};613struct amdgpu_bo *bo = attachment->bo_va->base.bo;614615amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);616return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);617}618619/**620* kfd_mem_dmamap_sg_bo() - Create DMA mapped sg_table to access DOORBELL or MMIO BO621* @mem: SG BO of the DOORBELL or MMIO resource on the owning device622* @attachment: Virtual address attachment of the BO on accessing device623*624* An access request from the device that owns DOORBELL does not require DMA mapping.625* This is because the request doesn't go through PCIe root complex i.e. it instead626* loops back. The need to DMA map arises only when accessing peer device's DOORBELL627*628* In contrast, all access requests for MMIO need to be DMA mapped without regard to629* device ownership. This is because access requests for MMIO go through PCIe root630* complex.631*632* This is accomplished in two steps:633* - Obtain DMA mapped address of DOORBELL or MMIO memory that could be used634* in updating requesting device's page table635* - Signal TTM to mark memory pointed to by requesting device's BO as GPU636* accessible. This allows an update of requesting device's page table637* with entries associated with DOOREBELL or MMIO memory638*639* This method is invoked in the following contexts:640* - Mapping of DOORBELL or MMIO BO of same or peer device641* - Validating an evicted DOOREBELL or MMIO BO on device seeking access642*643* Return: ZERO if successful, NON-ZERO otherwise644*/645static int646kfd_mem_dmamap_sg_bo(struct kgd_mem *mem,647struct kfd_mem_attachment *attachment)648{649struct ttm_operation_ctx ctx = {.interruptible = true};650struct amdgpu_bo *bo = attachment->bo_va->base.bo;651struct amdgpu_device *adev = attachment->adev;652struct ttm_tt *ttm = bo->tbo.ttm;653enum dma_data_direction dir;654dma_addr_t dma_addr;655bool mmio;656int ret;657658/* Expect SG Table of dmapmap BO to be NULL */659mmio = (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP);660if (unlikely(ttm->sg)) {661pr_err("SG Table of %d BO for peer device is UNEXPECTEDLY NON-NULL", mmio);662return -EINVAL;663}664665dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?666DMA_BIDIRECTIONAL : DMA_TO_DEVICE;667dma_addr = mem->bo->tbo.sg->sgl->dma_address;668pr_debug("%d BO size: %d\n", mmio, mem->bo->tbo.sg->sgl->length);669pr_debug("%d BO address before DMA mapping: %llx\n", mmio, dma_addr);670dma_addr = dma_map_resource(adev->dev, dma_addr,671mem->bo->tbo.sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);672ret = dma_mapping_error(adev->dev, dma_addr);673if (unlikely(ret))674return ret;675pr_debug("%d BO address after DMA mapping: %llx\n", mmio, dma_addr);676677ttm->sg = create_sg_table(dma_addr, mem->bo->tbo.sg->sgl->length);678if (unlikely(!ttm->sg)) {679ret = -ENOMEM;680goto unmap_sg;681}682683amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);684ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);685if (unlikely(ret))686goto free_sg;687688return ret;689690free_sg:691sg_free_table(ttm->sg);692kfree(ttm->sg);693ttm->sg = NULL;694unmap_sg:695dma_unmap_resource(adev->dev, dma_addr, mem->bo->tbo.sg->sgl->length,696dir, DMA_ATTR_SKIP_CPU_SYNC);697return ret;698}699700static int701kfd_mem_dmamap_attachment(struct kgd_mem *mem,702struct kfd_mem_attachment *attachment)703{704switch (attachment->type) {705case KFD_MEM_ATT_SHARED:706return 0;707case KFD_MEM_ATT_USERPTR:708return kfd_mem_dmamap_userptr(mem, attachment);709case KFD_MEM_ATT_DMABUF:710return kfd_mem_dmamap_dmabuf(attachment);711case KFD_MEM_ATT_SG:712return kfd_mem_dmamap_sg_bo(mem, attachment);713default:714WARN_ON_ONCE(1);715}716return -EINVAL;717}718719static void720kfd_mem_dmaunmap_userptr(struct kgd_mem *mem,721struct kfd_mem_attachment *attachment)722{723enum dma_data_direction direction =724mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?725DMA_BIDIRECTIONAL : DMA_TO_DEVICE;726struct ttm_operation_ctx ctx = {.interruptible = false};727struct amdgpu_bo *bo = attachment->bo_va->base.bo;728struct amdgpu_device *adev = attachment->adev;729struct ttm_tt *ttm = bo->tbo.ttm;730731if (unlikely(!ttm->sg))732return;733734amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);735(void)ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);736737dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);738sg_free_table(ttm->sg);739kfree(ttm->sg);740ttm->sg = NULL;741}742743static void744kfd_mem_dmaunmap_dmabuf(struct kfd_mem_attachment *attachment)745{746/* This is a no-op. We don't want to trigger eviction fences when747* unmapping DMABufs. Therefore the invalidation (moving to system748* domain) is done in kfd_mem_dmamap_dmabuf.749*/750}751752/**753* kfd_mem_dmaunmap_sg_bo() - Free DMA mapped sg_table of DOORBELL or MMIO BO754* @mem: SG BO of the DOORBELL or MMIO resource on the owning device755* @attachment: Virtual address attachment of the BO on accessing device756*757* The method performs following steps:758* - Signal TTM to mark memory pointed to by BO as GPU inaccessible759* - Free SG Table that is used to encapsulate DMA mapped memory of760* peer device's DOORBELL or MMIO memory761*762* This method is invoked in the following contexts:763* UNMapping of DOORBELL or MMIO BO on a device having access to its memory764* Eviction of DOOREBELL or MMIO BO on device having access to its memory765*766* Return: void767*/768static void769kfd_mem_dmaunmap_sg_bo(struct kgd_mem *mem,770struct kfd_mem_attachment *attachment)771{772struct ttm_operation_ctx ctx = {.interruptible = true};773struct amdgpu_bo *bo = attachment->bo_va->base.bo;774struct amdgpu_device *adev = attachment->adev;775struct ttm_tt *ttm = bo->tbo.ttm;776enum dma_data_direction dir;777778if (unlikely(!ttm->sg)) {779pr_debug("SG Table of BO is NULL");780return;781}782783amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);784(void)ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);785786dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?787DMA_BIDIRECTIONAL : DMA_TO_DEVICE;788dma_unmap_resource(adev->dev, ttm->sg->sgl->dma_address,789ttm->sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);790sg_free_table(ttm->sg);791kfree(ttm->sg);792ttm->sg = NULL;793bo->tbo.sg = NULL;794}795796static void797kfd_mem_dmaunmap_attachment(struct kgd_mem *mem,798struct kfd_mem_attachment *attachment)799{800switch (attachment->type) {801case KFD_MEM_ATT_SHARED:802break;803case KFD_MEM_ATT_USERPTR:804kfd_mem_dmaunmap_userptr(mem, attachment);805break;806case KFD_MEM_ATT_DMABUF:807kfd_mem_dmaunmap_dmabuf(attachment);808break;809case KFD_MEM_ATT_SG:810kfd_mem_dmaunmap_sg_bo(mem, attachment);811break;812default:813WARN_ON_ONCE(1);814}815}816817static int kfd_mem_export_dmabuf(struct kgd_mem *mem)818{819if (!mem->dmabuf) {820struct amdgpu_device *bo_adev;821struct dma_buf *dmabuf;822823bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);824dmabuf = drm_gem_prime_handle_to_dmabuf(&bo_adev->ddev, bo_adev->kfd.client.file,825mem->gem_handle,826mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?827DRM_RDWR : 0);828if (IS_ERR(dmabuf))829return PTR_ERR(dmabuf);830mem->dmabuf = dmabuf;831}832833return 0;834}835836static int837kfd_mem_attach_dmabuf(struct amdgpu_device *adev, struct kgd_mem *mem,838struct amdgpu_bo **bo)839{840struct drm_gem_object *gobj;841int ret;842843ret = kfd_mem_export_dmabuf(mem);844if (ret)845return ret;846847gobj = amdgpu_gem_prime_import(adev_to_drm(adev), mem->dmabuf);848if (IS_ERR(gobj))849return PTR_ERR(gobj);850851*bo = gem_to_amdgpu_bo(gobj);852(*bo)->flags |= AMDGPU_GEM_CREATE_PREEMPTIBLE;853854return 0;855}856857/* kfd_mem_attach - Add a BO to a VM858*859* Everything that needs to bo done only once when a BO is first added860* to a VM. It can later be mapped and unmapped many times without861* repeating these steps.862*863* 0. Create BO for DMA mapping, if needed864* 1. Allocate and initialize BO VA entry data structure865* 2. Add BO to the VM866* 3. Determine ASIC-specific PTE flags867* 4. Alloc page tables and directories if needed868* 4a. Validate new page tables and directories869*/870static int kfd_mem_attach(struct amdgpu_device *adev, struct kgd_mem *mem,871struct amdgpu_vm *vm, bool is_aql)872{873struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);874unsigned long bo_size = mem->bo->tbo.base.size;875uint64_t va = mem->va;876struct kfd_mem_attachment *attachment[2] = {NULL, NULL};877struct amdgpu_bo *bo[2] = {NULL, NULL};878struct amdgpu_bo_va *bo_va;879bool same_hive = false;880int i, ret;881882if (!va) {883pr_err("Invalid VA when adding BO to VM\n");884return -EINVAL;885}886887/* Determine access to VRAM, MMIO and DOORBELL BOs of peer devices888*889* The access path of MMIO and DOORBELL BOs of is always over PCIe.890* In contrast the access path of VRAM BOs depens upon the type of891* link that connects the peer device. Access over PCIe is allowed892* if peer device has large BAR. In contrast, access over xGMI is893* allowed for both small and large BAR configurations of peer device894*/895if ((adev != bo_adev && !adev->apu_prefer_gtt) &&896((mem->domain == AMDGPU_GEM_DOMAIN_VRAM) ||897(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) ||898(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {899if (mem->domain == AMDGPU_GEM_DOMAIN_VRAM)900same_hive = amdgpu_xgmi_same_hive(adev, bo_adev);901if (!same_hive && !amdgpu_device_is_peer_accessible(bo_adev, adev))902return -EINVAL;903}904905for (i = 0; i <= is_aql; i++) {906attachment[i] = kzalloc(sizeof(*attachment[i]), GFP_KERNEL);907if (unlikely(!attachment[i])) {908ret = -ENOMEM;909goto unwind;910}911912pr_debug("\t add VA 0x%llx - 0x%llx to vm %p\n", va,913va + bo_size, vm);914915if ((adev == bo_adev && !(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) ||916(amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) && reuse_dmamap(adev, bo_adev)) ||917(mem->domain == AMDGPU_GEM_DOMAIN_GTT && reuse_dmamap(adev, bo_adev)) ||918same_hive) {919/* Mappings on the local GPU, or VRAM mappings in the920* local hive, or userptr, or GTT mapping can reuse dma map921* address space share the original BO922*/923attachment[i]->type = KFD_MEM_ATT_SHARED;924bo[i] = mem->bo;925drm_gem_object_get(&bo[i]->tbo.base);926} else if (i > 0) {927/* Multiple mappings on the same GPU share the BO */928attachment[i]->type = KFD_MEM_ATT_SHARED;929bo[i] = bo[0];930drm_gem_object_get(&bo[i]->tbo.base);931} else if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {932/* Create an SG BO to DMA-map userptrs on other GPUs */933attachment[i]->type = KFD_MEM_ATT_USERPTR;934ret = create_dmamap_sg_bo(adev, mem, &bo[i]);935if (ret)936goto unwind;937/* Handle DOORBELL BOs of peer devices and MMIO BOs of local and peer devices */938} else if (mem->bo->tbo.type == ttm_bo_type_sg) {939WARN_ONCE(!(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL ||940mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP),941"Handing invalid SG BO in ATTACH request");942attachment[i]->type = KFD_MEM_ATT_SG;943ret = create_dmamap_sg_bo(adev, mem, &bo[i]);944if (ret)945goto unwind;946/* Enable acces to GTT and VRAM BOs of peer devices */947} else if (mem->domain == AMDGPU_GEM_DOMAIN_GTT ||948mem->domain == AMDGPU_GEM_DOMAIN_VRAM) {949attachment[i]->type = KFD_MEM_ATT_DMABUF;950ret = kfd_mem_attach_dmabuf(adev, mem, &bo[i]);951if (ret)952goto unwind;953pr_debug("Employ DMABUF mechanism to enable peer GPU access\n");954} else {955WARN_ONCE(true, "Handling invalid ATTACH request");956ret = -EINVAL;957goto unwind;958}959960/* Add BO to VM internal data structures */961ret = amdgpu_bo_reserve(bo[i], false);962if (ret) {963pr_debug("Unable to reserve BO during memory attach");964goto unwind;965}966bo_va = amdgpu_vm_bo_find(vm, bo[i]);967if (!bo_va)968bo_va = amdgpu_vm_bo_add(adev, vm, bo[i]);969else970++bo_va->ref_count;971attachment[i]->bo_va = bo_va;972amdgpu_bo_unreserve(bo[i]);973if (unlikely(!attachment[i]->bo_va)) {974ret = -ENOMEM;975pr_err("Failed to add BO object to VM. ret == %d\n",976ret);977goto unwind;978}979attachment[i]->va = va;980attachment[i]->pte_flags = get_pte_flags(adev, vm, mem);981attachment[i]->adev = adev;982list_add(&attachment[i]->list, &mem->attachments);983984va += bo_size;985}986987return 0;988989unwind:990for (; i >= 0; i--) {991if (!attachment[i])992continue;993if (attachment[i]->bo_va) {994(void)amdgpu_bo_reserve(bo[i], true);995if (--attachment[i]->bo_va->ref_count == 0)996amdgpu_vm_bo_del(adev, attachment[i]->bo_va);997amdgpu_bo_unreserve(bo[i]);998list_del(&attachment[i]->list);999}1000if (bo[i])1001drm_gem_object_put(&bo[i]->tbo.base);1002kfree(attachment[i]);1003}1004return ret;1005}10061007static void kfd_mem_detach(struct kfd_mem_attachment *attachment)1008{1009struct amdgpu_bo *bo = attachment->bo_va->base.bo;10101011pr_debug("\t remove VA 0x%llx in entry %p\n",1012attachment->va, attachment);1013if (--attachment->bo_va->ref_count == 0)1014amdgpu_vm_bo_del(attachment->adev, attachment->bo_va);1015drm_gem_object_put(&bo->tbo.base);1016list_del(&attachment->list);1017kfree(attachment);1018}10191020static void add_kgd_mem_to_kfd_bo_list(struct kgd_mem *mem,1021struct amdkfd_process_info *process_info,1022bool userptr)1023{1024mutex_lock(&process_info->lock);1025if (userptr)1026list_add_tail(&mem->validate_list,1027&process_info->userptr_valid_list);1028else1029list_add_tail(&mem->validate_list, &process_info->kfd_bo_list);1030mutex_unlock(&process_info->lock);1031}10321033static void remove_kgd_mem_from_kfd_bo_list(struct kgd_mem *mem,1034struct amdkfd_process_info *process_info)1035{1036mutex_lock(&process_info->lock);1037list_del(&mem->validate_list);1038mutex_unlock(&process_info->lock);1039}10401041/* Initializes user pages. It registers the MMU notifier and validates1042* the userptr BO in the GTT domain.1043*1044* The BO must already be on the userptr_valid_list. Otherwise an1045* eviction and restore may happen that leaves the new BO unmapped1046* with the user mode queues running.1047*1048* Takes the process_info->lock to protect against concurrent restore1049* workers.1050*1051* Returns 0 for success, negative errno for errors.1052*/1053static int init_user_pages(struct kgd_mem *mem, uint64_t user_addr,1054bool criu_resume)1055{1056struct amdkfd_process_info *process_info = mem->process_info;1057struct amdgpu_bo *bo = mem->bo;1058struct ttm_operation_ctx ctx = { true, false };1059struct hmm_range *range;1060int ret = 0;10611062mutex_lock(&process_info->lock);10631064ret = amdgpu_ttm_tt_set_userptr(&bo->tbo, user_addr, 0);1065if (ret) {1066pr_err("%s: Failed to set userptr: %d\n", __func__, ret);1067goto out;1068}10691070ret = amdgpu_hmm_register(bo, user_addr);1071if (ret) {1072pr_err("%s: Failed to register MMU notifier: %d\n",1073__func__, ret);1074goto out;1075}10761077if (criu_resume) {1078/*1079* During a CRIU restore operation, the userptr buffer objects1080* will be validated in the restore_userptr_work worker at a1081* later stage when it is scheduled by another ioctl called by1082* CRIU master process for the target pid for restore.1083*/1084mutex_lock(&process_info->notifier_lock);1085mem->invalid++;1086mutex_unlock(&process_info->notifier_lock);1087mutex_unlock(&process_info->lock);1088return 0;1089}10901091ret = amdgpu_ttm_tt_get_user_pages(bo, &range);1092if (ret) {1093if (ret == -EAGAIN)1094pr_debug("Failed to get user pages, try again\n");1095else1096pr_err("%s: Failed to get user pages: %d\n", __func__, ret);1097goto unregister_out;1098}10991100ret = amdgpu_bo_reserve(bo, true);1101if (ret) {1102pr_err("%s: Failed to reserve BO\n", __func__);1103goto release_out;1104}11051106amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, range);11071108amdgpu_bo_placement_from_domain(bo, mem->domain);1109ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);1110if (ret)1111pr_err("%s: failed to validate BO\n", __func__);1112amdgpu_bo_unreserve(bo);11131114release_out:1115amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm, range);1116unregister_out:1117if (ret)1118amdgpu_hmm_unregister(bo);1119out:1120mutex_unlock(&process_info->lock);1121return ret;1122}11231124/* Reserving a BO and its page table BOs must happen atomically to1125* avoid deadlocks. Some operations update multiple VMs at once. Track1126* all the reservation info in a context structure. Optionally a sync1127* object can track VM updates.1128*/1129struct bo_vm_reservation_context {1130/* DRM execution context for the reservation */1131struct drm_exec exec;1132/* Number of VMs reserved */1133unsigned int n_vms;1134/* Pointer to sync object */1135struct amdgpu_sync *sync;1136};11371138enum bo_vm_match {1139BO_VM_NOT_MAPPED = 0, /* Match VMs where a BO is not mapped */1140BO_VM_MAPPED, /* Match VMs where a BO is mapped */1141BO_VM_ALL, /* Match all VMs a BO was added to */1142};11431144/**1145* reserve_bo_and_vm - reserve a BO and a VM unconditionally.1146* @mem: KFD BO structure.1147* @vm: the VM to reserve.1148* @ctx: the struct that will be used in unreserve_bo_and_vms().1149*/1150static int reserve_bo_and_vm(struct kgd_mem *mem,1151struct amdgpu_vm *vm,1152struct bo_vm_reservation_context *ctx)1153{1154struct amdgpu_bo *bo = mem->bo;1155int ret;11561157WARN_ON(!vm);11581159ctx->n_vms = 1;1160ctx->sync = &mem->sync;1161drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT, 0);1162drm_exec_until_all_locked(&ctx->exec) {1163ret = amdgpu_vm_lock_pd(vm, &ctx->exec, 2);1164drm_exec_retry_on_contention(&ctx->exec);1165if (unlikely(ret))1166goto error;11671168ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1);1169drm_exec_retry_on_contention(&ctx->exec);1170if (unlikely(ret))1171goto error;1172}1173return 0;11741175error:1176pr_err("Failed to reserve buffers in ttm.\n");1177drm_exec_fini(&ctx->exec);1178return ret;1179}11801181/**1182* reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally1183* @mem: KFD BO structure.1184* @vm: the VM to reserve. If NULL, then all VMs associated with the BO1185* is used. Otherwise, a single VM associated with the BO.1186* @map_type: the mapping status that will be used to filter the VMs.1187* @ctx: the struct that will be used in unreserve_bo_and_vms().1188*1189* Returns 0 for success, negative for failure.1190*/1191static int reserve_bo_and_cond_vms(struct kgd_mem *mem,1192struct amdgpu_vm *vm, enum bo_vm_match map_type,1193struct bo_vm_reservation_context *ctx)1194{1195struct kfd_mem_attachment *entry;1196struct amdgpu_bo *bo = mem->bo;1197int ret;11981199ctx->sync = &mem->sync;1200drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT |1201DRM_EXEC_IGNORE_DUPLICATES, 0);1202drm_exec_until_all_locked(&ctx->exec) {1203ctx->n_vms = 0;1204list_for_each_entry(entry, &mem->attachments, list) {1205if ((vm && vm != entry->bo_va->base.vm) ||1206(entry->is_mapped != map_type1207&& map_type != BO_VM_ALL))1208continue;12091210ret = amdgpu_vm_lock_pd(entry->bo_va->base.vm,1211&ctx->exec, 2);1212drm_exec_retry_on_contention(&ctx->exec);1213if (unlikely(ret))1214goto error;1215++ctx->n_vms;1216}12171218ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1);1219drm_exec_retry_on_contention(&ctx->exec);1220if (unlikely(ret))1221goto error;1222}1223return 0;12241225error:1226pr_err("Failed to reserve buffers in ttm.\n");1227drm_exec_fini(&ctx->exec);1228return ret;1229}12301231/**1232* unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context1233* @ctx: Reservation context to unreserve1234* @wait: Optionally wait for a sync object representing pending VM updates1235* @intr: Whether the wait is interruptible1236*1237* Also frees any resources allocated in1238* reserve_bo_and_(cond_)vm(s). Returns the status from1239* amdgpu_sync_wait.1240*/1241static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx,1242bool wait, bool intr)1243{1244int ret = 0;12451246if (wait)1247ret = amdgpu_sync_wait(ctx->sync, intr);12481249drm_exec_fini(&ctx->exec);1250ctx->sync = NULL;1251return ret;1252}12531254static int unmap_bo_from_gpuvm(struct kgd_mem *mem,1255struct kfd_mem_attachment *entry,1256struct amdgpu_sync *sync)1257{1258struct amdgpu_bo_va *bo_va = entry->bo_va;1259struct amdgpu_device *adev = entry->adev;1260struct amdgpu_vm *vm = bo_va->base.vm;12611262if (bo_va->queue_refcount) {1263pr_debug("bo_va->queue_refcount %d\n", bo_va->queue_refcount);1264return -EBUSY;1265}12661267(void)amdgpu_vm_bo_unmap(adev, bo_va, entry->va);12681269(void)amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update);12701271(void)amdgpu_sync_fence(sync, bo_va->last_pt_update, GFP_KERNEL);12721273return 0;1274}12751276static int update_gpuvm_pte(struct kgd_mem *mem,1277struct kfd_mem_attachment *entry,1278struct amdgpu_sync *sync)1279{1280struct amdgpu_bo_va *bo_va = entry->bo_va;1281struct amdgpu_device *adev = entry->adev;1282int ret;12831284ret = kfd_mem_dmamap_attachment(mem, entry);1285if (ret)1286return ret;12871288/* Update the page tables */1289ret = amdgpu_vm_bo_update(adev, bo_va, false);1290if (ret) {1291pr_err("amdgpu_vm_bo_update failed\n");1292return ret;1293}12941295return amdgpu_sync_fence(sync, bo_va->last_pt_update, GFP_KERNEL);1296}12971298static int map_bo_to_gpuvm(struct kgd_mem *mem,1299struct kfd_mem_attachment *entry,1300struct amdgpu_sync *sync,1301bool no_update_pte)1302{1303int ret;13041305/* Set virtual address for the allocation */1306ret = amdgpu_vm_bo_map(entry->adev, entry->bo_va, entry->va, 0,1307amdgpu_bo_size(entry->bo_va->base.bo),1308entry->pte_flags);1309if (ret) {1310pr_err("Failed to map VA 0x%llx in vm. ret %d\n",1311entry->va, ret);1312return ret;1313}13141315if (no_update_pte)1316return 0;13171318ret = update_gpuvm_pte(mem, entry, sync);1319if (ret) {1320pr_err("update_gpuvm_pte() failed\n");1321goto update_gpuvm_pte_failed;1322}13231324return 0;13251326update_gpuvm_pte_failed:1327unmap_bo_from_gpuvm(mem, entry, sync);1328kfd_mem_dmaunmap_attachment(mem, entry);1329return ret;1330}13311332static int process_validate_vms(struct amdkfd_process_info *process_info,1333struct ww_acquire_ctx *ticket)1334{1335struct amdgpu_vm *peer_vm;1336int ret;13371338list_for_each_entry(peer_vm, &process_info->vm_list_head,1339vm_list_node) {1340ret = vm_validate_pt_pd_bos(peer_vm, ticket);1341if (ret)1342return ret;1343}13441345return 0;1346}13471348static int process_sync_pds_resv(struct amdkfd_process_info *process_info,1349struct amdgpu_sync *sync)1350{1351struct amdgpu_vm *peer_vm;1352int ret;13531354list_for_each_entry(peer_vm, &process_info->vm_list_head,1355vm_list_node) {1356struct amdgpu_bo *pd = peer_vm->root.bo;13571358ret = amdgpu_sync_resv(NULL, sync, pd->tbo.base.resv,1359AMDGPU_SYNC_NE_OWNER,1360AMDGPU_FENCE_OWNER_KFD);1361if (ret)1362return ret;1363}13641365return 0;1366}13671368static int process_update_pds(struct amdkfd_process_info *process_info,1369struct amdgpu_sync *sync)1370{1371struct amdgpu_vm *peer_vm;1372int ret;13731374list_for_each_entry(peer_vm, &process_info->vm_list_head,1375vm_list_node) {1376ret = vm_update_pds(peer_vm, sync);1377if (ret)1378return ret;1379}13801381return 0;1382}13831384static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info,1385struct dma_fence **ef)1386{1387struct amdkfd_process_info *info = NULL;1388int ret;13891390if (!*process_info) {1391info = kzalloc(sizeof(*info), GFP_KERNEL);1392if (!info)1393return -ENOMEM;13941395mutex_init(&info->lock);1396mutex_init(&info->notifier_lock);1397INIT_LIST_HEAD(&info->vm_list_head);1398INIT_LIST_HEAD(&info->kfd_bo_list);1399INIT_LIST_HEAD(&info->userptr_valid_list);1400INIT_LIST_HEAD(&info->userptr_inval_list);14011402info->eviction_fence =1403amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),1404current->mm,1405NULL);1406if (!info->eviction_fence) {1407pr_err("Failed to create eviction fence\n");1408ret = -ENOMEM;1409goto create_evict_fence_fail;1410}14111412info->pid = get_task_pid(current->group_leader, PIDTYPE_PID);1413INIT_DELAYED_WORK(&info->restore_userptr_work,1414amdgpu_amdkfd_restore_userptr_worker);14151416*process_info = info;1417}14181419vm->process_info = *process_info;14201421/* Validate page directory and attach eviction fence */1422ret = amdgpu_bo_reserve(vm->root.bo, true);1423if (ret)1424goto reserve_pd_fail;1425ret = vm_validate_pt_pd_bos(vm, NULL);1426if (ret) {1427pr_err("validate_pt_pd_bos() failed\n");1428goto validate_pd_fail;1429}1430ret = amdgpu_bo_sync_wait(vm->root.bo,1431AMDGPU_FENCE_OWNER_KFD, false);1432if (ret)1433goto wait_pd_fail;1434ret = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, 1);1435if (ret)1436goto reserve_shared_fail;1437dma_resv_add_fence(vm->root.bo->tbo.base.resv,1438&vm->process_info->eviction_fence->base,1439DMA_RESV_USAGE_BOOKKEEP);1440amdgpu_bo_unreserve(vm->root.bo);14411442/* Update process info */1443mutex_lock(&vm->process_info->lock);1444list_add_tail(&vm->vm_list_node,1445&(vm->process_info->vm_list_head));1446vm->process_info->n_vms++;1447if (ef)1448*ef = dma_fence_get(&vm->process_info->eviction_fence->base);1449mutex_unlock(&vm->process_info->lock);14501451return 0;14521453reserve_shared_fail:1454wait_pd_fail:1455validate_pd_fail:1456amdgpu_bo_unreserve(vm->root.bo);1457reserve_pd_fail:1458vm->process_info = NULL;1459if (info) {1460dma_fence_put(&info->eviction_fence->base);1461*process_info = NULL;1462put_pid(info->pid);1463create_evict_fence_fail:1464mutex_destroy(&info->lock);1465mutex_destroy(&info->notifier_lock);1466kfree(info);1467}1468return ret;1469}14701471/**1472* amdgpu_amdkfd_gpuvm_pin_bo() - Pins a BO using following criteria1473* @bo: Handle of buffer object being pinned1474* @domain: Domain into which BO should be pinned1475*1476* - USERPTR BOs are UNPINNABLE and will return error1477* - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their1478* PIN count incremented. It is valid to PIN a BO multiple times1479*1480* Return: ZERO if successful in pinning, Non-Zero in case of error.1481*/1482static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain)1483{1484int ret = 0;14851486ret = amdgpu_bo_reserve(bo, false);1487if (unlikely(ret))1488return ret;14891490if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS) {1491/*1492* If bo is not contiguous on VRAM, move to system memory first to ensure1493* we can get contiguous VRAM space after evicting other BOs.1494*/1495if (!(bo->tbo.resource->placement & TTM_PL_FLAG_CONTIGUOUS)) {1496struct ttm_operation_ctx ctx = { true, false };14971498amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);1499ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);1500if (unlikely(ret)) {1501pr_debug("validate bo 0x%p to GTT failed %d\n", &bo->tbo, ret);1502goto out;1503}1504}1505}15061507ret = amdgpu_bo_pin(bo, domain);1508if (ret)1509pr_err("Error in Pinning BO to domain: %d\n", domain);15101511amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);1512out:1513amdgpu_bo_unreserve(bo);1514return ret;1515}15161517/**1518* amdgpu_amdkfd_gpuvm_unpin_bo() - Unpins BO using following criteria1519* @bo: Handle of buffer object being unpinned1520*1521* - Is a illegal request for USERPTR BOs and is ignored1522* - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their1523* PIN count decremented. Calls to UNPIN must balance calls to PIN1524*/1525static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo)1526{1527int ret = 0;15281529ret = amdgpu_bo_reserve(bo, false);1530if (unlikely(ret))1531return;15321533amdgpu_bo_unpin(bo);1534amdgpu_bo_unreserve(bo);1535}15361537int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct amdgpu_device *adev,1538struct amdgpu_vm *avm,1539void **process_info,1540struct dma_fence **ef)1541{1542int ret;15431544/* Already a compute VM? */1545if (avm->process_info)1546return -EINVAL;15471548/* Convert VM into a compute VM */1549ret = amdgpu_vm_make_compute(adev, avm);1550if (ret)1551return ret;15521553/* Initialize KFD part of the VM and process info */1554ret = init_kfd_vm(avm, process_info, ef);1555if (ret)1556return ret;15571558amdgpu_vm_set_task_info(avm);15591560return 0;1561}15621563void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,1564struct amdgpu_vm *vm)1565{1566struct amdkfd_process_info *process_info = vm->process_info;15671568if (!process_info)1569return;15701571/* Update process info */1572mutex_lock(&process_info->lock);1573process_info->n_vms--;1574list_del(&vm->vm_list_node);1575mutex_unlock(&process_info->lock);15761577vm->process_info = NULL;15781579/* Release per-process resources when last compute VM is destroyed */1580if (!process_info->n_vms) {1581WARN_ON(!list_empty(&process_info->kfd_bo_list));1582WARN_ON(!list_empty(&process_info->userptr_valid_list));1583WARN_ON(!list_empty(&process_info->userptr_inval_list));15841585dma_fence_put(&process_info->eviction_fence->base);1586cancel_delayed_work_sync(&process_info->restore_userptr_work);1587put_pid(process_info->pid);1588mutex_destroy(&process_info->lock);1589mutex_destroy(&process_info->notifier_lock);1590kfree(process_info);1591}1592}15931594uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)1595{1596struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);1597struct amdgpu_bo *pd = avm->root.bo;1598struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);15991600if (adev->asic_type < CHIP_VEGA10)1601return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT;1602return avm->pd_phys_addr;1603}16041605void amdgpu_amdkfd_block_mmu_notifications(void *p)1606{1607struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;16081609mutex_lock(&pinfo->lock);1610WRITE_ONCE(pinfo->block_mmu_notifications, true);1611mutex_unlock(&pinfo->lock);1612}16131614int amdgpu_amdkfd_criu_resume(void *p)1615{1616int ret = 0;1617struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;16181619mutex_lock(&pinfo->lock);1620pr_debug("scheduling work\n");1621mutex_lock(&pinfo->notifier_lock);1622pinfo->evicted_bos++;1623mutex_unlock(&pinfo->notifier_lock);1624if (!READ_ONCE(pinfo->block_mmu_notifications)) {1625ret = -EINVAL;1626goto out_unlock;1627}1628WRITE_ONCE(pinfo->block_mmu_notifications, false);1629queue_delayed_work(system_freezable_wq,1630&pinfo->restore_userptr_work, 0);16311632out_unlock:1633mutex_unlock(&pinfo->lock);1634return ret;1635}16361637size_t amdgpu_amdkfd_get_available_memory(struct amdgpu_device *adev,1638uint8_t xcp_id)1639{1640uint64_t reserved_for_pt =1641ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);1642struct amdgpu_ras *con = amdgpu_ras_get_context(adev);1643uint64_t reserved_for_ras = (con ? con->reserved_pages_in_bytes : 0);1644ssize_t available;1645uint64_t vram_available, system_mem_available, ttm_mem_available;16461647spin_lock(&kfd_mem_limit.mem_limit_lock);1648if (adev->apu_prefer_gtt && !adev->gmc.is_app_apu)1649vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id)1650- adev->kfd.vram_used_aligned[xcp_id];1651else1652vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id)1653- adev->kfd.vram_used_aligned[xcp_id]1654- atomic64_read(&adev->vram_pin_size)1655- reserved_for_pt1656- reserved_for_ras;16571658if (adev->apu_prefer_gtt) {1659system_mem_available = no_system_mem_limit ?1660kfd_mem_limit.max_system_mem_limit :1661kfd_mem_limit.max_system_mem_limit -1662kfd_mem_limit.system_mem_used;16631664ttm_mem_available = kfd_mem_limit.max_ttm_mem_limit -1665kfd_mem_limit.ttm_mem_used;16661667available = min3(system_mem_available, ttm_mem_available,1668vram_available);1669available = ALIGN_DOWN(available, PAGE_SIZE);1670} else {1671available = ALIGN_DOWN(vram_available, VRAM_AVAILABLITY_ALIGN);1672}16731674spin_unlock(&kfd_mem_limit.mem_limit_lock);16751676if (available < 0)1677available = 0;16781679return available;1680}16811682int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(1683struct amdgpu_device *adev, uint64_t va, uint64_t size,1684void *drm_priv, struct kgd_mem **mem,1685uint64_t *offset, uint32_t flags, bool criu_resume)1686{1687struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);1688struct amdgpu_fpriv *fpriv = container_of(avm, struct amdgpu_fpriv, vm);1689enum ttm_bo_type bo_type = ttm_bo_type_device;1690struct sg_table *sg = NULL;1691uint64_t user_addr = 0;1692struct amdgpu_bo *bo;1693struct drm_gem_object *gobj = NULL;1694u32 domain, alloc_domain;1695uint64_t aligned_size;1696int8_t xcp_id = -1;1697u64 alloc_flags;1698int ret;16991700/*1701* Check on which domain to allocate BO1702*/1703if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {1704domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;17051706if (adev->apu_prefer_gtt) {1707domain = AMDGPU_GEM_DOMAIN_GTT;1708alloc_domain = AMDGPU_GEM_DOMAIN_GTT;1709alloc_flags = 0;1710} else {1711alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;1712alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ?1713AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0;17141715/* For contiguous VRAM allocation */1716if (flags & KFD_IOC_ALLOC_MEM_FLAGS_CONTIGUOUS)1717alloc_flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;1718}1719xcp_id = fpriv->xcp_id == AMDGPU_XCP_NO_PARTITION ?17200 : fpriv->xcp_id;1721} else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {1722domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;1723alloc_flags = 0;1724} else {1725domain = AMDGPU_GEM_DOMAIN_GTT;1726alloc_domain = AMDGPU_GEM_DOMAIN_CPU;1727alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE;17281729if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {1730if (!offset || !*offset)1731return -EINVAL;1732user_addr = untagged_addr(*offset);1733} else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |1734KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {1735bo_type = ttm_bo_type_sg;1736if (size > UINT_MAX)1737return -EINVAL;1738sg = create_sg_table(*offset, size);1739if (!sg)1740return -ENOMEM;1741} else {1742return -EINVAL;1743}1744}17451746if (flags & KFD_IOC_ALLOC_MEM_FLAGS_COHERENT)1747alloc_flags |= AMDGPU_GEM_CREATE_COHERENT;1748if (flags & KFD_IOC_ALLOC_MEM_FLAGS_EXT_COHERENT)1749alloc_flags |= AMDGPU_GEM_CREATE_EXT_COHERENT;1750if (flags & KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED)1751alloc_flags |= AMDGPU_GEM_CREATE_UNCACHED;17521753*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);1754if (!*mem) {1755ret = -ENOMEM;1756goto err;1757}1758INIT_LIST_HEAD(&(*mem)->attachments);1759mutex_init(&(*mem)->lock);1760(*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);17611762/* Workaround for AQL queue wraparound bug. Map the same1763* memory twice. That means we only actually allocate half1764* the memory.1765*/1766if ((*mem)->aql_queue)1767size >>= 1;1768aligned_size = PAGE_ALIGN(size);17691770(*mem)->alloc_flags = flags;17711772amdgpu_sync_create(&(*mem)->sync);17731774ret = amdgpu_amdkfd_reserve_mem_limit(adev, aligned_size, flags,1775xcp_id);1776if (ret) {1777pr_debug("Insufficient memory\n");1778goto err_reserve_limit;1779}17801781pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s xcp_id %d\n",1782va, (*mem)->aql_queue ? size << 1 : size,1783domain_string(alloc_domain), xcp_id);17841785ret = amdgpu_gem_object_create(adev, aligned_size, 1, alloc_domain, alloc_flags,1786bo_type, NULL, &gobj, xcp_id + 1);1787if (ret) {1788pr_debug("Failed to create BO on domain %s. ret %d\n",1789domain_string(alloc_domain), ret);1790goto err_bo_create;1791}1792ret = drm_vma_node_allow(&gobj->vma_node, drm_priv);1793if (ret) {1794pr_debug("Failed to allow vma node access. ret %d\n", ret);1795goto err_node_allow;1796}1797ret = drm_gem_handle_create(adev->kfd.client.file, gobj, &(*mem)->gem_handle);1798if (ret)1799goto err_gem_handle_create;1800bo = gem_to_amdgpu_bo(gobj);1801if (bo_type == ttm_bo_type_sg) {1802bo->tbo.sg = sg;1803bo->tbo.ttm->sg = sg;1804}1805bo->kfd_bo = *mem;1806(*mem)->bo = bo;1807if (user_addr)1808bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO;18091810(*mem)->va = va;1811(*mem)->domain = domain;1812(*mem)->mapped_to_gpu_memory = 0;1813(*mem)->process_info = avm->process_info;18141815add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);18161817if (user_addr) {1818pr_debug("creating userptr BO for user_addr = %llx\n", user_addr);1819ret = init_user_pages(*mem, user_addr, criu_resume);1820if (ret)1821goto allocate_init_user_pages_failed;1822} else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |1823KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {1824ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT);1825if (ret) {1826pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n");1827goto err_pin_bo;1828}1829bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;1830bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;1831} else {1832mutex_lock(&avm->process_info->lock);1833if (avm->process_info->eviction_fence &&1834!dma_fence_is_signaled(&avm->process_info->eviction_fence->base))1835ret = amdgpu_amdkfd_bo_validate_and_fence(bo, domain,1836&avm->process_info->eviction_fence->base);1837mutex_unlock(&avm->process_info->lock);1838if (ret)1839goto err_validate_bo;1840}18411842if (offset)1843*offset = amdgpu_bo_mmap_offset(bo);18441845return 0;18461847allocate_init_user_pages_failed:1848err_pin_bo:1849err_validate_bo:1850remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);1851drm_gem_handle_delete(adev->kfd.client.file, (*mem)->gem_handle);1852err_gem_handle_create:1853drm_vma_node_revoke(&gobj->vma_node, drm_priv);1854err_node_allow:1855/* Don't unreserve system mem limit twice */1856goto err_reserve_limit;1857err_bo_create:1858amdgpu_amdkfd_unreserve_mem_limit(adev, aligned_size, flags, xcp_id);1859err_reserve_limit:1860amdgpu_sync_free(&(*mem)->sync);1861mutex_destroy(&(*mem)->lock);1862if (gobj)1863drm_gem_object_put(gobj);1864else1865kfree(*mem);1866err:1867if (sg) {1868sg_free_table(sg);1869kfree(sg);1870}1871return ret;1872}18731874int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(1875struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv,1876uint64_t *size)1877{1878struct amdkfd_process_info *process_info = mem->process_info;1879unsigned long bo_size = mem->bo->tbo.base.size;1880bool use_release_notifier = (mem->bo->kfd_bo == mem);1881struct kfd_mem_attachment *entry, *tmp;1882struct bo_vm_reservation_context ctx;1883unsigned int mapped_to_gpu_memory;1884int ret;1885bool is_imported = false;18861887mutex_lock(&mem->lock);18881889/* Unpin MMIO/DOORBELL BO's that were pinned during allocation */1890if (mem->alloc_flags &1891(KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |1892KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {1893amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo);1894}18951896mapped_to_gpu_memory = mem->mapped_to_gpu_memory;1897is_imported = mem->is_imported;1898mutex_unlock(&mem->lock);1899/* lock is not needed after this, since mem is unused and will1900* be freed anyway1901*/19021903if (mapped_to_gpu_memory > 0) {1904pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",1905mem->va, bo_size);1906return -EBUSY;1907}19081909/* Make sure restore workers don't access the BO any more */1910mutex_lock(&process_info->lock);1911list_del(&mem->validate_list);1912mutex_unlock(&process_info->lock);19131914/* Cleanup user pages and MMU notifiers */1915if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {1916amdgpu_hmm_unregister(mem->bo);1917mutex_lock(&process_info->notifier_lock);1918amdgpu_ttm_tt_discard_user_pages(mem->bo->tbo.ttm, mem->range);1919mutex_unlock(&process_info->notifier_lock);1920}19211922ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);1923if (unlikely(ret))1924return ret;19251926amdgpu_amdkfd_remove_eviction_fence(mem->bo,1927process_info->eviction_fence);1928pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,1929mem->va + bo_size * (1 + mem->aql_queue));19301931/* Remove from VM internal data structures */1932list_for_each_entry_safe(entry, tmp, &mem->attachments, list) {1933kfd_mem_dmaunmap_attachment(mem, entry);1934kfd_mem_detach(entry);1935}19361937ret = unreserve_bo_and_vms(&ctx, false, false);19381939/* Free the sync object */1940amdgpu_sync_free(&mem->sync);19411942/* If the SG is not NULL, it's one we created for a doorbell or mmio1943* remap BO. We need to free it.1944*/1945if (mem->bo->tbo.sg) {1946sg_free_table(mem->bo->tbo.sg);1947kfree(mem->bo->tbo.sg);1948}19491950/* Update the size of the BO being freed if it was allocated from1951* VRAM and is not imported. For APP APU VRAM allocations are done1952* in GTT domain1953*/1954if (size) {1955if (!is_imported &&1956(mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_VRAM ||1957(adev->apu_prefer_gtt &&1958mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_GTT)))1959*size = bo_size;1960else1961*size = 0;1962}19631964/* Free the BO*/1965drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv);1966drm_gem_handle_delete(adev->kfd.client.file, mem->gem_handle);1967if (mem->dmabuf) {1968dma_buf_put(mem->dmabuf);1969mem->dmabuf = NULL;1970}1971mutex_destroy(&mem->lock);19721973/* If this releases the last reference, it will end up calling1974* amdgpu_amdkfd_release_notify and kfree the mem struct. That's why1975* this needs to be the last call here.1976*/1977drm_gem_object_put(&mem->bo->tbo.base);19781979/*1980* For kgd_mem allocated in amdgpu_amdkfd_gpuvm_import_dmabuf(),1981* explicitly free it here.1982*/1983if (!use_release_notifier)1984kfree(mem);19851986return ret;1987}19881989int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(1990struct amdgpu_device *adev, struct kgd_mem *mem,1991void *drm_priv)1992{1993struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);1994int ret;1995struct amdgpu_bo *bo;1996uint32_t domain;1997struct kfd_mem_attachment *entry;1998struct bo_vm_reservation_context ctx;1999unsigned long bo_size;2000bool is_invalid_userptr = false;20012002bo = mem->bo;2003if (!bo) {2004pr_err("Invalid BO when mapping memory to GPU\n");2005return -EINVAL;2006}20072008/* Make sure restore is not running concurrently. Since we2009* don't map invalid userptr BOs, we rely on the next restore2010* worker to do the mapping2011*/2012mutex_lock(&mem->process_info->lock);20132014/* Lock notifier lock. If we find an invalid userptr BO, we can be2015* sure that the MMU notifier is no longer running2016* concurrently and the queues are actually stopped2017*/2018if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {2019mutex_lock(&mem->process_info->notifier_lock);2020is_invalid_userptr = !!mem->invalid;2021mutex_unlock(&mem->process_info->notifier_lock);2022}20232024mutex_lock(&mem->lock);20252026domain = mem->domain;2027bo_size = bo->tbo.base.size;20282029pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",2030mem->va,2031mem->va + bo_size * (1 + mem->aql_queue),2032avm, domain_string(domain));20332034if (!kfd_mem_is_attached(avm, mem)) {2035ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue);2036if (ret)2037goto out;2038}20392040ret = reserve_bo_and_vm(mem, avm, &ctx);2041if (unlikely(ret))2042goto out;20432044/* Userptr can be marked as "not invalid", but not actually be2045* validated yet (still in the system domain). In that case2046* the queues are still stopped and we can leave mapping for2047* the next restore worker2048*/2049if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&2050bo->tbo.resource->mem_type == TTM_PL_SYSTEM)2051is_invalid_userptr = true;20522053ret = vm_validate_pt_pd_bos(avm, NULL);2054if (unlikely(ret))2055goto out_unreserve;20562057list_for_each_entry(entry, &mem->attachments, list) {2058if (entry->bo_va->base.vm != avm || entry->is_mapped)2059continue;20602061pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",2062entry->va, entry->va + bo_size, entry);20632064ret = map_bo_to_gpuvm(mem, entry, ctx.sync,2065is_invalid_userptr);2066if (ret) {2067pr_err("Failed to map bo to gpuvm\n");2068goto out_unreserve;2069}20702071ret = vm_update_pds(avm, ctx.sync);2072if (ret) {2073pr_err("Failed to update page directories\n");2074goto out_unreserve;2075}20762077entry->is_mapped = true;2078mem->mapped_to_gpu_memory++;2079pr_debug("\t INC mapping count %d\n",2080mem->mapped_to_gpu_memory);2081}20822083ret = unreserve_bo_and_vms(&ctx, false, false);20842085goto out;20862087out_unreserve:2088unreserve_bo_and_vms(&ctx, false, false);2089out:2090mutex_unlock(&mem->process_info->lock);2091mutex_unlock(&mem->lock);2092return ret;2093}20942095int amdgpu_amdkfd_gpuvm_dmaunmap_mem(struct kgd_mem *mem, void *drm_priv)2096{2097struct kfd_mem_attachment *entry;2098struct amdgpu_vm *vm;2099int ret;21002101vm = drm_priv_to_vm(drm_priv);21022103mutex_lock(&mem->lock);21042105ret = amdgpu_bo_reserve(mem->bo, true);2106if (ret)2107goto out;21082109list_for_each_entry(entry, &mem->attachments, list) {2110if (entry->bo_va->base.vm != vm)2111continue;2112if (entry->bo_va->base.bo->tbo.ttm &&2113!entry->bo_va->base.bo->tbo.ttm->sg)2114continue;21152116kfd_mem_dmaunmap_attachment(mem, entry);2117}21182119amdgpu_bo_unreserve(mem->bo);2120out:2121mutex_unlock(&mem->lock);21222123return ret;2124}21252126int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(2127struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv)2128{2129struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);2130unsigned long bo_size = mem->bo->tbo.base.size;2131struct kfd_mem_attachment *entry;2132struct bo_vm_reservation_context ctx;2133int ret;21342135mutex_lock(&mem->lock);21362137ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx);2138if (unlikely(ret))2139goto out;2140/* If no VMs were reserved, it means the BO wasn't actually mapped */2141if (ctx.n_vms == 0) {2142ret = -EINVAL;2143goto unreserve_out;2144}21452146ret = vm_validate_pt_pd_bos(avm, NULL);2147if (unlikely(ret))2148goto unreserve_out;21492150pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",2151mem->va,2152mem->va + bo_size * (1 + mem->aql_queue),2153avm);21542155list_for_each_entry(entry, &mem->attachments, list) {2156if (entry->bo_va->base.vm != avm || !entry->is_mapped)2157continue;21582159pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",2160entry->va, entry->va + bo_size, entry);21612162ret = unmap_bo_from_gpuvm(mem, entry, ctx.sync);2163if (ret)2164goto unreserve_out;21652166entry->is_mapped = false;21672168mem->mapped_to_gpu_memory--;2169pr_debug("\t DEC mapping count %d\n",2170mem->mapped_to_gpu_memory);2171}21722173unreserve_out:2174unreserve_bo_and_vms(&ctx, false, false);2175out:2176mutex_unlock(&mem->lock);2177return ret;2178}21792180int amdgpu_amdkfd_gpuvm_sync_memory(2181struct amdgpu_device *adev, struct kgd_mem *mem, bool intr)2182{2183struct amdgpu_sync sync;2184int ret;21852186amdgpu_sync_create(&sync);21872188mutex_lock(&mem->lock);2189amdgpu_sync_clone(&mem->sync, &sync);2190mutex_unlock(&mem->lock);21912192ret = amdgpu_sync_wait(&sync, intr);2193amdgpu_sync_free(&sync);2194return ret;2195}21962197/**2198* amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count2199* @bo: Buffer object to be mapped2200* @bo_gart: Return bo reference2201*2202* Before return, bo reference count is incremented. To release the reference and unpin/2203* unmap the BO, call amdgpu_amdkfd_free_gtt_mem.2204*/2205int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_bo *bo, struct amdgpu_bo **bo_gart)2206{2207int ret;22082209ret = amdgpu_bo_reserve(bo, true);2210if (ret) {2211pr_err("Failed to reserve bo. ret %d\n", ret);2212goto err_reserve_bo_failed;2213}22142215ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);2216if (ret) {2217pr_err("Failed to pin bo. ret %d\n", ret);2218goto err_pin_bo_failed;2219}22202221ret = amdgpu_ttm_alloc_gart(&bo->tbo);2222if (ret) {2223pr_err("Failed to bind bo to GART. ret %d\n", ret);2224goto err_map_bo_gart_failed;2225}22262227amdgpu_amdkfd_remove_eviction_fence(2228bo, bo->vm_bo->vm->process_info->eviction_fence);22292230amdgpu_bo_unreserve(bo);22312232*bo_gart = amdgpu_bo_ref(bo);22332234return 0;22352236err_map_bo_gart_failed:2237amdgpu_bo_unpin(bo);2238err_pin_bo_failed:2239amdgpu_bo_unreserve(bo);2240err_reserve_bo_failed:22412242return ret;2243}22442245/** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Map a GTT BO for kernel CPU access2246*2247* @mem: Buffer object to be mapped for CPU access2248* @kptr[out]: pointer in kernel CPU address space2249* @size[out]: size of the buffer2250*2251* Pins the BO and maps it for kernel CPU access. The eviction fence is removed2252* from the BO, since pinned BOs cannot be evicted. The bo must remain on the2253* validate_list, so the GPU mapping can be restored after a page table was2254* evicted.2255*2256* Return: 0 on success, error code on failure2257*/2258int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem,2259void **kptr, uint64_t *size)2260{2261int ret;2262struct amdgpu_bo *bo = mem->bo;22632264if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {2265pr_err("userptr can't be mapped to kernel\n");2266return -EINVAL;2267}22682269mutex_lock(&mem->process_info->lock);22702271ret = amdgpu_bo_reserve(bo, true);2272if (ret) {2273pr_err("Failed to reserve bo. ret %d\n", ret);2274goto bo_reserve_failed;2275}22762277ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);2278if (ret) {2279pr_err("Failed to pin bo. ret %d\n", ret);2280goto pin_failed;2281}22822283ret = amdgpu_bo_kmap(bo, kptr);2284if (ret) {2285pr_err("Failed to map bo to kernel. ret %d\n", ret);2286goto kmap_failed;2287}22882289amdgpu_amdkfd_remove_eviction_fence(2290bo, mem->process_info->eviction_fence);22912292if (size)2293*size = amdgpu_bo_size(bo);22942295amdgpu_bo_unreserve(bo);22962297mutex_unlock(&mem->process_info->lock);2298return 0;22992300kmap_failed:2301amdgpu_bo_unpin(bo);2302pin_failed:2303amdgpu_bo_unreserve(bo);2304bo_reserve_failed:2305mutex_unlock(&mem->process_info->lock);23062307return ret;2308}23092310/** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Unmap a GTT BO for kernel CPU access2311*2312* @mem: Buffer object to be unmapped for CPU access2313*2314* Removes the kernel CPU mapping and unpins the BO. It does not restore the2315* eviction fence, so this function should only be used for cleanup before the2316* BO is destroyed.2317*/2318void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem *mem)2319{2320struct amdgpu_bo *bo = mem->bo;23212322(void)amdgpu_bo_reserve(bo, true);2323amdgpu_bo_kunmap(bo);2324amdgpu_bo_unpin(bo);2325amdgpu_bo_unreserve(bo);2326}23272328int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev,2329struct kfd_vm_fault_info *mem)2330{2331if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) {2332*mem = *adev->gmc.vm_fault_info;2333mb(); /* make sure read happened */2334atomic_set(&adev->gmc.vm_fault_info_updated, 0);2335}2336return 0;2337}23382339static int import_obj_create(struct amdgpu_device *adev,2340struct dma_buf *dma_buf,2341struct drm_gem_object *obj,2342uint64_t va, void *drm_priv,2343struct kgd_mem **mem, uint64_t *size,2344uint64_t *mmap_offset)2345{2346struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);2347struct amdgpu_bo *bo;2348int ret;23492350bo = gem_to_amdgpu_bo(obj);2351if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM |2352AMDGPU_GEM_DOMAIN_GTT)))2353/* Only VRAM and GTT BOs are supported */2354return -EINVAL;23552356*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);2357if (!*mem)2358return -ENOMEM;23592360ret = drm_vma_node_allow(&obj->vma_node, drm_priv);2361if (ret)2362goto err_free_mem;23632364if (size)2365*size = amdgpu_bo_size(bo);23662367if (mmap_offset)2368*mmap_offset = amdgpu_bo_mmap_offset(bo);23692370INIT_LIST_HEAD(&(*mem)->attachments);2371mutex_init(&(*mem)->lock);23722373(*mem)->alloc_flags =2374((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?2375KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT)2376| KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE2377| KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;23782379get_dma_buf(dma_buf);2380(*mem)->dmabuf = dma_buf;2381(*mem)->bo = bo;2382(*mem)->va = va;2383(*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) &&2384!adev->apu_prefer_gtt ?2385AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT;23862387(*mem)->mapped_to_gpu_memory = 0;2388(*mem)->process_info = avm->process_info;2389add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false);2390amdgpu_sync_create(&(*mem)->sync);2391(*mem)->is_imported = true;23922393mutex_lock(&avm->process_info->lock);2394if (avm->process_info->eviction_fence &&2395!dma_fence_is_signaled(&avm->process_info->eviction_fence->base))2396ret = amdgpu_amdkfd_bo_validate_and_fence(bo, (*mem)->domain,2397&avm->process_info->eviction_fence->base);2398mutex_unlock(&avm->process_info->lock);2399if (ret)2400goto err_remove_mem;24012402return 0;24032404err_remove_mem:2405remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);2406drm_vma_node_revoke(&obj->vma_node, drm_priv);2407err_free_mem:2408kfree(*mem);2409return ret;2410}24112412int amdgpu_amdkfd_gpuvm_import_dmabuf_fd(struct amdgpu_device *adev, int fd,2413uint64_t va, void *drm_priv,2414struct kgd_mem **mem, uint64_t *size,2415uint64_t *mmap_offset)2416{2417struct drm_gem_object *obj;2418uint32_t handle;2419int ret;24202421ret = drm_gem_prime_fd_to_handle(&adev->ddev, adev->kfd.client.file, fd,2422&handle);2423if (ret)2424return ret;2425obj = drm_gem_object_lookup(adev->kfd.client.file, handle);2426if (!obj) {2427ret = -EINVAL;2428goto err_release_handle;2429}24302431ret = import_obj_create(adev, obj->dma_buf, obj, va, drm_priv, mem, size,2432mmap_offset);2433if (ret)2434goto err_put_obj;24352436(*mem)->gem_handle = handle;24372438return 0;24392440err_put_obj:2441drm_gem_object_put(obj);2442err_release_handle:2443drm_gem_handle_delete(adev->kfd.client.file, handle);2444return ret;2445}24462447int amdgpu_amdkfd_gpuvm_export_dmabuf(struct kgd_mem *mem,2448struct dma_buf **dma_buf)2449{2450int ret;24512452mutex_lock(&mem->lock);2453ret = kfd_mem_export_dmabuf(mem);2454if (ret)2455goto out;24562457get_dma_buf(mem->dmabuf);2458*dma_buf = mem->dmabuf;2459out:2460mutex_unlock(&mem->lock);2461return ret;2462}24632464/* Evict a userptr BO by stopping the queues if necessary2465*2466* Runs in MMU notifier, may be in RECLAIM_FS context. This means it2467* cannot do any memory allocations, and cannot take any locks that2468* are held elsewhere while allocating memory.2469*2470* It doesn't do anything to the BO itself. The real work happens in2471* restore, where we get updated page addresses. This function only2472* ensures that GPU access to the BO is stopped.2473*/2474int amdgpu_amdkfd_evict_userptr(struct mmu_interval_notifier *mni,2475unsigned long cur_seq, struct kgd_mem *mem)2476{2477struct amdkfd_process_info *process_info = mem->process_info;2478int r = 0;24792480/* Do not process MMU notifications during CRIU restore until2481* KFD_CRIU_OP_RESUME IOCTL is received2482*/2483if (READ_ONCE(process_info->block_mmu_notifications))2484return 0;24852486mutex_lock(&process_info->notifier_lock);2487mmu_interval_set_seq(mni, cur_seq);24882489mem->invalid++;2490if (++process_info->evicted_bos == 1) {2491/* First eviction, stop the queues */2492r = kgd2kfd_quiesce_mm(mni->mm,2493KFD_QUEUE_EVICTION_TRIGGER_USERPTR);24942495if (r && r != -ESRCH)2496pr_err("Failed to quiesce KFD\n");24972498if (r != -ESRCH)2499queue_delayed_work(system_freezable_wq,2500&process_info->restore_userptr_work,2501msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));2502}2503mutex_unlock(&process_info->notifier_lock);25042505return r;2506}25072508/* Update invalid userptr BOs2509*2510* Moves invalidated (evicted) userptr BOs from userptr_valid_list to2511* userptr_inval_list and updates user pages for all BOs that have2512* been invalidated since their last update.2513*/2514static int update_invalid_user_pages(struct amdkfd_process_info *process_info,2515struct mm_struct *mm)2516{2517struct kgd_mem *mem, *tmp_mem;2518struct amdgpu_bo *bo;2519struct ttm_operation_ctx ctx = { false, false };2520uint32_t invalid;2521int ret = 0;25222523mutex_lock(&process_info->notifier_lock);25242525/* Move all invalidated BOs to the userptr_inval_list */2526list_for_each_entry_safe(mem, tmp_mem,2527&process_info->userptr_valid_list,2528validate_list)2529if (mem->invalid)2530list_move_tail(&mem->validate_list,2531&process_info->userptr_inval_list);25322533/* Go through userptr_inval_list and update any invalid user_pages */2534list_for_each_entry(mem, &process_info->userptr_inval_list,2535validate_list) {2536invalid = mem->invalid;2537if (!invalid)2538/* BO hasn't been invalidated since the last2539* revalidation attempt. Keep its page list.2540*/2541continue;25422543bo = mem->bo;25442545amdgpu_ttm_tt_discard_user_pages(bo->tbo.ttm, mem->range);2546mem->range = NULL;25472548/* BO reservations and getting user pages (hmm_range_fault)2549* must happen outside the notifier lock2550*/2551mutex_unlock(&process_info->notifier_lock);25522553/* Move the BO to system (CPU) domain if necessary to unmap2554* and free the SG table2555*/2556if (bo->tbo.resource->mem_type != TTM_PL_SYSTEM) {2557if (amdgpu_bo_reserve(bo, true))2558return -EAGAIN;2559amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);2560ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);2561amdgpu_bo_unreserve(bo);2562if (ret) {2563pr_err("%s: Failed to invalidate userptr BO\n",2564__func__);2565return -EAGAIN;2566}2567}25682569/* Get updated user pages */2570ret = amdgpu_ttm_tt_get_user_pages(bo, &mem->range);2571if (ret) {2572pr_debug("Failed %d to get user pages\n", ret);25732574/* Return -EFAULT bad address error as success. It will2575* fail later with a VM fault if the GPU tries to access2576* it. Better than hanging indefinitely with stalled2577* user mode queues.2578*2579* Return other error -EBUSY or -ENOMEM to retry restore2580*/2581if (ret != -EFAULT)2582return ret;25832584/* If applications unmap memory before destroying the userptr2585* from the KFD, trigger a segmentation fault in VM debug mode.2586*/2587if (amdgpu_ttm_adev(bo->tbo.bdev)->debug_vm_userptr) {2588pr_err("Pid %d unmapped memory before destroying userptr at GPU addr 0x%llx\n",2589pid_nr(process_info->pid), mem->va);25902591// Send GPU VM fault to user space2592kfd_signal_vm_fault_event_with_userptr(kfd_lookup_process_by_pid(process_info->pid),2593mem->va);2594}25952596ret = 0;2597}25982599amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, mem->range);26002601mutex_lock(&process_info->notifier_lock);26022603/* Mark the BO as valid unless it was invalidated2604* again concurrently.2605*/2606if (mem->invalid != invalid) {2607ret = -EAGAIN;2608goto unlock_out;2609}2610/* set mem valid if mem has hmm range associated */2611if (mem->range)2612mem->invalid = 0;2613}26142615unlock_out:2616mutex_unlock(&process_info->notifier_lock);26172618return ret;2619}26202621/* Validate invalid userptr BOs2622*2623* Validates BOs on the userptr_inval_list. Also updates GPUVM page tables2624* with new page addresses and waits for the page table updates to complete.2625*/2626static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)2627{2628struct ttm_operation_ctx ctx = { false, false };2629struct amdgpu_sync sync;2630struct drm_exec exec;26312632struct amdgpu_vm *peer_vm;2633struct kgd_mem *mem, *tmp_mem;2634struct amdgpu_bo *bo;2635int ret;26362637amdgpu_sync_create(&sync);26382639drm_exec_init(&exec, 0, 0);2640/* Reserve all BOs and page tables for validation */2641drm_exec_until_all_locked(&exec) {2642/* Reserve all the page directories */2643list_for_each_entry(peer_vm, &process_info->vm_list_head,2644vm_list_node) {2645ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2);2646drm_exec_retry_on_contention(&exec);2647if (unlikely(ret))2648goto unreserve_out;2649}26502651/* Reserve the userptr_inval_list entries to resv_list */2652list_for_each_entry(mem, &process_info->userptr_inval_list,2653validate_list) {2654struct drm_gem_object *gobj;26552656gobj = &mem->bo->tbo.base;2657ret = drm_exec_prepare_obj(&exec, gobj, 1);2658drm_exec_retry_on_contention(&exec);2659if (unlikely(ret))2660goto unreserve_out;2661}2662}26632664ret = process_validate_vms(process_info, NULL);2665if (ret)2666goto unreserve_out;26672668/* Validate BOs and update GPUVM page tables */2669list_for_each_entry_safe(mem, tmp_mem,2670&process_info->userptr_inval_list,2671validate_list) {2672struct kfd_mem_attachment *attachment;26732674bo = mem->bo;26752676/* Validate the BO if we got user pages */2677if (bo->tbo.ttm->pages[0]) {2678amdgpu_bo_placement_from_domain(bo, mem->domain);2679ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);2680if (ret) {2681pr_err("%s: failed to validate BO\n", __func__);2682goto unreserve_out;2683}2684}26852686/* Update mapping. If the BO was not validated2687* (because we couldn't get user pages), this will2688* clear the page table entries, which will result in2689* VM faults if the GPU tries to access the invalid2690* memory.2691*/2692list_for_each_entry(attachment, &mem->attachments, list) {2693if (!attachment->is_mapped)2694continue;26952696kfd_mem_dmaunmap_attachment(mem, attachment);2697ret = update_gpuvm_pte(mem, attachment, &sync);2698if (ret) {2699pr_err("%s: update PTE failed\n", __func__);2700/* make sure this gets validated again */2701mutex_lock(&process_info->notifier_lock);2702mem->invalid++;2703mutex_unlock(&process_info->notifier_lock);2704goto unreserve_out;2705}2706}2707}27082709/* Update page directories */2710ret = process_update_pds(process_info, &sync);27112712unreserve_out:2713drm_exec_fini(&exec);2714amdgpu_sync_wait(&sync, false);2715amdgpu_sync_free(&sync);27162717return ret;2718}27192720/* Confirm that all user pages are valid while holding the notifier lock2721*2722* Moves valid BOs from the userptr_inval_list back to userptr_val_list.2723*/2724static int confirm_valid_user_pages_locked(struct amdkfd_process_info *process_info)2725{2726struct kgd_mem *mem, *tmp_mem;2727int ret = 0;27282729list_for_each_entry_safe(mem, tmp_mem,2730&process_info->userptr_inval_list,2731validate_list) {2732bool valid;27332734/* keep mem without hmm range at userptr_inval_list */2735if (!mem->range)2736continue;27372738/* Only check mem with hmm range associated */2739valid = amdgpu_ttm_tt_get_user_pages_done(2740mem->bo->tbo.ttm, mem->range);27412742mem->range = NULL;2743if (!valid) {2744WARN(!mem->invalid, "Invalid BO not marked invalid");2745ret = -EAGAIN;2746continue;2747}27482749if (mem->invalid) {2750WARN(1, "Valid BO is marked invalid");2751ret = -EAGAIN;2752continue;2753}27542755list_move_tail(&mem->validate_list,2756&process_info->userptr_valid_list);2757}27582759return ret;2760}27612762/* Worker callback to restore evicted userptr BOs2763*2764* Tries to update and validate all userptr BOs. If successful and no2765* concurrent evictions happened, the queues are restarted. Otherwise,2766* reschedule for another attempt later.2767*/2768static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)2769{2770struct delayed_work *dwork = to_delayed_work(work);2771struct amdkfd_process_info *process_info =2772container_of(dwork, struct amdkfd_process_info,2773restore_userptr_work);2774struct task_struct *usertask;2775struct mm_struct *mm;2776uint32_t evicted_bos;27772778mutex_lock(&process_info->notifier_lock);2779evicted_bos = process_info->evicted_bos;2780mutex_unlock(&process_info->notifier_lock);2781if (!evicted_bos)2782return;27832784/* Reference task and mm in case of concurrent process termination */2785usertask = get_pid_task(process_info->pid, PIDTYPE_PID);2786if (!usertask)2787return;2788mm = get_task_mm(usertask);2789if (!mm) {2790put_task_struct(usertask);2791return;2792}27932794mutex_lock(&process_info->lock);27952796if (update_invalid_user_pages(process_info, mm))2797goto unlock_out;2798/* userptr_inval_list can be empty if all evicted userptr BOs2799* have been freed. In that case there is nothing to validate2800* and we can just restart the queues.2801*/2802if (!list_empty(&process_info->userptr_inval_list)) {2803if (validate_invalid_user_pages(process_info))2804goto unlock_out;2805}2806/* Final check for concurrent evicton and atomic update. If2807* another eviction happens after successful update, it will2808* be a first eviction that calls quiesce_mm. The eviction2809* reference counting inside KFD will handle this case.2810*/2811mutex_lock(&process_info->notifier_lock);2812if (process_info->evicted_bos != evicted_bos)2813goto unlock_notifier_out;28142815if (confirm_valid_user_pages_locked(process_info)) {2816WARN(1, "User pages unexpectedly invalid");2817goto unlock_notifier_out;2818}28192820process_info->evicted_bos = evicted_bos = 0;28212822if (kgd2kfd_resume_mm(mm)) {2823pr_err("%s: Failed to resume KFD\n", __func__);2824/* No recovery from this failure. Probably the CP is2825* hanging. No point trying again.2826*/2827}28282829unlock_notifier_out:2830mutex_unlock(&process_info->notifier_lock);2831unlock_out:2832mutex_unlock(&process_info->lock);28332834/* If validation failed, reschedule another attempt */2835if (evicted_bos) {2836queue_delayed_work(system_freezable_wq,2837&process_info->restore_userptr_work,2838msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));28392840kfd_smi_event_queue_restore_rescheduled(mm);2841}2842mmput(mm);2843put_task_struct(usertask);2844}28452846static void replace_eviction_fence(struct dma_fence __rcu **ef,2847struct dma_fence *new_ef)2848{2849struct dma_fence *old_ef = rcu_replace_pointer(*ef, new_ef, true2850/* protected by process_info->lock */);28512852/* If we're replacing an unsignaled eviction fence, that fence will2853* never be signaled, and if anyone is still waiting on that fence,2854* they will hang forever. This should never happen. We should only2855* replace the fence in restore_work that only gets scheduled after2856* eviction work signaled the fence.2857*/2858WARN_ONCE(!dma_fence_is_signaled(old_ef),2859"Replacing unsignaled eviction fence");2860dma_fence_put(old_ef);2861}28622863/** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given2864* KFD process identified by process_info2865*2866* @process_info: amdkfd_process_info of the KFD process2867*2868* After memory eviction, restore thread calls this function. The function2869* should be called when the Process is still valid. BO restore involves -2870*2871* 1. Release old eviction fence and create new one2872* 2. Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.2873* 3 Use the second PD list and kfd_bo_list to create a list (ctx.list) of2874* BOs that need to be reserved.2875* 4. Reserve all the BOs2876* 5. Validate of PD and PT BOs.2877* 6. Validate all KFD BOs using kfd_bo_list and Map them and add new fence2878* 7. Add fence to all PD and PT BOs.2879* 8. Unreserve all BOs2880*/2881int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence __rcu **ef)2882{2883struct amdkfd_process_info *process_info = info;2884struct amdgpu_vm *peer_vm;2885struct kgd_mem *mem;2886struct list_head duplicate_save;2887struct amdgpu_sync sync_obj;2888unsigned long failed_size = 0;2889unsigned long total_size = 0;2890struct drm_exec exec;2891int ret;28922893INIT_LIST_HEAD(&duplicate_save);28942895mutex_lock(&process_info->lock);28962897drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);2898drm_exec_until_all_locked(&exec) {2899list_for_each_entry(peer_vm, &process_info->vm_list_head,2900vm_list_node) {2901ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2);2902drm_exec_retry_on_contention(&exec);2903if (unlikely(ret)) {2904pr_err("Locking VM PD failed, ret: %d\n", ret);2905goto ttm_reserve_fail;2906}2907}29082909/* Reserve all BOs and page tables/directory. Add all BOs from2910* kfd_bo_list to ctx.list2911*/2912list_for_each_entry(mem, &process_info->kfd_bo_list,2913validate_list) {2914struct drm_gem_object *gobj;29152916gobj = &mem->bo->tbo.base;2917ret = drm_exec_prepare_obj(&exec, gobj, 1);2918drm_exec_retry_on_contention(&exec);2919if (unlikely(ret)) {2920pr_err("drm_exec_prepare_obj failed, ret: %d\n", ret);2921goto ttm_reserve_fail;2922}2923}2924}29252926amdgpu_sync_create(&sync_obj);29272928/* Validate BOs managed by KFD */2929list_for_each_entry(mem, &process_info->kfd_bo_list,2930validate_list) {29312932struct amdgpu_bo *bo = mem->bo;2933uint32_t domain = mem->domain;2934struct dma_resv_iter cursor;2935struct dma_fence *fence;29362937total_size += amdgpu_bo_size(bo);29382939ret = amdgpu_amdkfd_bo_validate(bo, domain, false);2940if (ret) {2941pr_debug("Memory eviction: Validate BOs failed\n");2942failed_size += amdgpu_bo_size(bo);2943ret = amdgpu_amdkfd_bo_validate(bo,2944AMDGPU_GEM_DOMAIN_GTT, false);2945if (ret) {2946pr_debug("Memory eviction: Try again\n");2947goto validate_map_fail;2948}2949}2950dma_resv_for_each_fence(&cursor, bo->tbo.base.resv,2951DMA_RESV_USAGE_KERNEL, fence) {2952ret = amdgpu_sync_fence(&sync_obj, fence, GFP_KERNEL);2953if (ret) {2954pr_debug("Memory eviction: Sync BO fence failed. Try again\n");2955goto validate_map_fail;2956}2957}2958}29592960if (failed_size)2961pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size);29622963/* Validate PDs, PTs and evicted DMABuf imports last. Otherwise BO2964* validations above would invalidate DMABuf imports again.2965*/2966ret = process_validate_vms(process_info, &exec.ticket);2967if (ret) {2968pr_debug("Validating VMs failed, ret: %d\n", ret);2969goto validate_map_fail;2970}29712972/* Update mappings managed by KFD. */2973list_for_each_entry(mem, &process_info->kfd_bo_list,2974validate_list) {2975struct kfd_mem_attachment *attachment;29762977list_for_each_entry(attachment, &mem->attachments, list) {2978if (!attachment->is_mapped)2979continue;29802981kfd_mem_dmaunmap_attachment(mem, attachment);2982ret = update_gpuvm_pte(mem, attachment, &sync_obj);2983if (ret) {2984pr_debug("Memory eviction: update PTE failed. Try again\n");2985goto validate_map_fail;2986}2987}2988}29892990/* Update mappings not managed by KFD */2991list_for_each_entry(peer_vm, &process_info->vm_list_head,2992vm_list_node) {2993struct amdgpu_device *adev = amdgpu_ttm_adev(2994peer_vm->root.bo->tbo.bdev);29952996struct amdgpu_fpriv *fpriv =2997container_of(peer_vm, struct amdgpu_fpriv, vm);29982999ret = amdgpu_vm_bo_update(adev, fpriv->prt_va, false);3000if (ret) {3001dev_dbg(adev->dev,3002"Memory eviction: handle PRT moved failed, pid %8d. Try again.\n",3003pid_nr(process_info->pid));3004goto validate_map_fail;3005}30063007ret = amdgpu_vm_handle_moved(adev, peer_vm, &exec.ticket);3008if (ret) {3009dev_dbg(adev->dev,3010"Memory eviction: handle moved failed, pid %8d. Try again.\n",3011pid_nr(process_info->pid));3012goto validate_map_fail;3013}3014}30153016/* Update page directories */3017ret = process_update_pds(process_info, &sync_obj);3018if (ret) {3019pr_debug("Memory eviction: update PDs failed. Try again\n");3020goto validate_map_fail;3021}30223023/* Sync with fences on all the page tables. They implicitly depend on any3024* move fences from amdgpu_vm_handle_moved above.3025*/3026ret = process_sync_pds_resv(process_info, &sync_obj);3027if (ret) {3028pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");3029goto validate_map_fail;3030}30313032/* Wait for validate and PT updates to finish */3033amdgpu_sync_wait(&sync_obj, false);30343035/* The old eviction fence may be unsignaled if restore happens3036* after a GPU reset or suspend/resume. Keep the old fence in that3037* case. Otherwise release the old eviction fence and create new3038* one, because fence only goes from unsignaled to signaled once3039* and cannot be reused. Use context and mm from the old fence.3040*3041* If an old eviction fence signals after this check, that's OK.3042* Anyone signaling an eviction fence must stop the queues first3043* and schedule another restore worker.3044*/3045if (dma_fence_is_signaled(&process_info->eviction_fence->base)) {3046struct amdgpu_amdkfd_fence *new_fence =3047amdgpu_amdkfd_fence_create(3048process_info->eviction_fence->base.context,3049process_info->eviction_fence->mm,3050NULL);30513052if (!new_fence) {3053pr_err("Failed to create eviction fence\n");3054ret = -ENOMEM;3055goto validate_map_fail;3056}3057dma_fence_put(&process_info->eviction_fence->base);3058process_info->eviction_fence = new_fence;3059replace_eviction_fence(ef, dma_fence_get(&new_fence->base));3060} else {3061WARN_ONCE(*ef != &process_info->eviction_fence->base,3062"KFD eviction fence doesn't match KGD process_info");3063}30643065/* Attach new eviction fence to all BOs except pinned ones */3066list_for_each_entry(mem, &process_info->kfd_bo_list, validate_list) {3067if (mem->bo->tbo.pin_count)3068continue;30693070dma_resv_add_fence(mem->bo->tbo.base.resv,3071&process_info->eviction_fence->base,3072DMA_RESV_USAGE_BOOKKEEP);3073}3074/* Attach eviction fence to PD / PT BOs and DMABuf imports */3075list_for_each_entry(peer_vm, &process_info->vm_list_head,3076vm_list_node) {3077struct amdgpu_bo *bo = peer_vm->root.bo;30783079dma_resv_add_fence(bo->tbo.base.resv,3080&process_info->eviction_fence->base,3081DMA_RESV_USAGE_BOOKKEEP);3082}30833084validate_map_fail:3085amdgpu_sync_free(&sync_obj);3086ttm_reserve_fail:3087drm_exec_fini(&exec);3088mutex_unlock(&process_info->lock);3089return ret;3090}30913092int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem)3093{3094struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;3095struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws;3096int ret;30973098if (!info || !gws)3099return -EINVAL;31003101*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);3102if (!*mem)3103return -ENOMEM;31043105mutex_init(&(*mem)->lock);3106INIT_LIST_HEAD(&(*mem)->attachments);3107(*mem)->bo = amdgpu_bo_ref(gws_bo);3108(*mem)->domain = AMDGPU_GEM_DOMAIN_GWS;3109(*mem)->process_info = process_info;3110add_kgd_mem_to_kfd_bo_list(*mem, process_info, false);3111amdgpu_sync_create(&(*mem)->sync);311231133114/* Validate gws bo the first time it is added to process */3115mutex_lock(&(*mem)->process_info->lock);3116ret = amdgpu_bo_reserve(gws_bo, false);3117if (unlikely(ret)) {3118pr_err("Reserve gws bo failed %d\n", ret);3119goto bo_reservation_failure;3120}31213122ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true);3123if (ret) {3124pr_err("GWS BO validate failed %d\n", ret);3125goto bo_validation_failure;3126}3127/* GWS resource is shared b/t amdgpu and amdkfd3128* Add process eviction fence to bo so they can3129* evict each other.3130*/3131ret = dma_resv_reserve_fences(gws_bo->tbo.base.resv, 1);3132if (ret)3133goto reserve_shared_fail;3134dma_resv_add_fence(gws_bo->tbo.base.resv,3135&process_info->eviction_fence->base,3136DMA_RESV_USAGE_BOOKKEEP);3137amdgpu_bo_unreserve(gws_bo);3138mutex_unlock(&(*mem)->process_info->lock);31393140return ret;31413142reserve_shared_fail:3143bo_validation_failure:3144amdgpu_bo_unreserve(gws_bo);3145bo_reservation_failure:3146mutex_unlock(&(*mem)->process_info->lock);3147amdgpu_sync_free(&(*mem)->sync);3148remove_kgd_mem_from_kfd_bo_list(*mem, process_info);3149amdgpu_bo_unref(&gws_bo);3150mutex_destroy(&(*mem)->lock);3151kfree(*mem);3152*mem = NULL;3153return ret;3154}31553156int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem)3157{3158int ret;3159struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;3160struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;3161struct amdgpu_bo *gws_bo = kgd_mem->bo;31623163/* Remove BO from process's validate list so restore worker won't touch3164* it anymore3165*/3166remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info);31673168ret = amdgpu_bo_reserve(gws_bo, false);3169if (unlikely(ret)) {3170pr_err("Reserve gws bo failed %d\n", ret);3171//TODO add BO back to validate_list?3172return ret;3173}3174amdgpu_amdkfd_remove_eviction_fence(gws_bo,3175process_info->eviction_fence);3176amdgpu_bo_unreserve(gws_bo);3177amdgpu_sync_free(&kgd_mem->sync);3178amdgpu_bo_unref(&gws_bo);3179mutex_destroy(&kgd_mem->lock);3180kfree(mem);3181return 0;3182}31833184/* Returns GPU-specific tiling mode information */3185int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev,3186struct tile_config *config)3187{3188config->gb_addr_config = adev->gfx.config.gb_addr_config;3189config->tile_config_ptr = adev->gfx.config.tile_mode_array;3190config->num_tile_configs =3191ARRAY_SIZE(adev->gfx.config.tile_mode_array);3192config->macro_tile_config_ptr =3193adev->gfx.config.macrotile_mode_array;3194config->num_macro_tile_configs =3195ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);31963197/* Those values are not set from GFX9 onwards */3198config->num_banks = adev->gfx.config.num_banks;3199config->num_ranks = adev->gfx.config.num_ranks;32003201return 0;3202}32033204bool amdgpu_amdkfd_bo_mapped_to_dev(void *drm_priv, struct kgd_mem *mem)3205{3206struct amdgpu_vm *vm = drm_priv_to_vm(drm_priv);3207struct kfd_mem_attachment *entry;32083209list_for_each_entry(entry, &mem->attachments, list) {3210if (entry->is_mapped && entry->bo_va->base.vm == vm)3211return true;3212}3213return false;3214}32153216#if defined(CONFIG_DEBUG_FS)32173218int kfd_debugfs_kfd_mem_limits(struct seq_file *m, void *data)3219{32203221spin_lock(&kfd_mem_limit.mem_limit_lock);3222seq_printf(m, "System mem used %lldM out of %lluM\n",3223(kfd_mem_limit.system_mem_used >> 20),3224(kfd_mem_limit.max_system_mem_limit >> 20));3225seq_printf(m, "TTM mem used %lldM out of %lluM\n",3226(kfd_mem_limit.ttm_mem_used >> 20),3227(kfd_mem_limit.max_ttm_mem_limit >> 20));3228spin_unlock(&kfd_mem_limit.mem_limit_lock);32293230return 0;3231}32323233#endif323432353236