amdgpu_amdkfd_gpuvm.c 80.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Copyright 2014-2018 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
22
#include <linux/dma-buf.h>
23
#include <linux/list.h>
24
#include <linux/pagemap.h>
25
#include <linux/sched/mm.h>
26 27
#include <linux/sched/task.h>

28
#include "amdgpu_object.h"
29
#include "amdgpu_gem.h"
30 31
#include "amdgpu_vm.h"
#include "amdgpu_amdkfd.h"
32
#include "amdgpu_dma_buf.h"
33
#include <uapi/linux/kfd_ioctl.h>
34
#include "amdgpu_xgmi.h"
35
#include "kfd_smi_events.h"
36

37 38 39 40 41
/* Userptr restore delay, just long enough to allow consecutive VM
 * changes to accumulate
 */
#define AMDGPU_USERPTR_RESTORE_DELAY_MS 1

42 43 44 45 46 47
/*
 * Align VRAM allocations to 2MB to avoid fragmentation caused by 4K allocations in the tail 2MB
 * BO chunk
 */
#define VRAM_ALLOCATION_ALIGN (1 << 21)

48 49 50
/* Impose limit on how much memory KFD can use */
static struct {
	uint64_t max_system_mem_limit;
51
	uint64_t max_ttm_mem_limit;
52
	int64_t system_mem_used;
53
	int64_t ttm_mem_used;
54 55 56 57 58 59 60 61 62 63 64 65 66 67
	spinlock_t mem_limit_lock;
} kfd_mem_limit;

static const char * const domain_bit_to_string[] = {
		"CPU",
		"GTT",
		"VRAM",
		"GDS",
		"GWS",
		"OA"
};

#define domain_string(domain) domain_bit_to_string[ffs(domain)-1]

68
static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work);
69

70
static bool kfd_mem_is_attached(struct amdgpu_vm *avm,
71 72
		struct kgd_mem *mem)
{
73
	struct kfd_mem_attachment *entry;
74

75
	list_for_each_entry(entry, &mem->attachments, list)
76
		if (entry->bo_va->base.vm == avm)
77
			return true;
78

79
	return false;
80 81 82
}

/* Set memory usage limits. Current, limits are
83
 *  System (TTM + userptr) memory - 15/16th System RAM
84
 *  TTM memory - 3/8th System RAM
85 86 87 88 89 90 91
 */
void amdgpu_amdkfd_gpuvm_init_mem_limits(void)
{
	struct sysinfo si;
	uint64_t mem;

	si_meminfo(&si);
92
	mem = si.freeram - si.freehigh;
93 94 95
	mem *= si.mem_unit;

	spin_lock_init(&kfd_mem_limit.mem_limit_lock);
96
	kfd_mem_limit.max_system_mem_limit = mem - (mem >> 4);
97 98
	kfd_mem_limit.max_ttm_mem_limit = (mem >> 1) - (mem >> 3);
	pr_debug("Kernel memory limit %lluM, TTM limit %lluM\n",
99
		(kfd_mem_limit.max_system_mem_limit >> 20),
100
		(kfd_mem_limit.max_ttm_mem_limit >> 20));
101 102
}

103 104 105 106 107
void amdgpu_amdkfd_reserve_system_mem(uint64_t size)
{
	kfd_mem_limit.system_mem_used += size;
}

108 109 110 111 112 113 114 115 116 117
/* Estimate page table size needed to represent a given memory size
 *
 * With 4KB pages, we need one 8 byte PTE for each 4KB of memory
 * (factor 512, >> 9). With 2MB pages, we need one 8 byte PTE for 2MB
 * of memory (factor 256K, >> 18). ROCm user mode tries to optimize
 * for 2MB pages for TLB efficiency. However, small allocations and
 * fragmented system memory still need some 4KB pages. We choose a
 * compromise that should work in most cases without reserving too
 * much memory for page tables unnecessarily (factor 16K, >> 14).
 */
118
#define ESTIMATE_PT_SIZE(mem_size) max(((mem_size) >> 14), AMDGPU_VM_RESERVED_VRAM)
119

120 121 122 123 124 125 126 127 128 129
static size_t amdgpu_amdkfd_acc_size(uint64_t size)
{
	size >>= PAGE_SHIFT;
	size *= sizeof(dma_addr_t) + sizeof(void *);

	return __roundup_pow_of_two(sizeof(struct amdgpu_bo)) +
		__roundup_pow_of_two(sizeof(struct ttm_tt)) +
		PAGE_ALIGN(size);
}

130
/**
131
 * amdgpu_amdkfd_reserve_mem_limit() - Decrease available memory by size
132 133 134 135 136 137 138 139 140
 * of buffer including any reserved for control structures
 *
 * @adev: Device to which allocated BO belongs to
 * @size: Size of buffer, in bytes, encapsulated by B0. This should be
 * equivalent to amdgpu_bo_size(BO)
 * @alloc_flag: Flag used in allocating a BO as noted above
 *
 * Return: returns -ENOMEM in case of error, ZERO otherwise
 */
141
static int amdgpu_amdkfd_reserve_mem_limit(struct amdgpu_device *adev,
142
		uint64_t size, u32 alloc_flag)
143
{
144 145
	uint64_t reserved_for_pt =
		ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);
146
	size_t acc_size, system_mem_needed, ttm_mem_needed, vram_needed;
147 148
	int ret = 0;

149
	acc_size = amdgpu_amdkfd_acc_size(size);
150

151
	vram_needed = 0;
152
	if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
153 154
		system_mem_needed = acc_size + size;
		ttm_mem_needed = acc_size + size;
155 156 157
	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
		system_mem_needed = acc_size;
		ttm_mem_needed = acc_size;
158 159 160 161 162 163 164

		/*
		 * Conservatively round up the allocation requirement to 2 MB
		 * to avoid fragmentation caused by 4K allocations in the tail
		 * 2M BO chunk.
		 */
		vram_needed = ALIGN(size, VRAM_ALLOCATION_ALIGN);
165
	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
166 167
		system_mem_needed = acc_size + size;
		ttm_mem_needed = acc_size;
168 169 170
	} else if (alloc_flag &
		   (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
		    KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
171 172
		system_mem_needed = acc_size;
		ttm_mem_needed = acc_size;
173 174 175
	} else {
		pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
		return -ENOMEM;
176 177
	}

178 179
	spin_lock(&kfd_mem_limit.mem_limit_lock);

180 181 182 183
	if (kfd_mem_limit.system_mem_used + system_mem_needed >
	    kfd_mem_limit.max_system_mem_limit)
		pr_debug("Set no_system_mem_limit=1 if using shared memory\n");

184
	if ((kfd_mem_limit.system_mem_used + system_mem_needed >
185
	     kfd_mem_limit.max_system_mem_limit && !no_system_mem_limit) ||
186 187 188
	    (kfd_mem_limit.ttm_mem_used + ttm_mem_needed >
	     kfd_mem_limit.max_ttm_mem_limit) ||
	    (adev->kfd.vram_used + vram_needed >
189 190 191
	     adev->gmc.real_vram_size -
	     atomic64_read(&adev->vram_pin_size) -
	     reserved_for_pt)) {
192
		ret = -ENOMEM;
193
		goto release;
194
	}
195

196 197 198 199 200 201 202 203
	/* Update memory accounting by decreasing available system
	 * memory, TTM memory and GPU memory as computed above
	 */
	adev->kfd.vram_used += vram_needed;
	kfd_mem_limit.system_mem_used += system_mem_needed;
	kfd_mem_limit.ttm_mem_used += ttm_mem_needed;

release:
204 205 206 207
	spin_unlock(&kfd_mem_limit.mem_limit_lock);
	return ret;
}

208
static void unreserve_mem_limit(struct amdgpu_device *adev,
209
		uint64_t size, u32 alloc_flag)
210 211 212
{
	size_t acc_size;

213
	acc_size = amdgpu_amdkfd_acc_size(size);
214 215

	spin_lock(&kfd_mem_limit.mem_limit_lock);
216 217

	if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
218
		kfd_mem_limit.system_mem_used -= (acc_size + size);
219
		kfd_mem_limit.ttm_mem_used -= (acc_size + size);
220 221 222
	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
		kfd_mem_limit.system_mem_used -= acc_size;
		kfd_mem_limit.ttm_mem_used -= acc_size;
223
		adev->kfd.vram_used -= ALIGN(size, VRAM_ALLOCATION_ALIGN);
224
	} else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
225 226
		kfd_mem_limit.system_mem_used -= (acc_size + size);
		kfd_mem_limit.ttm_mem_used -= acc_size;
227 228 229
	} else if (alloc_flag &
		   (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
		    KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
230
		kfd_mem_limit.system_mem_used -= acc_size;
231
		kfd_mem_limit.ttm_mem_used -= acc_size;
232 233 234
	} else {
		pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag);
		goto release;
235
	}
236 237 238

	WARN_ONCE(adev->kfd.vram_used < 0,
		  "KFD VRAM memory accounting unbalanced");
239
	WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0,
240 241 242
		  "KFD TTM memory accounting unbalanced");
	WARN_ONCE(kfd_mem_limit.system_mem_used < 0,
		  "KFD system memory accounting unbalanced");
243

244
release:
245 246 247
	spin_unlock(&kfd_mem_limit.mem_limit_lock);
}

248
void amdgpu_amdkfd_release_notify(struct amdgpu_bo *bo)
249
{
250
	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
251 252
	u32 alloc_flags = bo->kfd_bo->alloc_flags;
	u64 size = amdgpu_bo_size(bo);
253

254
	unreserve_mem_limit(adev, size, alloc_flags);
255 256

	kfree(bo->kfd_bo);
257 258
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
/**
 * @create_dmamap_sg_bo: Creates a amdgpu_bo object to reflect information
 * about USERPTR or DOOREBELL or MMIO BO.
 * @adev: Device for which dmamap BO is being created
 * @mem: BO of peer device that is being DMA mapped. Provides parameters
 *	 in building the dmamap BO
 * @bo_out: Output parameter updated with handle of dmamap BO
 */
static int
create_dmamap_sg_bo(struct amdgpu_device *adev,
		 struct kgd_mem *mem, struct amdgpu_bo **bo_out)
{
	struct drm_gem_object *gem_obj;
	int ret, align;

	ret = amdgpu_bo_reserve(mem->bo, false);
	if (ret)
		return ret;

	align = 1;
	ret = amdgpu_gem_object_create(adev, mem->bo->tbo.base.size, align,
			AMDGPU_GEM_DOMAIN_CPU, AMDGPU_GEM_CREATE_PREEMPTIBLE,
			ttm_bo_type_sg, mem->bo->tbo.base.resv, &gem_obj);

	amdgpu_bo_unreserve(mem->bo);

	if (ret) {
		pr_err("Error in creating DMA mappable SG BO on domain: %d\n", ret);
		return -EINVAL;
	}

	*bo_out = gem_to_amdgpu_bo(gem_obj);
	(*bo_out)->parent = amdgpu_bo_ref(mem->bo);
	return ret;
}

295
/* amdgpu_amdkfd_remove_eviction_fence - Removes eviction fence from BO's
296 297 298
 *  reservation object.
 *
 * @bo: [IN] Remove eviction fence(s) from this BO
299
 * @ef: [IN] This eviction fence is removed if it
300 301 302 303 304
 *  is present in the shared list.
 *
 * NOTE: Must be called with BO reserved i.e. bo->tbo.resv->lock held.
 */
static int amdgpu_amdkfd_remove_eviction_fence(struct amdgpu_bo *bo,
305
					struct amdgpu_amdkfd_fence *ef)
306
{
307
	struct dma_fence *replacement;
308

309
	if (!ef)
310 311
		return -EINVAL;

312 313
	/* TODO: Instead of block before we should use the fence of the page
	 * table update and TLB flush here directly.
314
	 */
315 316
	replacement = dma_fence_get_stub();
	dma_resv_replace_fences(bo->tbo.base.resv, ef->base.context,
317
				replacement, DMA_RESV_USAGE_READ);
318
	dma_fence_put(replacement);
319 320 321
	return 0;
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
int amdgpu_amdkfd_remove_fence_on_pt_pd_bos(struct amdgpu_bo *bo)
{
	struct amdgpu_bo *root = bo;
	struct amdgpu_vm_bo_base *vm_bo;
	struct amdgpu_vm *vm;
	struct amdkfd_process_info *info;
	struct amdgpu_amdkfd_fence *ef;
	int ret;

	/* we can always get vm_bo from root PD bo.*/
	while (root->parent)
		root = root->parent;

	vm_bo = root->vm_bo;
	if (!vm_bo)
		return 0;

	vm = vm_bo->vm;
	if (!vm)
		return 0;

	info = vm->process_info;
	if (!info || !info->eviction_fence)
		return 0;

	ef = container_of(dma_fence_get(&info->eviction_fence->base),
			struct amdgpu_amdkfd_fence, base);

	BUG_ON(!dma_resv_trylock(bo->tbo.base.resv));
	ret = amdgpu_amdkfd_remove_eviction_fence(bo, ef);
	dma_resv_unlock(bo->tbo.base.resv);

	dma_fence_put(&ef->base);
	return ret;
}

358 359 360 361 362 363 364 365 366 367
static int amdgpu_amdkfd_bo_validate(struct amdgpu_bo *bo, uint32_t domain,
				     bool wait)
{
	struct ttm_operation_ctx ctx = { false, false };
	int ret;

	if (WARN(amdgpu_ttm_tt_get_usermm(bo->tbo.ttm),
		 "Called with userptr BO"))
		return -EINVAL;

368
	amdgpu_bo_placement_from_domain(bo, domain);
369 370 371 372

	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
	if (ret)
		goto validate_fail;
373
	if (wait)
374
		amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
375 376 377 378 379

validate_fail:
	return ret;
}

380
static int amdgpu_amdkfd_validate_vm_bo(void *_unused, struct amdgpu_bo *bo)
381
{
382
	return amdgpu_amdkfd_bo_validate(bo, bo->allowed_domains, false);
383 384 385 386 387 388 389 390 391
}

/* vm_validate_pt_pd_bos - Validate page table and directory BOs
 *
 * Page directories are not updated here because huge page handling
 * during page table updates can invalidate page directory entries
 * again. Page directories are only updated after updating page
 * tables.
 */
392
static int vm_validate_pt_pd_bos(struct amdgpu_vm *vm)
393
{
N
Nirmoy Das 已提交
394
	struct amdgpu_bo *pd = vm->root.bo;
395 396 397
	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
	int ret;

398
	ret = amdgpu_vm_validate_pt_bos(adev, vm, amdgpu_amdkfd_validate_vm_bo, NULL);
399
	if (ret) {
400
		pr_err("failed to validate PT BOs\n");
401 402 403
		return ret;
	}

N
Nirmoy Das 已提交
404
	vm->pd_phys_addr = amdgpu_gmc_pd_addr(vm->root.bo);
405 406 407 408 409 410

	return 0;
}

static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync)
{
N
Nirmoy Das 已提交
411
	struct amdgpu_bo *pd = vm->root.bo;
412 413 414
	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
	int ret;

415
	ret = amdgpu_vm_update_pdes(adev, vm, false);
416 417 418
	if (ret)
		return ret;

419
	return amdgpu_sync_fence(sync, vm->last_update);
420 421
}

422 423
static uint64_t get_pte_flags(struct amdgpu_device *adev, struct kgd_mem *mem)
{
424
	struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);
425
	bool coherent = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_COHERENT;
426
	bool uncached = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED;
427
	uint32_t mapping_flags;
428 429
	uint64_t pte_flags;
	bool snoop = false;
430 431

	mapping_flags = AMDGPU_VM_PAGE_READABLE;
432
	if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE)
