File Index
Files and directories
Sign in
FILE

amdgpu_amdkfd_gpuvm.c

File preview with syntax highlighting.

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