Path: blob/master/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c
49830 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 amdgpu_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}10901091range = amdgpu_hmm_range_alloc(NULL);1092if (unlikely(!range)) {1093ret = -ENOMEM;1094goto unregister_out;1095}10961097ret = amdgpu_ttm_tt_get_user_pages(bo, range);1098if (ret) {1099amdgpu_hmm_range_free(range);1100if (ret == -EAGAIN)1101pr_debug("Failed to get user pages, try again\n");1102else1103pr_err("%s: Failed to get user pages: %d\n", __func__, ret);1104goto unregister_out;1105}11061107ret = amdgpu_bo_reserve(bo, true);1108if (ret) {1109pr_err("%s: Failed to reserve BO\n", __func__);1110goto release_out;1111}11121113amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, range);11141115amdgpu_bo_placement_from_domain(bo, mem->domain);1116ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);1117if (ret)1118pr_err("%s: failed to validate BO\n", __func__);1119amdgpu_bo_unreserve(bo);11201121release_out:1122amdgpu_hmm_range_free(range);1123unregister_out:1124if (ret)1125amdgpu_hmm_unregister(bo);1126out:1127mutex_unlock(&process_info->lock);1128return ret;1129}11301131/* Reserving a BO and its page table BOs must happen atomically to1132* avoid deadlocks. Some operations update multiple VMs at once. Track1133* all the reservation info in a context structure. Optionally a sync1134* object can track VM updates.1135*/1136struct bo_vm_reservation_context {1137/* DRM execution context for the reservation */1138struct drm_exec exec;1139/* Number of VMs reserved */1140unsigned int n_vms;1141/* Pointer to sync object */1142struct amdgpu_sync *sync;1143};11441145enum bo_vm_match {1146BO_VM_NOT_MAPPED = 0, /* Match VMs where a BO is not mapped */1147BO_VM_MAPPED, /* Match VMs where a BO is mapped */1148BO_VM_ALL, /* Match all VMs a BO was added to */1149};11501151/**1152* reserve_bo_and_vm - reserve a BO and a VM unconditionally.1153* @mem: KFD BO structure.1154* @vm: the VM to reserve.1155* @ctx: the struct that will be used in unreserve_bo_and_vms().1156*/1157static int reserve_bo_and_vm(struct kgd_mem *mem,1158struct amdgpu_vm *vm,1159struct bo_vm_reservation_context *ctx)1160{1161struct amdgpu_bo *bo = mem->bo;1162int ret;11631164WARN_ON(!vm);11651166ctx->n_vms = 1;1167ctx->sync = &mem->sync;1168drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT, 0);1169drm_exec_until_all_locked(&ctx->exec) {1170ret = amdgpu_vm_lock_pd(vm, &ctx->exec, 2);1171drm_exec_retry_on_contention(&ctx->exec);1172if (unlikely(ret))1173goto error;11741175ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1);1176drm_exec_retry_on_contention(&ctx->exec);1177if (unlikely(ret))1178goto error;1179}1180return 0;11811182error:1183pr_err("Failed to reserve buffers in ttm.\n");1184drm_exec_fini(&ctx->exec);1185return ret;1186}11871188/**1189* reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally1190* @mem: KFD BO structure.1191* @vm: the VM to reserve. If NULL, then all VMs associated with the BO1192* is used. Otherwise, a single VM associated with the BO.1193* @map_type: the mapping status that will be used to filter the VMs.1194* @ctx: the struct that will be used in unreserve_bo_and_vms().1195*1196* Returns 0 for success, negative for failure.1197*/1198static int reserve_bo_and_cond_vms(struct kgd_mem *mem,1199struct amdgpu_vm *vm, enum bo_vm_match map_type,1200struct bo_vm_reservation_context *ctx)1201{1202struct kfd_mem_attachment *entry;1203struct amdgpu_bo *bo = mem->bo;1204int ret;12051206ctx->sync = &mem->sync;1207drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT |1208DRM_EXEC_IGNORE_DUPLICATES, 0);1209drm_exec_until_all_locked(&ctx->exec) {1210ctx->n_vms = 0;1211list_for_each_entry(entry, &mem->attachments, list) {1212if ((vm && vm != entry->bo_va->base.vm) ||1213(entry->is_mapped != map_type1214&& map_type != BO_VM_ALL))1215continue;12161217ret = amdgpu_vm_lock_pd(entry->bo_va->base.vm,1218&ctx->exec, 2);1219drm_exec_retry_on_contention(&ctx->exec);1220if (unlikely(ret))1221goto error;1222++ctx->n_vms;1223}12241225ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1);1226drm_exec_retry_on_contention(&ctx->exec);1227if (unlikely(ret))1228goto error;1229}1230return 0;12311232error:1233pr_err("Failed to reserve buffers in ttm.\n");1234drm_exec_fini(&ctx->exec);1235return ret;1236}12371238/**1239* unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context1240* @ctx: Reservation context to unreserve1241* @wait: Optionally wait for a sync object representing pending VM updates1242* @intr: Whether the wait is interruptible1243*1244* Also frees any resources allocated in1245* reserve_bo_and_(cond_)vm(s). Returns the status from1246* amdgpu_sync_wait.1247*/1248static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx,1249bool wait, bool intr)1250{1251int ret = 0;12521253if (wait)1254ret = amdgpu_sync_wait(ctx->sync, intr);12551256drm_exec_fini(&ctx->exec);1257ctx->sync = NULL;1258return ret;1259}12601261static int unmap_bo_from_gpuvm(struct kgd_mem *mem,1262struct kfd_mem_attachment *entry,1263struct amdgpu_sync *sync)1264{1265struct amdgpu_bo_va *bo_va = entry->bo_va;1266struct amdgpu_device *adev = entry->adev;1267struct amdgpu_vm *vm = bo_va->base.vm;12681269if (bo_va->queue_refcount) {1270pr_debug("bo_va->queue_refcount %d\n", bo_va->queue_refcount);1271return -EBUSY;1272}12731274(void)amdgpu_vm_bo_unmap(adev, bo_va, entry->va);12751276/* VM entity stopped if process killed, don't clear freed pt bo */1277if (!amdgpu_vm_ready(vm))1278return 0;12791280(void)amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update);12811282(void)amdgpu_sync_fence(sync, bo_va->last_pt_update, GFP_KERNEL);12831284return 0;1285}12861287static int update_gpuvm_pte(struct kgd_mem *mem,1288struct kfd_mem_attachment *entry,1289struct amdgpu_sync *sync)1290{1291struct amdgpu_bo_va *bo_va = entry->bo_va;1292struct amdgpu_device *adev = entry->adev;1293int ret;12941295ret = kfd_mem_dmamap_attachment(mem, entry);1296if (ret)1297return ret;12981299/* Update the page tables */1300ret = amdgpu_vm_bo_update(adev, bo_va, false);1301if (ret) {1302pr_err("amdgpu_vm_bo_update failed\n");1303return ret;1304}13051306return amdgpu_sync_fence(sync, bo_va->last_pt_update, GFP_KERNEL);1307}13081309static int map_bo_to_gpuvm(struct kgd_mem *mem,1310struct kfd_mem_attachment *entry,1311struct amdgpu_sync *sync,1312bool no_update_pte)1313{1314int ret;13151316/* Set virtual address for the allocation */1317ret = amdgpu_vm_bo_map(entry->adev, entry->bo_va, entry->va, 0,1318amdgpu_bo_size(entry->bo_va->base.bo),1319entry->pte_flags);1320if (ret) {1321pr_err("Failed to map VA 0x%llx in vm. ret %d\n",1322entry->va, ret);1323return ret;1324}13251326if (no_update_pte)1327return 0;13281329ret = update_gpuvm_pte(mem, entry, sync);1330if (ret) {1331pr_err("update_gpuvm_pte() failed\n");1332goto update_gpuvm_pte_failed;1333}13341335return 0;13361337update_gpuvm_pte_failed:1338unmap_bo_from_gpuvm(mem, entry, sync);1339kfd_mem_dmaunmap_attachment(mem, entry);1340return ret;1341}13421343static int process_validate_vms(struct amdkfd_process_info *process_info,1344struct ww_acquire_ctx *ticket)1345{1346struct amdgpu_vm *peer_vm;1347int ret;13481349list_for_each_entry(peer_vm, &process_info->vm_list_head,1350vm_list_node) {1351ret = vm_validate_pt_pd_bos(peer_vm, ticket);1352if (ret)1353return ret;1354}13551356return 0;1357}13581359static int process_sync_pds_resv(struct amdkfd_process_info *process_info,1360struct amdgpu_sync *sync)1361{1362struct amdgpu_vm *peer_vm;1363int ret;13641365list_for_each_entry(peer_vm, &process_info->vm_list_head,1366vm_list_node) {1367struct amdgpu_bo *pd = peer_vm->root.bo;13681369ret = amdgpu_sync_resv(NULL, sync, pd->tbo.base.resv,1370AMDGPU_SYNC_NE_OWNER,1371AMDGPU_FENCE_OWNER_KFD);1372if (ret)1373return ret;1374}13751376return 0;1377}13781379static int process_update_pds(struct amdkfd_process_info *process_info,1380struct amdgpu_sync *sync)1381{1382struct amdgpu_vm *peer_vm;1383int ret;13841385list_for_each_entry(peer_vm, &process_info->vm_list_head,1386vm_list_node) {1387ret = vm_update_pds(peer_vm, sync);1388if (ret)1389return ret;1390}13911392return 0;1393}13941395static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info,1396struct dma_fence **ef)1397{1398struct amdkfd_process_info *info = NULL;1399int ret;14001401if (!*process_info) {1402info = kzalloc(sizeof(*info), GFP_KERNEL);1403if (!info)1404return -ENOMEM;14051406mutex_init(&info->lock);1407mutex_init(&info->notifier_lock);1408INIT_LIST_HEAD(&info->vm_list_head);1409INIT_LIST_HEAD(&info->kfd_bo_list);1410INIT_LIST_HEAD(&info->userptr_valid_list);1411INIT_LIST_HEAD(&info->userptr_inval_list);14121413info->eviction_fence =1414amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),1415current->mm,1416NULL);1417if (!info->eviction_fence) {1418pr_err("Failed to create eviction fence\n");1419ret = -ENOMEM;1420goto create_evict_fence_fail;1421}14221423info->pid = get_task_pid(current->group_leader, PIDTYPE_PID);1424INIT_DELAYED_WORK(&info->restore_userptr_work,1425amdgpu_amdkfd_restore_userptr_worker);14261427*process_info = info;1428}14291430vm->process_info = *process_info;14311432/* Validate page directory and attach eviction fence */1433ret = amdgpu_bo_reserve(vm->root.bo, true);1434if (ret)1435goto reserve_pd_fail;1436ret = vm_validate_pt_pd_bos(vm, NULL);1437if (ret) {1438pr_err("validate_pt_pd_bos() failed\n");1439goto validate_pd_fail;1440}1441ret = amdgpu_bo_sync_wait(vm->root.bo,1442AMDGPU_FENCE_OWNER_KFD, false);1443if (ret)1444goto wait_pd_fail;1445ret = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, 1);1446if (ret)1447goto reserve_shared_fail;1448dma_resv_add_fence(vm->root.bo->tbo.base.resv,1449&vm->process_info->eviction_fence->base,1450DMA_RESV_USAGE_BOOKKEEP);1451amdgpu_bo_unreserve(vm->root.bo);14521453/* Update process info */1454mutex_lock(&vm->process_info->lock);1455list_add_tail(&vm->vm_list_node,1456&(vm->process_info->vm_list_head));1457vm->process_info->n_vms++;1458if (ef)1459*ef = dma_fence_get(&vm->process_info->eviction_fence->base);1460mutex_unlock(&vm->process_info->lock);14611462return 0;14631464reserve_shared_fail:1465wait_pd_fail:1466validate_pd_fail:1467amdgpu_bo_unreserve(vm->root.bo);1468reserve_pd_fail:1469vm->process_info = NULL;1470if (info) {1471dma_fence_put(&info->eviction_fence->base);1472*process_info = NULL;1473put_pid(info->pid);1474create_evict_fence_fail:1475mutex_destroy(&info->lock);1476mutex_destroy(&info->notifier_lock);1477kfree(info);1478}1479return ret;1480}14811482/**1483* amdgpu_amdkfd_gpuvm_pin_bo() - Pins a BO using following criteria1484* @bo: Handle of buffer object being pinned1485* @domain: Domain into which BO should be pinned1486*1487* - USERPTR BOs are UNPINNABLE and will return error1488* - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their1489* PIN count incremented. It is valid to PIN a BO multiple times1490*1491* Return: ZERO if successful in pinning, Non-Zero in case of error.1492*/1493static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain)1494{1495int ret = 0;14961497ret = amdgpu_bo_reserve(bo, false);1498if (unlikely(ret))1499return ret;15001501if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS) {1502/*1503* If bo is not contiguous on VRAM, move to system memory first to ensure1504* we can get contiguous VRAM space after evicting other BOs.1505*/1506if (!(bo->tbo.resource->placement & TTM_PL_FLAG_CONTIGUOUS)) {1507struct ttm_operation_ctx ctx = { true, false };15081509amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);1510ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);1511if (unlikely(ret)) {1512pr_debug("validate bo 0x%p to GTT failed %d\n", &bo->tbo, ret);1513goto out;1514}1515}1516}15171518ret = amdgpu_bo_pin(bo, domain);1519if (ret)1520pr_err("Error in Pinning BO to domain: %d\n", domain);15211522amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);1523out:1524amdgpu_bo_unreserve(bo);1525return ret;1526}15271528/**1529* amdgpu_amdkfd_gpuvm_unpin_bo() - Unpins BO using following criteria1530* @bo: Handle of buffer object being unpinned1531*1532* - Is a illegal request for USERPTR BOs and is ignored1533* - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their1534* PIN count decremented. Calls to UNPIN must balance calls to PIN1535*/1536static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo)1537{1538int ret = 0;15391540ret = amdgpu_bo_reserve(bo, false);1541if (unlikely(ret))1542return;15431544amdgpu_bo_unpin(bo);1545amdgpu_bo_unreserve(bo);1546}15471548int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct amdgpu_device *adev,1549struct amdgpu_vm *avm,1550void **process_info,1551struct dma_fence **ef)1552{1553int ret;15541555/* Already a compute VM? */1556if (avm->process_info)1557return -EINVAL;15581559/* Convert VM into a compute VM */1560ret = amdgpu_vm_make_compute(adev, avm);1561if (ret)1562return ret;15631564/* Initialize KFD part of the VM and process info */1565ret = init_kfd_vm(avm, process_info, ef);1566if (ret)1567return ret;15681569amdgpu_vm_set_task_info(avm);15701571return 0;1572}15731574void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,1575struct amdgpu_vm *vm)1576{1577struct amdkfd_process_info *process_info = vm->process_info;15781579if (!process_info)1580return;15811582/* Update process info */1583mutex_lock(&process_info->lock);1584process_info->n_vms--;1585list_del(&vm->vm_list_node);1586mutex_unlock(&process_info->lock);15871588vm->process_info = NULL;15891590/* Release per-process resources when last compute VM is destroyed */1591if (!process_info->n_vms) {1592WARN_ON(!list_empty(&process_info->kfd_bo_list));1593WARN_ON(!list_empty(&process_info->userptr_valid_list));1594WARN_ON(!list_empty(&process_info->userptr_inval_list));15951596dma_fence_put(&process_info->eviction_fence->base);1597cancel_delayed_work_sync(&process_info->restore_userptr_work);1598put_pid(process_info->pid);1599mutex_destroy(&process_info->lock);1600mutex_destroy(&process_info->notifier_lock);1601kfree(process_info);1602}1603}16041605uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)1606{1607struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);1608struct amdgpu_bo *pd = avm->root.bo;1609struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);16101611if (adev->asic_type < CHIP_VEGA10)1612return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT;1613return avm->pd_phys_addr;1614}16151616void amdgpu_amdkfd_block_mmu_notifications(void *p)1617{1618struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;16191620mutex_lock(&pinfo->lock);1621WRITE_ONCE(pinfo->block_mmu_notifications, true);1622mutex_unlock(&pinfo->lock);1623}16241625int amdgpu_amdkfd_criu_resume(void *p)1626{1627int ret = 0;1628struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;16291630mutex_lock(&pinfo->lock);1631pr_debug("scheduling work\n");1632mutex_lock(&pinfo->notifier_lock);1633pinfo->evicted_bos++;1634mutex_unlock(&pinfo->notifier_lock);1635if (!READ_ONCE(pinfo->block_mmu_notifications)) {1636ret = -EINVAL;1637goto out_unlock;1638}1639WRITE_ONCE(pinfo->block_mmu_notifications, false);1640queue_delayed_work(system_freezable_wq,1641&pinfo->restore_userptr_work, 0);16421643out_unlock:1644mutex_unlock(&pinfo->lock);1645return ret;1646}16471648size_t amdgpu_amdkfd_get_available_memory(struct amdgpu_device *adev,1649uint8_t xcp_id)1650{1651uint64_t reserved_for_pt =1652ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);1653struct amdgpu_ras *con = amdgpu_ras_get_context(adev);1654uint64_t reserved_for_ras = (con ? con->reserved_pages_in_bytes : 0);1655ssize_t available;1656uint64_t vram_available, system_mem_available, ttm_mem_available;16571658spin_lock(&kfd_mem_limit.mem_limit_lock);1659if (adev->apu_prefer_gtt && !adev->gmc.is_app_apu)1660vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id)1661- adev->kfd.vram_used_aligned[xcp_id];1662else1663vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id)1664- adev->kfd.vram_used_aligned[xcp_id]1665- atomic64_read(&adev->vram_pin_size)1666- reserved_for_pt1667- reserved_for_ras;16681669if (adev->apu_prefer_gtt) {1670system_mem_available = no_system_mem_limit ?1671kfd_mem_limit.max_system_mem_limit :1672kfd_mem_limit.max_system_mem_limit -1673kfd_mem_limit.system_mem_used;16741675ttm_mem_available = kfd_mem_limit.max_ttm_mem_limit -1676kfd_mem_limit.ttm_mem_used;16771678available = min3(system_mem_available, ttm_mem_available,1679vram_available);1680available = ALIGN_DOWN(available, PAGE_SIZE);1681} else {1682available = ALIGN_DOWN(vram_available, VRAM_AVAILABLITY_ALIGN);1683}16841685spin_unlock(&kfd_mem_limit.mem_limit_lock);16861687if (available < 0)1688available = 0;16891690return available;1691}16921693int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(1694struct amdgpu_device *adev, uint64_t va, uint64_t size,1695void *drm_priv, struct kgd_mem **mem,1696uint64_t *offset, uint32_t flags, bool criu_resume)1697{1698struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);1699struct amdgpu_fpriv *fpriv = container_of(avm, struct amdgpu_fpriv, vm);1700enum ttm_bo_type bo_type = ttm_bo_type_device;1701struct sg_table *sg = NULL;1702uint64_t user_addr = 0;1703struct amdgpu_bo *bo;1704struct drm_gem_object *gobj = NULL;1705u32 domain, alloc_domain;1706uint64_t aligned_size;1707int8_t xcp_id = -1;1708u64 alloc_flags;1709int ret;17101711/*1712* Check on which domain to allocate BO1713*/1714if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {1715domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;17161717if (adev->apu_prefer_gtt) {1718domain = AMDGPU_GEM_DOMAIN_GTT;1719alloc_domain = AMDGPU_GEM_DOMAIN_GTT;1720alloc_flags = 0;1721} else {1722alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;1723alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ?1724AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0;17251726/* For contiguous VRAM allocation */1727if (flags & KFD_IOC_ALLOC_MEM_FLAGS_CONTIGUOUS)1728alloc_flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;1729}1730xcp_id = fpriv->xcp_id == AMDGPU_XCP_NO_PARTITION ?17310 : fpriv->xcp_id;1732} else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {1733domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;1734alloc_flags = 0;1735} else {1736domain = AMDGPU_GEM_DOMAIN_GTT;1737alloc_domain = AMDGPU_GEM_DOMAIN_CPU;1738alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE;17391740if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {1741if (!offset || !*offset)1742return -EINVAL;1743user_addr = untagged_addr(*offset);1744} else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |1745KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {1746bo_type = ttm_bo_type_sg;1747if (size > UINT_MAX)1748return -EINVAL;1749sg = create_sg_table(*offset, size);1750if (!sg)1751return -ENOMEM;1752} else {1753return -EINVAL;1754}1755}17561757if (flags & KFD_IOC_ALLOC_MEM_FLAGS_COHERENT)1758alloc_flags |= AMDGPU_GEM_CREATE_COHERENT;1759if (flags & KFD_IOC_ALLOC_MEM_FLAGS_EXT_COHERENT)1760alloc_flags |= AMDGPU_GEM_CREATE_EXT_COHERENT;1761if (flags & KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED)1762alloc_flags |= AMDGPU_GEM_CREATE_UNCACHED;17631764*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);1765if (!*mem) {1766ret = -ENOMEM;1767goto err;1768}1769INIT_LIST_HEAD(&(*mem)->attachments);1770mutex_init(&(*mem)->lock);1771(*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);17721773/* Workaround for AQL queue wraparound bug. Map the same1774* memory twice. That means we only actually allocate half1775* the memory.1776*/1777if ((*mem)->aql_queue)1778size >>= 1;1779aligned_size = PAGE_ALIGN(size);17801781(*mem)->alloc_flags = flags;17821783amdgpu_sync_create(&(*mem)->sync);17841785ret = amdgpu_amdkfd_reserve_mem_limit(adev, aligned_size, flags,1786xcp_id);1787if (ret) {1788pr_debug("Insufficient memory\n");1789goto err_reserve_limit;1790}17911792pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s xcp_id %d\n",1793va, (*mem)->aql_queue ? size << 1 : size,1794domain_string(alloc_domain), xcp_id);17951796ret = amdgpu_gem_object_create(adev, aligned_size, 1, alloc_domain, alloc_flags,1797bo_type, NULL, &gobj, xcp_id + 1);1798if (ret) {1799pr_debug("Failed to create BO on domain %s. ret %d\n",1800domain_string(alloc_domain), ret);1801goto err_bo_create;1802}1803ret = drm_vma_node_allow(&gobj->vma_node, drm_priv);1804if (ret) {1805pr_debug("Failed to allow vma node access. ret %d\n", ret);1806goto err_node_allow;1807}1808ret = drm_gem_handle_create(adev->kfd.client.file, gobj, &(*mem)->gem_handle);1809if (ret)1810goto err_gem_handle_create;1811bo = gem_to_amdgpu_bo(gobj);1812if (bo_type == ttm_bo_type_sg) {1813bo->tbo.sg = sg;1814bo->tbo.ttm->sg = sg;1815}1816bo->kfd_bo = *mem;1817(*mem)->bo = bo;1818if (user_addr)1819bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO;18201821(*mem)->va = va;1822(*mem)->domain = domain;1823(*mem)->mapped_to_gpu_memory = 0;1824(*mem)->process_info = avm->process_info;18251826add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);18271828if (user_addr) {1829pr_debug("creating userptr BO for user_addr = %llx\n", user_addr);1830ret = init_user_pages(*mem, user_addr, criu_resume);1831if (ret)1832goto allocate_init_user_pages_failed;1833} else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |1834KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {1835ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT);1836if (ret) {1837pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n");1838goto err_pin_bo;1839}1840bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;1841bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;1842} else {1843mutex_lock(&avm->process_info->lock);1844if (avm->process_info->eviction_fence &&1845!dma_fence_is_signaled(&avm->process_info->eviction_fence->base))1846ret = amdgpu_amdkfd_bo_validate_and_fence(bo, domain,1847&avm->process_info->eviction_fence->base);1848mutex_unlock(&avm->process_info->lock);1849if (ret)1850goto err_validate_bo;1851}18521853if (offset)1854*offset = amdgpu_bo_mmap_offset(bo);18551856return 0;18571858allocate_init_user_pages_failed:1859err_pin_bo:1860err_validate_bo:1861remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);1862drm_gem_handle_delete(adev->kfd.client.file, (*mem)->gem_handle);1863err_gem_handle_create:1864drm_vma_node_revoke(&gobj->vma_node, drm_priv);1865err_node_allow:1866/* Don't unreserve system mem limit twice */1867goto err_reserve_limit;1868err_bo_create:1869amdgpu_amdkfd_unreserve_mem_limit(adev, aligned_size, flags, xcp_id);1870err_reserve_limit:1871amdgpu_sync_free(&(*mem)->sync);1872mutex_destroy(&(*mem)->lock);1873if (gobj)1874drm_gem_object_put(gobj);1875else1876kfree(*mem);1877err:1878if (sg) {1879sg_free_table(sg);1880kfree(sg);1881}1882return ret;1883}18841885int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(1886struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv,1887uint64_t *size)1888{1889struct amdkfd_process_info *process_info = mem->process_info;1890unsigned long bo_size = mem->bo->tbo.base.size;1891bool use_release_notifier = (mem->bo->kfd_bo == mem);1892struct kfd_mem_attachment *entry, *tmp;1893struct bo_vm_reservation_context ctx;1894unsigned int mapped_to_gpu_memory;1895int ret;1896bool is_imported = false;18971898mutex_lock(&mem->lock);18991900/* Unpin MMIO/DOORBELL BO's that were pinned during allocation */1901if (mem->alloc_flags &1902(KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |1903KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {1904amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo);1905}19061907mapped_to_gpu_memory = mem->mapped_to_gpu_memory;1908is_imported = mem->is_imported;1909mutex_unlock(&mem->lock);1910/* lock is not needed after this, since mem is unused and will1911* be freed anyway1912*/19131914if (mapped_to_gpu_memory > 0) {1915pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",1916mem->va, bo_size);1917return -EBUSY;1918}19191920/* Make sure restore workers don't access the BO any more */1921mutex_lock(&process_info->lock);1922if (!list_empty(&mem->validate_list))1923list_del_init(&mem->validate_list);1924mutex_unlock(&process_info->lock);19251926ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);1927if (unlikely(ret))1928return ret;19291930/* Cleanup user pages and MMU notifiers */1931if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {1932amdgpu_hmm_unregister(mem->bo);1933amdgpu_hmm_range_free(mem->range);1934mem->range = NULL;1935}19361937amdgpu_amdkfd_remove_eviction_fence(mem->bo,1938process_info->eviction_fence);1939pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,1940mem->va + bo_size * (1 + mem->aql_queue));19411942/* Remove from VM internal data structures */1943list_for_each_entry_safe(entry, tmp, &mem->attachments, list) {1944kfd_mem_dmaunmap_attachment(mem, entry);1945kfd_mem_detach(entry);1946}19471948ret = unreserve_bo_and_vms(&ctx, false, false);19491950/* Free the sync object */1951amdgpu_sync_free(&mem->sync);19521953/* If the SG is not NULL, it's one we created for a doorbell or mmio1954* remap BO. We need to free it.1955*/1956if (mem->bo->tbo.sg) {1957sg_free_table(mem->bo->tbo.sg);1958kfree(mem->bo->tbo.sg);1959}19601961/* Update the size of the BO being freed if it was allocated from1962* VRAM and is not imported. For APP APU VRAM allocations are done1963* in GTT domain1964*/1965if (size) {1966if (!is_imported &&1967mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM)1968*size = bo_size;1969else1970*size = 0;1971}19721973/* Free the BO*/1974drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv);1975drm_gem_handle_delete(adev->kfd.client.file, mem->gem_handle);1976if (mem->dmabuf) {1977dma_buf_put(mem->dmabuf);1978mem->dmabuf = NULL;1979}1980mutex_destroy(&mem->lock);19811982/* If this releases the last reference, it will end up calling1983* amdgpu_amdkfd_release_notify and kfree the mem struct. That's why1984* this needs to be the last call here.1985*/1986drm_gem_object_put(&mem->bo->tbo.base);19871988/*1989* For kgd_mem allocated in amdgpu_amdkfd_gpuvm_import_dmabuf(),1990* explicitly free it here.1991*/1992if (!use_release_notifier)1993kfree(mem);19941995return ret;1996}19971998int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(1999struct amdgpu_device *adev, struct kgd_mem *mem,2000void *drm_priv)2001{2002struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);2003int ret;2004struct amdgpu_bo *bo;2005uint32_t domain;2006struct kfd_mem_attachment *entry;2007struct bo_vm_reservation_context ctx;2008unsigned long bo_size;2009bool is_invalid_userptr = false;20102011bo = mem->bo;2012if (!bo) {2013pr_err("Invalid BO when mapping memory to GPU\n");2014return -EINVAL;2015}20162017/* Make sure restore is not running concurrently. Since we2018* don't map invalid userptr BOs, we rely on the next restore2019* worker to do the mapping2020*/2021mutex_lock(&mem->process_info->lock);20222023/* Lock notifier lock. If we find an invalid userptr BO, we can be2024* sure that the MMU notifier is no longer running2025* concurrently and the queues are actually stopped2026*/2027if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {2028mutex_lock(&mem->process_info->notifier_lock);2029is_invalid_userptr = !!mem->invalid;2030mutex_unlock(&mem->process_info->notifier_lock);2031}20322033mutex_lock(&mem->lock);20342035domain = mem->domain;2036bo_size = bo->tbo.base.size;20372038pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",2039mem->va,2040mem->va + bo_size * (1 + mem->aql_queue),2041avm, domain_string(domain));20422043if (!kfd_mem_is_attached(avm, mem)) {2044ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue);2045if (ret)2046goto out;2047}20482049ret = reserve_bo_and_vm(mem, avm, &ctx);2050if (unlikely(ret))2051goto out;20522053/* Userptr can be marked as "not invalid", but not actually be2054* validated yet (still in the system domain). In that case2055* the queues are still stopped and we can leave mapping for2056* the next restore worker2057*/2058if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&2059bo->tbo.resource->mem_type == TTM_PL_SYSTEM)2060is_invalid_userptr = true;20612062ret = vm_validate_pt_pd_bos(avm, NULL);2063if (unlikely(ret))2064goto out_unreserve;20652066list_for_each_entry(entry, &mem->attachments, list) {2067if (entry->bo_va->base.vm != avm || entry->is_mapped)2068continue;20692070pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",2071entry->va, entry->va + bo_size, entry);20722073ret = map_bo_to_gpuvm(mem, entry, ctx.sync,2074is_invalid_userptr);2075if (ret) {2076pr_err("Failed to map bo to gpuvm\n");2077goto out_unreserve;2078}20792080ret = vm_update_pds(avm, ctx.sync);2081if (ret) {2082pr_err("Failed to update page directories\n");2083goto out_unreserve;2084}20852086entry->is_mapped = true;2087mem->mapped_to_gpu_memory++;2088pr_debug("\t INC mapping count %d\n",2089mem->mapped_to_gpu_memory);2090}20912092ret = unreserve_bo_and_vms(&ctx, false, false);20932094goto out;20952096out_unreserve:2097unreserve_bo_and_vms(&ctx, false, false);2098out:2099mutex_unlock(&mem->process_info->lock);2100mutex_unlock(&mem->lock);2101return ret;2102}21032104int amdgpu_amdkfd_gpuvm_dmaunmap_mem(struct kgd_mem *mem, void *drm_priv)2105{2106struct kfd_mem_attachment *entry;2107struct amdgpu_vm *vm;2108int ret;21092110vm = drm_priv_to_vm(drm_priv);21112112mutex_lock(&mem->lock);21132114ret = amdgpu_bo_reserve(mem->bo, true);2115if (ret)2116goto out;21172118list_for_each_entry(entry, &mem->attachments, list) {2119if (entry->bo_va->base.vm != vm)2120continue;2121if (entry->bo_va->base.bo->tbo.ttm &&2122!entry->bo_va->base.bo->tbo.ttm->sg)2123continue;21242125kfd_mem_dmaunmap_attachment(mem, entry);2126}21272128amdgpu_bo_unreserve(mem->bo);2129out:2130mutex_unlock(&mem->lock);21312132return ret;2133}21342135int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(2136struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv)2137{2138struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);2139unsigned long bo_size = mem->bo->tbo.base.size;2140struct kfd_mem_attachment *entry;2141struct bo_vm_reservation_context ctx;2142int ret;21432144mutex_lock(&mem->lock);21452146ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx);2147if (unlikely(ret))2148goto out;2149/* If no VMs were reserved, it means the BO wasn't actually mapped */2150if (ctx.n_vms == 0) {2151ret = -EINVAL;2152goto unreserve_out;2153}21542155ret = vm_validate_pt_pd_bos(avm, NULL);2156if (unlikely(ret))2157goto unreserve_out;21582159pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",2160mem->va,2161mem->va + bo_size * (1 + mem->aql_queue),2162avm);21632164list_for_each_entry(entry, &mem->attachments, list) {2165if (entry->bo_va->base.vm != avm || !entry->is_mapped)2166continue;21672168pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",2169entry->va, entry->va + bo_size, entry);21702171ret = unmap_bo_from_gpuvm(mem, entry, ctx.sync);2172if (ret)2173goto unreserve_out;21742175entry->is_mapped = false;21762177mem->mapped_to_gpu_memory--;2178pr_debug("\t DEC mapping count %d\n",2179mem->mapped_to_gpu_memory);2180}21812182unreserve_out:2183unreserve_bo_and_vms(&ctx, false, false);2184out:2185mutex_unlock(&mem->lock);2186return ret;2187}21882189int amdgpu_amdkfd_gpuvm_sync_memory(2190struct amdgpu_device *adev, struct kgd_mem *mem, bool intr)2191{2192struct amdgpu_sync sync;2193int ret;21942195amdgpu_sync_create(&sync);21962197mutex_lock(&mem->lock);2198amdgpu_sync_clone(&mem->sync, &sync);2199mutex_unlock(&mem->lock);22002201ret = amdgpu_sync_wait(&sync, intr);2202amdgpu_sync_free(&sync);2203return ret;2204}22052206/**2207* amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count2208* @bo: Buffer object to be mapped2209* @bo_gart: Return bo reference2210*2211* Before return, bo reference count is incremented. To release the reference and unpin/2212* unmap the BO, call amdgpu_amdkfd_free_gtt_mem.2213*/2214int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_bo *bo, struct amdgpu_bo **bo_gart)2215{2216int ret;22172218ret = amdgpu_bo_reserve(bo, true);2219if (ret) {2220pr_err("Failed to reserve bo. ret %d\n", ret);2221goto err_reserve_bo_failed;2222}22232224ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);2225if (ret) {2226pr_err("Failed to pin bo. ret %d\n", ret);2227goto err_pin_bo_failed;2228}22292230ret = amdgpu_ttm_alloc_gart(&bo->tbo);2231if (ret) {2232pr_err("Failed to bind bo to GART. ret %d\n", ret);2233goto err_map_bo_gart_failed;2234}22352236amdgpu_amdkfd_remove_eviction_fence(2237bo, bo->vm_bo->vm->process_info->eviction_fence);22382239amdgpu_bo_unreserve(bo);22402241*bo_gart = amdgpu_bo_ref(bo);22422243return 0;22442245err_map_bo_gart_failed:2246amdgpu_bo_unpin(bo);2247err_pin_bo_failed:2248amdgpu_bo_unreserve(bo);2249err_reserve_bo_failed:22502251return ret;2252}22532254/** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Map a GTT BO for kernel CPU access2255*2256* @mem: Buffer object to be mapped for CPU access2257* @kptr[out]: pointer in kernel CPU address space2258* @size[out]: size of the buffer2259*2260* Pins the BO and maps it for kernel CPU access. The eviction fence is removed2261* from the BO, since pinned BOs cannot be evicted. The bo must remain on the2262* validate_list, so the GPU mapping can be restored after a page table was2263* evicted.2264*2265* Return: 0 on success, error code on failure2266*/2267int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem,2268void **kptr, uint64_t *size)2269{2270int ret;2271struct amdgpu_bo *bo = mem->bo;22722273if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {2274pr_err("userptr can't be mapped to kernel\n");2275return -EINVAL;2276}22772278mutex_lock(&mem->process_info->lock);22792280ret = amdgpu_bo_reserve(bo, true);2281if (ret) {2282pr_err("Failed to reserve bo. ret %d\n", ret);2283goto bo_reserve_failed;2284}22852286ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);2287if (ret) {2288pr_err("Failed to pin bo. ret %d\n", ret);2289goto pin_failed;2290}22912292ret = amdgpu_bo_kmap(bo, kptr);2293if (ret) {2294pr_err("Failed to map bo to kernel. ret %d\n", ret);2295goto kmap_failed;2296}22972298amdgpu_amdkfd_remove_eviction_fence(2299bo, mem->process_info->eviction_fence);23002301if (size)2302*size = amdgpu_bo_size(bo);23032304amdgpu_bo_unreserve(bo);23052306mutex_unlock(&mem->process_info->lock);2307return 0;23082309kmap_failed:2310amdgpu_bo_unpin(bo);2311pin_failed:2312amdgpu_bo_unreserve(bo);2313bo_reserve_failed:2314mutex_unlock(&mem->process_info->lock);23152316return ret;2317}23182319/** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Unmap a GTT BO for kernel CPU access2320*2321* @mem: Buffer object to be unmapped for CPU access2322*2323* Removes the kernel CPU mapping and unpins the BO. It does not restore the2324* eviction fence, so this function should only be used for cleanup before the2325* BO is destroyed.2326*/2327void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem *mem)2328{2329struct amdgpu_bo *bo = mem->bo;23302331(void)amdgpu_bo_reserve(bo, true);2332amdgpu_bo_kunmap(bo);2333amdgpu_bo_unpin(bo);2334amdgpu_bo_unreserve(bo);2335}23362337int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev,2338struct kfd_vm_fault_info *mem)2339{2340if (atomic_read_acquire(&adev->gmc.vm_fault_info_updated) == 1) {2341*mem = *adev->gmc.vm_fault_info;2342atomic_set_release(&adev->gmc.vm_fault_info_updated, 0);2343}2344return 0;2345}23462347static int import_obj_create(struct amdgpu_device *adev,2348struct dma_buf *dma_buf,2349struct drm_gem_object *obj,2350uint64_t va, void *drm_priv,2351struct kgd_mem **mem, uint64_t *size,2352uint64_t *mmap_offset)2353{2354struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);2355struct amdgpu_bo *bo;2356int ret;23572358bo = gem_to_amdgpu_bo(obj);2359if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM |2360AMDGPU_GEM_DOMAIN_GTT)))2361/* Only VRAM and GTT BOs are supported */2362return -EINVAL;23632364*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);2365if (!*mem)2366return -ENOMEM;23672368ret = drm_vma_node_allow(&obj->vma_node, drm_priv);2369if (ret)2370goto err_free_mem;23712372if (size)2373*size = amdgpu_bo_size(bo);23742375if (mmap_offset)2376*mmap_offset = amdgpu_bo_mmap_offset(bo);23772378INIT_LIST_HEAD(&(*mem)->attachments);2379mutex_init(&(*mem)->lock);23802381(*mem)->alloc_flags =2382((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?2383KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT)2384| KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE2385| KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;23862387get_dma_buf(dma_buf);2388(*mem)->dmabuf = dma_buf;2389(*mem)->bo = bo;2390(*mem)->va = va;2391(*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) &&2392!adev->apu_prefer_gtt ?2393AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT;23942395(*mem)->mapped_to_gpu_memory = 0;2396(*mem)->process_info = avm->process_info;2397add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false);2398amdgpu_sync_create(&(*mem)->sync);2399(*mem)->is_imported = true;24002401mutex_lock(&avm->process_info->lock);2402if (avm->process_info->eviction_fence &&2403!dma_fence_is_signaled(&avm->process_info->eviction_fence->base))2404ret = amdgpu_amdkfd_bo_validate_and_fence(bo, (*mem)->domain,2405&avm->process_info->eviction_fence->base);2406mutex_unlock(&avm->process_info->lock);2407if (ret)2408goto err_remove_mem;24092410return 0;24112412err_remove_mem:2413remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);2414drm_vma_node_revoke(&obj->vma_node, drm_priv);2415err_free_mem:2416kfree(*mem);2417return ret;2418}24192420int amdgpu_amdkfd_gpuvm_import_dmabuf_fd(struct amdgpu_device *adev, int fd,2421uint64_t va, void *drm_priv,2422struct kgd_mem **mem, uint64_t *size,2423uint64_t *mmap_offset)2424{2425struct drm_gem_object *obj;2426uint32_t handle;2427int ret;24282429ret = drm_gem_prime_fd_to_handle(&adev->ddev, adev->kfd.client.file, fd,2430&handle);2431if (ret)2432return ret;2433obj = drm_gem_object_lookup(adev->kfd.client.file, handle);2434if (!obj) {2435ret = -EINVAL;2436goto err_release_handle;2437}24382439ret = import_obj_create(adev, obj->dma_buf, obj, va, drm_priv, mem, size,2440mmap_offset);2441if (ret)2442goto err_put_obj;24432444(*mem)->gem_handle = handle;24452446return 0;24472448err_put_obj:2449drm_gem_object_put(obj);2450err_release_handle:2451drm_gem_handle_delete(adev->kfd.client.file, handle);2452return ret;2453}24542455int amdgpu_amdkfd_gpuvm_export_dmabuf(struct kgd_mem *mem,2456struct dma_buf **dma_buf)2457{2458int ret;24592460mutex_lock(&mem->lock);2461ret = kfd_mem_export_dmabuf(mem);2462if (ret)2463goto out;24642465get_dma_buf(mem->dmabuf);2466*dma_buf = mem->dmabuf;2467out:2468mutex_unlock(&mem->lock);2469return ret;2470}24712472/* Evict a userptr BO by stopping the queues if necessary2473*2474* Runs in MMU notifier, may be in RECLAIM_FS context. This means it2475* cannot do any memory allocations, and cannot take any locks that2476* are held elsewhere while allocating memory.2477*2478* It doesn't do anything to the BO itself. The real work happens in2479* restore, where we get updated page addresses. This function only2480* ensures that GPU access to the BO is stopped.2481*/2482int amdgpu_amdkfd_evict_userptr(struct mmu_interval_notifier *mni,2483unsigned long cur_seq, struct kgd_mem *mem)2484{2485struct amdkfd_process_info *process_info = mem->process_info;2486int r = 0;24872488/* Do not process MMU notifications during CRIU restore until2489* KFD_CRIU_OP_RESUME IOCTL is received2490*/2491if (READ_ONCE(process_info->block_mmu_notifications))2492return 0;24932494mutex_lock(&process_info->notifier_lock);2495mmu_interval_set_seq(mni, cur_seq);24962497mem->invalid++;2498if (++process_info->evicted_bos == 1) {2499/* First eviction, stop the queues */2500r = kgd2kfd_quiesce_mm(mni->mm,2501KFD_QUEUE_EVICTION_TRIGGER_USERPTR);25022503if (r && r != -ESRCH)2504pr_err("Failed to quiesce KFD\n");25052506if (r != -ESRCH)2507queue_delayed_work(system_freezable_wq,2508&process_info->restore_userptr_work,2509msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));2510}2511mutex_unlock(&process_info->notifier_lock);25122513return r;2514}25152516/* Update invalid userptr BOs2517*2518* Moves invalidated (evicted) userptr BOs from userptr_valid_list to2519* userptr_inval_list and updates user pages for all BOs that have2520* been invalidated since their last update.2521*/2522static int update_invalid_user_pages(struct amdkfd_process_info *process_info,2523struct mm_struct *mm)2524{2525struct kgd_mem *mem, *tmp_mem;2526struct amdgpu_bo *bo;2527struct ttm_operation_ctx ctx = { false, false };2528uint32_t invalid;2529int ret = 0;25302531mutex_lock(&process_info->notifier_lock);25322533/* Move all invalidated BOs to the userptr_inval_list */2534list_for_each_entry_safe(mem, tmp_mem,2535&process_info->userptr_valid_list,2536validate_list)2537if (mem->invalid)2538list_move_tail(&mem->validate_list,2539&process_info->userptr_inval_list);25402541/* Go through userptr_inval_list and update any invalid user_pages */2542list_for_each_entry(mem, &process_info->userptr_inval_list,2543validate_list) {2544invalid = mem->invalid;2545if (!invalid)2546/* BO hasn't been invalidated since the last2547* revalidation attempt. Keep its page list.2548*/2549continue;25502551bo = mem->bo;25522553amdgpu_hmm_range_free(mem->range);2554mem->range = NULL;25552556/* BO reservations and getting user pages (hmm_range_fault)2557* must happen outside the notifier lock2558*/2559mutex_unlock(&process_info->notifier_lock);25602561/* Move the BO to system (CPU) domain if necessary to unmap2562* and free the SG table2563*/2564if (bo->tbo.resource->mem_type != TTM_PL_SYSTEM) {2565if (amdgpu_bo_reserve(bo, true))2566return -EAGAIN;2567amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);2568ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);2569amdgpu_bo_unreserve(bo);2570if (ret) {2571pr_err("%s: Failed to invalidate userptr BO\n",2572__func__);2573return -EAGAIN;2574}2575}25762577mem->range = amdgpu_hmm_range_alloc(NULL);2578if (unlikely(!mem->range))2579return -ENOMEM;2580/* Get updated user pages */2581ret = amdgpu_ttm_tt_get_user_pages(bo, mem->range);2582if (ret) {2583amdgpu_hmm_range_free(mem->range);2584mem->range = NULL;2585pr_debug("Failed %d to get user pages\n", ret);25862587/* Return -EFAULT bad address error as success. It will2588* fail later with a VM fault if the GPU tries to access2589* it. Better than hanging indefinitely with stalled2590* user mode queues.2591*2592* Return other error -EBUSY or -ENOMEM to retry restore2593*/2594if (ret != -EFAULT)2595return ret;25962597/* If applications unmap memory before destroying the userptr2598* from the KFD, trigger a segmentation fault in VM debug mode.2599*/2600if (amdgpu_ttm_adev(bo->tbo.bdev)->debug_vm_userptr) {2601struct kfd_process *p;26022603pr_err("Pid %d unmapped memory before destroying userptr at GPU addr 0x%llx\n",2604pid_nr(process_info->pid), mem->va);26052606// Send GPU VM fault to user space2607p = kfd_lookup_process_by_pid(process_info->pid);2608if (p) {2609kfd_signal_vm_fault_event_with_userptr(p, mem->va);2610kfd_unref_process(p);2611}2612}26132614ret = 0;2615}26162617amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, mem->range);26182619mutex_lock(&process_info->notifier_lock);26202621/* Mark the BO as valid unless it was invalidated2622* again concurrently.2623*/2624if (mem->invalid != invalid) {2625ret = -EAGAIN;2626goto unlock_out;2627}2628/* set mem valid if mem has hmm range associated */2629if (mem->range)2630mem->invalid = 0;2631}26322633unlock_out:2634mutex_unlock(&process_info->notifier_lock);26352636return ret;2637}26382639/* Validate invalid userptr BOs2640*2641* Validates BOs on the userptr_inval_list. Also updates GPUVM page tables2642* with new page addresses and waits for the page table updates to complete.2643*/2644static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)2645{2646struct ttm_operation_ctx ctx = { false, false };2647struct amdgpu_sync sync;2648struct drm_exec exec;26492650struct amdgpu_vm *peer_vm;2651struct kgd_mem *mem, *tmp_mem;2652struct amdgpu_bo *bo;2653int ret;26542655amdgpu_sync_create(&sync);26562657drm_exec_init(&exec, 0, 0);2658/* Reserve all BOs and page tables for validation */2659drm_exec_until_all_locked(&exec) {2660/* Reserve all the page directories */2661list_for_each_entry(peer_vm, &process_info->vm_list_head,2662vm_list_node) {2663ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2);2664drm_exec_retry_on_contention(&exec);2665if (unlikely(ret))2666goto unreserve_out;2667}26682669/* Reserve the userptr_inval_list entries to resv_list */2670list_for_each_entry(mem, &process_info->userptr_inval_list,2671validate_list) {2672struct drm_gem_object *gobj;26732674gobj = &mem->bo->tbo.base;2675ret = drm_exec_prepare_obj(&exec, gobj, 1);2676drm_exec_retry_on_contention(&exec);2677if (unlikely(ret))2678goto unreserve_out;2679}2680}26812682ret = process_validate_vms(process_info, NULL);2683if (ret)2684goto unreserve_out;26852686/* Validate BOs and update GPUVM page tables */2687list_for_each_entry_safe(mem, tmp_mem,2688&process_info->userptr_inval_list,2689validate_list) {2690struct kfd_mem_attachment *attachment;26912692bo = mem->bo;26932694/* Validate the BO if we got user pages */2695if (bo->tbo.ttm->pages[0]) {2696amdgpu_bo_placement_from_domain(bo, mem->domain);2697ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);2698if (ret) {2699pr_err("%s: failed to validate BO\n", __func__);2700goto unreserve_out;2701}2702}27032704/* Update mapping. If the BO was not validated2705* (because we couldn't get user pages), this will2706* clear the page table entries, which will result in2707* VM faults if the GPU tries to access the invalid2708* memory.2709*/2710list_for_each_entry(attachment, &mem->attachments, list) {2711if (!attachment->is_mapped)2712continue;27132714kfd_mem_dmaunmap_attachment(mem, attachment);2715ret = update_gpuvm_pte(mem, attachment, &sync);2716if (ret) {2717pr_err("%s: update PTE failed\n", __func__);2718/* make sure this gets validated again */2719mutex_lock(&process_info->notifier_lock);2720mem->invalid++;2721mutex_unlock(&process_info->notifier_lock);2722goto unreserve_out;2723}2724}2725}27262727/* Update page directories */2728ret = process_update_pds(process_info, &sync);27292730unreserve_out:2731drm_exec_fini(&exec);2732amdgpu_sync_wait(&sync, false);2733amdgpu_sync_free(&sync);27342735return ret;2736}27372738/* Confirm that all user pages are valid while holding the notifier lock2739*2740* Moves valid BOs from the userptr_inval_list back to userptr_val_list.2741*/2742static int confirm_valid_user_pages_locked(struct amdkfd_process_info *process_info)2743{2744struct kgd_mem *mem, *tmp_mem;2745int ret = 0;27462747list_for_each_entry_safe(mem, tmp_mem,2748&process_info->userptr_inval_list,2749validate_list) {2750bool valid;27512752/* keep mem without hmm range at userptr_inval_list */2753if (!mem->range)2754continue;27552756/* Only check mem with hmm range associated */2757valid = amdgpu_hmm_range_valid(mem->range);2758amdgpu_hmm_range_free(mem->range);27592760mem->range = NULL;2761if (!valid) {2762WARN(!mem->invalid, "Invalid BO not marked invalid");2763ret = -EAGAIN;2764continue;2765}27662767if (mem->invalid) {2768WARN(1, "Valid BO is marked invalid");2769ret = -EAGAIN;2770continue;2771}27722773list_move_tail(&mem->validate_list,2774&process_info->userptr_valid_list);2775}27762777return ret;2778}27792780/* Worker callback to restore evicted userptr BOs2781*2782* Tries to update and validate all userptr BOs. If successful and no2783* concurrent evictions happened, the queues are restarted. Otherwise,2784* reschedule for another attempt later.2785*/2786static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)2787{2788struct delayed_work *dwork = to_delayed_work(work);2789struct amdkfd_process_info *process_info =2790container_of(dwork, struct amdkfd_process_info,2791restore_userptr_work);2792struct task_struct *usertask;2793struct mm_struct *mm;2794uint32_t evicted_bos;27952796mutex_lock(&process_info->notifier_lock);2797evicted_bos = process_info->evicted_bos;2798mutex_unlock(&process_info->notifier_lock);2799if (!evicted_bos)2800return;28012802/* Reference task and mm in case of concurrent process termination */2803usertask = get_pid_task(process_info->pid, PIDTYPE_PID);2804if (!usertask)2805return;2806mm = get_task_mm(usertask);2807if (!mm) {2808put_task_struct(usertask);2809return;2810}28112812mutex_lock(&process_info->lock);28132814if (update_invalid_user_pages(process_info, mm))2815goto unlock_out;2816/* userptr_inval_list can be empty if all evicted userptr BOs2817* have been freed. In that case there is nothing to validate2818* and we can just restart the queues.2819*/2820if (!list_empty(&process_info->userptr_inval_list)) {2821if (validate_invalid_user_pages(process_info))2822goto unlock_out;2823}2824/* Final check for concurrent evicton and atomic update. If2825* another eviction happens after successful update, it will2826* be a first eviction that calls quiesce_mm. The eviction2827* reference counting inside KFD will handle this case.2828*/2829mutex_lock(&process_info->notifier_lock);2830if (process_info->evicted_bos != evicted_bos)2831goto unlock_notifier_out;28322833if (confirm_valid_user_pages_locked(process_info)) {2834WARN(1, "User pages unexpectedly invalid");2835goto unlock_notifier_out;2836}28372838process_info->evicted_bos = evicted_bos = 0;28392840if (kgd2kfd_resume_mm(mm)) {2841pr_err("%s: Failed to resume KFD\n", __func__);2842/* No recovery from this failure. Probably the CP is2843* hanging. No point trying again.2844*/2845}28462847unlock_notifier_out:2848mutex_unlock(&process_info->notifier_lock);2849unlock_out:2850mutex_unlock(&process_info->lock);28512852/* If validation failed, reschedule another attempt */2853if (evicted_bos) {2854queue_delayed_work(system_freezable_wq,2855&process_info->restore_userptr_work,2856msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));28572858kfd_smi_event_queue_restore_rescheduled(mm);2859}2860mmput(mm);2861put_task_struct(usertask);2862}28632864static void replace_eviction_fence(struct dma_fence __rcu **ef,2865struct dma_fence *new_ef)2866{2867struct dma_fence *old_ef = rcu_replace_pointer(*ef, new_ef, true2868/* protected by process_info->lock */);28692870/* If we're replacing an unsignaled eviction fence, that fence will2871* never be signaled, and if anyone is still waiting on that fence,2872* they will hang forever. This should never happen. We should only2873* replace the fence in restore_work that only gets scheduled after2874* eviction work signaled the fence.2875*/2876WARN_ONCE(!dma_fence_is_signaled(old_ef),2877"Replacing unsignaled eviction fence");2878dma_fence_put(old_ef);2879}28802881/** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given2882* KFD process identified by process_info2883*2884* @process_info: amdkfd_process_info of the KFD process2885*2886* After memory eviction, restore thread calls this function. The function2887* should be called when the Process is still valid. BO restore involves -2888*2889* 1. Release old eviction fence and create new one2890* 2. Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.2891* 3 Use the second PD list and kfd_bo_list to create a list (ctx.list) of2892* BOs that need to be reserved.2893* 4. Reserve all the BOs2894* 5. Validate of PD and PT BOs.2895* 6. Validate all KFD BOs using kfd_bo_list and Map them and add new fence2896* 7. Add fence to all PD and PT BOs.2897* 8. Unreserve all BOs2898*/2899int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence __rcu **ef)2900{2901struct amdkfd_process_info *process_info = info;2902struct amdgpu_vm *peer_vm;2903struct kgd_mem *mem;2904struct list_head duplicate_save;2905struct amdgpu_sync sync_obj;2906unsigned long failed_size = 0;2907unsigned long total_size = 0;2908struct drm_exec exec;2909int ret;29102911INIT_LIST_HEAD(&duplicate_save);29122913mutex_lock(&process_info->lock);29142915drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);2916drm_exec_until_all_locked(&exec) {2917list_for_each_entry(peer_vm, &process_info->vm_list_head,2918vm_list_node) {2919ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2);2920drm_exec_retry_on_contention(&exec);2921if (unlikely(ret)) {2922pr_err("Locking VM PD failed, ret: %d\n", ret);2923goto ttm_reserve_fail;2924}2925}29262927/* Reserve all BOs and page tables/directory. Add all BOs from2928* kfd_bo_list to ctx.list2929*/2930list_for_each_entry(mem, &process_info->kfd_bo_list,2931validate_list) {2932struct drm_gem_object *gobj;29332934gobj = &mem->bo->tbo.base;2935ret = drm_exec_prepare_obj(&exec, gobj, 1);2936drm_exec_retry_on_contention(&exec);2937if (unlikely(ret)) {2938pr_err("drm_exec_prepare_obj failed, ret: %d\n", ret);2939goto ttm_reserve_fail;2940}2941}2942}29432944amdgpu_sync_create(&sync_obj);29452946/* Validate BOs managed by KFD */2947list_for_each_entry(mem, &process_info->kfd_bo_list,2948validate_list) {29492950struct amdgpu_bo *bo = mem->bo;2951uint32_t domain = mem->domain;2952struct dma_resv_iter cursor;2953struct dma_fence *fence;29542955total_size += amdgpu_bo_size(bo);29562957ret = amdgpu_amdkfd_bo_validate(bo, domain, false);2958if (ret) {2959pr_debug("Memory eviction: Validate BOs failed\n");2960failed_size += amdgpu_bo_size(bo);2961ret = amdgpu_amdkfd_bo_validate(bo,2962AMDGPU_GEM_DOMAIN_GTT, false);2963if (ret) {2964pr_debug("Memory eviction: Try again\n");2965goto validate_map_fail;2966}2967}2968dma_resv_for_each_fence(&cursor, bo->tbo.base.resv,2969DMA_RESV_USAGE_KERNEL, fence) {2970ret = amdgpu_sync_fence(&sync_obj, fence, GFP_KERNEL);2971if (ret) {2972pr_debug("Memory eviction: Sync BO fence failed. Try again\n");2973goto validate_map_fail;2974}2975}2976}29772978if (failed_size)2979pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size);29802981/* Validate PDs, PTs and evicted DMABuf imports last. Otherwise BO2982* validations above would invalidate DMABuf imports again.2983*/2984ret = process_validate_vms(process_info, &exec.ticket);2985if (ret) {2986pr_debug("Validating VMs failed, ret: %d\n", ret);2987goto validate_map_fail;2988}29892990/* Update mappings managed by KFD. */2991list_for_each_entry(mem, &process_info->kfd_bo_list,2992validate_list) {2993struct kfd_mem_attachment *attachment;29942995list_for_each_entry(attachment, &mem->attachments, list) {2996if (!attachment->is_mapped)2997continue;29982999kfd_mem_dmaunmap_attachment(mem, attachment);3000ret = update_gpuvm_pte(mem, attachment, &sync_obj);3001if (ret) {3002pr_debug("Memory eviction: update PTE failed. Try again\n");3003goto validate_map_fail;3004}3005}3006}30073008/* Update mappings not managed by KFD */3009list_for_each_entry(peer_vm, &process_info->vm_list_head,3010vm_list_node) {3011struct amdgpu_device *adev = amdgpu_ttm_adev(3012peer_vm->root.bo->tbo.bdev);30133014struct amdgpu_fpriv *fpriv =3015container_of(peer_vm, struct amdgpu_fpriv, vm);30163017ret = amdgpu_vm_bo_update(adev, fpriv->prt_va, false);3018if (ret) {3019dev_dbg(adev->dev,3020"Memory eviction: handle PRT moved failed, pid %8d. Try again.\n",3021pid_nr(process_info->pid));3022goto validate_map_fail;3023}30243025ret = amdgpu_vm_handle_moved(adev, peer_vm, &exec.ticket);3026if (ret) {3027dev_dbg(adev->dev,3028"Memory eviction: handle moved failed, pid %8d. Try again.\n",3029pid_nr(process_info->pid));3030goto validate_map_fail;3031}3032}30333034/* Update page directories */3035ret = process_update_pds(process_info, &sync_obj);3036if (ret) {3037pr_debug("Memory eviction: update PDs failed. Try again\n");3038goto validate_map_fail;3039}30403041/* Sync with fences on all the page tables. They implicitly depend on any3042* move fences from amdgpu_vm_handle_moved above.3043*/3044ret = process_sync_pds_resv(process_info, &sync_obj);3045if (ret) {3046pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");3047goto validate_map_fail;3048}30493050/* Wait for validate and PT updates to finish */3051amdgpu_sync_wait(&sync_obj, false);30523053/* The old eviction fence may be unsignaled if restore happens3054* after a GPU reset or suspend/resume. Keep the old fence in that3055* case. Otherwise release the old eviction fence and create new3056* one, because fence only goes from unsignaled to signaled once3057* and cannot be reused. Use context and mm from the old fence.3058*3059* If an old eviction fence signals after this check, that's OK.3060* Anyone signaling an eviction fence must stop the queues first3061* and schedule another restore worker.3062*/3063if (dma_fence_is_signaled(&process_info->eviction_fence->base)) {3064struct amdgpu_amdkfd_fence *new_fence =3065amdgpu_amdkfd_fence_create(3066process_info->eviction_fence->base.context,3067process_info->eviction_fence->mm,3068NULL);30693070if (!new_fence) {3071pr_err("Failed to create eviction fence\n");3072ret = -ENOMEM;3073goto validate_map_fail;3074}3075dma_fence_put(&process_info->eviction_fence->base);3076process_info->eviction_fence = new_fence;3077replace_eviction_fence(ef, dma_fence_get(&new_fence->base));3078} else {3079WARN_ONCE(*ef != &process_info->eviction_fence->base,3080"KFD eviction fence doesn't match KGD process_info");3081}30823083/* Attach new eviction fence to all BOs except pinned ones */3084list_for_each_entry(mem, &process_info->kfd_bo_list, validate_list) {3085if (mem->bo->tbo.pin_count)3086continue;30873088dma_resv_add_fence(mem->bo->tbo.base.resv,3089&process_info->eviction_fence->base,3090DMA_RESV_USAGE_BOOKKEEP);3091}3092/* Attach eviction fence to PD / PT BOs and DMABuf imports */3093list_for_each_entry(peer_vm, &process_info->vm_list_head,3094vm_list_node) {3095struct amdgpu_bo *bo = peer_vm->root.bo;30963097dma_resv_add_fence(bo->tbo.base.resv,3098&process_info->eviction_fence->base,3099DMA_RESV_USAGE_BOOKKEEP);3100}31013102validate_map_fail:3103amdgpu_sync_free(&sync_obj);3104ttm_reserve_fail:3105drm_exec_fini(&exec);3106mutex_unlock(&process_info->lock);3107return ret;3108}31093110int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem)3111{3112struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;3113struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws;3114int ret;31153116if (!info || !gws)3117return -EINVAL;31183119*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);3120if (!*mem)3121return -ENOMEM;31223123mutex_init(&(*mem)->lock);3124INIT_LIST_HEAD(&(*mem)->attachments);3125(*mem)->bo = amdgpu_bo_ref(gws_bo);3126(*mem)->domain = AMDGPU_GEM_DOMAIN_GWS;3127(*mem)->process_info = process_info;3128add_kgd_mem_to_kfd_bo_list(*mem, process_info, false);3129amdgpu_sync_create(&(*mem)->sync);313031313132/* Validate gws bo the first time it is added to process */3133mutex_lock(&(*mem)->process_info->lock);3134ret = amdgpu_bo_reserve(gws_bo, false);3135if (unlikely(ret)) {3136pr_err("Reserve gws bo failed %d\n", ret);3137goto bo_reservation_failure;3138}31393140ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true);3141if (ret) {3142pr_err("GWS BO validate failed %d\n", ret);3143goto bo_validation_failure;3144}3145/* GWS resource is shared b/t amdgpu and amdkfd3146* Add process eviction fence to bo so they can3147* evict each other.3148*/3149ret = dma_resv_reserve_fences(gws_bo->tbo.base.resv, 1);3150if (ret)3151goto reserve_shared_fail;3152dma_resv_add_fence(gws_bo->tbo.base.resv,3153&process_info->eviction_fence->base,3154DMA_RESV_USAGE_BOOKKEEP);3155amdgpu_bo_unreserve(gws_bo);3156mutex_unlock(&(*mem)->process_info->lock);31573158return ret;31593160reserve_shared_fail:3161bo_validation_failure:3162amdgpu_bo_unreserve(gws_bo);3163bo_reservation_failure:3164mutex_unlock(&(*mem)->process_info->lock);3165amdgpu_sync_free(&(*mem)->sync);3166remove_kgd_mem_from_kfd_bo_list(*mem, process_info);3167amdgpu_bo_unref(&gws_bo);3168mutex_destroy(&(*mem)->lock);3169kfree(*mem);3170*mem = NULL;3171return ret;3172}31733174int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem)3175{3176int ret;3177struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;3178struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;3179struct amdgpu_bo *gws_bo = kgd_mem->bo;31803181/* Remove BO from process's validate list so restore worker won't touch3182* it anymore3183*/3184remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info);31853186ret = amdgpu_bo_reserve(gws_bo, false);3187if (unlikely(ret)) {3188pr_err("Reserve gws bo failed %d\n", ret);3189//TODO add BO back to validate_list?3190return ret;3191}3192amdgpu_amdkfd_remove_eviction_fence(gws_bo,3193process_info->eviction_fence);3194amdgpu_bo_unreserve(gws_bo);3195amdgpu_sync_free(&kgd_mem->sync);3196amdgpu_bo_unref(&gws_bo);3197mutex_destroy(&kgd_mem->lock);3198kfree(mem);3199return 0;3200}32013202/* Returns GPU-specific tiling mode information */3203int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev,3204struct tile_config *config)3205{3206config->gb_addr_config = adev->gfx.config.gb_addr_config;3207config->tile_config_ptr = adev->gfx.config.tile_mode_array;3208config->num_tile_configs =3209ARRAY_SIZE(adev->gfx.config.tile_mode_array);3210config->macro_tile_config_ptr =3211adev->gfx.config.macrotile_mode_array;3212config->num_macro_tile_configs =3213ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);32143215/* Those values are not set from GFX9 onwards */3216config->num_banks = adev->gfx.config.num_banks;3217config->num_ranks = adev->gfx.config.num_ranks;32183219return 0;3220}32213222bool amdgpu_amdkfd_bo_mapped_to_dev(void *drm_priv, struct kgd_mem *mem)3223{3224struct amdgpu_vm *vm = drm_priv_to_vm(drm_priv);3225struct kfd_mem_attachment *entry;32263227list_for_each_entry(entry, &mem->attachments, list) {3228if (entry->is_mapped && entry->bo_va->base.vm == vm)3229return true;3230}3231return false;3232}32333234#if defined(CONFIG_DEBUG_FS)32353236int kfd_debugfs_kfd_mem_limits(struct seq_file *m, void *data)3237{32383239spin_lock(&kfd_mem_limit.mem_limit_lock);3240seq_printf(m, "System mem used %lldM out of %lluM\n",3241(kfd_mem_limit.system_mem_used >> 20),3242(kfd_mem_limit.max_system_mem_limit >> 20));3243seq_printf(m, "TTM mem used %lldM out of %lluM\n",3244(kfd_mem_limit.ttm_mem_used >> 20),3245(kfd_mem_limit.max_ttm_mem_limit >> 20));3246spin_unlock(&kfd_mem_limit.mem_limit_lock);32473248return 0;3249}32503251#endif325232533254