433
		mapping_flags |= AMDGPU_VM_PAGE_WRITEABLE;
434
	if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE)
435 436
		mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE;

437 438
	switch (adev->asic_type) {
	case CHIP_ARCTURUS:
439
		if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
440 441 442 443
			if (bo_adev == adev)
				mapping_flags |= coherent ?
					AMDGPU_VM_MTYPE_CC : AMDGPU_VM_MTYPE_RW;
			else
444 445
				mapping_flags |= coherent ?
					AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
446 447 448 449 450
		} else {
			mapping_flags |= coherent ?
				AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
		}
		break;
451
	case CHIP_ALDEBARAN:
452 453 454 455 456 457
		if (coherent && uncached) {
			if (adev->gmc.xgmi.connected_to_cpu ||
				!(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM))
				snoop = true;
			mapping_flags |= AMDGPU_VM_MTYPE_UC;
		} else if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
458
			if (bo_adev == adev) {
459 460
				mapping_flags |= coherent ?
					AMDGPU_VM_MTYPE_CC : AMDGPU_VM_MTYPE_RW;
461 462 463
				if (adev->gmc.xgmi.connected_to_cpu)
					snoop = true;
			} else {
464 465
				mapping_flags |= coherent ?
					AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
466 467 468 469 470
				if (amdgpu_xgmi_same_hive(adev, bo_adev))
					snoop = true;
			}
		} else {
			snoop = true;
471 472
			mapping_flags |= coherent ?
				AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
473 474
		}
		break;
475 476 477 478
	default:
		mapping_flags |= coherent ?
			AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
	}
479

480 481 482 483
	pte_flags = amdgpu_gem_va_map_flags(adev, mapping_flags);
	pte_flags |= snoop ? AMDGPU_PTE_SNOOPED : 0;

	return pte_flags;
484 485
}

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
/**
 * create_sg_table() - Create an sg_table for a contiguous DMA addr range
 * @addr: The starting address to point to
 * @size: Size of memory area in bytes being pointed to
 *
 * Allocates an instance of sg_table and initializes it to point to memory
 * area specified by input parameters. The address used to build is assumed
 * to be DMA mapped, if needed.
 *
 * DOORBELL or MMIO BOs use only one scatterlist node in their sg_table
 * because they are physically contiguous.
 *
 * Return: Initialized instance of SG Table or NULL
 */
static struct sg_table *create_sg_table(uint64_t addr, uint32_t size)
{
	struct sg_table *sg = kmalloc(sizeof(*sg), GFP_KERNEL);

	if (!sg)
		return NULL;
	if (sg_alloc_table(sg, 1, GFP_KERNEL)) {
		kfree(sg);
		return NULL;
	}
	sg_dma_address(sg->sgl) = addr;
	sg->sgl->length = size;
#ifdef CONFIG_NEED_SG_DMA_LENGTH
	sg->sgl->dma_length = size;
#endif
	return sg;
}

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
static int
kfd_mem_dmamap_userptr(struct kgd_mem *mem,
		       struct kfd_mem_attachment *attachment)
{
	enum dma_data_direction direction =
		mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
	struct ttm_operation_ctx ctx = {.interruptible = true};
	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
	struct amdgpu_device *adev = attachment->adev;
	struct ttm_tt *src_ttm = mem->bo->tbo.ttm;
	struct ttm_tt *ttm = bo->tbo.ttm;
	int ret;

	ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL);
	if (unlikely(!ttm->sg))
		return -ENOMEM;

	if (WARN_ON(ttm->num_pages != src_ttm->num_pages))
		return -EINVAL;

	/* Same sequence as in amdgpu_ttm_tt_pin_userptr */
	ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages,
					ttm->num_pages, 0,
					(u64)ttm->num_pages << PAGE_SHIFT,
					GFP_KERNEL);
	if (unlikely(ret))
		goto free_sg;

	ret = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
	if (unlikely(ret))
		goto release_sg;

	drm_prime_sg_to_dma_addr_array(ttm->sg, ttm->dma_address,
				       ttm->num_pages);

	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
	if (ret)
		goto unmap_sg;

	return 0;

unmap_sg:
	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
release_sg:
	pr_err("DMA map userptr failed: %d\n", ret);
	sg_free_table(ttm->sg);
free_sg:
	kfree(ttm->sg);
	ttm->sg = NULL;
	return ret;
}

572 573 574 575 576 577 578 579 580 581
static int
kfd_mem_dmamap_dmabuf(struct kfd_mem_attachment *attachment)
{
	struct ttm_operation_ctx ctx = {.interruptible = true};
	struct amdgpu_bo *bo = attachment->bo_va->base.bo;

	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
	return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
}

582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
/**
 * kfd_mem_dmamap_sg_bo() - Create DMA mapped sg_table to access DOORBELL or MMIO BO
 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device
 * @attachment: Virtual address attachment of the BO on accessing device
 *
 * An access request from the device that owns DOORBELL does not require DMA mapping.
 * This is because the request doesn't go through PCIe root complex i.e. it instead
 * loops back. The need to DMA map arises only when accessing peer device's DOORBELL
 *
 * In contrast, all access requests for MMIO need to be DMA mapped without regard to
 * device ownership. This is because access requests for MMIO go through PCIe root
 * complex.
 *
 * This is accomplished in two steps:
 *   - Obtain DMA mapped address of DOORBELL or MMIO memory that could be used
 *         in updating requesting device's page table
 *   - Signal TTM to mark memory pointed to by requesting device's BO as GPU
 *         accessible. This allows an update of requesting device's page table
 *         with entries associated with DOOREBELL or MMIO memory
 *
 * This method is invoked in the following contexts:
 *   - Mapping of DOORBELL or MMIO BO of same or peer device
 *   - Validating an evicted DOOREBELL or MMIO BO on device seeking access
 *
 * Return: ZERO if successful, NON-ZERO otherwise
 */
static int
kfd_mem_dmamap_sg_bo(struct kgd_mem *mem,
		     struct kfd_mem_attachment *attachment)
{
	struct ttm_operation_ctx ctx = {.interruptible = true};
	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
	struct amdgpu_device *adev = attachment->adev;
	struct ttm_tt *ttm = bo->tbo.ttm;
	enum dma_data_direction dir;
	dma_addr_t dma_addr;
	bool mmio;
	int ret;

	/* Expect SG Table of dmapmap BO to be NULL */
	mmio = (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP);
	if (unlikely(ttm->sg)) {
		pr_err("SG Table of %d BO for peer device is UNEXPECTEDLY NON-NULL", mmio);
		return -EINVAL;
	}

	dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
			DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
	dma_addr = mem->bo->tbo.sg->sgl->dma_address;
	pr_debug("%d BO size: %d\n", mmio, mem->bo->tbo.sg->sgl->length);
	pr_debug("%d BO address before DMA mapping: %llx\n", mmio, dma_addr);
	dma_addr = dma_map_resource(adev->dev, dma_addr,
			mem->bo->tbo.sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);
	ret = dma_mapping_error(adev->dev, dma_addr);
	if (unlikely(ret))
		return ret;
	pr_debug("%d BO address after DMA mapping: %llx\n", mmio, dma_addr);

	ttm->sg = create_sg_table(dma_addr, mem->bo->tbo.sg->sgl->length);
	if (unlikely(!ttm->sg)) {
		ret = -ENOMEM;
		goto unmap_sg;
	}

	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
	if (unlikely(ret))
		goto free_sg;

	return ret;

free_sg:
	sg_free_table(ttm->sg);
	kfree(ttm->sg);
	ttm->sg = NULL;
unmap_sg:
	dma_unmap_resource(adev->dev, dma_addr, mem->bo->tbo.sg->sgl->length,
			   dir, DMA_ATTR_SKIP_CPU_SYNC);
	return ret;
}

663 664 665 666 667 668 669 670 671
static int
kfd_mem_dmamap_attachment(struct kgd_mem *mem,
			  struct kfd_mem_attachment *attachment)
{
	switch (attachment->type) {
	case KFD_MEM_ATT_SHARED:
		return 0;
	case KFD_MEM_ATT_USERPTR:
		return kfd_mem_dmamap_userptr(mem, attachment);
672 673
	case KFD_MEM_ATT_DMABUF:
		return kfd_mem_dmamap_dmabuf(attachment);
674 675
	case KFD_MEM_ATT_SG:
		return kfd_mem_dmamap_sg_bo(mem, attachment);
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
	default:
		WARN_ON_ONCE(1);
	}
	return -EINVAL;
}

static void
kfd_mem_dmaunmap_userptr(struct kgd_mem *mem,
			 struct kfd_mem_attachment *attachment)
{
	enum dma_data_direction direction =
		mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
	struct ttm_operation_ctx ctx = {.interruptible = false};
	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
	struct amdgpu_device *adev = attachment->adev;
	struct ttm_tt *ttm = bo->tbo.ttm;

	if (unlikely(!ttm->sg))
		return;

	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
	ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);

	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
	sg_free_table(ttm->sg);
702
	kfree(ttm->sg);
703 704 705
	ttm->sg = NULL;
}

706 707 708 709 710 711 712 713 714 715
static void
kfd_mem_dmaunmap_dmabuf(struct kfd_mem_attachment *attachment)
{
	struct ttm_operation_ctx ctx = {.interruptible = true};
	struct amdgpu_bo *bo = attachment->bo_va->base.bo;

	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
	ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
}

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
/**
 * kfd_mem_dmaunmap_sg_bo() - Free DMA mapped sg_table of DOORBELL or MMIO BO
 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device
 * @attachment: Virtual address attachment of the BO on accessing device
 *
 * The method performs following steps:
 *   - Signal TTM to mark memory pointed to by BO as GPU inaccessible
 *   - Free SG Table that is used to encapsulate DMA mapped memory of
 *          peer device's DOORBELL or MMIO memory
 *
 * This method is invoked in the following contexts:
 *     UNMapping of DOORBELL or MMIO BO on a device having access to its memory
 *     Eviction of DOOREBELL or MMIO BO on device having access to its memory
 *
 * Return: void
 */
static void
kfd_mem_dmaunmap_sg_bo(struct kgd_mem *mem,
		       struct kfd_mem_attachment *attachment)
{
	struct ttm_operation_ctx ctx = {.interruptible = true};
	struct amdgpu_bo *bo = attachment->bo_va->base.bo;
	struct amdgpu_device *adev = attachment->adev;
	struct ttm_tt *ttm = bo->tbo.ttm;
	enum dma_data_direction dir;

	if (unlikely(!ttm->sg)) {
		pr_err("SG Table of BO is UNEXPECTEDLY NULL");
		return;
	}

	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
	ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);

	dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
				DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
	dma_unmap_resource(adev->dev, ttm->sg->sgl->dma_address,
			ttm->sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC);
	sg_free_table(ttm->sg);
	kfree(ttm->sg);
	ttm->sg = NULL;
	bo->tbo.sg = NULL;
}

760 761 762 763 764 765 766 767 768 769
static void
kfd_mem_dmaunmap_attachment(struct kgd_mem *mem,
			    struct kfd_mem_attachment *attachment)
{
	switch (attachment->type) {
	case KFD_MEM_ATT_SHARED:
		break;
	case KFD_MEM_ATT_USERPTR:
		kfd_mem_dmaunmap_userptr(mem, attachment);
		break;
770 771 772
	case KFD_MEM_ATT_DMABUF:
		kfd_mem_dmaunmap_dmabuf(attachment);
		break;
773 774 775
	case KFD_MEM_ATT_SG:
		kfd_mem_dmaunmap_sg_bo(mem, attachment);
		break;
776 777 778 779 780
	default:
		WARN_ON_ONCE(1);
	}
}

781 782 783 784 785
static int
kfd_mem_attach_dmabuf(struct amdgpu_device *adev, struct kgd_mem *mem,
		      struct amdgpu_bo **bo)
{
	struct drm_gem_object *gobj;
786
	int ret;
787 788 789 790 791 792

	if (!mem->dmabuf) {
		mem->dmabuf = amdgpu_gem_prime_export(&mem->bo->tbo.base,
			mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ?
				DRM_RDWR : 0);
		if (IS_ERR(mem->dmabuf)) {
793
			ret = PTR_ERR(mem->dmabuf);
794
			mem->dmabuf = NULL;
795
			return ret;
796 797 798
		}
	}

799
	gobj = amdgpu_gem_prime_import(adev_to_drm(adev), mem->dmabuf);
800 801 802 803
	if (IS_ERR(gobj))
		return PTR_ERR(gobj);

	*bo = gem_to_amdgpu_bo(gobj);
804
	(*bo)->flags |= AMDGPU_GEM_CREATE_PREEMPTIBLE;
805 806 807 808 809
	(*bo)->parent = amdgpu_bo_ref(mem->bo);

	return 0;
}

810
/* kfd_mem_attach - Add a BO to a VM
811 812 813 814 815
 *
 * Everything that needs to bo done only once when a BO is first added
 * to a VM. It can later be mapped and unmapped many times without
 * repeating these steps.
 *
816
 * 0. Create BO for DMA mapping, if needed
817 818 819 820 821 822
 * 1. Allocate and initialize BO VA entry data structure
 * 2. Add BO to the VM
 * 3. Determine ASIC-specific PTE flags
 * 4. Alloc page tables and directories if needed
 * 4a.  Validate new page tables and directories
 */
823
static int kfd_mem_attach(struct amdgpu_device *adev, struct kgd_mem *mem,
824
		struct amdgpu_vm *vm, bool is_aql)
825
{
826
	struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev);
827
	unsigned long bo_size = mem->bo->tbo.base.size;
828
	uint64_t va = mem->va;
829 830
	struct kfd_mem_attachment *attachment[2] = {NULL, NULL};
	struct amdgpu_bo *bo[2] = {NULL, NULL};
831
	bool same_hive = false;
832
	int i, ret;
833 834 835 836 837 838

	if (!va) {
		pr_err("Invalid VA when adding BO to VM\n");
		return -EINVAL;
	}

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
	/* Determine access to VRAM, MMIO and DOORBELL BOs of peer devices
	 *
	 * The access path of MMIO and DOORBELL BOs of is always over PCIe.
	 * In contrast the access path of VRAM BOs depens upon the type of
	 * link that connects the peer device. Access over PCIe is allowed
	 * if peer device has large BAR. In contrast, access over xGMI is
	 * allowed for both small and large BAR configurations of peer device
	 */
	if ((adev != bo_adev) &&
	    ((mem->domain == AMDGPU_GEM_DOMAIN_VRAM) ||
	     (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) ||
	     (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) {
		if (mem->domain == AMDGPU_GEM_DOMAIN_VRAM)
			same_hive = amdgpu_xgmi_same_hive(adev, bo_adev);
		if (!same_hive && !amdgpu_device_is_peer_accessible(bo_adev, adev))
			return -EINVAL;
	}

857 858 859 860 861 862
	for (i = 0; i <= is_aql; i++) {
		attachment[i] = kzalloc(sizeof(*attachment[i]), GFP_KERNEL);
		if (unlikely(!attachment[i])) {
			ret = -ENOMEM;
			goto unwind;
		}
863

864 865
		pr_debug("\t add VA 0x%llx - 0x%llx to vm %p\n", va,
			 va + bo_size, vm);
866

867 868 869
		if ((adev == bo_adev && !(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) ||
		    (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) && adev->ram_is_direct_mapped) ||
		    same_hive) {
870 871 872
			/* Mappings on the local GPU, or VRAM mappings in the
			 * local hive, or userptr mapping IOMMU direct map mode
			 * share the original BO
873 874 875 876 877 878 879 880 881 882 883 884
			 */
			attachment[i]->type = KFD_MEM_ATT_SHARED;
			bo[i] = mem->bo;
			drm_gem_object_get(&bo[i]->tbo.base);
		} else if (i > 0) {
			/* Multiple mappings on the same GPU share the BO */
			attachment[i]->type = KFD_MEM_ATT_SHARED;
			bo[i] = bo[0];
			drm_gem_object_get(&bo[i]->tbo.base);
		} else if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) {
			/* Create an SG BO to DMA-map userptrs on other GPUs */
			attachment[i]->type = KFD_MEM_ATT_USERPTR;
885
			ret = create_dmamap_sg_bo(adev, mem, &bo[i]);
886 887
			if (ret)
				goto unwind;
888 889 890 891 892 893 894 895 896 897 898 899
		/* Handle DOORBELL BOs of peer devices and MMIO BOs of local and peer devices */
		} else if (mem->bo->tbo.type == ttm_bo_type_sg) {
			WARN_ONCE(!(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL ||
				    mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP),
				  "Handing invalid SG BO in ATTACH request");
			attachment[i]->type = KFD_MEM_ATT_SG;
			ret = create_dmamap_sg_bo(adev, mem, &bo[i]);
			if (ret)
				goto unwind;
		/* Enable acces to GTT and VRAM BOs of peer devices */
		} else if (mem->domain == AMDGPU_GEM_DOMAIN_GTT ||
			   mem->domain == AMDGPU_GEM_DOMAIN_VRAM) {
900 901 902 903
			attachment[i]->type = KFD_MEM_ATT_DMABUF;
			ret = kfd_mem_attach_dmabuf(adev, mem, &bo[i]);
			if (ret)
				goto unwind;
904
			pr_debug("Employ DMABUF mechanism to enable peer GPU access\n");
905
		} else {
906 907 908
			WARN_ONCE(true, "Handling invalid ATTACH request");
			ret = -EINVAL;
			goto unwind;
909
		}
910

911
		/* Add BO to VM internal data structures */
912 913 914 915 916
		ret = amdgpu_bo_reserve(bo[i], false);
		if (ret) {
			pr_debug("Unable to reserve BO during memory attach");
			goto unwind;
		}
917
		attachment[i]->bo_va = amdgpu_vm_bo_add(adev, vm, bo[i]);
918
		amdgpu_bo_unreserve(bo[i]);
919 920 921 922 923 924 925 926 927 928
		if (unlikely(!attachment[i]->bo_va)) {
			ret = -ENOMEM;
			pr_err("Failed to add BO object to VM. ret == %d\n",
			       ret);
			goto unwind;
		}
		attachment[i]->va = va;
		attachment[i]->pte_flags = get_pte_flags(adev, mem);
		attachment[i]->adev = adev;
		list_add(&attachment[i]->list, &mem->attachments);
929

930 931
		va += bo_size;
	}
932 933 934

	return 0;

935 936 937 938 939
unwind:
	for (; i >= 0; i--) {
		if (!attachment[i])
			continue;
		if (attachment[i]->bo_va) {
940
			amdgpu_bo_reserve(bo[i], true);
941
			amdgpu_vm_bo_del(adev, attachment[i]->bo_va);
942
			amdgpu_bo_unreserve(bo[i]);
943 944 945 946 947 948
			list_del(&attachment[i]->list);
		}
		if (bo[i])
			drm_gem_object_put(&bo[i]->tbo.base);
		kfree(attachment[i]);
	}
949 950 951
	return ret;
}

952
static void kfd_mem_detach(struct kfd_mem_attachment *attachment)
953
{
954 955
	struct amdgpu_bo *bo = attachment->bo_va->base.bo;

956 957
	pr_debug("\t remove VA 0x%llx in entry %p\n",
			attachment->va, attachment);
958
	amdgpu_vm_bo_del(attachment->adev, attachment->bo_va);
959
	drm_gem_object_put(&bo->tbo.base);
960 961
	list_del(&attachment->list);
	kfree(attachment);
962 963 964
}

static void add_kgd_mem_to_kfd_bo_list(struct kgd_mem *mem,
965 966
				struct amdkfd_process_info *process_info,
				bool userptr)
967 968 969 970 971
{
	struct ttm_validate_buffer *entry = &mem->validate_list;
	struct amdgpu_bo *bo = mem->bo;

	INIT_LIST_HEAD(&entry->head);
972
	entry->num_shared = 1;
973 974
	entry->bo = &bo->tbo;
	mutex_lock(&process_info->lock);
975 976 977 978
	if (userptr)
		list_add_tail(&entry->head, &process_info->userptr_valid_list);
	else
		list_add_tail(&entry->head, &process_info->kfd_bo_list);
979 980 981
	mutex_unlock(&process_info->lock);
}

982 983 984 985 986 987 988 989 990 991 992
static void remove_kgd_mem_from_kfd_bo_list(struct kgd_mem *mem,
		struct amdkfd_process_info *process_info)
{
	struct ttm_validate_buffer *bo_list_entry;

	bo_list_entry = &mem->validate_list;
	mutex_lock(&process_info->lock);
	list_del(&bo_list_entry->head);
	mutex_unlock(&process_info->lock);
}

993 994 995 996 997 998 999 1000 1001 1002 1003 1004
/* Initializes user pages. It registers the MMU notifier and validates
 * the userptr BO in the GTT domain.
 *
 * The BO must already be on the userptr_valid_list. Otherwise an
 * eviction and restore may happen that leaves the new BO unmapped
 * with the user mode queues running.
 *
 * Takes the process_info->lock to protect against concurrent restore
 * workers.
 *
 * Returns 0 for success, negative errno for errors.
 */
1005 1006
static int init_user_pages(struct kgd_mem *mem, uint64_t user_addr,
			   bool criu_resume)
1007 1008 1009 1010 1011 1012 1013 1014
{
	struct amdkfd_process_info *process_info = mem->process_info;
	struct amdgpu_bo *bo = mem->bo;
	struct ttm_operation_ctx ctx = { true, false };
	int ret = 0;

	mutex_lock(&process_info->lock);

1015
	ret = amdgpu_ttm_tt_set_userptr(&bo->tbo, user_addr, 0);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
	if (ret) {
		pr_err("%s: Failed to set userptr: %d\n", __func__, ret);
		goto out;
	}

	ret = amdgpu_mn_register(bo, user_addr);
	if (ret) {
		pr_err("%s: Failed to register MMU notifier: %d\n",
		       __func__, ret);
		goto out;
	}

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
	if (criu_resume) {
		/*
		 * During a CRIU restore operation, the userptr buffer objects
		 * will be validated in the restore_userptr_work worker at a
		 * later stage when it is scheduled by another ioctl called by
		 * CRIU master process for the target pid for restore.
		 */
		atomic_inc(&mem->invalid);
		mutex_unlock(&process_info->lock);
		return 0;
	}

1040
	ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages);
1041 1042
	if (ret) {
		pr_err("%s: Failed to get user pages: %d\n", __func__, ret);
1043
		goto unregister_out;
1044 1045 1046 1047 1048 1049 1050
	}

	ret = amdgpu_bo_reserve(bo, true);
	if (ret) {
		pr_err("%s: Failed to reserve BO\n", __func__);
		goto release_out;
	}
1051
	amdgpu_bo_placement_from_domain(bo, mem->domain);
1052 1053 1054 1055 1056 1057
	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
	if (ret)
		pr_err("%s: failed to validate BO\n", __func__);
	amdgpu_bo_unreserve(bo);

release_out:
1058
	amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm);
1059 1060 1061 1062 1063 1064 1065 1066
unregister_out:
	if (ret)
		amdgpu_mn_unregister(bo);
out:
	mutex_unlock(&process_info->lock);
	return ret;
}

1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
/* Reserving a BO and its page table BOs must happen atomically to
 * avoid deadlocks. Some operations update multiple VMs at once. Track
 * all the reservation info in a context structure. Optionally a sync
 * object can track VM updates.
 */
struct bo_vm_reservation_context {
	struct amdgpu_bo_list_entry kfd_bo; /* BO list entry for the KFD BO */
	unsigned int n_vms;		    /* Number of VMs reserved	    */
	struct amdgpu_bo_list_entry *vm_pd; /* Array of VM BO list entries  */
	struct ww_acquire_ctx ticket;	    /* Reservation ticket	    */
	struct list_head list, duplicates;  /* BO lists			    */
	struct amdgpu_sync *sync;	    /* Pointer to sync object	    */
	bool reserved;			    /* Whether BOs are reserved	    */
};

enum bo_vm_match {
	BO_VM_NOT_MAPPED = 0,	/* Match VMs where a BO is not mapped */
	BO_VM_MAPPED,		/* Match VMs where a BO is mapped     */
	BO_VM_ALL,		/* Match all VMs a BO was added to    */
};

/**
 * reserve_bo_and_vm - reserve a BO and a VM unconditionally.
 * @mem: KFD BO structure.
 * @vm: the VM to reserve.
 * @ctx: the struct that will be used in unreserve_bo_and_vms().
 */
static int reserve_bo_and_vm(struct kgd_mem *mem,
			      struct amdgpu_vm *vm,
			      struct bo_vm_reservation_context *ctx)
{
	struct amdgpu_bo *bo = mem->bo;
	int ret;

	WARN_ON(!vm);

	ctx->reserved = false;
	ctx->n_vms = 1;
	ctx->sync = &mem->sync;

	INIT_LIST_HEAD(&ctx->list);
	INIT_LIST_HEAD(&ctx->duplicates);

	ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd), GFP_KERNEL);
	if (!ctx->vm_pd)
		return -ENOMEM;

	ctx->kfd_bo.priority = 0;
	ctx->kfd_bo.tv.bo = &bo->tbo;
1116
	ctx->kfd_bo.tv.num_shared = 1;
1117 1118 1119 1120 1121
	list_add(&ctx->kfd_bo.tv.head, &ctx->list);

	amdgpu_vm_get_pd_bo(vm, &ctx->list, &ctx->vm_pd[0]);

	ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
1122
				     false, &ctx->duplicates);
1123 1124
	if (ret) {
		pr_err("Failed to reserve buffers in ttm.\n");
1125 1126
		kfree(ctx->vm_pd);
		ctx->vm_pd = NULL;
1127
		return ret;
1128 1129
	}

1130 1131
	ctx->reserved = true;
	return 0;
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
}

/**
 * reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally
 * @mem: KFD BO structure.
 * @vm: the VM to reserve. If NULL, then all VMs associated with the BO
 * is used. Otherwise, a single VM associated with the BO.
 * @map_type: the mapping status that will be used to filter the VMs.
 * @ctx: the struct that will be used in unreserve_bo_and_vms().
 *
 * Returns 0 for success, negative for failure.
 */
static int reserve_bo_and_cond_vms(struct kgd_mem *mem,
				struct amdgpu_vm *vm, enum bo_vm_match map_type,
				struct bo_vm_reservation_context *ctx)
{
	struct amdgpu_bo *bo = mem->bo;
1149
	struct kfd_mem_attachment *entry;
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	unsigned int i;
	int ret;

	ctx->reserved = false;
	ctx->n_vms = 0;
	ctx->vm_pd = NULL;
	ctx->sync = &mem->sync;

	INIT_LIST_HEAD(&ctx->list);
	INIT_LIST_HEAD(&ctx->duplicates);

1161
	list_for_each_entry(entry, &mem->attachments, list) {
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
		if ((vm && vm != entry->bo_va->base.vm) ||
			(entry->is_mapped != map_type
			&& map_type != BO_VM_ALL))
			continue;

		ctx->n_vms++;
	}

	if (ctx->n_vms != 0) {
		ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd),
				     GFP_KERNEL);
		if (!ctx->vm_pd)
			return -ENOMEM;
	}

	ctx->kfd_bo.priority = 0;
	ctx->kfd_bo.tv.bo = &bo->tbo;
1179
	ctx->kfd_bo.tv.num_shared = 1;
1180 1181 1182
	list_add(&ctx->kfd_bo.tv.head, &ctx->list);

	i = 0;
1183
	list_for_each_entry(entry, &mem->attachments, list) {
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
		if ((vm && vm != entry->bo_va->base.vm) ||
			(entry->is_mapped != map_type
			&& map_type != BO_VM_ALL))
			continue;

		amdgpu_vm_get_pd_bo(entry->bo_va->base.vm, &ctx->list,
				&ctx->vm_pd[i]);
		i++;
	}

	ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
1195
				     false, &ctx->duplicates);
1196
	if (ret) {
1197
		pr_err("Failed to reserve buffers in ttm.\n");
1198 1199
		kfree(ctx->vm_pd);
		ctx->vm_pd = NULL;
1200
		return ret;
1201 1202
	}

1203 1204
	ctx->reserved = true;
	return 0;
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
}

/**
 * unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context
 * @ctx: Reservation context to unreserve
 * @wait: Optionally wait for a sync object representing pending VM updates
 * @intr: Whether the wait is interruptible
 *
 * Also frees any resources allocated in
 * reserve_bo_and_(cond_)vm(s). Returns the status from
 * amdgpu_sync_wait.
 */
static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx,
				 bool wait, bool intr)
{
	int ret = 0;

	if (wait)
		ret = amdgpu_sync_wait(ctx->sync, intr);

	if (ctx->reserved)
		ttm_eu_backoff_reservation(&ctx->ticket, &ctx->list);
	kfree(ctx->vm_pd);

	ctx->sync = NULL;

	ctx->reserved = false;
	ctx->vm_pd = NULL;

	return ret;
}

1237
static void unmap_bo_from_gpuvm(struct kgd_mem *mem,
1238
				struct kfd_mem_attachment *entry,
1239 1240 1241
				struct amdgpu_sync *sync)
{
	struct amdgpu_bo_va *bo_va = entry->bo_va;
1242
	struct amdgpu_device *adev = entry->adev;
1243 1244 1245 1246 1247 1248
	struct amdgpu_vm *vm = bo_va->base.vm;

	amdgpu_vm_bo_unmap(adev, bo_va, entry->va);

	amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update);

1249
	amdgpu_sync_fence(sync, bo_va->last_pt_update);
1250

1251
	kfd_mem_dmaunmap_attachment(mem, entry);
1252 1253
}

1254 1255
static int update_gpuvm_pte(struct kgd_mem *mem,
			    struct kfd_mem_attachment *entry,
1256
			    struct amdgpu_sync *sync)
1257
{
1258
	struct amdgpu_bo_va *bo_va = entry->bo_va;
1259 1260 1261 1262 1263 1264
	struct amdgpu_device *adev = entry->adev;
	int ret;

	ret = kfd_mem_dmamap_attachment(mem, entry);
	if (ret)
		return ret;
1265 1266

	/* Update the page tables  */
1267
	ret = amdgpu_vm_bo_update(adev, bo_va, false);
1268 1269 1270 1271 1272
	if (ret) {
		pr_err("amdgpu_vm_bo_update failed\n");
		return ret;
	}

1273
	return amdgpu_sync_fence(sync, bo_va->last_pt_update);
1274 1275
}

1276 1277 1278
static int map_bo_to_gpuvm(struct kgd_mem *mem,
			   struct kfd_mem_attachment *entry,
			   struct amdgpu_sync *sync,
1279
			   bool no_update_pte)
1280 1281 1282 1283
{
	int ret;

	/* Set virtual address for the allocation */
1284
	ret = amdgpu_vm_bo_map(entry->adev, entry->bo_va, entry->va, 0,
1285 1286 1287 1288 1289 1290 1291 1292
			       amdgpu_bo_size(entry->bo_va->base.bo),
			       entry->pte_flags);
	if (ret) {
		pr_err("Failed to map VA 0x%llx in vm. ret %d\n",
				entry->va, ret);
		return ret;
	}

1293 1294 1295
	if (no_update_pte)
		return 0;

1296
	ret = update_gpuvm_pte(mem, entry, sync);
1297 1298 1299 1300 1301 1302 1303 1304
	if (ret) {
		pr_err("update_gpuvm_pte() failed\n");
		goto update_gpuvm_pte_failed;
	}

	return 0;

update_gpuvm_pte_failed:
1305
	unmap_bo_from_gpuvm(mem, entry, sync);
1306 1307 1308 1309 1310
	return ret;
}

static int process_validate_vms(struct amdkfd_process_info *process_info)
{
1311
	struct amdgpu_vm *peer_vm;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
	int ret;

	list_for_each_entry(peer_vm, &process_info->vm_list_head,
			    vm_list_node) {
		ret = vm_validate_pt_pd_bos(peer_vm);
		if (ret)
			return ret;
	}

	return 0;
}

1324 1325 1326 1327 1328 1329 1330 1331
static int process_sync_pds_resv(struct amdkfd_process_info *process_info,
				 struct amdgpu_sync *sync)
{
	struct amdgpu_vm *peer_vm;
	int ret;

	list_for_each_entry(peer_vm, &process_info->vm_list_head,
			    vm_list_node) {
N
Nirmoy Das 已提交
1332
		struct amdgpu_bo *pd = peer_vm->root.bo;
1333

1334 1335 1336
		ret = amdgpu_sync_resv(NULL, sync, pd->tbo.base.resv,
				       AMDGPU_SYNC_NE_OWNER,
				       AMDGPU_FENCE_OWNER_KFD);
1337 1338 1339 1340 1341 1342 1343
		if (ret)
			return ret;
	}

	return 0;
}

1344 1345 1346
static int process_update_pds(struct amdkfd_process_info *process_info,
			      struct amdgpu_sync *sync)
{
1347
	struct amdgpu_vm *peer_vm;
1348 1349 1350 1351
	int ret;

	list_for_each_entry(peer_vm, &process_info->vm_list_head,
			    vm_list_node) {
1352
		ret = vm_update_pds(peer_vm, sync);
1353 1354 1355 1356 1357 1358 1359
		if (ret)
			return ret;
	}

	return 0;
}

1360 1361
static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info,
		       struct dma_fence **ef)
1362
{
1363
	struct amdkfd_process_info *info = NULL;
1364
	int ret;
1365 1366 1367

	if (!*process_info) {
		info = kzalloc(sizeof(*info), GFP_KERNEL);
1368 1369
		if (!info)
			return -ENOMEM;
1370 1371 1372 1373

		mutex_init(&info->lock);
		INIT_LIST_HEAD(&info->vm_list_head);
		INIT_LIST_HEAD(&info->kfd_bo_list);
1374 1375
		INIT_LIST_HEAD(&info->userptr_valid_list);
		INIT_LIST_HEAD(&info->userptr_inval_list);
1376 1377 1378

		info->eviction_fence =
			amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),
1379 1380
						   current->mm,
						   NULL);
1381 1382
		if (!info->eviction_fence) {
			pr_err("Failed to create eviction fence\n");
1383
			ret = -ENOMEM;
1384 1385 1386
			goto create_evict_fence_fail;
		}

1387 1388 1389 1390 1391
		info->pid = get_task_pid(current->group_leader, PIDTYPE_PID);
		atomic_set(&info->evicted_bos, 0);
		INIT_DELAYED_WORK(&info->restore_userptr_work,
				  amdgpu_amdkfd_restore_userptr_worker);

1392 1393 1394 1395
		*process_info = info;
		*ef = dma_fence_get(&info->eviction_fence->base);
	}

1396
	vm->process_info = *process_info;
1397

1398
	/* Validate page directory and attach eviction fence */
N
Nirmoy Das 已提交
1399
	ret = amdgpu_bo_reserve(vm->root.bo, true);
1400 1401
	if (ret)
		goto reserve_pd_fail;
1402
	ret = vm_validate_pt_pd_bos(vm);
1403 1404 1405 1406
	if (ret) {
		pr_err("validate_pt_pd_bos() failed\n");
		goto validate_pd_fail;
	}
N
Nirmoy Das 已提交
1407
	ret = amdgpu_bo_sync_wait(vm->root.bo,
1408
				  AMDGPU_FENCE_OWNER_KFD, false);
1409 1410
	if (ret)
		goto wait_pd_fail;
1411
	ret = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, 1);
1412 1413
	if (ret)
		goto reserve_shared_fail;
N
Nirmoy Das 已提交
1414
	amdgpu_bo_fence(vm->root.bo,
1415
			&vm->process_info->eviction_fence->base, true);
N
Nirmoy Das 已提交
1416
	amdgpu_bo_unreserve(vm->root.bo);
1417 1418

	/* Update process info */
1419 1420 1421 1422 1423
	mutex_lock(&vm->process_info->lock);
	list_add_tail(&vm->vm_list_node,
			&(vm->process_info->vm_list_head));
	vm->process_info->n_vms++;
	mutex_unlock(&vm->process_info->lock);
1424

1425
	return 0;
1426

1427
reserve_shared_fail:
1428 1429
wait_pd_fail:
validate_pd_fail:
N
Nirmoy Das 已提交
1430
	amdgpu_bo_unreserve(vm->root.bo);
1431
reserve_pd_fail:
1432 1433 1434 1435 1436 1437 1438
	vm->process_info = NULL;
	if (info) {
		/* Two fence references: one in info and one in *ef */
		dma_fence_put(&info->eviction_fence->base);
		dma_fence_put(*ef);
		*ef = NULL;
		*process_info = NULL;
1439
		put_pid(info->pid);
1440
create_evict_fence_fail:
1441 1442 1443 1444 1445 1446
		mutex_destroy(&info->lock);
		kfree(info);
	}
	return ret;
}

1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
/**
 * amdgpu_amdkfd_gpuvm_pin_bo() - Pins a BO using following criteria
 * @bo: Handle of buffer object being pinned
 * @domain: Domain into which BO should be pinned
 *
 *   - USERPTR BOs are UNPINNABLE and will return error
 *   - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
 *     PIN count incremented. It is valid to PIN a BO multiple times
 *
 * Return: ZERO if successful in pinning, Non-Zero in case of error.
 */
static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain)
{
	int ret = 0;

	ret = amdgpu_bo_reserve(bo, false);
	if (unlikely(ret))
		return ret;

	ret = amdgpu_bo_pin_restricted(bo, domain, 0, 0);
	if (ret)
		pr_err("Error in Pinning BO to domain: %d\n", domain);

	amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
	amdgpu_bo_unreserve(bo);

	return ret;
}

/**
 * amdgpu_amdkfd_gpuvm_unpin_bo() - Unpins BO using following criteria
 * @bo: Handle of buffer object being unpinned
 *
 *   - Is a illegal request for USERPTR BOs and is ignored
 *   - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their
 *     PIN count decremented. Calls to UNPIN must balance calls to PIN
 */
1484
static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo)
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
{
	int ret = 0;

	ret = amdgpu_bo_reserve(bo, false);
	if (unlikely(ret))
		return;

	amdgpu_bo_unpin(bo);
	amdgpu_bo_unreserve(bo);
}

1496
int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct amdgpu_device *adev,
1497
					   struct file *filp, u32 pasid,
1498
					   void **process_info,
1499
					   struct dma_fence **ef)
1500
{
1501 1502
	struct amdgpu_fpriv *drv_priv;
	struct amdgpu_vm *avm;
1503
	int ret;
1504

1505 1506 1507 1508 1509
	ret = amdgpu_file_to_fpriv(filp, &drv_priv);
	if (ret)
		return ret;
	avm = &drv_priv->vm;

1510 1511 1512 1513
	/* Already a compute VM? */
	if (avm->process_info)
		return -EINVAL;

1514 1515 1516 1517 1518 1519 1520 1521
	/* Free the original amdgpu allocated pasid,
	 * will be replaced with kfd allocated pasid.
	 */
	if (avm->pasid) {
		amdgpu_pasid_free(avm->pasid);
		amdgpu_vm_set_pasid(adev, avm, 0);
	}

1522
	/* Convert VM into a compute VM */
1523
	ret = amdgpu_vm_make_compute(adev, avm);
1524 1525 1526
	if (ret)
		return ret;

1527 1528 1529
	ret = amdgpu_vm_set_pasid(adev, avm, pasid);
	if (ret)
		return ret;
1530 1531 1532 1533 1534
	/* Initialize KFD part of the VM and process info */
	ret = init_kfd_vm(avm, process_info, ef);
	if (ret)
		return ret;

1535
	amdgpu_vm_set_task_info(avm);
1536 1537 1538 1539 1540 1541 1542 1543

	return 0;
}

void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,
				    struct amdgpu_vm *vm)
{
	struct amdkfd_process_info *process_info = vm->process_info;
N
Nirmoy Das 已提交
1544
	struct amdgpu_bo *pd = vm->root.bo;
1545 1546

	if (!process_info)
1547 1548 1549 1550 1551 1552 1553
		return;

	/* Release eviction fence from PD */
	amdgpu_bo_reserve(pd, false);
	amdgpu_bo_fence(pd, NULL, false);
	amdgpu_bo_unreserve(pd);

1554
	/* Update process info */
1555 1556
	mutex_lock(&process_info->lock);
	process_info->n_vms--;
1557
	list_del(&vm->vm_list_node);
1558 1559
	mutex_unlock(&process_info->lock);

1560 1561
	vm->process_info = NULL;

1562
	/* Release per-process resources when last compute VM is destroyed */
1563 1564
	if (!process_info->n_vms) {
		WARN_ON(!list_empty(&process_info->kfd_bo_list));
1565 1566
		WARN_ON(!list_empty(&process_info->userptr_valid_list));
		WARN_ON(!list_empty(&process_info->userptr_inval_list));
1567 1568

		dma_fence_put(&process_info->eviction_fence->base);
1569 1570
		cancel_delayed_work_sync(&process_info->restore_userptr_work);
		put_pid(process_info->pid);
1571 1572 1573
		mutex_destroy(&process_info->lock);
		kfree(process_info);
	}
1574 1575
}

1576 1577
void amdgpu_amdkfd_gpuvm_release_process_vm(struct amdgpu_device *adev,
					    void *drm_priv)
1578
{
1579
	struct amdgpu_vm *avm;
1580

1581
	if (WARN_ON(!adev || !drm_priv))
1582
		return;
1583

1584 1585 1586
	avm = drm_priv_to_vm(drm_priv);

	pr_debug("Releasing process vm %p\n", avm);
1587

1588 1589 1590 1591 1592 1593
	/* The original pasid of amdgpu vm has already been
	 * released during making a amdgpu vm to a compute vm
	 * The current pasid is managed by kfd and will be
	 * released on kfd process destroy. Set amdgpu pasid
	 * to 0 to avoid duplicate release.
	 */
1594 1595 1596
	amdgpu_vm_release_compute(adev, avm);
}

1597
uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv)
1598
{
1599
	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
N
Nirmoy Das 已提交
1600
	struct amdgpu_bo *pd = avm->root.bo;
1601
	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
1602

1603 1604 1605
	if (adev->asic_type < CHIP_VEGA10)
		return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT;
	return avm->pd_phys_addr;
1606 1607
}

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
void amdgpu_amdkfd_block_mmu_notifications(void *p)
{
	struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;

	mutex_lock(&pinfo->lock);
	WRITE_ONCE(pinfo->block_mmu_notifications, true);
	mutex_unlock(&pinfo->lock);
}

int amdgpu_amdkfd_criu_resume(void *p)
{
	int ret = 0;
	struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p;

	mutex_lock(&pinfo->lock);
	pr_debug("scheduling work\n");
	atomic_inc(&pinfo->evicted_bos);
	if (!READ_ONCE(pinfo->block_mmu_notifications)) {
		ret = -EINVAL;
		goto out_unlock;
	}
	WRITE_ONCE(pinfo->block_mmu_notifications, false);
	schedule_delayed_work(&pinfo->restore_userptr_work, 0);

out_unlock:
	mutex_unlock(&pinfo->lock);
	return ret;
}

1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
size_t amdgpu_amdkfd_get_available_memory(struct amdgpu_device *adev)
{
	uint64_t reserved_for_pt =
		ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size);
	size_t available;

	spin_lock(&kfd_mem_limit.mem_limit_lock);
	available = adev->gmc.real_vram_size
		- adev->kfd.vram_used
		- atomic64_read(&adev->vram_pin_size)
		- reserved_for_pt;
	spin_unlock(&kfd_mem_limit.mem_limit_lock);

	return ALIGN_DOWN(available, VRAM_ALLOCATION_ALIGN);
}

1653
int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(
1654
		struct amdgpu_device *adev, uint64_t va, uint64_t size,
1655
		void *drm_priv, struct kgd_mem **mem,
1656
		uint64_t *offset, uint32_t flags, bool criu_resume)
1657
{
1658
	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1659 1660
	enum ttm_bo_type bo_type = ttm_bo_type_device;
	struct sg_table *sg = NULL;
1661
	uint64_t user_addr = 0;
1662
	struct amdgpu_bo *bo;
1663
	struct drm_gem_object *gobj = NULL;
1664
	u32 domain, alloc_domain;
1665 1666 1667 1668 1669 1670
	u64 alloc_flags;
	int ret;

	/*
	 * Check on which domain to allocate BO
	 */
1671
	if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) {
1672
		domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;
1673
		alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE;
1674
		alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ?
1675
			AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0;
1676
	} else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) {
1677 1678
		domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
		alloc_flags = 0;
1679
	} else {
1680 1681
		domain = AMDGPU_GEM_DOMAIN_GTT;
		alloc_domain = AMDGPU_GEM_DOMAIN_CPU;
1682
		alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE;
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692

		if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) {
			if (!offset || !*offset)
				return -EINVAL;
			user_addr = untagged_addr(*offset);
		} else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
				    KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
			bo_type = ttm_bo_type_sg;
			if (size > UINT_MAX)
				return -EINVAL;
1693
			sg = create_sg_table(*offset, size);
1694 1695 1696
			if (!sg)
				return -ENOMEM;
		} else {
1697
			return -EINVAL;
1698
		}
1699 1700 1701
	}

	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
1702 1703 1704 1705
	if (!*mem) {
		ret = -ENOMEM;
		goto err;
	}
1706
	INIT_LIST_HEAD(&(*mem)->attachments);
1707
	mutex_init(&(*mem)->lock);
1708
	(*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);
1709 1710 1711 1712 1713 1714 1715 1716

	/* Workaround for AQL queue wraparound bug. Map the same
	 * memory twice. That means we only actually allocate half
	 * the memory.
	 */
	if ((*mem)->aql_queue)
		size = size >> 1;

1717
	(*mem)->alloc_flags = flags;
1718 1719 1720

	amdgpu_sync_create(&(*mem)->sync);

1721
	ret = amdgpu_amdkfd_reserve_mem_limit(adev, size, flags);
1722
	if (ret) {
1723
		pr_debug("Insufficient memory\n");
1724
		goto err_reserve_limit;
1725 1726 1727 1728 1729
	}

	pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s\n",
			va, size, domain_string(alloc_domain));

1730 1731
	ret = amdgpu_gem_object_create(adev, size, 1, alloc_domain, alloc_flags,
				       bo_type, NULL, &gobj);
1732 1733
	if (ret) {
		pr_debug("Failed to create BO on domain %s. ret %d\n",
1734
			 domain_string(alloc_domain), ret);
1735 1736
		goto err_bo_create;
	}
1737 1738 1739 1740 1741
	ret = drm_vma_node_allow(&gobj->vma_node, drm_priv);
	if (ret) {
		pr_debug("Failed to allow vma node access. ret %d\n", ret);
		goto err_node_allow;
	}
1742
	bo = gem_to_amdgpu_bo(gobj);
1743 1744 1745 1746
	if (bo_type == ttm_bo_type_sg) {
		bo->tbo.sg = sg;
		bo->tbo.ttm->sg = sg;
	}
1747 1748
	bo->kfd_bo = *mem;
	(*mem)->bo = bo;
1749
	if (user_addr)
1750
		bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO;
1751 1752

	(*mem)->va = va;
1753
	(*mem)->domain = domain;
1754
	(*mem)->mapped_to_gpu_memory = 0;
1755
	(*mem)->process_info = avm->process_info;
1756 1757 1758
	add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);

	if (user_addr) {
1759 1760
		pr_debug("creating userptr BO for user_addr = %llu\n", user_addr);
		ret = init_user_pages(*mem, user_addr, criu_resume);
1761
		if (ret)
1762
			goto allocate_init_user_pages_failed;
1763 1764
	} else  if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
				KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
1765 1766 1767 1768 1769 1770 1771 1772 1773
		ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT);
		if (ret) {
			pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n");
			goto err_pin_bo;
		}
		bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT;
		bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT;
	}

1774 1775 1776
	if (offset)
		*offset = amdgpu_bo_mmap_offset(bo);

1777 1778
	return 0;

1779
allocate_init_user_pages_failed:
1780
err_pin_bo:
1781
	remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info);
1782 1783
	drm_vma_node_revoke(&gobj->vma_node, drm_priv);
err_node_allow:
1784
	/* Don't unreserve system mem limit twice */
1785
	goto err_reserve_limit;
1786
err_bo_create:
1787
	unreserve_mem_limit(adev, size, flags);
1788
err_reserve_limit:
1789
	mutex_destroy(&(*mem)->lock);
1790 1791 1792 1793
	if (gobj)
		drm_gem_object_put(gobj);
	else
		kfree(*mem);
1794 1795 1796 1797 1798
err:
	if (sg) {
		sg_free_table(sg);
		kfree(sg);
	}
1799 1800 1801 1802
	return ret;
}

int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(
1803
		struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv,
1804
		uint64_t *size)
1805 1806
{
	struct amdkfd_process_info *process_info = mem->process_info;
1807
	unsigned long bo_size = mem->bo->tbo.base.size;
1808
	struct kfd_mem_attachment *entry, *tmp;
1809 1810
	struct bo_vm_reservation_context ctx;
	struct ttm_validate_buffer *bo_list_entry;
1811
	unsigned int mapped_to_gpu_memory;
1812
	int ret;
1813
	bool is_imported = false;
1814 1815

	mutex_lock(&mem->lock);
1816

J
Julia Lawall 已提交
1817
	/* Unpin MMIO/DOORBELL BO's that were pinned during allocation */
1818 1819 1820 1821 1822 1823
	if (mem->alloc_flags &
	    (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL |
	     KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) {
		amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo);
	}

1824
	mapped_to_gpu_memory = mem->mapped_to_gpu_memory;
1825
	is_imported = mem->is_imported;
1826 1827 1828 1829
	mutex_unlock(&mem->lock);
	/* lock is not needed after this, since mem is unused and will
	 * be freed anyway
	 */
1830

1831
	if (mapped_to_gpu_memory > 0) {
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
		pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",
				mem->va, bo_size);
		return -EBUSY;
	}

	/* Make sure restore workers don't access the BO any more */
	bo_list_entry = &mem->validate_list;
	mutex_lock(&process_info->lock);
	list_del(&bo_list_entry->head);
	mutex_unlock(&process_info->lock);

1843 1844 1845
	/* No more MMU notifiers */
	amdgpu_mn_unregister(mem->bo);

1846 1847 1848 1849 1850 1851 1852 1853 1854
	ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);
	if (unlikely(ret))
		return ret;

	/* The eviction fence should be removed by the last unmap.
	 * TODO: Log an error condition if the bo still has the eviction fence
	 * attached
	 */
	amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1855
					process_info->eviction_fence);
1856 1857 1858 1859
	pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,
		mem->va + bo_size * (1 + mem->aql_queue));

	/* Remove from VM internal data structures */
1860 1861
	list_for_each_entry_safe(entry, tmp, &mem->attachments, list)
		kfd_mem_detach(entry);
1862

1863 1864
	ret = unreserve_bo_and_vms(&ctx, false, false);

1865 1866 1867
	/* Free the sync object */
	amdgpu_sync_free(&mem->sync);

1868 1869
	/* If the SG is not NULL, it's one we created for a doorbell or mmio
	 * remap BO. We need to free it.
1870 1871 1872 1873 1874 1875
	 */
	if (mem->bo->tbo.sg) {
		sg_free_table(mem->bo->tbo.sg);
		kfree(mem->bo->tbo.sg);
	}

1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
	/* Update the size of the BO being freed if it was allocated from
	 * VRAM and is not imported.
	 */
	if (size) {
		if ((mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_VRAM) &&
		    (!is_imported))
			*size = bo_size;
		else
			*size = 0;
	}

1887
	/* Free the BO*/
1888
	drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv);
1889 1890
	if (mem->dmabuf)
		dma_buf_put(mem->dmabuf);
1891
	mutex_destroy(&mem->lock);
1892 1893 1894 1895 1896 1897

	/* If this releases the last reference, it will end up calling
	 * amdgpu_amdkfd_release_notify and kfree the mem struct. That's why
	 * this needs to be the last call here.
	 */
	drm_gem_object_put(&mem->bo->tbo.base);
1898 1899 1900 1901 1902

	return ret;
}

int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1903
		struct amdgpu_device *adev, struct kgd_mem *mem,
1904
		void *drm_priv)
1905
{
1906
	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
1907 1908 1909
	int ret;
	struct amdgpu_bo *bo;
	uint32_t domain;
1910
	struct kfd_mem_attachment *entry;
1911 1912
	struct bo_vm_reservation_context ctx;
	unsigned long bo_size;
1913
	bool is_invalid_userptr = false;
1914 1915 1916 1917

	bo = mem->bo;
	if (!bo) {
		pr_err("Invalid BO when mapping memory to GPU\n");
1918
		return -EINVAL;
1919 1920
	}

1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
	/* Make sure restore is not running concurrently. Since we
	 * don't map invalid userptr BOs, we rely on the next restore
	 * worker to do the mapping
	 */
	mutex_lock(&mem->process_info->lock);

	/* Lock mmap-sem. If we find an invalid userptr BO, we can be
	 * sure that the MMU notifier is no longer running
	 * concurrently and the queues are actually stopped
	 */
	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1932
		mmap_write_lock(current->mm);
1933
		is_invalid_userptr = atomic_read(&mem->invalid);
1934
		mmap_write_unlock(current->mm);
1935 1936 1937 1938
	}

	mutex_lock(&mem->lock);

1939
	domain = mem->domain;
1940
	bo_size = bo->tbo.base.size;
1941 1942 1943 1944

	pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",
			mem->va,
			mem->va + bo_size * (1 + mem->aql_queue),
1945
			avm, domain_string(domain));
1946

1947 1948 1949 1950 1951 1952
	if (!kfd_mem_is_attached(avm, mem)) {
		ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue);
		if (ret)
			goto out;
	}

1953
	ret = reserve_bo_and_vm(mem, avm, &ctx);
1954 1955 1956
	if (unlikely(ret))
		goto out;

1957 1958 1959 1960 1961
	/* Userptr can be marked as "not invalid", but not actually be
	 * validated yet (still in the system domain). In that case
	 * the queues are still stopped and we can leave mapping for
	 * the next restore worker
	 */
1962
	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&
1963
	    bo->tbo.resource->mem_type == TTM_PL_SYSTEM)
1964 1965
		is_invalid_userptr = true;

1966 1967 1968
	ret = vm_validate_pt_pd_bos(avm);
	if (unlikely(ret))
		goto out_unreserve;
1969

1970 1971
	if (mem->mapped_to_gpu_memory == 0 &&
	    !amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1972 1973 1974 1975 1976 1977 1978
		/* Validate BO only once. The eviction fence gets added to BO
		 * the first time it is mapped. Validate will wait for all
		 * background evictions to complete.
		 */
		ret = amdgpu_amdkfd_bo_validate(bo, domain, true);
		if (ret) {
			pr_debug("Validate failed\n");
1979
			goto out_unreserve;
1980 1981 1982
		}
	}

1983 1984 1985
	list_for_each_entry(entry, &mem->attachments, list) {
		if (entry->bo_va->base.vm != avm || entry->is_mapped)
			continue;
1986

1987 1988
		pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",
			 entry->va, entry->va + bo_size, entry);
1989

1990
		ret = map_bo_to_gpuvm(mem, entry, ctx.sync,
1991
				      is_invalid_userptr);
1992 1993
		if (ret) {
			pr_err("Failed to map bo to gpuvm\n");
1994
			goto out_unreserve;
1995
		}
1996

1997 1998 1999
		ret = vm_update_pds(avm, ctx.sync);
		if (ret) {
			pr_err("Failed to update page directories\n");
2000
			goto out_unreserve;
2001
		}
2002 2003 2004 2005 2006

		entry->is_mapped = true;
		mem->mapped_to_gpu_memory++;
		pr_debug("\t INC mapping count %d\n",
			 mem->mapped_to_gpu_memory);
2007 2008
	}

2009
	if (!amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) && !bo->tbo.pin_count)
2010
		amdgpu_bo_fence(bo,
2011
				&avm->process_info->eviction_fence->base,
2012 2013 2014 2015 2016
				true);
	ret = unreserve_bo_and_vms(&ctx, false, false);

	goto out;

2017
out_unreserve:
2018 2019 2020 2021 2022 2023 2024 2025
	unreserve_bo_and_vms(&ctx, false, false);
out:
	mutex_unlock(&mem->process_info->lock);
	mutex_unlock(&mem->lock);
	return ret;
}

int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
2026
		struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv)
2027
{
2028 2029
	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
	struct amdkfd_process_info *process_info = avm->process_info;
2030
	unsigned long bo_size = mem->bo->tbo.base.size;
2031
	struct kfd_mem_attachment *entry;
2032 2033 2034 2035 2036
	struct bo_vm_reservation_context ctx;
	int ret;

	mutex_lock(&mem->lock);

2037
	ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx);
2038 2039 2040 2041 2042 2043 2044 2045
	if (unlikely(ret))
		goto out;
	/* If no VMs were reserved, it means the BO wasn't actually mapped */
	if (ctx.n_vms == 0) {
		ret = -EINVAL;
		goto unreserve_out;
	}

2046
	ret = vm_validate_pt_pd_bos(avm);
2047 2048 2049 2050 2051 2052
	if (unlikely(ret))
		goto unreserve_out;

	pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",
		mem->va,
		mem->va + bo_size * (1 + mem->aql_queue),
2053
		avm);
2054

2055 2056 2057
	list_for_each_entry(entry, &mem->attachments, list) {
		if (entry->bo_va->base.vm != avm || !entry->is_mapped)
			continue;
2058

2059 2060
		pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",
			 entry->va, entry->va + bo_size, entry);
2061

2062 2063
		unmap_bo_from_gpuvm(mem, entry, ctx.sync);
		entry->is_mapped = false;
2064 2065 2066 2067

		mem->mapped_to_gpu_memory--;
		pr_debug("\t DEC mapping count %d\n",
			 mem->mapped_to_gpu_memory);
2068 2069 2070 2071 2072 2073
	}

	/* If BO is unmapped from all VMs, unfence it. It can be evicted if
	 * required.
	 */
	if (mem->mapped_to_gpu_memory == 0 &&
2074 2075
	    !amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) &&
	    !mem->bo->tbo.pin_count)
2076
		amdgpu_amdkfd_remove_eviction_fence(mem->bo,
2077
						process_info->eviction_fence);
2078 2079 2080 2081 2082 2083 2084 2085 2086

unreserve_out:
	unreserve_bo_and_vms(&ctx, false, false);
out:
	mutex_unlock(&mem->lock);
	return ret;
}

int amdgpu_amdkfd_gpuvm_sync_memory(
2087
		struct amdgpu_device *adev, struct kgd_mem *mem, bool intr)
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
{
	struct amdgpu_sync sync;
	int ret;

	amdgpu_sync_create(&sync);

	mutex_lock(&mem->lock);
	amdgpu_sync_clone(&mem->sync, &sync);
	mutex_unlock(&mem->lock);

	ret = amdgpu_sync_wait(&sync, intr);
	amdgpu_sync_free(&sync);
	return ret;
}

2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
/**
 * amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count
 * @adev: Device to which allocated BO belongs
 * @bo: Buffer object to be mapped
 *
 * Before return, bo reference count is incremented. To release the reference and unpin/
 * unmap the BO, call amdgpu_amdkfd_free_gtt_mem.
 */
int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_device *adev, struct amdgpu_bo *bo)
{
	int ret;

	ret = amdgpu_bo_reserve(bo, true);
	if (ret) {
		pr_err("Failed to reserve bo. ret %d\n", ret);
		goto err_reserve_bo_failed;
	}

	ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
	if (ret) {
		pr_err("Failed to pin bo. ret %d\n", ret);
		goto err_pin_bo_failed;
	}

	ret = amdgpu_ttm_alloc_gart(&bo->tbo);
	if (ret) {
		pr_err("Failed to bind bo to GART. ret %d\n", ret);
		goto err_map_bo_gart_failed;
	}

	amdgpu_amdkfd_remove_eviction_fence(
		bo, bo->kfd_bo->process_info->eviction_fence);

	amdgpu_bo_unreserve(bo);

	bo = amdgpu_bo_ref(bo);

	return 0;

err_map_bo_gart_failed:
	amdgpu_bo_unpin(bo);
err_pin_bo_failed:
	amdgpu_bo_unreserve(bo);
err_reserve_bo_failed:

	return ret;
}

2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
/** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Map a GTT BO for kernel CPU access
 *
 * @mem: Buffer object to be mapped for CPU access
 * @kptr[out]: pointer in kernel CPU address space
 * @size[out]: size of the buffer
 *
 * Pins the BO and maps it for kernel CPU access. The eviction fence is removed
 * from the BO, since pinned BOs cannot be evicted. The bo must remain on the
 * validate_list, so the GPU mapping can be restored after a page table was
 * evicted.
 *
 * Return: 0 on success, error code on failure
 */
int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem,
					     void **kptr, uint64_t *size)
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
{
	int ret;
	struct amdgpu_bo *bo = mem->bo;

	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
		pr_err("userptr can't be mapped to kernel\n");
		return -EINVAL;
	}

	mutex_lock(&mem->process_info->lock);

	ret = amdgpu_bo_reserve(bo, true);
	if (ret) {
		pr_err("Failed to reserve bo. ret %d\n", ret);
		goto bo_reserve_failed;
	}

2183
	ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
	if (ret) {
		pr_err("Failed to pin bo. ret %d\n", ret);
		goto pin_failed;
	}

	ret = amdgpu_bo_kmap(bo, kptr);
	if (ret) {
		pr_err("Failed to map bo to kernel. ret %d\n", ret);
		goto kmap_failed;
	}

	amdgpu_amdkfd_remove_eviction_fence(
2196
		bo, mem->process_info->eviction_fence);
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215

	if (size)
		*size = amdgpu_bo_size(bo);

	amdgpu_bo_unreserve(bo);

	mutex_unlock(&mem->process_info->lock);
	return 0;

kmap_failed:
	amdgpu_bo_unpin(bo);
pin_failed:
	amdgpu_bo_unreserve(bo);
bo_reserve_failed:
	mutex_unlock(&mem->process_info->lock);

	return ret;
}

2216 2217 2218 2219 2220 2221 2222 2223 2224
/** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Unmap a GTT BO for kernel CPU access
 *
 * @mem: Buffer object to be unmapped for CPU access
 *
 * Removes the kernel CPU mapping and unpins the BO. It does not restore the
 * eviction fence, so this function should only be used for cleanup before the
 * BO is destroyed.
 */
void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem *mem)
2225 2226 2227 2228 2229 2230 2231 2232 2233
{
	struct amdgpu_bo *bo = mem->bo;

	amdgpu_bo_reserve(bo, true);
	amdgpu_bo_kunmap(bo);
	amdgpu_bo_unpin(bo);
	amdgpu_bo_unreserve(bo);
}

2234 2235
int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev,
					  struct kfd_vm_fault_info *mem)
2236 2237 2238 2239 2240 2241 2242 2243 2244
{
	if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) {
		*mem = *adev->gmc.vm_fault_info;
		mb();
		atomic_set(&adev->gmc.vm_fault_info_updated, 0);
	}
	return 0;
}

2245
int amdgpu_amdkfd_gpuvm_import_dmabuf(struct amdgpu_device *adev,
2246
				      struct dma_buf *dma_buf,
2247
				      uint64_t va, void *drm_priv,
2248 2249 2250
				      struct kgd_mem **mem, uint64_t *size,
				      uint64_t *mmap_offset)
{
2251
	struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv);
2252 2253
	struct drm_gem_object *obj;
	struct amdgpu_bo *bo;
2254
	int ret;
2255 2256 2257 2258 2259 2260

	if (dma_buf->ops != &amdgpu_dmabuf_ops)
		/* Can't handle non-graphics buffers */
		return -EINVAL;

	obj = dma_buf->priv;
2261
	if (drm_to_adev(obj->dev) != adev)
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
		/* Can't handle buffers from other devices */
		return -EINVAL;

	bo = gem_to_amdgpu_bo(obj);
	if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM |
				    AMDGPU_GEM_DOMAIN_GTT)))
		/* Only VRAM and GTT BOs are supported */
		return -EINVAL;

	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
	if (!*mem)
		return -ENOMEM;

2275 2276 2277 2278 2279 2280
	ret = drm_vma_node_allow(&obj->vma_node, drm_priv);
	if (ret) {
		kfree(mem);
		return ret;
	}

2281 2282 2283 2284 2285 2286
	if (size)
		*size = amdgpu_bo_size(bo);

	if (mmap_offset)
		*mmap_offset = amdgpu_bo_mmap_offset(bo);

2287
	INIT_LIST_HEAD(&(*mem)->attachments);
2288
	mutex_init(&(*mem)->lock);
2289

2290 2291
	(*mem)->alloc_flags =
		((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
2292 2293 2294
		KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT)
		| KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE
		| KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE;
2295

2296 2297
	drm_gem_object_get(&bo->tbo.base);
	(*mem)->bo = bo;
2298 2299 2300 2301 2302 2303 2304
	(*mem)->va = va;
	(*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ?
		AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT;
	(*mem)->mapped_to_gpu_memory = 0;
	(*mem)->process_info = avm->process_info;
	add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false);
	amdgpu_sync_create(&(*mem)->sync);
2305
	(*mem)->is_imported = true;
2306 2307 2308 2309

	return 0;
}

2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
/* Evict a userptr BO by stopping the queues if necessary
 *
 * Runs in MMU notifier, may be in RECLAIM_FS context. This means it
 * cannot do any memory allocations, and cannot take any locks that
 * are held elsewhere while allocating memory. Therefore this is as
 * simple as possible, using atomic counters.
 *
 * It doesn't do anything to the BO itself. The real work happens in
 * restore, where we get updated page addresses. This function only
 * ensures that GPU access to the BO is stopped.
 */
2321 2322 2323
int amdgpu_amdkfd_evict_userptr(struct kgd_mem *mem,
				struct mm_struct *mm)
{
2324
	struct amdkfd_process_info *process_info = mem->process_info;
2325
	int evicted_bos;
2326 2327
	int r = 0;

2328 2329 2330 2331
	/* Do not process MMU notifications until stage-4 IOCTL is received */
	if (READ_ONCE(process_info->block_mmu_notifications))
		return 0;

2332
	atomic_inc(&mem->invalid);
2333 2334 2335
	evicted_bos = atomic_inc_return(&process_info->evicted_bos);
	if (evicted_bos == 1) {
		/* First eviction, stop the queues */
2336
		r = kgd2kfd_quiesce_mm(mm, KFD_QUEUE_EVICTION_TRIGGER_USERPTR);
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
		if (r)
			pr_err("Failed to quiesce KFD\n");
		schedule_delayed_work(&process_info->restore_userptr_work,
			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
	}

	return r;
}

/* Update invalid userptr BOs
 *
 * Moves invalidated (evicted) userptr BOs from userptr_valid_list to
 * userptr_inval_list and updates user pages for all BOs that have
 * been invalidated since their last update.
 */
static int update_invalid_user_pages(struct amdkfd_process_info *process_info,
				     struct mm_struct *mm)
{
	struct kgd_mem *mem, *tmp_mem;
	struct amdgpu_bo *bo;
	struct ttm_operation_ctx ctx = { false, false };
	int invalid, ret;

	/* Move all invalidated BOs to the userptr_inval_list and
	 * release their user pages by migration to the CPU domain
	 */
	list_for_each_entry_safe(mem, tmp_mem,
				 &process_info->userptr_valid_list,
				 validate_list.head) {
		if (!atomic_read(&mem->invalid))
			continue; /* BO is still valid */

		bo = mem->bo;

		if (amdgpu_bo_reserve(bo, true))
			return -EAGAIN;
2373
		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
		amdgpu_bo_unreserve(bo);
		if (ret) {
			pr_err("%s: Failed to invalidate userptr BO\n",
			       __func__);
			return -EAGAIN;
		}

		list_move_tail(&mem->validate_list.head,
			       &process_info->userptr_inval_list);
	}

	if (list_empty(&process_info->userptr_inval_list))
		return 0; /* All evicted userptr BOs were freed */

	/* Go through userptr_inval_list and update any invalid user_pages */
	list_for_each_entry(mem, &process_info->userptr_inval_list,
			    validate_list.head) {
		invalid = atomic_read(&mem->invalid);
		if (!invalid)
			/* BO hasn't been invalidated since the last
			 * revalidation attempt. Keep its BO list.
			 */
			continue;

		bo = mem->bo;

		/* Get updated user pages */
2402
		ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages);
2403
		if (ret) {
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
			pr_debug("Failed %d to get user pages\n", ret);

			/* Return -EFAULT bad address error as success. It will
			 * fail later with a VM fault if the GPU tries to access
			 * it. Better than hanging indefinitely with stalled
			 * user mode queues.
			 *
			 * Return other error -EBUSY or -ENOMEM to retry restore
			 */
			if (ret != -EFAULT)
				return ret;
		} else {
2416

2417 2418 2419 2420 2421
			/*
			 * FIXME: Cannot ignore the return code, must hold
			 * notifier_lock
			 */
			amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm);
2422
		}
2423

2424 2425 2426 2427 2428
		/* Mark the BO as valid unless it was invalidated
		 * again concurrently.
		 */
		if (atomic_cmpxchg(&mem->invalid, invalid, 0) != invalid)
			return -EAGAIN;
2429
	}
2430 2431

	return 0;
2432 2433
}

2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
/* Validate invalid userptr BOs
 *
 * Validates BOs on the userptr_inval_list, and moves them back to the
 * userptr_valid_list. Also updates GPUVM page tables with new page
 * addresses and waits for the page table updates to complete.
 */
static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)
{
	struct amdgpu_bo_list_entry *pd_bo_list_entries;
	struct list_head resv_list, duplicates;
	struct ww_acquire_ctx ticket;
	struct amdgpu_sync sync;

	struct amdgpu_vm *peer_vm;
	struct kgd_mem *mem, *tmp_mem;
	struct amdgpu_bo *bo;
	struct ttm_operation_ctx ctx = { false, false };
	int i, ret;

	pd_bo_list_entries = kcalloc(process_info->n_vms,
				     sizeof(struct amdgpu_bo_list_entry),
				     GFP_KERNEL);
	if (!pd_bo_list_entries) {
		pr_err("%s: Failed to allocate PD BO list entries\n", __func__);
2458 2459
		ret = -ENOMEM;
		goto out_no_mem;
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
	}

	INIT_LIST_HEAD(&resv_list);
	INIT_LIST_HEAD(&duplicates);

	/* Get all the page directory BOs that need to be reserved */
	i = 0;
	list_for_each_entry(peer_vm, &process_info->vm_list_head,
			    vm_list_node)
		amdgpu_vm_get_pd_bo(peer_vm, &resv_list,
				    &pd_bo_list_entries[i++]);
	/* Add the userptr_inval_list entries to resv_list */
	list_for_each_entry(mem, &process_info->userptr_inval_list,
			    validate_list.head) {
		list_add_tail(&mem->resv_list.head, &resv_list);
		mem->resv_list.bo = mem->validate_list.bo;
2476
		mem->resv_list.num_shared = mem->validate_list.num_shared;
2477 2478 2479
	}

	/* Reserve all BOs and page tables for validation */
2480
	ret = ttm_eu_reserve_buffers(&ticket, &resv_list, false, &duplicates);
2481 2482
	WARN(!list_empty(&duplicates), "Duplicates should be empty");
	if (ret)
2483
		goto out_free;
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494

	amdgpu_sync_create(&sync);

	ret = process_validate_vms(process_info);
	if (ret)
		goto unreserve_out;

	/* Validate BOs and update GPUVM page tables */
	list_for_each_entry_safe(mem, tmp_mem,
				 &process_info->userptr_inval_list,
				 validate_list.head) {
2495
		struct kfd_mem_attachment *attachment;
2496 2497 2498

		bo = mem->bo;

2499 2500
		/* Validate the BO if we got user pages */
		if (bo->tbo.ttm->pages[0]) {
2501
			amdgpu_bo_placement_from_domain(bo, mem->domain);
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
			if (ret) {
				pr_err("%s: failed to validate BO\n", __func__);
				goto unreserve_out;
			}
		}

		list_move_tail(&mem->validate_list.head,
			       &process_info->userptr_valid_list);

		/* Update mapping. If the BO was not validated
		 * (because we couldn't get user pages), this will
		 * clear the page table entries, which will result in
		 * VM faults if the GPU tries to access the invalid
		 * memory.
		 */
2518 2519
		list_for_each_entry(attachment, &mem->attachments, list) {
			if (!attachment->is_mapped)
2520 2521
				continue;

2522
			kfd_mem_dmaunmap_attachment(mem, attachment);
2523
			ret = update_gpuvm_pte(mem, attachment, &sync);
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
			if (ret) {
				pr_err("%s: update PTE failed\n", __func__);
				/* make sure this gets validated again */
				atomic_inc(&mem->invalid);
				goto unreserve_out;
			}
		}
	}

	/* Update page directories */
	ret = process_update_pds(process_info, &sync);

unreserve_out:
	ttm_eu_backoff_reservation(&ticket, &resv_list);
	amdgpu_sync_wait(&sync, false);
	amdgpu_sync_free(&sync);
2540
out_free:
2541
	kfree(pd_bo_list_entries);
2542
out_no_mem:
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600

	return ret;
}

/* Worker callback to restore evicted userptr BOs
 *
 * Tries to update and validate all userptr BOs. If successful and no
 * concurrent evictions happened, the queues are restarted. Otherwise,
 * reschedule for another attempt later.
 */
static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
{
	struct delayed_work *dwork = to_delayed_work(work);
	struct amdkfd_process_info *process_info =
		container_of(dwork, struct amdkfd_process_info,
			     restore_userptr_work);
	struct task_struct *usertask;
	struct mm_struct *mm;
	int evicted_bos;

	evicted_bos = atomic_read(&process_info->evicted_bos);
	if (!evicted_bos)
		return;

	/* Reference task and mm in case of concurrent process termination */
	usertask = get_pid_task(process_info->pid, PIDTYPE_PID);
	if (!usertask)
		return;
	mm = get_task_mm(usertask);
	if (!mm) {
		put_task_struct(usertask);
		return;
	}

	mutex_lock(&process_info->lock);

	if (update_invalid_user_pages(process_info, mm))
		goto unlock_out;
	/* userptr_inval_list can be empty if all evicted userptr BOs
	 * have been freed. In that case there is nothing to validate
	 * and we can just restart the queues.
	 */
	if (!list_empty(&process_info->userptr_inval_list)) {
		if (atomic_read(&process_info->evicted_bos) != evicted_bos)
			goto unlock_out; /* Concurrent eviction, try again */

		if (validate_invalid_user_pages(process_info))
			goto unlock_out;
	}
	/* Final check for concurrent evicton and atomic update. If
	 * another eviction happens after successful update, it will
	 * be a first eviction that calls quiesce_mm. The eviction
	 * reference counting inside KFD will handle this case.
	 */
	if (atomic_cmpxchg(&process_info->evicted_bos, evicted_bos, 0) !=
	    evicted_bos)
		goto unlock_out;
	evicted_bos = 0;
2601
	if (kgd2kfd_resume_mm(mm)) {
2602 2603 2604 2605 2606
		pr_err("%s: Failed to resume KFD\n", __func__);
		/* No recovery from this failure. Probably the CP is
		 * hanging. No point trying again.
		 */
	}
2607

2608 2609 2610 2611
unlock_out:
	mutex_unlock(&process_info->lock);

	/* If validation failed, reschedule another attempt */
2612
	if (evicted_bos) {
2613 2614
		schedule_delayed_work(&process_info->restore_userptr_work,
			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
2615 2616 2617 2618 2619

		kfd_smi_event_queue_restore_rescheduled(mm);
	}
	mmput(mm);
	put_task_struct(usertask);
2620 2621
}

2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
/** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given
 *   KFD process identified by process_info
 *
 * @process_info: amdkfd_process_info of the KFD process
 *
 * After memory eviction, restore thread calls this function. The function
 * should be called when the Process is still valid. BO restore involves -
 *
 * 1.  Release old eviction fence and create new one
 * 2.  Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.
 * 3   Use the second PD list and kfd_bo_list to create a list (ctx.list) of
 *     BOs that need to be reserved.
 * 4.  Reserve all the BOs
 * 5.  Validate of PD and PT BOs.
 * 6.  Validate all KFD BOs using kfd_bo_list and Map them and add new fence
 * 7.  Add fence to all PD and PT BOs.
 * 8.  Unreserve all BOs
 */
int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence **ef)
{
	struct amdgpu_bo_list_entry *pd_bo_list;
	struct amdkfd_process_info *process_info = info;
2644
	struct amdgpu_vm *peer_vm;
2645 2646 2647 2648 2649 2650
	struct kgd_mem *mem;
	struct bo_vm_reservation_context ctx;
	struct amdgpu_amdkfd_fence *new_fence;
	int ret = 0, i;
	struct list_head duplicate_save;
	struct amdgpu_sync sync_obj;
2651 2652
	unsigned long failed_size = 0;
	unsigned long total_size = 0;
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667

	INIT_LIST_HEAD(&duplicate_save);
	INIT_LIST_HEAD(&ctx.list);
	INIT_LIST_HEAD(&ctx.duplicates);

	pd_bo_list = kcalloc(process_info->n_vms,
			     sizeof(struct amdgpu_bo_list_entry),
			     GFP_KERNEL);
	if (!pd_bo_list)
		return -ENOMEM;

	i = 0;
	mutex_lock(&process_info->lock);
	list_for_each_entry(peer_vm, &process_info->vm_list_head,
			vm_list_node)
2668
		amdgpu_vm_get_pd_bo(peer_vm, &ctx.list, &pd_bo_list[i++]);
2669 2670 2671 2672 2673 2674 2675 2676 2677

	/* Reserve all BOs and page tables/directory. Add all BOs from
	 * kfd_bo_list to ctx.list
	 */
	list_for_each_entry(mem, &process_info->kfd_bo_list,
			    validate_list.head) {

		list_add_tail(&mem->resv_list.head, &ctx.list);
		mem->resv_list.bo = mem->validate_list.bo;
2678
		mem->resv_list.num_shared = mem->validate_list.num_shared;
2679 2680 2681
	}

	ret = ttm_eu_reserve_buffers(&ctx.ticket, &ctx.list,
2682
				     false, &duplicate_save);
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
	if (ret) {
		pr_debug("Memory eviction: TTM Reserve Failed. Try again\n");
		goto ttm_reserve_fail;
	}

	amdgpu_sync_create(&sync_obj);

	/* Validate PDs and PTs */
	ret = process_validate_vms(process_info);
	if (ret)
		goto validate_map_fail;

2695 2696 2697 2698
	ret = process_sync_pds_resv(process_info, &sync_obj);
	if (ret) {
		pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");
		goto validate_map_fail;
2699 2700 2701 2702 2703 2704 2705 2706
	}

	/* Validate BOs and map them to GPUVM (update VM page tables). */
	list_for_each_entry(mem, &process_info->kfd_bo_list,
			    validate_list.head) {

		struct amdgpu_bo *bo = mem->bo;
		uint32_t domain = mem->domain;
2707
		struct kfd_mem_attachment *attachment;
C
Christian König 已提交
2708 2709
		struct dma_resv_iter cursor;
		struct dma_fence *fence;
2710

2711 2712
		total_size += amdgpu_bo_size(bo);

2713 2714
		ret = amdgpu_amdkfd_bo_validate(bo, domain, false);
		if (ret) {
2715 2716 2717 2718 2719 2720 2721 2722
			pr_debug("Memory eviction: Validate BOs failed\n");
			failed_size += amdgpu_bo_size(bo);
			ret = amdgpu_amdkfd_bo_validate(bo,
						AMDGPU_GEM_DOMAIN_GTT, false);
			if (ret) {
				pr_debug("Memory eviction: Try again\n");
				goto validate_map_fail;
			}
2723
		}
C
Christian König 已提交
2724 2725 2726 2727 2728 2729 2730
		dma_resv_for_each_fence(&cursor, bo->tbo.base.resv,
					DMA_RESV_USAGE_KERNEL, fence) {
			ret = amdgpu_sync_fence(&sync_obj, fence);
			if (ret) {
				pr_debug("Memory eviction: Sync BO fence failed. Try again\n");
				goto validate_map_fail;
			}
2731
		}
2732
		list_for_each_entry(attachment, &mem->attachments, list) {
2733 2734 2735 2736
			if (!attachment->is_mapped)
				continue;

			kfd_mem_dmaunmap_attachment(mem, attachment);
2737
			ret = update_gpuvm_pte(mem, attachment, &sync_obj);
2738 2739 2740 2741 2742 2743 2744
			if (ret) {
				pr_debug("Memory eviction: update PTE failed. Try again\n");
				goto validate_map_fail;
			}
		}
	}

2745 2746 2747
	if (failed_size)
		pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size);

2748 2749 2750 2751 2752 2753 2754
	/* Update page directories */
	ret = process_update_pds(process_info, &sync_obj);
	if (ret) {
		pr_debug("Memory eviction: update PDs failed. Try again\n");
		goto validate_map_fail;
	}

2755
	/* Wait for validate and PT updates to finish */
2756 2757 2758 2759 2760 2761 2762 2763
	amdgpu_sync_wait(&sync_obj, false);

	/* Release old eviction fence and create new one, because fence only
	 * goes from unsignaled to signaled, fence cannot be reused.
	 * Use context and mm from the old fence.
	 */
	new_fence = amdgpu_amdkfd_fence_create(
				process_info->eviction_fence->base.context,
2764 2765
				process_info->eviction_fence->mm,
				NULL);
2766 2767 2768 2769 2770 2771 2772 2773 2774
	if (!new_fence) {
		pr_err("Failed to create eviction fence\n");
		ret = -ENOMEM;
		goto validate_map_fail;
	}
	dma_fence_put(&process_info->eviction_fence->base);
	process_info->eviction_fence = new_fence;
	*ef = dma_fence_get(&new_fence->base);

2775
	/* Attach new eviction fence to all BOs except pinned ones */
2776
	list_for_each_entry(mem, &process_info->kfd_bo_list,
2777 2778 2779 2780
		validate_list.head) {
		if (mem->bo->tbo.pin_count)
			continue;

2781 2782
		amdgpu_bo_fence(mem->bo,
			&process_info->eviction_fence->base, true);
2783
	}
2784 2785 2786
	/* Attach eviction fence to PD / PT BOs */
	list_for_each_entry(peer_vm, &process_info->vm_list_head,
			    vm_list_node) {
N
Nirmoy Das 已提交
2787
		struct amdgpu_bo *bo = peer_vm->root.bo;
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799

		amdgpu_bo_fence(bo, &process_info->eviction_fence->base, true);
	}

validate_map_fail:
	ttm_eu_backoff_reservation(&ctx.ticket, &ctx.list);
	amdgpu_sync_free(&sync_obj);
ttm_reserve_fail:
	mutex_unlock(&process_info->lock);
	kfree(pd_bo_list);
	return ret;
}
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811

int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem)
{
	struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
	struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws;
	int ret;

	if (!info || !gws)
		return -EINVAL;

	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
	if (!*mem)
2812
		return -ENOMEM;
2813 2814

	mutex_init(&(*mem)->lock);
2815
	INIT_LIST_HEAD(&(*mem)->attachments);
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
	(*mem)->bo = amdgpu_bo_ref(gws_bo);
	(*mem)->domain = AMDGPU_GEM_DOMAIN_GWS;
	(*mem)->process_info = process_info;
	add_kgd_mem_to_kfd_bo_list(*mem, process_info, false);
	amdgpu_sync_create(&(*mem)->sync);


	/* Validate gws bo the first time it is added to process */
	mutex_lock(&(*mem)->process_info->lock);
	ret = amdgpu_bo_reserve(gws_bo, false);
	if (unlikely(ret)) {
		pr_err("Reserve gws bo failed %d\n", ret);
		goto bo_reservation_failure;
	}

	ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true);
	if (ret) {
		pr_err("GWS BO validate failed %d\n", ret);
		goto bo_validation_failure;
	}
	/* GWS resource is shared b/t amdgpu and amdkfd
	 * Add process eviction fence to bo so they can
	 * evict each other.
	 */
2840
	ret = dma_resv_reserve_fences(gws_bo->tbo.base.resv, 1);
2841 2842
	if (ret)
		goto reserve_shared_fail;
2843 2844 2845 2846 2847 2848
	amdgpu_bo_fence(gws_bo, &process_info->eviction_fence->base, true);
	amdgpu_bo_unreserve(gws_bo);
	mutex_unlock(&(*mem)->process_info->lock);

	return ret;

2849
reserve_shared_fail:
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
bo_validation_failure:
	amdgpu_bo_unreserve(gws_bo);
bo_reservation_failure:
	mutex_unlock(&(*mem)->process_info->lock);
	amdgpu_sync_free(&(*mem)->sync);
	remove_kgd_mem_from_kfd_bo_list(*mem, process_info);
	amdgpu_bo_unref(&gws_bo);
	mutex_destroy(&(*mem)->lock);
	kfree(*mem);
	*mem = NULL;
	return ret;
}

int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem)
{
	int ret;
	struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info;
	struct kgd_mem *kgd_mem = (struct kgd_mem *)mem;
	struct amdgpu_bo *gws_bo = kgd_mem->bo;

	/* Remove BO from process's validate list so restore worker won't touch
	 * it anymore
	 */
	remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info);

	ret = amdgpu_bo_reserve(gws_bo, false);
	if (unlikely(ret)) {
		pr_err("Reserve gws bo failed %d\n", ret);
		//TODO add BO back to validate_list?
		return ret;
	}
	amdgpu_amdkfd_remove_eviction_fence(gws_bo,
			process_info->eviction_fence);
	amdgpu_bo_unreserve(gws_bo);
	amdgpu_sync_free(&kgd_mem->sync);
	amdgpu_bo_unref(&gws_bo);
	mutex_destroy(&kgd_mem->lock);
	kfree(mem);
	return 0;
}
2890 2891

/* Returns GPU-specific tiling mode information */
2892
int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev,
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
				struct tile_config *config)
{
	config->gb_addr_config = adev->gfx.config.gb_addr_config;
	config->tile_config_ptr = adev->gfx.config.tile_mode_array;
	config->num_tile_configs =
			ARRAY_SIZE(adev->gfx.config.tile_mode_array);
	config->macro_tile_config_ptr =
			adev->gfx.config.macrotile_mode_array;
	config->num_macro_tile_configs =
			ARRAY_SIZE(adev->gfx.config.macrotile_mode_array);

	/* Those values are not set from GFX9 onwards */
	config->num_banks = adev->gfx.config.num_banks;
	config->num_ranks = adev->gfx.config.num_ranks;

	return 0;
}
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920

bool amdgpu_amdkfd_bo_mapped_to_dev(struct amdgpu_device *adev, struct kgd_mem *mem)
{
	struct kfd_mem_attachment *entry;

	list_for_each_entry(entry, &mem->attachments, list) {
		if (entry->is_mapped && entry->adev == adev)
			return true;
	}
	return false;
}