Linux Audio

Check our new training course

Loading...
v5.9
   1/*
   2 * Copyright 2009 Jerome Glisse.
   3 * All Rights Reserved.
   4 *
   5 * Permission is hereby granted, free of charge, to any person obtaining a
   6 * copy of this software and associated documentation files (the
   7 * "Software"), to deal in the Software without restriction, including
   8 * without limitation the rights to use, copy, modify, merge, publish,
   9 * distribute, sub license, and/or sell copies of the Software, and to
  10 * permit persons to whom the Software is furnished to do so, subject to
  11 * the following conditions:
  12 *
  13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
  16 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
  17 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  18 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19 * USE OR OTHER DEALINGS IN THE SOFTWARE.
  20 *
  21 * The above copyright notice and this permission notice (including the
  22 * next paragraph) shall be included in all copies or substantial portions
  23 * of the Software.
  24 *
  25 */
  26/*
  27 * Authors:
  28 *    Jerome Glisse <glisse@freedesktop.org>
  29 *    Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
  30 *    Dave Airlie
  31 */
  32
  33#include <linux/dma-mapping.h>
  34#include <linux/iommu.h>
  35#include <linux/hmm.h>
  36#include <linux/pagemap.h>
  37#include <linux/sched/task.h>
  38#include <linux/sched/mm.h>
  39#include <linux/seq_file.h>
  40#include <linux/slab.h>
  41#include <linux/swap.h>
  42#include <linux/swiotlb.h>
  43#include <linux/dma-buf.h>
  44#include <linux/sizes.h>
 
  45
  46#include <drm/ttm/ttm_bo_api.h>
  47#include <drm/ttm/ttm_bo_driver.h>
  48#include <drm/ttm/ttm_placement.h>
  49#include <drm/ttm/ttm_module.h>
  50#include <drm/ttm/ttm_page_alloc.h>
  51
  52#include <drm/drm_debugfs.h>
  53#include <drm/amdgpu_drm.h>
  54
  55#include "amdgpu.h"
  56#include "amdgpu_object.h"
  57#include "amdgpu_trace.h"
  58#include "amdgpu_amdkfd.h"
  59#include "amdgpu_sdma.h"
  60#include "amdgpu_ras.h"
 
  61#include "amdgpu_atomfirmware.h"
 
  62#include "bif/bif_4_1_d.h"
  63
  64#define AMDGPU_TTM_VRAM_MAX_DW_READ	(size_t)128
  65
 
  66
  67/**
  68 * amdgpu_init_mem_type - Initialize a memory manager for a specific type of
  69 * memory request.
  70 *
  71 * @bdev: The TTM BO device object (contains a reference to amdgpu_device)
  72 * @type: The type of memory requested
  73 * @man: The memory type manager for each domain
  74 *
  75 * This is called by ttm_bo_init_mm() when a buffer object is being
  76 * initialized.
  77 */
  78static int amdgpu_init_mem_type(struct ttm_bo_device *bdev, uint32_t type,
  79				struct ttm_mem_type_manager *man)
  80{
  81	struct amdgpu_device *adev;
  82
  83	adev = amdgpu_ttm_adev(bdev);
  84
  85	switch (type) {
  86	case TTM_PL_SYSTEM:
  87		/* System memory */
  88		man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
  89		man->available_caching = TTM_PL_MASK_CACHING;
  90		man->default_caching = TTM_PL_FLAG_CACHED;
  91		break;
  92	case TTM_PL_TT:
  93		/* GTT memory  */
  94		man->func = &amdgpu_gtt_mgr_func;
  95		man->available_caching = TTM_PL_MASK_CACHING;
  96		man->default_caching = TTM_PL_FLAG_CACHED;
  97		man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
  98		break;
  99	case TTM_PL_VRAM:
 100		/* "On-card" video ram */
 101		man->func = &amdgpu_vram_mgr_func;
 102		man->flags = TTM_MEMTYPE_FLAG_FIXED |
 103			     TTM_MEMTYPE_FLAG_MAPPABLE;
 104		man->available_caching = TTM_PL_FLAG_UNCACHED | TTM_PL_FLAG_WC;
 105		man->default_caching = TTM_PL_FLAG_WC;
 106		break;
 107	case AMDGPU_PL_GDS:
 108	case AMDGPU_PL_GWS:
 109	case AMDGPU_PL_OA:
 110		/* On-chip GDS memory*/
 111		man->func = &ttm_bo_manager_func;
 112		man->flags = TTM_MEMTYPE_FLAG_FIXED;
 113		man->available_caching = TTM_PL_FLAG_UNCACHED;
 114		man->default_caching = TTM_PL_FLAG_UNCACHED;
 115		break;
 116	default:
 117		DRM_ERROR("Unsupported memory type %u\n", (unsigned)type);
 118		return -EINVAL;
 119	}
 120	return 0;
 121}
 122
 123/**
 124 * amdgpu_evict_flags - Compute placement flags
 125 *
 126 * @bo: The buffer object to evict
 127 * @placement: Possible destination(s) for evicted BO
 128 *
 129 * Fill in placement data when ttm_bo_evict() is called
 130 */
 131static void amdgpu_evict_flags(struct ttm_buffer_object *bo,
 132				struct ttm_placement *placement)
 133{
 134	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
 135	struct amdgpu_bo *abo;
 136	static const struct ttm_place placements = {
 137		.fpfn = 0,
 138		.lpfn = 0,
 139		.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_SYSTEM
 
 140	};
 141
 142	/* Don't handle scatter gather BOs */
 143	if (bo->type == ttm_bo_type_sg) {
 144		placement->num_placement = 0;
 145		placement->num_busy_placement = 0;
 146		return;
 147	}
 148
 149	/* Object isn't an AMDGPU object so ignore */
 150	if (!amdgpu_bo_is_amdgpu_bo(bo)) {
 151		placement->placement = &placements;
 152		placement->busy_placement = &placements;
 153		placement->num_placement = 1;
 154		placement->num_busy_placement = 1;
 155		return;
 156	}
 157
 158	abo = ttm_to_amdgpu_bo(bo);
 159	switch (bo->mem.mem_type) {
 
 
 
 
 
 
 160	case AMDGPU_PL_GDS:
 161	case AMDGPU_PL_GWS:
 162	case AMDGPU_PL_OA:
 
 163		placement->num_placement = 0;
 164		placement->num_busy_placement = 0;
 165		return;
 166
 167	case TTM_PL_VRAM:
 168		if (!adev->mman.buffer_funcs_enabled) {
 169			/* Move to system memory */
 170			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
 171		} else if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
 172			   !(abo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) &&
 173			   amdgpu_bo_in_cpu_visible_vram(abo)) {
 174
 175			/* Try evicting to the CPU inaccessible part of VRAM
 176			 * first, but only set GTT as busy placement, so this
 177			 * BO will be evicted to GTT rather than causing other
 178			 * BOs to be evicted from VRAM
 179			 */
 180			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
 181							 AMDGPU_GEM_DOMAIN_GTT);
 
 182			abo->placements[0].fpfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
 183			abo->placements[0].lpfn = 0;
 184			abo->placement.busy_placement = &abo->placements[1];
 185			abo->placement.num_busy_placement = 1;
 186		} else {
 187			/* Move to GTT memory */
 188			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_GTT);
 
 189		}
 190		break;
 191	case TTM_PL_TT:
 
 192	default:
 193		amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
 194		break;
 195	}
 196	*placement = abo->placement;
 197}
 198
 199/**
 200 * amdgpu_verify_access - Verify access for a mmap call
 201 *
 202 * @bo:	The buffer object to map
 203 * @filp: The file pointer from the process performing the mmap
 204 *
 205 * This is called by ttm_bo_mmap() to verify whether a process
 206 * has the right to mmap a BO to their process space.
 207 */
 208static int amdgpu_verify_access(struct ttm_buffer_object *bo, struct file *filp)
 209{
 210	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
 211
 212	/*
 213	 * Don't verify access for KFD BOs. They don't have a GEM
 214	 * object associated with them.
 215	 */
 216	if (abo->kfd_bo)
 217		return 0;
 218
 219	if (amdgpu_ttm_tt_get_usermm(bo->ttm))
 220		return -EPERM;
 221	return drm_vma_node_verify_access(&abo->tbo.base.vma_node,
 222					  filp->private_data);
 223}
 224
 225/**
 226 * amdgpu_move_null - Register memory for a buffer object
 227 *
 228 * @bo: The bo to assign the memory to
 229 * @new_mem: The memory to be assigned.
 230 *
 231 * Assign the memory from new_mem to the memory of the buffer object bo.
 232 */
 233static void amdgpu_move_null(struct ttm_buffer_object *bo,
 234			     struct ttm_mem_reg *new_mem)
 235{
 236	struct ttm_mem_reg *old_mem = &bo->mem;
 237
 238	BUG_ON(old_mem->mm_node != NULL);
 239	*old_mem = *new_mem;
 240	new_mem->mm_node = NULL;
 241}
 242
 243/**
 244 * amdgpu_mm_node_addr - Compute the GPU relative offset of a GTT buffer.
 245 *
 246 * @bo: The bo to assign the memory to.
 247 * @mm_node: Memory manager node for drm allocator.
 248 * @mem: The region where the bo resides.
 249 *
 250 */
 251static uint64_t amdgpu_mm_node_addr(struct ttm_buffer_object *bo,
 252				    struct drm_mm_node *mm_node,
 253				    struct ttm_mem_reg *mem)
 254{
 255	uint64_t addr = 0;
 256
 257	if (mm_node->start != AMDGPU_BO_INVALID_OFFSET) {
 258		addr = mm_node->start << PAGE_SHIFT;
 259		addr += amdgpu_ttm_domain_start(amdgpu_ttm_adev(bo->bdev),
 260						mem->mem_type);
 261	}
 262	return addr;
 263}
 264
 265/**
 266 * amdgpu_find_mm_node - Helper function finds the drm_mm_node corresponding to
 267 * @offset. It also modifies the offset to be within the drm_mm_node returned
 268 *
 269 * @mem: The region where the bo resides.
 270 * @offset: The offset that drm_mm_node is used for finding.
 271 *
 272 */
 273static struct drm_mm_node *amdgpu_find_mm_node(struct ttm_mem_reg *mem,
 274					       uint64_t *offset)
 275{
 276	struct drm_mm_node *mm_node = mem->mm_node;
 277
 278	while (*offset >= (mm_node->size << PAGE_SHIFT)) {
 279		*offset -= (mm_node->size << PAGE_SHIFT);
 280		++mm_node;
 281	}
 282	return mm_node;
 283}
 284
 285/**
 286 * amdgpu_ttm_map_buffer - Map memory into the GART windows
 287 * @bo: buffer object to map
 288 * @mem: memory object to map
 289 * @mm_node: drm_mm node object to map
 290 * @num_pages: number of pages to map
 291 * @offset: offset into @mm_node where to start
 292 * @window: which GART window to use
 293 * @ring: DMA ring to use for the copy
 294 * @tmz: if we should setup a TMZ enabled mapping
 
 295 * @addr: resulting address inside the MC address space
 296 *
 297 * Setup one of the GART windows to access a specific piece of memory or return
 298 * the physical address for local memory.
 299 */
 300static int amdgpu_ttm_map_buffer(struct ttm_buffer_object *bo,
 301				 struct ttm_mem_reg *mem,
 302				 struct drm_mm_node *mm_node,
 303				 unsigned num_pages, uint64_t offset,
 304				 unsigned window, struct amdgpu_ring *ring,
 305				 bool tmz, uint64_t *addr)
 306{
 307	struct amdgpu_device *adev = ring->adev;
 308	struct amdgpu_job *job;
 309	unsigned num_dw, num_bytes;
 310	struct dma_fence *fence;
 311	uint64_t src_addr, dst_addr;
 
 312	void *cpu_addr;
 313	uint64_t flags;
 314	unsigned int i;
 315	int r;
 316
 317	BUG_ON(adev->mman.buffer_funcs->copy_max_bytes <
 318	       AMDGPU_GTT_MAX_TRANSFER_SIZE * 8);
 319
 
 
 
 320	/* Map only what can't be accessed directly */
 321	if (!tmz && mem->start != AMDGPU_BO_INVALID_OFFSET) {
 322		*addr = amdgpu_mm_node_addr(bo, mm_node, mem) + offset;
 
 323		return 0;
 324	}
 325
 
 
 
 
 
 
 
 
 
 
 
 
 326	*addr = adev->gmc.gart_start;
 327	*addr += (u64)window * AMDGPU_GTT_MAX_TRANSFER_SIZE *
 328		AMDGPU_GPU_PAGE_SIZE;
 329	*addr += offset & ~PAGE_MASK;
 330
 331	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
 332	num_bytes = num_pages * 8;
 333
 334	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4 + num_bytes,
 
 
 335				     AMDGPU_IB_POOL_DELAYED, &job);
 336	if (r)
 337		return r;
 338
 339	src_addr = num_dw * 4;
 340	src_addr += job->ibs[0].gpu_addr;
 341
 342	dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
 343	dst_addr += window * AMDGPU_GTT_MAX_TRANSFER_SIZE * 8;
 344	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
 345				dst_addr, num_bytes, false);
 346
 347	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
 348	WARN_ON(job->ibs[0].length_dw > num_dw);
 349
 350	flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, mem);
 351	if (tmz)
 352		flags |= AMDGPU_PTE_TMZ;
 353
 354	cpu_addr = &job->ibs[0].ptr[num_dw];
 355
 356	if (mem->mem_type == TTM_PL_TT) {
 357		struct ttm_dma_tt *dma;
 358		dma_addr_t *dma_address;
 359
 360		dma = container_of(bo->ttm, struct ttm_dma_tt, ttm);
 361		dma_address = &dma->dma_address[offset >> PAGE_SHIFT];
 362		r = amdgpu_gart_map(adev, 0, num_pages, dma_address, flags,
 363				    cpu_addr);
 364		if (r)
 365			goto error_free;
 366	} else {
 367		dma_addr_t dma_address;
 368
 369		dma_address = (mm_node->start << PAGE_SHIFT) + offset;
 370		dma_address += adev->vm_manager.vram_base_offset;
 371
 372		for (i = 0; i < num_pages; ++i) {
 373			r = amdgpu_gart_map(adev, i << PAGE_SHIFT, 1,
 374					    &dma_address, flags, cpu_addr);
 375			if (r)
 376				goto error_free;
 377
 378			dma_address += PAGE_SIZE;
 379		}
 380	}
 381
 382	r = amdgpu_job_submit(job, &adev->mman.entity,
 383			      AMDGPU_FENCE_OWNER_UNDEFINED, &fence);
 384	if (r)
 385		goto error_free;
 386
 387	dma_fence_put(fence);
 388
 389	return r;
 390
 391error_free:
 392	amdgpu_job_free(job);
 393	return r;
 394}
 395
 396/**
 397 * amdgpu_copy_ttm_mem_to_mem - Helper function for copy
 398 * @adev: amdgpu device
 399 * @src: buffer/address where to read from
 400 * @dst: buffer/address where to write to
 401 * @size: number of bytes to copy
 402 * @tmz: if a secure copy should be used
 403 * @resv: resv object to sync to
 404 * @f: Returns the last fence if multiple jobs are submitted.
 405 *
 406 * The function copies @size bytes from {src->mem + src->offset} to
 407 * {dst->mem + dst->offset}. src->bo and dst->bo could be same BO for a
 408 * move and different for a BO to BO copy.
 409 *
 410 */
 411int amdgpu_ttm_copy_mem_to_mem(struct amdgpu_device *adev,
 412			       const struct amdgpu_copy_mem *src,
 413			       const struct amdgpu_copy_mem *dst,
 414			       uint64_t size, bool tmz,
 415			       struct dma_resv *resv,
 416			       struct dma_fence **f)
 417{
 418	const uint32_t GTT_MAX_BYTES = (AMDGPU_GTT_MAX_TRANSFER_SIZE *
 419					AMDGPU_GPU_PAGE_SIZE);
 420
 421	uint64_t src_node_size, dst_node_size, src_offset, dst_offset;
 422	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
 423	struct drm_mm_node *src_mm, *dst_mm;
 424	struct dma_fence *fence = NULL;
 425	int r = 0;
 426
 427	if (!adev->mman.buffer_funcs_enabled) {
 428		DRM_ERROR("Trying to move memory with ring turned off.\n");
 429		return -EINVAL;
 430	}
 431
 432	src_offset = src->offset;
 433	if (src->mem->mm_node) {
 434		src_mm = amdgpu_find_mm_node(src->mem, &src_offset);
 435		src_node_size = (src_mm->size << PAGE_SHIFT) - src_offset;
 436	} else {
 437		src_mm = NULL;
 438		src_node_size = ULLONG_MAX;
 439	}
 440
 441	dst_offset = dst->offset;
 442	if (dst->mem->mm_node) {
 443		dst_mm = amdgpu_find_mm_node(dst->mem, &dst_offset);
 444		dst_node_size = (dst_mm->size << PAGE_SHIFT) - dst_offset;
 445	} else {
 446		dst_mm = NULL;
 447		dst_node_size = ULLONG_MAX;
 448	}
 449
 450	mutex_lock(&adev->mman.gtt_window_lock);
 451
 452	while (size) {
 453		uint32_t src_page_offset = src_offset & ~PAGE_MASK;
 454		uint32_t dst_page_offset = dst_offset & ~PAGE_MASK;
 455		struct dma_fence *next;
 456		uint32_t cur_size;
 457		uint64_t from, to;
 458
 459		/* Copy size cannot exceed GTT_MAX_BYTES. So if src or dst
 460		 * begins at an offset, then adjust the size accordingly
 461		 */
 462		cur_size = max(src_page_offset, dst_page_offset);
 463		cur_size = min(min3(src_node_size, dst_node_size, size),
 464			       (uint64_t)(GTT_MAX_BYTES - cur_size));
 465
 466		/* Map src to window 0 and dst to window 1. */
 467		r = amdgpu_ttm_map_buffer(src->bo, src->mem, src_mm,
 468					  PFN_UP(cur_size + src_page_offset),
 469					  src_offset, 0, ring, tmz, &from);
 470		if (r)
 471			goto error;
 472
 473		r = amdgpu_ttm_map_buffer(dst->bo, dst->mem, dst_mm,
 474					  PFN_UP(cur_size + dst_page_offset),
 475					  dst_offset, 1, ring, tmz, &to);
 476		if (r)
 477			goto error;
 478
 479		r = amdgpu_copy_buffer(ring, from, to, cur_size,
 480				       resv, &next, false, true, tmz);
 481		if (r)
 482			goto error;
 483
 484		dma_fence_put(fence);
 485		fence = next;
 486
 487		size -= cur_size;
 488		if (!size)
 489			break;
 490
 491		src_node_size -= cur_size;
 492		if (!src_node_size) {
 493			++src_mm;
 494			src_node_size = src_mm->size << PAGE_SHIFT;
 495			src_offset = 0;
 496		} else {
 497			src_offset += cur_size;
 498		}
 499
 500		dst_node_size -= cur_size;
 501		if (!dst_node_size) {
 502			++dst_mm;
 503			dst_node_size = dst_mm->size << PAGE_SHIFT;
 504			dst_offset = 0;
 505		} else {
 506			dst_offset += cur_size;
 507		}
 508	}
 509error:
 510	mutex_unlock(&adev->mman.gtt_window_lock);
 511	if (f)
 512		*f = dma_fence_get(fence);
 513	dma_fence_put(fence);
 514	return r;
 515}
 516
 517/**
 518 * amdgpu_move_blit - Copy an entire buffer to another buffer
 519 *
 520 * This is a helper called by amdgpu_bo_move() and amdgpu_move_vram_ram() to
 521 * help move buffers to and from VRAM.
 522 */
 523static int amdgpu_move_blit(struct ttm_buffer_object *bo,
 524			    bool evict, bool no_wait_gpu,
 525			    struct ttm_mem_reg *new_mem,
 526			    struct ttm_mem_reg *old_mem)
 527{
 528	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
 529	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
 530	struct amdgpu_copy_mem src, dst;
 531	struct dma_fence *fence = NULL;
 532	int r;
 533
 534	src.bo = bo;
 535	dst.bo = bo;
 536	src.mem = old_mem;
 537	dst.mem = new_mem;
 538	src.offset = 0;
 539	dst.offset = 0;
 540
 541	r = amdgpu_ttm_copy_mem_to_mem(adev, &src, &dst,
 542				       new_mem->num_pages << PAGE_SHIFT,
 543				       amdgpu_bo_encrypted(abo),
 544				       bo->base.resv, &fence);
 545	if (r)
 546		goto error;
 547
 548	/* clear the space being freed */
 549	if (old_mem->mem_type == TTM_PL_VRAM &&
 550	    (abo->flags & AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE)) {
 551		struct dma_fence *wipe_fence = NULL;
 552
 553		r = amdgpu_fill_buffer(ttm_to_amdgpu_bo(bo), AMDGPU_POISON,
 554				       NULL, &wipe_fence);
 555		if (r) {
 556			goto error;
 557		} else if (wipe_fence) {
 558			dma_fence_put(fence);
 559			fence = wipe_fence;
 560		}
 561	}
 562
 563	/* Always block for VM page tables before committing the new location */
 564	if (bo->type == ttm_bo_type_kernel)
 565		r = ttm_bo_move_accel_cleanup(bo, fence, true, new_mem);
 566	else
 567		r = ttm_bo_pipeline_move(bo, fence, evict, new_mem);
 568	dma_fence_put(fence);
 569	return r;
 570
 571error:
 572	if (fence)
 573		dma_fence_wait(fence, false);
 574	dma_fence_put(fence);
 575	return r;
 576}
 577
 578/**
 579 * amdgpu_move_vram_ram - Copy VRAM buffer to RAM buffer
 580 *
 581 * Called by amdgpu_bo_move().
 582 */
 583static int amdgpu_move_vram_ram(struct ttm_buffer_object *bo, bool evict,
 584				struct ttm_operation_ctx *ctx,
 585				struct ttm_mem_reg *new_mem)
 586{
 587	struct ttm_mem_reg *old_mem = &bo->mem;
 588	struct ttm_mem_reg tmp_mem;
 589	struct ttm_place placements;
 590	struct ttm_placement placement;
 591	int r;
 592
 593	/* create space/pages for new_mem in GTT space */
 594	tmp_mem = *new_mem;
 595	tmp_mem.mm_node = NULL;
 596	placement.num_placement = 1;
 597	placement.placement = &placements;
 598	placement.num_busy_placement = 1;
 599	placement.busy_placement = &placements;
 600	placements.fpfn = 0;
 601	placements.lpfn = 0;
 602	placements.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
 603	r = ttm_bo_mem_space(bo, &placement, &tmp_mem, ctx);
 604	if (unlikely(r)) {
 605		pr_err("Failed to find GTT space for blit from VRAM\n");
 606		return r;
 607	}
 608
 609	/* set caching flags */
 610	r = ttm_tt_set_placement_caching(bo->ttm, tmp_mem.placement);
 611	if (unlikely(r)) {
 612		goto out_cleanup;
 613	}
 614
 615	/* Bind the memory to the GTT space */
 616	r = ttm_tt_bind(bo->ttm, &tmp_mem, ctx);
 617	if (unlikely(r)) {
 618		goto out_cleanup;
 619	}
 620
 621	/* blit VRAM to GTT */
 622	r = amdgpu_move_blit(bo, evict, ctx->no_wait_gpu, &tmp_mem, old_mem);
 623	if (unlikely(r)) {
 624		goto out_cleanup;
 625	}
 626
 627	/* move BO (in tmp_mem) to new_mem */
 628	r = ttm_bo_move_ttm(bo, ctx, new_mem);
 629out_cleanup:
 630	ttm_bo_mem_put(bo, &tmp_mem);
 631	return r;
 632}
 633
 634/**
 635 * amdgpu_move_ram_vram - Copy buffer from RAM to VRAM
 636 *
 637 * Called by amdgpu_bo_move().
 638 */
 639static int amdgpu_move_ram_vram(struct ttm_buffer_object *bo, bool evict,
 640				struct ttm_operation_ctx *ctx,
 641				struct ttm_mem_reg *new_mem)
 642{
 643	struct ttm_mem_reg *old_mem = &bo->mem;
 644	struct ttm_mem_reg tmp_mem;
 645	struct ttm_placement placement;
 646	struct ttm_place placements;
 647	int r;
 648
 649	/* make space in GTT for old_mem buffer */
 650	tmp_mem = *new_mem;
 651	tmp_mem.mm_node = NULL;
 652	placement.num_placement = 1;
 653	placement.placement = &placements;
 654	placement.num_busy_placement = 1;
 655	placement.busy_placement = &placements;
 656	placements.fpfn = 0;
 657	placements.lpfn = 0;
 658	placements.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
 659	r = ttm_bo_mem_space(bo, &placement, &tmp_mem, ctx);
 660	if (unlikely(r)) {
 661		pr_err("Failed to find GTT space for blit to VRAM\n");
 662		return r;
 663	}
 664
 665	/* move/bind old memory to GTT space */
 666	r = ttm_bo_move_ttm(bo, ctx, &tmp_mem);
 667	if (unlikely(r)) {
 668		goto out_cleanup;
 669	}
 670
 671	/* copy to VRAM */
 672	r = amdgpu_move_blit(bo, evict, ctx->no_wait_gpu, new_mem, old_mem);
 673	if (unlikely(r)) {
 674		goto out_cleanup;
 675	}
 676out_cleanup:
 677	ttm_bo_mem_put(bo, &tmp_mem);
 678	return r;
 679}
 680
 681/**
 682 * amdgpu_mem_visible - Check that memory can be accessed by ttm_bo_move_memcpy
 683 *
 684 * Called by amdgpu_bo_move()
 685 */
 686static bool amdgpu_mem_visible(struct amdgpu_device *adev,
 687			       struct ttm_mem_reg *mem)
 688{
 689	struct drm_mm_node *nodes = mem->mm_node;
 
 
 690
 691	if (mem->mem_type == TTM_PL_SYSTEM ||
 692	    mem->mem_type == TTM_PL_TT)
 693		return true;
 694	if (mem->mem_type != TTM_PL_VRAM)
 695		return false;
 696
 697	/* ttm_mem_reg_ioremap only supports contiguous memory */
 698	if (nodes->size != mem->num_pages)
 699		return false;
 
 700
 701	return ((nodes->start + nodes->size) << PAGE_SHIFT)
 702		<= adev->gmc.visible_vram_size;
 
 
 
 
 
 
 
 
 
 703}
 704
 705/**
 706 * amdgpu_bo_move - Move a buffer object to a new memory location
 707 *
 708 * Called by ttm_bo_handle_move_mem()
 709 */
 710static int amdgpu_bo_move(struct ttm_buffer_object *bo, bool evict,
 711			  struct ttm_operation_ctx *ctx,
 712			  struct ttm_mem_reg *new_mem)
 
 713{
 714	struct amdgpu_device *adev;
 715	struct amdgpu_bo *abo;
 716	struct ttm_mem_reg *old_mem = &bo->mem;
 717	int r;
 718
 719	/* Can't move a pinned BO */
 720	abo = ttm_to_amdgpu_bo(bo);
 721	if (WARN_ON_ONCE(abo->pin_count > 0))
 722		return -EINVAL;
 
 
 723
 
 724	adev = amdgpu_ttm_adev(bo->bdev);
 725
 726	if (old_mem->mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
 727		amdgpu_move_null(bo, new_mem);
 728		return 0;
 
 729	}
 730	if ((old_mem->mem_type == TTM_PL_TT &&
 731	     new_mem->mem_type == TTM_PL_SYSTEM) ||
 732	    (old_mem->mem_type == TTM_PL_SYSTEM &&
 733	     new_mem->mem_type == TTM_PL_TT)) {
 734		/* bind is enough */
 735		amdgpu_move_null(bo, new_mem);
 736		return 0;
 
 
 
 
 
 
 
 
 
 
 737	}
 
 738	if (old_mem->mem_type == AMDGPU_PL_GDS ||
 739	    old_mem->mem_type == AMDGPU_PL_GWS ||
 740	    old_mem->mem_type == AMDGPU_PL_OA ||
 
 741	    new_mem->mem_type == AMDGPU_PL_GDS ||
 742	    new_mem->mem_type == AMDGPU_PL_GWS ||
 743	    new_mem->mem_type == AMDGPU_PL_OA) {
 
 744		/* Nothing to save here */
 745		amdgpu_move_null(bo, new_mem);
 746		return 0;
 747	}
 748
 749	if (!adev->mman.buffer_funcs_enabled) {
 750		r = -ENODEV;
 751		goto memcpy;
 
 
 
 
 752	}
 753
 754	if (old_mem->mem_type == TTM_PL_VRAM &&
 755	    new_mem->mem_type == TTM_PL_SYSTEM) {
 756		r = amdgpu_move_vram_ram(bo, evict, ctx, new_mem);
 757	} else if (old_mem->mem_type == TTM_PL_SYSTEM &&
 758		   new_mem->mem_type == TTM_PL_VRAM) {
 759		r = amdgpu_move_ram_vram(bo, evict, ctx, new_mem);
 
 
 
 
 
 
 
 760	} else {
 761		r = amdgpu_move_blit(bo, evict, ctx->no_wait_gpu,
 762				     new_mem, old_mem);
 763	}
 764
 765	if (r) {
 766memcpy:
 767		/* Check that all memory is CPU accessible */
 768		if (!amdgpu_mem_visible(adev, old_mem) ||
 769		    !amdgpu_mem_visible(adev, new_mem)) {
 770			pr_err("Move buffer fallback to memcpy unavailable\n");
 771			return r;
 772		}
 773
 774		r = ttm_bo_move_memcpy(bo, ctx, new_mem);
 775		if (r)
 776			return r;
 777	}
 778
 779	if (bo->type == ttm_bo_type_device &&
 780	    new_mem->mem_type == TTM_PL_VRAM &&
 781	    old_mem->mem_type != TTM_PL_VRAM) {
 782		/* amdgpu_bo_fault_reserve_notify will re-set this if the CPU
 783		 * accesses the BO after it's moved.
 784		 */
 785		abo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
 786	}
 787
 788	/* update statistics */
 789	atomic64_add((u64)bo->num_pages << PAGE_SHIFT, &adev->num_bytes_moved);
 
 790	return 0;
 791}
 792
 793/**
 794 * amdgpu_ttm_io_mem_reserve - Reserve a block of memory during a fault
 795 *
 796 * Called by ttm_mem_io_reserve() ultimately via ttm_bo_vm_fault()
 797 */
 798static int amdgpu_ttm_io_mem_reserve(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
 
 799{
 800	struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
 801	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
 802	struct drm_mm_node *mm_node = mem->mm_node;
 803
 804	mem->bus.addr = NULL;
 805	mem->bus.offset = 0;
 806	mem->bus.size = mem->num_pages << PAGE_SHIFT;
 807	mem->bus.base = 0;
 808	mem->bus.is_iomem = false;
 809	if (!(man->flags & TTM_MEMTYPE_FLAG_MAPPABLE))
 810		return -EINVAL;
 811	switch (mem->mem_type) {
 812	case TTM_PL_SYSTEM:
 813		/* system memory */
 814		return 0;
 815	case TTM_PL_TT:
 
 816		break;
 817	case TTM_PL_VRAM:
 818		mem->bus.offset = mem->start << PAGE_SHIFT;
 819		/* check if it's visible */
 820		if ((mem->bus.offset + mem->bus.size) > adev->gmc.visible_vram_size)
 821			return -EINVAL;
 822		/* Only physically contiguous buffers apply. In a contiguous
 823		 * buffer, size of the first mm_node would match the number of
 824		 * pages in ttm_mem_reg.
 825		 */
 826		if (adev->mman.aper_base_kaddr &&
 827		    (mm_node->size == mem->num_pages))
 828			mem->bus.addr = (u8 *)adev->mman.aper_base_kaddr +
 829					mem->bus.offset;
 830
 831		mem->bus.base = adev->gmc.aper_base;
 
 
 
 
 
 832		mem->bus.is_iomem = true;
 
 833		break;
 834	default:
 835		return -EINVAL;
 836	}
 837	return 0;
 838}
 839
 840static unsigned long amdgpu_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
 841					   unsigned long page_offset)
 842{
 843	uint64_t offset = (page_offset << PAGE_SHIFT);
 844	struct drm_mm_node *mm;
 
 
 
 845
 846	mm = amdgpu_find_mm_node(&bo->mem, &offset);
 847	return (bo->mem.bus.base >> PAGE_SHIFT) + mm->start +
 848		(offset >> PAGE_SHIFT);
 
 849}
 850
 851/**
 852 * amdgpu_ttm_domain_start - Returns GPU start address
 853 * @adev: amdgpu device object
 854 * @type: type of the memory
 855 *
 856 * Returns:
 857 * GPU start address of a memory domain
 858 */
 859
 860uint64_t amdgpu_ttm_domain_start(struct amdgpu_device *adev, uint32_t type)
 861{
 862	switch (type) {
 863	case TTM_PL_TT:
 864		return adev->gmc.gart_start;
 865	case TTM_PL_VRAM:
 866		return adev->gmc.vram_start;
 867	}
 868
 869	return 0;
 870}
 871
 872/*
 873 * TTM backend functions.
 874 */
 875struct amdgpu_ttm_tt {
 876	struct ttm_dma_tt	ttm;
 877	struct drm_gem_object	*gobj;
 878	u64			offset;
 879	uint64_t		userptr;
 880	struct task_struct	*usertask;
 881	uint32_t		userflags;
 882#if IS_ENABLED(CONFIG_DRM_AMDGPU_USERPTR)
 883	struct hmm_range	*range;
 884#endif
 885};
 886
 
 
 887#ifdef CONFIG_DRM_AMDGPU_USERPTR
 888/**
 889 * amdgpu_ttm_tt_get_user_pages - get device accessible pages that back user
 890 * memory and start HMM tracking CPU page table update
 891 *
 892 * Calling function must call amdgpu_ttm_tt_userptr_range_done() once and only
 893 * once afterwards to stop HMM tracking
 894 */
 895int amdgpu_ttm_tt_get_user_pages(struct amdgpu_bo *bo, struct page **pages)
 
 896{
 897	struct ttm_tt *ttm = bo->tbo.ttm;
 898	struct amdgpu_ttm_tt *gtt = (void *)ttm;
 899	unsigned long start = gtt->userptr;
 900	struct vm_area_struct *vma;
 901	struct hmm_range *range;
 902	unsigned long timeout;
 903	struct mm_struct *mm;
 904	unsigned long i;
 905	int r = 0;
 906
 
 
 
 907	mm = bo->notifier.mm;
 908	if (unlikely(!mm)) {
 909		DRM_DEBUG_DRIVER("BO is not registered?\n");
 910		return -EFAULT;
 911	}
 912
 913	/* Another get_user_pages is running at the same time?? */
 914	if (WARN_ON(gtt->range))
 915		return -EFAULT;
 916
 917	if (!mmget_not_zero(mm)) /* Happens during process shutdown */
 918		return -ESRCH;
 919
 920	range = kzalloc(sizeof(*range), GFP_KERNEL);
 921	if (unlikely(!range)) {
 922		r = -ENOMEM;
 923		goto out;
 924	}
 925	range->notifier = &bo->notifier;
 926	range->start = bo->notifier.interval_tree.start;
 927	range->end = bo->notifier.interval_tree.last + 1;
 928	range->default_flags = HMM_PFN_REQ_FAULT;
 929	if (!amdgpu_ttm_tt_is_readonly(ttm))
 930		range->default_flags |= HMM_PFN_REQ_WRITE;
 931
 932	range->hmm_pfns = kvmalloc_array(ttm->num_pages,
 933					 sizeof(*range->hmm_pfns), GFP_KERNEL);
 934	if (unlikely(!range->hmm_pfns)) {
 935		r = -ENOMEM;
 936		goto out_free_ranges;
 937	}
 938
 939	mmap_read_lock(mm);
 940	vma = find_vma(mm, start);
 941	if (unlikely(!vma || start < vma->vm_start)) {
 942		r = -EFAULT;
 943		goto out_unlock;
 944	}
 945	if (unlikely((gtt->userflags & AMDGPU_GEM_USERPTR_ANONONLY) &&
 946		vma->vm_file)) {
 947		r = -EPERM;
 948		goto out_unlock;
 949	}
 950	mmap_read_unlock(mm);
 951	timeout = jiffies + msecs_to_jiffies(HMM_RANGE_DEFAULT_TIMEOUT);
 952
 953retry:
 954	range->notifier_seq = mmu_interval_read_begin(&bo->notifier);
 955
 956	mmap_read_lock(mm);
 957	r = hmm_range_fault(range);
 
 
 958	mmap_read_unlock(mm);
 959	if (unlikely(r)) {
 960		/*
 961		 * FIXME: This timeout should encompass the retry from
 962		 * mmu_interval_read_retry() as well.
 963		 */
 964		if (r == -EBUSY && !time_after(jiffies, timeout))
 965			goto retry;
 966		goto out_free_pfns;
 967	}
 968
 969	/*
 970	 * Due to default_flags, all pages are HMM_PFN_VALID or
 971	 * hmm_range_fault() fails. FIXME: The pages cannot be touched outside
 972	 * the notifier_lock, and mmu_interval_read_retry() must be done first.
 973	 */
 974	for (i = 0; i < ttm->num_pages; i++)
 975		pages[i] = hmm_pfn_to_page(range->hmm_pfns[i]);
 976
 977	gtt->range = range;
 978	mmput(mm);
 979
 980	return 0;
 981
 982out_unlock:
 983	mmap_read_unlock(mm);
 984out_free_pfns:
 985	kvfree(range->hmm_pfns);
 986out_free_ranges:
 987	kfree(range);
 988out:
 989	mmput(mm);
 990	return r;
 991}
 992
 993/**
 994 * amdgpu_ttm_tt_userptr_range_done - stop HMM track the CPU page table change
 
 
 
 
 
 
 
 
 
 
 
 995 * Check if the pages backing this ttm range have been invalidated
 996 *
 997 * Returns: true if pages are still valid
 998 */
 999bool amdgpu_ttm_tt_get_user_pages_done(struct ttm_tt *ttm)
 
1000{
1001	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1002	bool r = false;
1003
1004	if (!gtt || !gtt->userptr)
1005		return false;
1006
1007	DRM_DEBUG_DRIVER("user_pages_done 0x%llx pages 0x%lx\n",
1008		gtt->userptr, ttm->num_pages);
1009
1010	WARN_ONCE(!gtt->range || !gtt->range->hmm_pfns,
1011		"No user pages to check\n");
1012
1013	if (gtt->range) {
1014		/*
1015		 * FIXME: Must always hold notifier_lock for this, and must
1016		 * not ignore the return code.
1017		 */
1018		r = mmu_interval_read_retry(gtt->range->notifier,
1019					 gtt->range->notifier_seq);
1020		kvfree(gtt->range->hmm_pfns);
1021		kfree(gtt->range);
1022		gtt->range = NULL;
1023	}
1024
1025	return !r;
1026}
1027#endif
1028
1029/**
1030 * amdgpu_ttm_tt_set_user_pages - Copy pages in, putting old pages as necessary.
1031 *
1032 * Called by amdgpu_cs_list_validate(). This creates the page list
1033 * that backs user memory and will ultimately be mapped into the device
1034 * address space.
1035 */
1036void amdgpu_ttm_tt_set_user_pages(struct ttm_tt *ttm, struct page **pages)
1037{
1038	unsigned long i;
1039
1040	for (i = 0; i < ttm->num_pages; ++i)
1041		ttm->pages[i] = pages ? pages[i] : NULL;
1042}
1043
1044/**
1045 * amdgpu_ttm_tt_pin_userptr - 	prepare the sg table with the user pages
1046 *
1047 * Called by amdgpu_ttm_backend_bind()
1048 **/
1049static int amdgpu_ttm_tt_pin_userptr(struct ttm_tt *ttm)
 
1050{
1051	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1052	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1053	int r;
1054
1055	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1056	enum dma_data_direction direction = write ?
1057		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
 
1058
1059	/* Allocate an SG array and squash pages into it */
1060	r = sg_alloc_table_from_pages(ttm->sg, ttm->pages, ttm->num_pages, 0,
1061				      ttm->num_pages << PAGE_SHIFT,
1062				      GFP_KERNEL);
1063	if (r)
1064		goto release_sg;
1065
1066	/* Map SG to device */
1067	r = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
1068	if (r)
1069		goto release_sg;
1070
1071	/* convert SG to linear array of pages and dma addresses */
1072	drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
1073					 gtt->ttm.dma_address, ttm->num_pages);
1074
1075	return 0;
1076
1077release_sg:
1078	kfree(ttm->sg);
1079	ttm->sg = NULL;
1080	return r;
1081}
1082
1083/**
1084 * amdgpu_ttm_tt_unpin_userptr - Unpin and unmap userptr pages
1085 */
1086static void amdgpu_ttm_tt_unpin_userptr(struct ttm_tt *ttm)
 
1087{
1088	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1089	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1090
1091	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1092	enum dma_data_direction direction = write ?
1093		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
1094
1095	/* double check that we don't free the table twice */
1096	if (!ttm->sg->sgl)
1097		return;
1098
1099	/* unmap the pages mapped to the device */
1100	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
1101	sg_free_table(ttm->sg);
 
1102
1103#if IS_ENABLED(CONFIG_DRM_AMDGPU_USERPTR)
1104	if (gtt->range) {
1105		unsigned long i;
1106
1107		for (i = 0; i < ttm->num_pages; i++) {
1108			if (ttm->pages[i] !=
1109			    hmm_pfn_to_page(gtt->range->hmm_pfns[i]))
1110				break;
1111		}
 
 
 
 
 
 
 
 
 
 
 
1112
1113		WARN((i == ttm->num_pages), "Missing get_user_page_done\n");
 
 
 
 
 
 
 
 
 
 
 
 
 
1114	}
1115#endif
1116}
1117
1118static int amdgpu_ttm_gart_bind(struct amdgpu_device *adev,
1119				struct ttm_buffer_object *tbo,
1120				uint64_t flags)
1121{
1122	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(tbo);
1123	struct ttm_tt *ttm = tbo->ttm;
1124	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1125	int r;
1126
1127	if (amdgpu_bo_encrypted(abo))
1128		flags |= AMDGPU_PTE_TMZ;
1129
1130	if (abo->flags & AMDGPU_GEM_CREATE_CP_MQD_GFX9) {
1131		uint64_t page_idx = 1;
1132
1133		r = amdgpu_gart_bind(adev, gtt->offset, page_idx,
1134				ttm->pages, gtt->ttm.dma_address, flags);
1135		if (r)
1136			goto gart_bind_fail;
1137
1138		/* The memory type of the first page defaults to UC. Now
1139		 * modify the memory type to NC from the second page of
1140		 * the BO onward.
1141		 */
1142		flags &= ~AMDGPU_PTE_MTYPE_VG10_MASK;
1143		flags |= AMDGPU_PTE_MTYPE_VG10(AMDGPU_MTYPE_NC);
1144
1145		r = amdgpu_gart_bind(adev,
1146				gtt->offset + (page_idx << PAGE_SHIFT),
1147				ttm->num_pages - page_idx,
1148				&ttm->pages[page_idx],
1149				&(gtt->ttm.dma_address[page_idx]), flags);
1150	} else {
1151		r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
1152				     ttm->pages, gtt->ttm.dma_address, flags);
1153	}
1154
1155gart_bind_fail:
1156	if (r)
1157		DRM_ERROR("failed to bind %lu pages at 0x%08llX\n",
1158			  ttm->num_pages, gtt->offset);
1159
1160	return r;
1161}
1162
1163/**
1164 * amdgpu_ttm_backend_bind - Bind GTT memory
1165 *
1166 * Called by ttm_tt_bind() on behalf of ttm_bo_handle_move_mem().
1167 * This handles binding GTT memory to the device address space.
1168 */
1169static int amdgpu_ttm_backend_bind(struct ttm_tt *ttm,
1170				   struct ttm_mem_reg *bo_mem)
 
1171{
1172	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1173	struct amdgpu_ttm_tt *gtt = (void*)ttm;
1174	uint64_t flags;
1175	int r = 0;
 
 
 
 
 
 
1176
1177	if (gtt->userptr) {
1178		r = amdgpu_ttm_tt_pin_userptr(ttm);
1179		if (r) {
1180			DRM_ERROR("failed to pin userptr\n");
1181			return r;
1182		}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1183	}
 
1184	if (!ttm->num_pages) {
1185		WARN(1, "nothing to bind %lu pages for mreg %p back %p!\n",
1186		     ttm->num_pages, bo_mem, ttm);
1187	}
1188
1189	if (bo_mem->mem_type == AMDGPU_PL_GDS ||
1190	    bo_mem->mem_type == AMDGPU_PL_GWS ||
1191	    bo_mem->mem_type == AMDGPU_PL_OA)
1192		return -EINVAL;
1193
1194	if (!amdgpu_gtt_mgr_has_gart_addr(bo_mem)) {
1195		gtt->offset = AMDGPU_BO_INVALID_OFFSET;
1196		return 0;
1197	}
1198
1199	/* compute PTE flags relevant to this BO memory */
1200	flags = amdgpu_ttm_tt_pte_flags(adev, ttm, bo_mem);
1201
1202	/* bind pages into GART page tables */
1203	gtt->offset = (u64)bo_mem->start << PAGE_SHIFT;
1204	r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
1205		ttm->pages, gtt->ttm.dma_address, flags);
1206
1207	if (r)
1208		DRM_ERROR("failed to bind %lu pages at 0x%08llX\n",
1209			  ttm->num_pages, gtt->offset);
1210	return r;
1211}
1212
1213/**
1214 * amdgpu_ttm_alloc_gart - Allocate GART memory for buffer object
 
 
 
 
 
1215 */
1216int amdgpu_ttm_alloc_gart(struct ttm_buffer_object *bo)
1217{
1218	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1219	struct ttm_operation_ctx ctx = { false, false };
1220	struct amdgpu_ttm_tt *gtt = (void*)bo->ttm;
1221	struct ttm_mem_reg tmp;
1222	struct ttm_placement placement;
1223	struct ttm_place placements;
 
1224	uint64_t addr, flags;
1225	int r;
1226
1227	if (bo->mem.start != AMDGPU_BO_INVALID_OFFSET)
1228		return 0;
1229
1230	addr = amdgpu_gmc_agp_addr(bo);
1231	if (addr != AMDGPU_BO_INVALID_OFFSET) {
1232		bo->mem.start = addr >> PAGE_SHIFT;
1233	} else {
1234
1235		/* allocate GART space */
1236		tmp = bo->mem;
1237		tmp.mm_node = NULL;
1238		placement.num_placement = 1;
1239		placement.placement = &placements;
1240		placement.num_busy_placement = 1;
1241		placement.busy_placement = &placements;
1242		placements.fpfn = 0;
1243		placements.lpfn = adev->gmc.gart_size >> PAGE_SHIFT;
1244		placements.flags = (bo->mem.placement & ~TTM_PL_MASK_MEM) |
1245			TTM_PL_FLAG_TT;
1246
1247		r = ttm_bo_mem_space(bo, &placement, &tmp, &ctx);
1248		if (unlikely(r))
1249			return r;
 
 
 
 
 
 
1250
1251		/* compute PTE flags for this buffer object */
1252		flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, &tmp);
 
1253
1254		/* Bind pages */
1255		gtt->offset = (u64)tmp.start << PAGE_SHIFT;
1256		r = amdgpu_ttm_gart_bind(adev, bo, flags);
1257		if (unlikely(r)) {
1258			ttm_bo_mem_put(bo, &tmp);
1259			return r;
1260		}
1261
1262		ttm_bo_mem_put(bo, &bo->mem);
1263		bo->mem = tmp;
1264	}
 
 
 
1265
1266	return 0;
1267}
1268
1269/**
1270 * amdgpu_ttm_recover_gart - Rebind GTT pages
1271 *
1272 * Called by amdgpu_gtt_mgr_recover() from amdgpu_device_reset() to
1273 * rebind GTT pages during a GPU reset.
1274 */
1275int amdgpu_ttm_recover_gart(struct ttm_buffer_object *tbo)
1276{
1277	struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
1278	uint64_t flags;
1279	int r;
1280
1281	if (!tbo->ttm)
1282		return 0;
1283
1284	flags = amdgpu_ttm_tt_pte_flags(adev, tbo->ttm, &tbo->mem);
1285	r = amdgpu_ttm_gart_bind(adev, tbo, flags);
1286
1287	return r;
 
1288}
1289
1290/**
1291 * amdgpu_ttm_backend_unbind - Unbind GTT mapped pages
1292 *
1293 * Called by ttm_tt_unbind() on behalf of ttm_bo_move_ttm() and
1294 * ttm_tt_destroy().
1295 */
1296static void amdgpu_ttm_backend_unbind(struct ttm_tt *ttm)
 
1297{
1298	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1299	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1300	int r;
1301
1302	/* if the pages have userptr pinning then clear that first */
1303	if (gtt->userptr)
1304		amdgpu_ttm_tt_unpin_userptr(ttm);
 
 
 
 
 
 
 
 
 
 
1305
1306	if (gtt->offset == AMDGPU_BO_INVALID_OFFSET)
1307		return;
1308
1309	/* unbind shouldn't be done for GDS/GWS/OA in ttm_bo_clean_mm */
1310	r = amdgpu_gart_unbind(adev, gtt->offset, ttm->num_pages);
1311	if (r)
1312		DRM_ERROR("failed to unbind %lu pages at 0x%08llX\n",
1313			  gtt->ttm.ttm.num_pages, gtt->offset);
1314}
1315
1316static void amdgpu_ttm_backend_destroy(struct ttm_tt *ttm)
 
1317{
1318	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1319
1320	if (gtt->usertask)
1321		put_task_struct(gtt->usertask);
1322
1323	ttm_dma_tt_fini(&gtt->ttm);
1324	kfree(gtt);
1325}
1326
1327static struct ttm_backend_func amdgpu_backend_func = {
1328	.bind = &amdgpu_ttm_backend_bind,
1329	.unbind = &amdgpu_ttm_backend_unbind,
1330	.destroy = &amdgpu_ttm_backend_destroy,
1331};
1332
1333/**
1334 * amdgpu_ttm_tt_create - Create a ttm_tt object for a given BO
1335 *
1336 * @bo: The buffer object to create a GTT ttm_tt object around
 
1337 *
1338 * Called by ttm_tt_create().
1339 */
1340static struct ttm_tt *amdgpu_ttm_tt_create(struct ttm_buffer_object *bo,
1341					   uint32_t page_flags)
1342{
 
 
1343	struct amdgpu_ttm_tt *gtt;
 
1344
1345	gtt = kzalloc(sizeof(struct amdgpu_ttm_tt), GFP_KERNEL);
1346	if (gtt == NULL) {
1347		return NULL;
1348	}
1349	gtt->ttm.ttm.func = &amdgpu_backend_func;
1350	gtt->gobj = &bo->base;
 
 
 
 
 
 
 
 
 
1351
1352	/* allocate space for the uninitialized page entries */
1353	if (ttm_sg_tt_init(&gtt->ttm, bo, page_flags)) {
1354		kfree(gtt);
1355		return NULL;
1356	}
1357	return &gtt->ttm.ttm;
1358}
1359
1360/**
1361 * amdgpu_ttm_tt_populate - Map GTT pages visible to the device
1362 *
1363 * Map the pages of a ttm_tt object to an address space visible
1364 * to the underlying device.
1365 */
1366static int amdgpu_ttm_tt_populate(struct ttm_tt *ttm,
1367			struct ttm_operation_ctx *ctx)
 
1368{
1369	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1370	struct amdgpu_ttm_tt *gtt = (void *)ttm;
 
 
 
1371
1372	/* user pages are bound by amdgpu_ttm_tt_pin_userptr() */
1373	if (gtt && gtt->userptr) {
1374		ttm->sg = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
1375		if (!ttm->sg)
1376			return -ENOMEM;
1377
1378		ttm->page_flags |= TTM_PAGE_FLAG_SG;
1379		ttm->state = tt_unbound;
1380		return 0;
1381	}
1382
1383	if (ttm->page_flags & TTM_PAGE_FLAG_SG) {
1384		if (!ttm->sg) {
1385			struct dma_buf_attachment *attach;
1386			struct sg_table *sgt;
1387
1388			attach = gtt->gobj->import_attach;
1389			sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
1390			if (IS_ERR(sgt))
1391				return PTR_ERR(sgt);
1392
1393			ttm->sg = sgt;
1394		}
1395
1396		drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
1397						 gtt->ttm.dma_address,
1398						 ttm->num_pages);
1399		ttm->state = tt_unbound;
1400		return 0;
1401	}
1402
1403#ifdef CONFIG_SWIOTLB
1404	if (adev->need_swiotlb && swiotlb_nr_tbl()) {
1405		return ttm_dma_populate(&gtt->ttm, adev->dev, ctx);
1406	}
1407#endif
 
 
 
 
 
1408
1409	/* fall back to generic helper to populate the page array
1410	 * and map them to the device */
1411	return ttm_populate_and_map_pages(adev->dev, &gtt->ttm, ctx);
1412}
1413
1414/**
1415 * amdgpu_ttm_tt_unpopulate - unmap GTT pages and unpopulate page arrays
1416 *
1417 * Unmaps pages of a ttm_tt object from the device address space and
1418 * unpopulates the page array backing it.
1419 */
1420static void amdgpu_ttm_tt_unpopulate(struct ttm_tt *ttm)
 
1421{
1422	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1423	struct amdgpu_device *adev;
 
 
 
 
1424
1425	if (gtt && gtt->userptr) {
1426		amdgpu_ttm_tt_set_user_pages(ttm, NULL);
1427		kfree(ttm->sg);
1428		ttm->page_flags &= ~TTM_PAGE_FLAG_SG;
1429		return;
1430	}
1431
1432	if (ttm->sg && gtt->gobj->import_attach) {
1433		struct dma_buf_attachment *attach;
1434
1435		attach = gtt->gobj->import_attach;
1436		dma_buf_unmap_attachment(attach, ttm->sg, DMA_BIDIRECTIONAL);
1437		ttm->sg = NULL;
1438		return;
1439	}
1440
1441	if (ttm->page_flags & TTM_PAGE_FLAG_SG)
1442		return;
1443
1444	adev = amdgpu_ttm_adev(ttm->bdev);
 
1445
1446#ifdef CONFIG_SWIOTLB
1447	if (adev->need_swiotlb && swiotlb_nr_tbl()) {
1448		ttm_dma_unpopulate(&gtt->ttm, adev->dev);
1449		return;
1450	}
1451#endif
1452
1453	/* fall back to generic helper to unmap and unpopulate array */
1454	ttm_unmap_and_unpopulate_pages(adev->dev, &gtt->ttm);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1455}
1456
1457/**
1458 * amdgpu_ttm_tt_set_userptr - Initialize userptr GTT ttm_tt for the current
1459 * task
1460 *
1461 * @ttm: The ttm_tt object to bind this userptr object to
1462 * @addr:  The address in the current tasks VM space to use
1463 * @flags: Requirements of userptr object.
1464 *
1465 * Called by amdgpu_gem_userptr_ioctl() to bind userptr pages
1466 * to current task
 
1467 */
1468int amdgpu_ttm_tt_set_userptr(struct ttm_tt *ttm, uint64_t addr,
1469			      uint32_t flags)
1470{
1471	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1472
1473	if (gtt == NULL)
1474		return -EINVAL;
 
 
 
 
 
 
 
1475
 
1476	gtt->userptr = addr;
1477	gtt->userflags = flags;
1478
1479	if (gtt->usertask)
1480		put_task_struct(gtt->usertask);
1481	gtt->usertask = current->group_leader;
1482	get_task_struct(gtt->usertask);
1483
1484	return 0;
1485}
1486
1487/**
1488 * amdgpu_ttm_tt_get_usermm - Return memory manager for ttm_tt object
1489 */
1490struct mm_struct *amdgpu_ttm_tt_get_usermm(struct ttm_tt *ttm)
1491{
1492	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1493
1494	if (gtt == NULL)
1495		return NULL;
1496
1497	if (gtt->usertask == NULL)
1498		return NULL;
1499
1500	return gtt->usertask->mm;
1501}
1502
1503/**
1504 * amdgpu_ttm_tt_affect_userptr - Determine if a ttm_tt object lays inside an
1505 * address range for the current task.
1506 *
1507 */
1508bool amdgpu_ttm_tt_affect_userptr(struct ttm_tt *ttm, unsigned long start,
1509				  unsigned long end)
1510{
1511	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1512	unsigned long size;
1513
1514	if (gtt == NULL || !gtt->userptr)
1515		return false;
1516
1517	/* Return false if no part of the ttm_tt object lies within
1518	 * the range
1519	 */
1520	size = (unsigned long)gtt->ttm.ttm.num_pages * PAGE_SIZE;
1521	if (gtt->userptr > end || gtt->userptr + size <= start)
1522		return false;
1523
 
 
1524	return true;
1525}
1526
1527/**
1528 * amdgpu_ttm_tt_is_userptr - Have the pages backing by userptr?
1529 */
1530bool amdgpu_ttm_tt_is_userptr(struct ttm_tt *ttm)
1531{
1532	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1533
1534	if (gtt == NULL || !gtt->userptr)
1535		return false;
1536
1537	return true;
1538}
1539
1540/**
1541 * amdgpu_ttm_tt_is_readonly - Is the ttm_tt object read only?
1542 */
1543bool amdgpu_ttm_tt_is_readonly(struct ttm_tt *ttm)
1544{
1545	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1546
1547	if (gtt == NULL)
1548		return false;
1549
1550	return !!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1551}
1552
1553/**
1554 * amdgpu_ttm_tt_pde_flags - Compute PDE flags for ttm_tt object
1555 *
1556 * @ttm: The ttm_tt object to compute the flags for
1557 * @mem: The memory registry backing this ttm_tt object
1558 *
1559 * Figure out the flags to use for a VM PDE (Page Directory Entry).
1560 */
1561uint64_t amdgpu_ttm_tt_pde_flags(struct ttm_tt *ttm, struct ttm_mem_reg *mem)
1562{
1563	uint64_t flags = 0;
1564
1565	if (mem && mem->mem_type != TTM_PL_SYSTEM)
1566		flags |= AMDGPU_PTE_VALID;
1567
1568	if (mem && mem->mem_type == TTM_PL_TT) {
 
 
1569		flags |= AMDGPU_PTE_SYSTEM;
1570
1571		if (ttm->caching_state == tt_cached)
1572			flags |= AMDGPU_PTE_SNOOPED;
1573	}
1574
 
 
 
 
1575	return flags;
1576}
1577
1578/**
1579 * amdgpu_ttm_tt_pte_flags - Compute PTE flags for ttm_tt object
1580 *
 
1581 * @ttm: The ttm_tt object to compute the flags for
1582 * @mem: The memory registry backing this ttm_tt object
1583
1584 * Figure out the flags to use for a VM PTE (Page Table Entry).
1585 */
1586uint64_t amdgpu_ttm_tt_pte_flags(struct amdgpu_device *adev, struct ttm_tt *ttm,
1587				 struct ttm_mem_reg *mem)
1588{
1589	uint64_t flags = amdgpu_ttm_tt_pde_flags(ttm, mem);
1590
1591	flags |= adev->gart.gart_pte_flags;
1592	flags |= AMDGPU_PTE_READABLE;
1593
1594	if (!amdgpu_ttm_tt_is_readonly(ttm))
1595		flags |= AMDGPU_PTE_WRITEABLE;
1596
1597	return flags;
1598}
1599
1600/**
1601 * amdgpu_ttm_bo_eviction_valuable - Check to see if we can evict a buffer
1602 * object.
1603 *
1604 * Return true if eviction is sensible. Called by ttm_mem_evict_first() on
1605 * behalf of ttm_bo_mem_force_space() which tries to evict buffer objects until
1606 * it can find space for a new object and by ttm_bo_force_list_clean() which is
1607 * used to clean out a memory space.
1608 */
1609static bool amdgpu_ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
1610					    const struct ttm_place *place)
1611{
1612	unsigned long num_pages = bo->mem.num_pages;
1613	struct drm_mm_node *node = bo->mem.mm_node;
1614	struct dma_resv_list *flist;
1615	struct dma_fence *f;
1616	int i;
 
 
 
 
 
 
1617
1618	if (bo->type == ttm_bo_type_kernel &&
1619	    !amdgpu_vm_evictable(ttm_to_amdgpu_bo(bo)))
1620		return false;
1621
1622	/* If bo is a KFD BO, check if the bo belongs to the current process.
1623	 * If true, then return false as any KFD process needs all its BOs to
1624	 * be resident to run successfully
1625	 */
1626	flist = dma_resv_get_list(bo->base.resv);
1627	if (flist) {
1628		for (i = 0; i < flist->shared_count; ++i) {
1629			f = rcu_dereference_protected(flist->shared[i],
1630				dma_resv_held(bo->base.resv));
1631			if (amdkfd_fence_check_mm(f, current->mm))
1632				return false;
1633		}
1634	}
1635
1636	switch (bo->mem.mem_type) {
1637	case TTM_PL_TT:
1638		if (amdgpu_bo_is_amdgpu_bo(bo) &&
1639		    amdgpu_bo_encrypted(ttm_to_amdgpu_bo(bo)))
1640			return false;
1641		return true;
 
 
 
1642
1643	case TTM_PL_VRAM:
1644		/* Check each drm MM node individually */
1645		while (num_pages) {
1646			if (place->fpfn < (node->start + node->size) &&
1647			    !(place->lpfn && place->lpfn <= node->start))
1648				return true;
1649
1650			num_pages -= node->size;
1651			++node;
 
 
 
 
 
 
 
 
 
 
 
1652		}
1653		return false;
1654
1655	default:
1656		break;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1657	}
 
1658
1659	return ttm_bo_eviction_valuable(bo, place);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1660}
1661
1662/**
1663 * amdgpu_ttm_access_memory - Read or Write memory that backs a buffer object.
1664 *
1665 * @bo:  The buffer object to read/write
1666 * @offset:  Offset into buffer object
1667 * @buf:  Secondary buffer to write/read from
1668 * @len: Length in bytes of access
1669 * @write:  true if writing
1670 *
1671 * This is used to access VRAM that backs a buffer object via MMIO
1672 * access for debugging purposes.
1673 */
1674static int amdgpu_ttm_access_memory(struct ttm_buffer_object *bo,
1675				    unsigned long offset,
1676				    void *buf, int len, int write)
1677{
1678	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1679	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1680	struct drm_mm_node *nodes;
1681	uint32_t value = 0;
1682	int ret = 0;
1683	uint64_t pos;
1684	unsigned long flags;
1685
1686	if (bo->mem.mem_type != TTM_PL_VRAM)
1687		return -EIO;
1688
1689	pos = offset;
1690	nodes = amdgpu_find_mm_node(&abo->tbo.mem, &pos);
1691	pos += (nodes->start << PAGE_SHIFT);
1692
1693	while (len && pos < adev->gmc.mc_vram_size) {
1694		uint64_t aligned_pos = pos & ~(uint64_t)3;
1695		uint64_t bytes = 4 - (pos & 3);
1696		uint32_t shift = (pos & 3) * 8;
1697		uint32_t mask = 0xffffffff << shift;
1698
1699		if (len < bytes) {
1700			mask &= 0xffffffff >> (bytes - len) * 8;
1701			bytes = len;
 
 
 
1702		}
1703
1704		if (mask != 0xffffffff) {
1705			spin_lock_irqsave(&adev->mmio_idx_lock, flags);
1706			WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)aligned_pos) | 0x80000000);
1707			WREG32_NO_KIQ(mmMM_INDEX_HI, aligned_pos >> 31);
1708			if (!write || mask != 0xffffffff)
1709				value = RREG32_NO_KIQ(mmMM_DATA);
1710			if (write) {
1711				value &= ~mask;
1712				value |= (*(uint32_t *)buf << shift) & mask;
1713				WREG32_NO_KIQ(mmMM_DATA, value);
1714			}
1715			spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
1716			if (!write) {
1717				value = (value & mask) >> shift;
1718				memcpy(buf, &value, bytes);
1719			}
1720		} else {
1721			bytes = (nodes->start + nodes->size) << PAGE_SHIFT;
1722			bytes = min(bytes - pos, (uint64_t)len & ~0x3ull);
1723
1724			amdgpu_device_vram_access(adev, pos, (uint32_t *)buf,
1725						  bytes, write);
1726		}
1727
1728		ret += bytes;
1729		buf = (uint8_t *)buf + bytes;
1730		pos += bytes;
1731		len -= bytes;
1732		if (pos >= (nodes->start + nodes->size) << PAGE_SHIFT) {
1733			++nodes;
1734			pos = (nodes->start << PAGE_SHIFT);
1735		}
1736	}
1737
1738	return ret;
1739}
1740
1741static struct ttm_bo_driver amdgpu_bo_driver = {
 
 
 
 
 
 
1742	.ttm_tt_create = &amdgpu_ttm_tt_create,
1743	.ttm_tt_populate = &amdgpu_ttm_tt_populate,
1744	.ttm_tt_unpopulate = &amdgpu_ttm_tt_unpopulate,
1745	.init_mem_type = &amdgpu_init_mem_type,
1746	.eviction_valuable = amdgpu_ttm_bo_eviction_valuable,
1747	.evict_flags = &amdgpu_evict_flags,
1748	.move = &amdgpu_bo_move,
1749	.verify_access = &amdgpu_verify_access,
1750	.move_notify = &amdgpu_bo_move_notify,
1751	.release_notify = &amdgpu_bo_release_notify,
1752	.fault_reserve_notify = &amdgpu_bo_fault_reserve_notify,
1753	.io_mem_reserve = &amdgpu_ttm_io_mem_reserve,
1754	.io_mem_pfn = amdgpu_ttm_io_mem_pfn,
1755	.access_memory = &amdgpu_ttm_access_memory,
1756	.del_from_lru_notify = &amdgpu_vm_del_from_lru_notify
1757};
1758
1759/*
1760 * Firmware Reservation functions
1761 */
1762/**
1763 * amdgpu_ttm_fw_reserve_vram_fini - free fw reserved vram
1764 *
1765 * @adev: amdgpu_device pointer
1766 *
1767 * free fw reserved vram if it has been reserved.
1768 */
1769static void amdgpu_ttm_fw_reserve_vram_fini(struct amdgpu_device *adev)
1770{
1771	amdgpu_bo_free_kernel(&adev->fw_vram_usage.reserved_bo,
1772		NULL, &adev->fw_vram_usage.va);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1773}
1774
1775/**
1776 * amdgpu_ttm_fw_reserve_vram_init - create bo vram reservation from fw
1777 *
1778 * @adev: amdgpu_device pointer
1779 *
1780 * create bo vram reservation from fw.
1781 */
1782static int amdgpu_ttm_fw_reserve_vram_init(struct amdgpu_device *adev)
1783{
1784	uint64_t vram_size = adev->gmc.visible_vram_size;
1785
1786	adev->fw_vram_usage.va = NULL;
1787	adev->fw_vram_usage.reserved_bo = NULL;
1788
1789	if (adev->fw_vram_usage.size == 0 ||
1790	    adev->fw_vram_usage.size > vram_size)
1791		return 0;
1792
1793	return amdgpu_bo_create_kernel_at(adev,
1794					  adev->fw_vram_usage.start_offset,
1795					  adev->fw_vram_usage.size,
1796					  AMDGPU_GEM_DOMAIN_VRAM,
1797					  &adev->fw_vram_usage.reserved_bo,
1798					  &adev->fw_vram_usage.va);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1799}
1800
1801/*
1802 * Memoy training reservation functions
1803 */
1804
1805/**
1806 * amdgpu_ttm_training_reserve_vram_fini - free memory training reserved vram
1807 *
1808 * @adev: amdgpu_device pointer
1809 *
1810 * free memory training reserved vram if it has been reserved.
1811 */
1812static int amdgpu_ttm_training_reserve_vram_fini(struct amdgpu_device *adev)
1813{
1814	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1815
1816	ctx->init = PSP_MEM_TRAIN_NOT_SUPPORT;
1817	amdgpu_bo_free_kernel(&ctx->c2p_bo, NULL, NULL);
1818	ctx->c2p_bo = NULL;
1819
1820	return 0;
1821}
1822
1823static void amdgpu_ttm_training_data_block_init(struct amdgpu_device *adev)
 
1824{
1825	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1826
1827	memset(ctx, 0, sizeof(*ctx));
1828
1829	ctx->c2p_train_data_offset =
1830		ALIGN((adev->gmc.mc_vram_size - adev->discovery_tmr_size - SZ_1M), SZ_1M);
1831	ctx->p2c_train_data_offset =
1832		(adev->gmc.mc_vram_size - GDDR6_MEM_TRAINING_OFFSET);
1833	ctx->train_data_size =
1834		GDDR6_MEM_TRAINING_DATA_SIZE_IN_BYTES;
1835	
1836	DRM_DEBUG("train_data_size:%llx,p2c_train_data_offset:%llx,c2p_train_data_offset:%llx.\n",
1837			ctx->train_data_size,
1838			ctx->p2c_train_data_offset,
1839			ctx->c2p_train_data_offset);
1840}
1841
1842/*
1843 * reserve TMR memory at the top of VRAM which holds
1844 * IP Discovery data and is protected by PSP.
1845 */
1846static int amdgpu_ttm_reserve_tmr(struct amdgpu_device *adev)
1847{
1848	int ret;
1849	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1850	bool mem_train_support = false;
 
 
1851
1852	if (!amdgpu_sriov_vf(adev)) {
1853		ret = amdgpu_mem_train_support(adev);
1854		if (ret == 1)
1855			mem_train_support = true;
1856		else if (ret == -1)
1857			return -EINVAL;
1858		else
1859			DRM_DEBUG("memory training does not support!\n");
1860	}
1861
1862	/*
1863	 * Query reserved tmr size through atom firmwareinfo for Sienna_Cichlid and onwards for all
1864	 * the use cases (IP discovery/G6 memory training/profiling/diagnostic data.etc)
1865	 *
1866	 * Otherwise, fallback to legacy approach to check and reserve tmr block for ip
1867	 * discovery data and G6 memory training data respectively
1868	 */
1869	adev->discovery_tmr_size =
1870		amdgpu_atomfirmware_get_fw_reserved_fb_size(adev);
1871	if (!adev->discovery_tmr_size)
1872		adev->discovery_tmr_size = DISCOVERY_TMR_OFFSET;
 
 
 
 
 
1873
1874	if (mem_train_support) {
1875		/* reserve vram for mem train according to TMR location */
1876		amdgpu_ttm_training_data_block_init(adev);
1877		ret = amdgpu_bo_create_kernel_at(adev,
1878					 ctx->c2p_train_data_offset,
1879					 ctx->train_data_size,
1880					 AMDGPU_GEM_DOMAIN_VRAM,
1881					 &ctx->c2p_bo,
1882					 NULL);
1883		if (ret) {
1884			DRM_ERROR("alloc c2p_bo failed(%d)!\n", ret);
1885			amdgpu_ttm_training_reserve_vram_fini(adev);
1886			return ret;
1887		}
1888		ctx->init = PSP_MEM_TRAIN_RESERVE_SUCCESS;
1889	}
1890
1891	ret = amdgpu_bo_create_kernel_at(adev,
1892				adev->gmc.real_vram_size - adev->discovery_tmr_size,
1893				adev->discovery_tmr_size,
1894				AMDGPU_GEM_DOMAIN_VRAM,
1895				&adev->discovery_memory,
1896				NULL);
1897	if (ret) {
1898		DRM_ERROR("alloc tmr failed(%d)!\n", ret);
1899		amdgpu_bo_free_kernel(&adev->discovery_memory, NULL, NULL);
1900		return ret;
 
 
1901	}
1902
1903	return 0;
1904}
1905
1906/**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1907 * amdgpu_ttm_init - Init the memory management (ttm) as well as various
1908 * gtt/vram related fields.
1909 *
1910 * This initializes all of the memory space pools that the TTM layer
1911 * will need such as the GTT space (system memory mapped to the device),
1912 * VRAM (on-board memory), and on-chip memories (GDS, GWS, OA) which
1913 * can be mapped per VMID.
1914 */
1915int amdgpu_ttm_init(struct amdgpu_device *adev)
1916{
1917	uint64_t gtt_size;
1918	int r;
1919	u64 vis_vram_limit;
1920	void *stolen_vga_buf;
1921
1922	mutex_init(&adev->mman.gtt_window_lock);
1923
1924	/* No others user of address space so set it to 0 */
1925	r = ttm_bo_device_init(&adev->mman.bdev,
1926			       &amdgpu_bo_driver,
1927			       adev->ddev->anon_inode->i_mapping,
1928			       adev->ddev->vma_offset_manager,
1929			       dma_addressing_limited(adev->dev));
1930	if (r) {
1931		DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
1932		return r;
1933	}
1934	adev->mman.initialized = true;
1935
1936	/* We opt to avoid OOM on system pages allocations */
1937	adev->mman.bdev.no_retry = true;
 
 
 
 
1938
1939	/* Initialize VRAM pool with all of VRAM divided into pages */
1940	r = ttm_bo_init_mm(&adev->mman.bdev, TTM_PL_VRAM,
1941				adev->gmc.real_vram_size >> PAGE_SHIFT);
1942	if (r) {
1943		DRM_ERROR("Failed initializing VRAM heap.\n");
1944		return r;
1945	}
1946
1947	/* Reduce size of CPU-visible VRAM if requested */
1948	vis_vram_limit = (u64)amdgpu_vis_vram_limit * 1024 * 1024;
1949	if (amdgpu_vis_vram_limit > 0 &&
1950	    vis_vram_limit <= adev->gmc.visible_vram_size)
1951		adev->gmc.visible_vram_size = vis_vram_limit;
1952
1953	/* Change the size here instead of the init above so only lpfn is affected */
1954	amdgpu_ttm_set_buffer_funcs_status(adev, false);
1955#ifdef CONFIG_64BIT
1956	adev->mman.aper_base_kaddr = ioremap_wc(adev->gmc.aper_base,
1957						adev->gmc.visible_vram_size);
 
 
 
 
 
 
 
 
 
 
1958#endif
1959
1960	/*
1961	 *The reserved vram for firmware must be pinned to the specified
1962	 *place on the VRAM, so reserve it early.
1963	 */
1964	r = amdgpu_ttm_fw_reserve_vram_init(adev);
1965	if (r) {
 
 
 
 
 
 
 
 
1966		return r;
1967	}
1968
1969	/*
1970	 * only NAVI10 and onwards ASIC support for IP discovery.
1971	 * If IP discovery enabled, a block of memory should be
1972	 * reserved for IP discovey.
1973	 */
1974	if (adev->discovery_bin) {
1975		r = amdgpu_ttm_reserve_tmr(adev);
1976		if (r)
1977			return r;
1978	}
1979
1980	/* allocate memory as required for VGA
1981	 * This is used for VGA emulation and pre-OS scanout buffers to
1982	 * avoid display artifacts while transitioning between pre-OS
1983	 * and driver.  */
1984	r = amdgpu_bo_create_kernel(adev, adev->gmc.stolen_size, PAGE_SIZE,
1985				    AMDGPU_GEM_DOMAIN_VRAM,
1986				    &adev->stolen_vga_memory,
1987				    NULL, &stolen_vga_buf);
1988	if (r)
1989		return r;
 
 
1990
1991	DRM_INFO("amdgpu: %uM of VRAM memory ready\n",
1992		 (unsigned) (adev->gmc.real_vram_size / (1024 * 1024)));
 
 
1993
1994	/* Compute GTT size, either bsaed on 3/4th the size of RAM size
1995	 * or whatever the user passed on module init */
1996	if (amdgpu_gtt_size == -1) {
1997		struct sysinfo si;
1998
1999		si_meminfo(&si);
2000		gtt_size = min(max((AMDGPU_DEFAULT_GTT_SIZE_MB << 20),
2001			       adev->gmc.mc_vram_size),
2002			       ((uint64_t)si.totalram * si.mem_unit * 3/4));
 
 
 
2003	}
 
 
 
 
 
 
 
 
 
2004	else
2005		gtt_size = (uint64_t)amdgpu_gtt_size << 20;
2006
2007	/* Initialize GTT memory pool */
2008	r = ttm_bo_init_mm(&adev->mman.bdev, TTM_PL_TT, gtt_size >> PAGE_SHIFT);
2009	if (r) {
2010		DRM_ERROR("Failed initializing GTT heap.\n");
2011		return r;
2012	}
2013	DRM_INFO("amdgpu: %uM of GTT memory ready.\n",
2014		 (unsigned)(gtt_size / (1024 * 1024)));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2015
2016	/* Initialize various on-chip memory pools */
2017	r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_GDS,
2018			   adev->gds.gds_size);
2019	if (r) {
2020		DRM_ERROR("Failed initializing GDS heap.\n");
2021		return r;
2022	}
2023
2024	r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_GWS,
2025			   adev->gds.gws_size);
2026	if (r) {
2027		DRM_ERROR("Failed initializing gws heap.\n");
2028		return r;
2029	}
2030
2031	r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_OA,
2032			   adev->gds.oa_size);
2033	if (r) {
2034		DRM_ERROR("Failed initializing oa heap.\n");
2035		return r;
2036	}
 
 
 
 
 
2037
2038	return 0;
2039}
2040
2041/**
2042 * amdgpu_ttm_late_init - Handle any late initialization for amdgpu_ttm
2043 */
2044void amdgpu_ttm_late_init(struct amdgpu_device *adev)
2045{
2046	void *stolen_vga_buf;
2047	/* return the VGA stolen memory (if any) back to VRAM */
2048	amdgpu_bo_free_kernel(&adev->stolen_vga_memory, NULL, &stolen_vga_buf);
2049}
2050
2051/**
2052 * amdgpu_ttm_fini - De-initialize the TTM memory pools
2053 */
2054void amdgpu_ttm_fini(struct amdgpu_device *adev)
2055{
 
 
2056	if (!adev->mman.initialized)
2057		return;
2058
 
 
2059	amdgpu_ttm_training_reserve_vram_fini(adev);
2060	/* return the IP Discovery TMR memory back to VRAM */
2061	amdgpu_bo_free_kernel(&adev->discovery_memory, NULL, NULL);
 
 
 
 
 
 
 
 
 
 
 
2062	amdgpu_ttm_fw_reserve_vram_fini(adev);
 
2063
2064	if (adev->mman.aper_base_kaddr)
2065		iounmap(adev->mman.aper_base_kaddr);
2066	adev->mman.aper_base_kaddr = NULL;
2067
2068	ttm_bo_clean_mm(&adev->mman.bdev, TTM_PL_VRAM);
2069	ttm_bo_clean_mm(&adev->mman.bdev, TTM_PL_TT);
2070	ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_GDS);
2071	ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_GWS);
2072	ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_OA);
2073	ttm_bo_device_release(&adev->mman.bdev);
 
 
 
 
 
 
2074	adev->mman.initialized = false;
2075	DRM_INFO("amdgpu: ttm finalized\n");
2076}
2077
2078/**
2079 * amdgpu_ttm_set_buffer_funcs_status - enable/disable use of buffer functions
2080 *
2081 * @adev: amdgpu_device pointer
2082 * @enable: true when we can use buffer functions.
2083 *
2084 * Enable/disable use of buffer functions during suspend/resume. This should
2085 * only be called at bootup or when userspace isn't running.
2086 */
2087void amdgpu_ttm_set_buffer_funcs_status(struct amdgpu_device *adev, bool enable)
2088{
2089	struct ttm_mem_type_manager *man = &adev->mman.bdev.man[TTM_PL_VRAM];
2090	uint64_t size;
2091	int r;
2092
2093	if (!adev->mman.initialized || adev->in_gpu_reset ||
2094	    adev->mman.buffer_funcs_enabled == enable)
2095		return;
2096
2097	if (enable) {
2098		struct amdgpu_ring *ring;
2099		struct drm_gpu_scheduler *sched;
2100
2101		ring = adev->mman.buffer_funcs_ring;
2102		sched = &ring->sched;
2103		r = drm_sched_entity_init(&adev->mman.entity,
2104				          DRM_SCHED_PRIORITY_KERNEL, &sched,
2105					  1, NULL);
2106		if (r) {
2107			DRM_ERROR("Failed setting up TTM BO move entity (%d)\n",
2108				  r);
2109			return;
2110		}
 
 
 
 
 
 
 
 
 
2111	} else {
2112		drm_sched_entity_destroy(&adev->mman.entity);
 
2113		dma_fence_put(man->move);
2114		man->move = NULL;
2115	}
2116
2117	/* this just adjusts TTM size idea, which sets lpfn to the correct value */
2118	if (enable)
2119		size = adev->gmc.real_vram_size;
2120	else
2121		size = adev->gmc.visible_vram_size;
2122	man->size = size >> PAGE_SHIFT;
2123	adev->mman.buffer_funcs_enabled = enable;
 
 
 
 
 
2124}
2125
2126int amdgpu_mmap(struct file *filp, struct vm_area_struct *vma)
 
 
 
 
 
 
2127{
2128	struct drm_file *file_priv = filp->private_data;
2129	struct amdgpu_device *adev = file_priv->minor->dev->dev_private;
 
 
 
 
 
 
 
 
 
2130
2131	if (adev == NULL)
2132		return -EINVAL;
 
 
 
 
 
 
2133
2134	return ttm_bo_mmap(filp, vma, &adev->mman.bdev);
 
2135}
2136
2137int amdgpu_copy_buffer(struct amdgpu_ring *ring, uint64_t src_offset,
2138		       uint64_t dst_offset, uint32_t byte_count,
2139		       struct dma_resv *resv,
2140		       struct dma_fence **fence, bool direct_submit,
2141		       bool vm_needs_flush, bool tmz)
2142{
2143	enum amdgpu_ib_pool_type pool = direct_submit ? AMDGPU_IB_POOL_DIRECT :
2144		AMDGPU_IB_POOL_DELAYED;
2145	struct amdgpu_device *adev = ring->adev;
 
2146	struct amdgpu_job *job;
2147
2148	uint32_t max_bytes;
2149	unsigned num_loops, num_dw;
2150	unsigned i;
2151	int r;
2152
2153	if (direct_submit && !ring->sched.ready) {
2154		DRM_ERROR("Trying to move memory with ring turned off.\n");
2155		return -EINVAL;
2156	}
2157
2158	max_bytes = adev->mman.buffer_funcs->copy_max_bytes;
2159	num_loops = DIV_ROUND_UP(byte_count, max_bytes);
2160	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->copy_num_dw, 8);
2161
2162	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, pool, &job);
2163	if (r)
2164		return r;
2165
2166	if (vm_needs_flush) {
2167		job->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gart.bo);
2168		job->vm_needs_flush = true;
2169	}
2170	if (resv) {
2171		r = amdgpu_sync_resv(adev, &job->sync, resv,
2172				     AMDGPU_SYNC_ALWAYS,
2173				     AMDGPU_FENCE_OWNER_UNDEFINED);
2174		if (r) {
2175			DRM_ERROR("sync failed (%d).\n", r);
2176			goto error_free;
2177		}
2178	}
2179
2180	for (i = 0; i < num_loops; i++) {
2181		uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
2182
2183		amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
2184					dst_offset, cur_size_in_bytes, tmz);
2185
2186		src_offset += cur_size_in_bytes;
2187		dst_offset += cur_size_in_bytes;
2188		byte_count -= cur_size_in_bytes;
2189	}
2190
2191	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2192	WARN_ON(job->ibs[0].length_dw > num_dw);
2193	if (direct_submit)
2194		r = amdgpu_job_submit_direct(job, ring, fence);
2195	else
2196		r = amdgpu_job_submit(job, &adev->mman.entity,
2197				      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
2198	if (r)
2199		goto error_free;
2200
2201	return r;
2202
2203error_free:
2204	amdgpu_job_free(job);
2205	DRM_ERROR("Error scheduling IBs (%d)\n", r);
2206	return r;
2207}
2208
2209int amdgpu_fill_buffer(struct amdgpu_bo *bo,
2210		       uint32_t src_data,
2211		       struct dma_resv *resv,
2212		       struct dma_fence **fence)
 
2213{
2214	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
2215	uint32_t max_bytes = adev->mman.buffer_funcs->fill_max_bytes;
2216	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
2217
2218	struct drm_mm_node *mm_node;
2219	unsigned long num_pages;
2220	unsigned int num_loops, num_dw;
2221
2222	struct amdgpu_job *job;
 
 
2223	int r;
2224
2225	if (!adev->mman.buffer_funcs_enabled) {
2226		DRM_ERROR("Trying to clear memory with ring turned off.\n");
2227		return -EINVAL;
2228	}
 
 
 
2229
2230	if (bo->tbo.mem.mem_type == TTM_PL_TT) {
2231		r = amdgpu_ttm_alloc_gart(&bo->tbo);
2232		if (r)
2233			return r;
2234	}
2235
2236	num_pages = bo->tbo.num_pages;
2237	mm_node = bo->tbo.mem.mm_node;
2238	num_loops = 0;
2239	while (num_pages) {
2240		uint64_t byte_count = mm_node->size << PAGE_SHIFT;
2241
2242		num_loops += DIV_ROUND_UP_ULL(byte_count, max_bytes);
2243		num_pages -= mm_node->size;
2244		++mm_node;
2245	}
2246	num_dw = num_loops * adev->mman.buffer_funcs->fill_num_dw;
2247
2248	/* for IB padding */
2249	num_dw += 64;
 
 
 
2250
2251	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, AMDGPU_IB_POOL_DELAYED,
2252				     &job);
2253	if (r)
2254		return r;
 
 
 
 
 
 
 
2255
2256	if (resv) {
2257		r = amdgpu_sync_resv(adev, &job->sync, resv,
2258				     AMDGPU_SYNC_ALWAYS,
2259				     AMDGPU_FENCE_OWNER_UNDEFINED);
2260		if (r) {
2261			DRM_ERROR("sync failed (%d).\n", r);
2262			goto error_free;
2263		}
2264	}
2265
2266	num_pages = bo->tbo.num_pages;
2267	mm_node = bo->tbo.mem.mm_node;
2268
2269	while (num_pages) {
2270		uint64_t byte_count = mm_node->size << PAGE_SHIFT;
2271		uint64_t dst_addr;
2272
2273		dst_addr = amdgpu_mm_node_addr(&bo->tbo, mm_node, &bo->tbo.mem);
2274		while (byte_count) {
2275			uint32_t cur_size_in_bytes = min_t(uint64_t, byte_count,
2276							   max_bytes);
2277
2278			amdgpu_emit_fill_buffer(adev, &job->ibs[0], src_data,
2279						dst_addr, cur_size_in_bytes);
2280
2281			dst_addr += cur_size_in_bytes;
2282			byte_count -= cur_size_in_bytes;
2283		}
 
2284
2285		num_pages -= mm_node->size;
2286		++mm_node;
 
 
 
 
 
 
 
2287	}
 
 
 
 
 
 
 
2288
2289	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2290	WARN_ON(job->ibs[0].length_dw > num_dw);
2291	r = amdgpu_job_submit(job, &adev->mman.entity,
2292			      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
2293	if (r)
2294		goto error_free;
 
 
 
 
 
 
 
2295
2296	return 0;
 
 
 
 
 
 
 
 
 
 
 
2297
2298error_free:
2299	amdgpu_job_free(job);
2300	return r;
2301}
2302
2303#if defined(CONFIG_DEBUG_FS)
2304
2305static int amdgpu_mm_dump_table(struct seq_file *m, void *data)
2306{
2307	struct drm_info_node *node = (struct drm_info_node *)m->private;
2308	unsigned ttm_pl = (uintptr_t)node->info_ent->data;
2309	struct drm_device *dev = node->minor->dev;
2310	struct amdgpu_device *adev = dev->dev_private;
2311	struct ttm_mem_type_manager *man = &adev->mman.bdev.man[ttm_pl];
2312	struct drm_printer p = drm_seq_file_printer(m);
2313
2314	man->func->debug(man, &p);
2315	return 0;
2316}
2317
2318static const struct drm_info_list amdgpu_ttm_debugfs_list[] = {
2319	{"amdgpu_vram_mm", amdgpu_mm_dump_table, 0, (void *)TTM_PL_VRAM},
2320	{"amdgpu_gtt_mm", amdgpu_mm_dump_table, 0, (void *)TTM_PL_TT},
2321	{"amdgpu_gds_mm", amdgpu_mm_dump_table, 0, (void *)AMDGPU_PL_GDS},
2322	{"amdgpu_gws_mm", amdgpu_mm_dump_table, 0, (void *)AMDGPU_PL_GWS},
2323	{"amdgpu_oa_mm", amdgpu_mm_dump_table, 0, (void *)AMDGPU_PL_OA},
2324	{"ttm_page_pool", ttm_page_alloc_debugfs, 0, NULL},
2325#ifdef CONFIG_SWIOTLB
2326	{"ttm_dma_page_pool", ttm_dma_page_alloc_debugfs, 0, NULL}
2327#endif
2328};
2329
2330/**
2331 * amdgpu_ttm_vram_read - Linear read access to VRAM
2332 *
2333 * Accesses VRAM via MMIO for debugging purposes.
2334 */
2335static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
2336				    size_t size, loff_t *pos)
2337{
2338	struct amdgpu_device *adev = file_inode(f)->i_private;
2339	ssize_t result = 0;
2340
2341	if (size & 0x3 || *pos & 0x3)
2342		return -EINVAL;
2343
2344	if (*pos >= adev->gmc.mc_vram_size)
2345		return -ENXIO;
2346
2347	size = min(size, (size_t)(adev->gmc.mc_vram_size - *pos));
2348	while (size) {
2349		size_t bytes = min(size, AMDGPU_TTM_VRAM_MAX_DW_READ * 4);
2350		uint32_t value[AMDGPU_TTM_VRAM_MAX_DW_READ];
2351
2352		amdgpu_device_vram_access(adev, *pos, value, bytes, false);
2353		if (copy_to_user(buf, value, bytes))
2354			return -EFAULT;
2355
2356		result += bytes;
2357		buf += bytes;
2358		*pos += bytes;
2359		size -= bytes;
2360	}
2361
2362	return result;
2363}
2364
2365/**
2366 * amdgpu_ttm_vram_write - Linear write access to VRAM
2367 *
2368 * Accesses VRAM via MMIO for debugging purposes.
2369 */
2370static ssize_t amdgpu_ttm_vram_write(struct file *f, const char __user *buf,
2371				    size_t size, loff_t *pos)
2372{
2373	struct amdgpu_device *adev = file_inode(f)->i_private;
2374	ssize_t result = 0;
2375	int r;
2376
2377	if (size & 0x3 || *pos & 0x3)
2378		return -EINVAL;
2379
2380	if (*pos >= adev->gmc.mc_vram_size)
2381		return -ENXIO;
2382
2383	while (size) {
2384		unsigned long flags;
2385		uint32_t value;
2386
2387		if (*pos >= adev->gmc.mc_vram_size)
2388			return result;
2389
2390		r = get_user(value, (uint32_t *)buf);
2391		if (r)
2392			return r;
2393
2394		spin_lock_irqsave(&adev->mmio_idx_lock, flags);
2395		WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)*pos) | 0x80000000);
2396		WREG32_NO_KIQ(mmMM_INDEX_HI, *pos >> 31);
2397		WREG32_NO_KIQ(mmMM_DATA, value);
2398		spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
2399
2400		result += 4;
2401		buf += 4;
2402		*pos += 4;
2403		size -= 4;
2404	}
2405
2406	return result;
2407}
2408
2409static const struct file_operations amdgpu_ttm_vram_fops = {
2410	.owner = THIS_MODULE,
2411	.read = amdgpu_ttm_vram_read,
2412	.write = amdgpu_ttm_vram_write,
2413	.llseek = default_llseek,
2414};
2415
2416#ifdef CONFIG_DRM_AMDGPU_GART_DEBUGFS
2417
2418/**
2419 * amdgpu_ttm_gtt_read - Linear read access to GTT memory
2420 */
2421static ssize_t amdgpu_ttm_gtt_read(struct file *f, char __user *buf,
2422				   size_t size, loff_t *pos)
2423{
2424	struct amdgpu_device *adev = file_inode(f)->i_private;
2425	ssize_t result = 0;
2426	int r;
2427
2428	while (size) {
2429		loff_t p = *pos / PAGE_SIZE;
2430		unsigned off = *pos & ~PAGE_MASK;
2431		size_t cur_size = min_t(size_t, size, PAGE_SIZE - off);
2432		struct page *page;
2433		void *ptr;
2434
2435		if (p >= adev->gart.num_cpu_pages)
2436			return result;
2437
2438		page = adev->gart.pages[p];
2439		if (page) {
2440			ptr = kmap(page);
2441			ptr += off;
2442
2443			r = copy_to_user(buf, ptr, cur_size);
2444			kunmap(adev->gart.pages[p]);
2445		} else
2446			r = clear_user(buf, cur_size);
2447
2448		if (r)
2449			return -EFAULT;
2450
2451		result += cur_size;
2452		buf += cur_size;
2453		*pos += cur_size;
2454		size -= cur_size;
2455	}
2456
2457	return result;
2458}
2459
2460static const struct file_operations amdgpu_ttm_gtt_fops = {
2461	.owner = THIS_MODULE,
2462	.read = amdgpu_ttm_gtt_read,
2463	.llseek = default_llseek
2464};
2465
2466#endif
2467
2468/**
2469 * amdgpu_iomem_read - Virtual read access to GPU mapped memory
2470 *
2471 * This function is used to read memory that has been mapped to the
2472 * GPU and the known addresses are not physical addresses but instead
2473 * bus addresses (e.g., what you'd put in an IB or ring buffer).
2474 */
2475static ssize_t amdgpu_iomem_read(struct file *f, char __user *buf,
2476				 size_t size, loff_t *pos)
2477{
2478	struct amdgpu_device *adev = file_inode(f)->i_private;
2479	struct iommu_domain *dom;
2480	ssize_t result = 0;
2481	int r;
2482
2483	/* retrieve the IOMMU domain if any for this device */
2484	dom = iommu_get_domain_for_dev(adev->dev);
2485
2486	while (size) {
2487		phys_addr_t addr = *pos & PAGE_MASK;
2488		loff_t off = *pos & ~PAGE_MASK;
2489		size_t bytes = PAGE_SIZE - off;
2490		unsigned long pfn;
2491		struct page *p;
2492		void *ptr;
2493
2494		bytes = bytes < size ? bytes : size;
2495
2496		/* Translate the bus address to a physical address.  If
2497		 * the domain is NULL it means there is no IOMMU active
2498		 * and the address translation is the identity
2499		 */
2500		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2501
2502		pfn = addr >> PAGE_SHIFT;
2503		if (!pfn_valid(pfn))
2504			return -EPERM;
2505
2506		p = pfn_to_page(pfn);
2507		if (p->mapping != adev->mman.bdev.dev_mapping)
2508			return -EPERM;
2509
2510		ptr = kmap(p);
2511		r = copy_to_user(buf, ptr + off, bytes);
2512		kunmap(p);
2513		if (r)
2514			return -EFAULT;
2515
2516		size -= bytes;
2517		*pos += bytes;
2518		result += bytes;
2519	}
2520
2521	return result;
2522}
2523
2524/**
2525 * amdgpu_iomem_write - Virtual write access to GPU mapped memory
2526 *
2527 * This function is used to write memory that has been mapped to the
2528 * GPU and the known addresses are not physical addresses but instead
2529 * bus addresses (e.g., what you'd put in an IB or ring buffer).
2530 */
2531static ssize_t amdgpu_iomem_write(struct file *f, const char __user *buf,
2532				 size_t size, loff_t *pos)
2533{
2534	struct amdgpu_device *adev = file_inode(f)->i_private;
2535	struct iommu_domain *dom;
2536	ssize_t result = 0;
2537	int r;
2538
2539	dom = iommu_get_domain_for_dev(adev->dev);
2540
2541	while (size) {
2542		phys_addr_t addr = *pos & PAGE_MASK;
2543		loff_t off = *pos & ~PAGE_MASK;
2544		size_t bytes = PAGE_SIZE - off;
2545		unsigned long pfn;
2546		struct page *p;
2547		void *ptr;
2548
2549		bytes = bytes < size ? bytes : size;
2550
2551		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2552
2553		pfn = addr >> PAGE_SHIFT;
2554		if (!pfn_valid(pfn))
2555			return -EPERM;
2556
2557		p = pfn_to_page(pfn);
2558		if (p->mapping != adev->mman.bdev.dev_mapping)
2559			return -EPERM;
2560
2561		ptr = kmap(p);
2562		r = copy_from_user(ptr + off, buf, bytes);
2563		kunmap(p);
2564		if (r)
2565			return -EFAULT;
2566
2567		size -= bytes;
2568		*pos += bytes;
2569		result += bytes;
2570	}
2571
2572	return result;
2573}
2574
2575static const struct file_operations amdgpu_ttm_iomem_fops = {
2576	.owner = THIS_MODULE,
2577	.read = amdgpu_iomem_read,
2578	.write = amdgpu_iomem_write,
2579	.llseek = default_llseek
2580};
2581
2582static const struct {
2583	char *name;
2584	const struct file_operations *fops;
2585	int domain;
2586} ttm_debugfs_entries[] = {
2587	{ "amdgpu_vram", &amdgpu_ttm_vram_fops, TTM_PL_VRAM },
2588#ifdef CONFIG_DRM_AMDGPU_GART_DEBUGFS
2589	{ "amdgpu_gtt", &amdgpu_ttm_gtt_fops, TTM_PL_TT },
2590#endif
2591	{ "amdgpu_iomem", &amdgpu_ttm_iomem_fops, TTM_PL_SYSTEM },
2592};
2593
2594#endif
2595
2596int amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
2597{
2598#if defined(CONFIG_DEBUG_FS)
2599	unsigned count;
 
2600
2601	struct drm_minor *minor = adev->ddev->primary;
2602	struct dentry *ent, *root = minor->debugfs_root;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2603
2604	for (count = 0; count < ARRAY_SIZE(ttm_debugfs_entries); count++) {
2605		ent = debugfs_create_file(
2606				ttm_debugfs_entries[count].name,
2607				S_IFREG | S_IRUGO, root,
2608				adev,
2609				ttm_debugfs_entries[count].fops);
2610		if (IS_ERR(ent))
2611			return PTR_ERR(ent);
2612		if (ttm_debugfs_entries[count].domain == TTM_PL_VRAM)
2613			i_size_write(ent->d_inode, adev->gmc.mc_vram_size);
2614		else if (ttm_debugfs_entries[count].domain == TTM_PL_TT)
2615			i_size_write(ent->d_inode, adev->gmc.gart_size);
2616		adev->mman.debugfs_entries[count] = ent;
2617	}
2618
2619	count = ARRAY_SIZE(amdgpu_ttm_debugfs_list);
2620
2621#ifdef CONFIG_SWIOTLB
2622	if (!(adev->need_swiotlb && swiotlb_nr_tbl()))
2623		--count;
2624#endif
2625
2626	return amdgpu_debugfs_add_files(adev, amdgpu_ttm_debugfs_list, count);
2627#else
2628	return 0;
2629#endif
2630}
v6.8
   1/*
   2 * Copyright 2009 Jerome Glisse.
   3 * All Rights Reserved.
   4 *
   5 * Permission is hereby granted, free of charge, to any person obtaining a
   6 * copy of this software and associated documentation files (the
   7 * "Software"), to deal in the Software without restriction, including
   8 * without limitation the rights to use, copy, modify, merge, publish,
   9 * distribute, sub license, and/or sell copies of the Software, and to
  10 * permit persons to whom the Software is furnished to do so, subject to
  11 * the following conditions:
  12 *
  13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
  16 * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
  17 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  18 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  19 * USE OR OTHER DEALINGS IN THE SOFTWARE.
  20 *
  21 * The above copyright notice and this permission notice (including the
  22 * next paragraph) shall be included in all copies or substantial portions
  23 * of the Software.
  24 *
  25 */
  26/*
  27 * Authors:
  28 *    Jerome Glisse <glisse@freedesktop.org>
  29 *    Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
  30 *    Dave Airlie
  31 */
  32
  33#include <linux/dma-mapping.h>
  34#include <linux/iommu.h>
 
  35#include <linux/pagemap.h>
  36#include <linux/sched/task.h>
  37#include <linux/sched/mm.h>
  38#include <linux/seq_file.h>
  39#include <linux/slab.h>
  40#include <linux/swap.h>
 
  41#include <linux/dma-buf.h>
  42#include <linux/sizes.h>
  43#include <linux/module.h>
  44
  45#include <drm/drm_drv.h>
  46#include <drm/ttm/ttm_bo.h>
  47#include <drm/ttm/ttm_placement.h>
  48#include <drm/ttm/ttm_range_manager.h>
  49#include <drm/ttm/ttm_tt.h>
  50
 
  51#include <drm/amdgpu_drm.h>
  52
  53#include "amdgpu.h"
  54#include "amdgpu_object.h"
  55#include "amdgpu_trace.h"
  56#include "amdgpu_amdkfd.h"
  57#include "amdgpu_sdma.h"
  58#include "amdgpu_ras.h"
  59#include "amdgpu_hmm.h"
  60#include "amdgpu_atomfirmware.h"
  61#include "amdgpu_res_cursor.h"
  62#include "bif/bif_4_1_d.h"
  63
  64MODULE_IMPORT_NS(DMA_BUF);
  65
  66#define AMDGPU_TTM_VRAM_MAX_DW_READ	((size_t)128)
  67
  68static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
  69				   struct ttm_tt *ttm,
  70				   struct ttm_resource *bo_mem);
  71static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
  72				      struct ttm_tt *ttm);
  73
  74static int amdgpu_ttm_init_on_chip(struct amdgpu_device *adev,
  75				    unsigned int type,
  76				    uint64_t size_in_page)
 
 
 
 
  77{
  78	return ttm_range_man_init(&adev->mman.bdev, type,
  79				  false, size_in_page);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  80}
  81
  82/**
  83 * amdgpu_evict_flags - Compute placement flags
  84 *
  85 * @bo: The buffer object to evict
  86 * @placement: Possible destination(s) for evicted BO
  87 *
  88 * Fill in placement data when ttm_bo_evict() is called
  89 */
  90static void amdgpu_evict_flags(struct ttm_buffer_object *bo,
  91				struct ttm_placement *placement)
  92{
  93	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
  94	struct amdgpu_bo *abo;
  95	static const struct ttm_place placements = {
  96		.fpfn = 0,
  97		.lpfn = 0,
  98		.mem_type = TTM_PL_SYSTEM,
  99		.flags = 0
 100	};
 101
 102	/* Don't handle scatter gather BOs */
 103	if (bo->type == ttm_bo_type_sg) {
 104		placement->num_placement = 0;
 105		placement->num_busy_placement = 0;
 106		return;
 107	}
 108
 109	/* Object isn't an AMDGPU object so ignore */
 110	if (!amdgpu_bo_is_amdgpu_bo(bo)) {
 111		placement->placement = &placements;
 112		placement->busy_placement = &placements;
 113		placement->num_placement = 1;
 114		placement->num_busy_placement = 1;
 115		return;
 116	}
 117
 118	abo = ttm_to_amdgpu_bo(bo);
 119	if (abo->flags & AMDGPU_GEM_CREATE_DISCARDABLE) {
 120		placement->num_placement = 0;
 121		placement->num_busy_placement = 0;
 122		return;
 123	}
 124
 125	switch (bo->resource->mem_type) {
 126	case AMDGPU_PL_GDS:
 127	case AMDGPU_PL_GWS:
 128	case AMDGPU_PL_OA:
 129	case AMDGPU_PL_DOORBELL:
 130		placement->num_placement = 0;
 131		placement->num_busy_placement = 0;
 132		return;
 133
 134	case TTM_PL_VRAM:
 135		if (!adev->mman.buffer_funcs_enabled) {
 136			/* Move to system memory */
 137			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
 138		} else if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
 139			   !(abo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) &&
 140			   amdgpu_bo_in_cpu_visible_vram(abo)) {
 141
 142			/* Try evicting to the CPU inaccessible part of VRAM
 143			 * first, but only set GTT as busy placement, so this
 144			 * BO will be evicted to GTT rather than causing other
 145			 * BOs to be evicted from VRAM
 146			 */
 147			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
 148							AMDGPU_GEM_DOMAIN_GTT |
 149							AMDGPU_GEM_DOMAIN_CPU);
 150			abo->placements[0].fpfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
 151			abo->placements[0].lpfn = 0;
 152			abo->placement.busy_placement = &abo->placements[1];
 153			abo->placement.num_busy_placement = 1;
 154		} else {
 155			/* Move to GTT memory */
 156			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_GTT |
 157							AMDGPU_GEM_DOMAIN_CPU);
 158		}
 159		break;
 160	case TTM_PL_TT:
 161	case AMDGPU_PL_PREEMPT:
 162	default:
 163		amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
 164		break;
 165	}
 166	*placement = abo->placement;
 167}
 168
 169/**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 170 * amdgpu_ttm_map_buffer - Map memory into the GART windows
 171 * @bo: buffer object to map
 172 * @mem: memory object to map
 173 * @mm_cur: range to map
 
 
 174 * @window: which GART window to use
 175 * @ring: DMA ring to use for the copy
 176 * @tmz: if we should setup a TMZ enabled mapping
 177 * @size: in number of bytes to map, out number of bytes mapped
 178 * @addr: resulting address inside the MC address space
 179 *
 180 * Setup one of the GART windows to access a specific piece of memory or return
 181 * the physical address for local memory.
 182 */
 183static int amdgpu_ttm_map_buffer(struct ttm_buffer_object *bo,
 184				 struct ttm_resource *mem,
 185				 struct amdgpu_res_cursor *mm_cur,
 186				 unsigned int window, struct amdgpu_ring *ring,
 187				 bool tmz, uint64_t *size, uint64_t *addr)
 
 188{
 189	struct amdgpu_device *adev = ring->adev;
 190	unsigned int offset, num_pages, num_dw, num_bytes;
 
 
 191	uint64_t src_addr, dst_addr;
 192	struct amdgpu_job *job;
 193	void *cpu_addr;
 194	uint64_t flags;
 195	unsigned int i;
 196	int r;
 197
 198	BUG_ON(adev->mman.buffer_funcs->copy_max_bytes <
 199	       AMDGPU_GTT_MAX_TRANSFER_SIZE * 8);
 200
 201	if (WARN_ON(mem->mem_type == AMDGPU_PL_PREEMPT))
 202		return -EINVAL;
 203
 204	/* Map only what can't be accessed directly */
 205	if (!tmz && mem->start != AMDGPU_BO_INVALID_OFFSET) {
 206		*addr = amdgpu_ttm_domain_start(adev, mem->mem_type) +
 207			mm_cur->start;
 208		return 0;
 209	}
 210
 211
 212	/*
 213	 * If start begins at an offset inside the page, then adjust the size
 214	 * and addr accordingly
 215	 */
 216	offset = mm_cur->start & ~PAGE_MASK;
 217
 218	num_pages = PFN_UP(*size + offset);
 219	num_pages = min_t(uint32_t, num_pages, AMDGPU_GTT_MAX_TRANSFER_SIZE);
 220
 221	*size = min(*size, (uint64_t)num_pages * PAGE_SIZE - offset);
 222
 223	*addr = adev->gmc.gart_start;
 224	*addr += (u64)window * AMDGPU_GTT_MAX_TRANSFER_SIZE *
 225		AMDGPU_GPU_PAGE_SIZE;
 226	*addr += offset;
 227
 228	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
 229	num_bytes = num_pages * 8 * AMDGPU_GPU_PAGES_IN_CPU_PAGE;
 230
 231	r = amdgpu_job_alloc_with_ib(adev, &adev->mman.high_pr,
 232				     AMDGPU_FENCE_OWNER_UNDEFINED,
 233				     num_dw * 4 + num_bytes,
 234				     AMDGPU_IB_POOL_DELAYED, &job);
 235	if (r)
 236		return r;
 237
 238	src_addr = num_dw * 4;
 239	src_addr += job->ibs[0].gpu_addr;
 240
 241	dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
 242	dst_addr += window * AMDGPU_GTT_MAX_TRANSFER_SIZE * 8;
 243	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
 244				dst_addr, num_bytes, false);
 245
 246	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
 247	WARN_ON(job->ibs[0].length_dw > num_dw);
 248
 249	flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, mem);
 250	if (tmz)
 251		flags |= AMDGPU_PTE_TMZ;
 252
 253	cpu_addr = &job->ibs[0].ptr[num_dw];
 254
 255	if (mem->mem_type == TTM_PL_TT) {
 256		dma_addr_t *dma_addr;
 
 257
 258		dma_addr = &bo->ttm->dma_address[mm_cur->start >> PAGE_SHIFT];
 259		amdgpu_gart_map(adev, 0, num_pages, dma_addr, flags, cpu_addr);
 
 
 
 
 260	} else {
 261		dma_addr_t dma_address;
 262
 263		dma_address = mm_cur->start;
 264		dma_address += adev->vm_manager.vram_base_offset;
 265
 266		for (i = 0; i < num_pages; ++i) {
 267			amdgpu_gart_map(adev, i << PAGE_SHIFT, 1, &dma_address,
 268					flags, cpu_addr);
 
 
 
 269			dma_address += PAGE_SIZE;
 270		}
 271	}
 272
 273	dma_fence_put(amdgpu_job_submit(job));
 274	return 0;
 
 
 
 
 
 
 
 
 
 
 275}
 276
 277/**
 278 * amdgpu_ttm_copy_mem_to_mem - Helper function for copy
 279 * @adev: amdgpu device
 280 * @src: buffer/address where to read from
 281 * @dst: buffer/address where to write to
 282 * @size: number of bytes to copy
 283 * @tmz: if a secure copy should be used
 284 * @resv: resv object to sync to
 285 * @f: Returns the last fence if multiple jobs are submitted.
 286 *
 287 * The function copies @size bytes from {src->mem + src->offset} to
 288 * {dst->mem + dst->offset}. src->bo and dst->bo could be same BO for a
 289 * move and different for a BO to BO copy.
 290 *
 291 */
 292int amdgpu_ttm_copy_mem_to_mem(struct amdgpu_device *adev,
 293			       const struct amdgpu_copy_mem *src,
 294			       const struct amdgpu_copy_mem *dst,
 295			       uint64_t size, bool tmz,
 296			       struct dma_resv *resv,
 297			       struct dma_fence **f)
 298{
 
 
 
 
 299	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
 300	struct amdgpu_res_cursor src_mm, dst_mm;
 301	struct dma_fence *fence = NULL;
 302	int r = 0;
 303
 304	if (!adev->mman.buffer_funcs_enabled) {
 305		DRM_ERROR("Trying to move memory with ring turned off.\n");
 306		return -EINVAL;
 307	}
 308
 309	amdgpu_res_first(src->mem, src->offset, size, &src_mm);
 310	amdgpu_res_first(dst->mem, dst->offset, size, &dst_mm);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 311
 312	mutex_lock(&adev->mman.gtt_window_lock);
 313	while (src_mm.remaining) {
 314		uint64_t from, to, cur_size;
 
 
 315		struct dma_fence *next;
 
 
 316
 317		/* Never copy more than 256MiB at once to avoid a timeout */
 318		cur_size = min3(src_mm.size, dst_mm.size, 256ULL << 20);
 
 
 
 
 319
 320		/* Map src to window 0 and dst to window 1. */
 321		r = amdgpu_ttm_map_buffer(src->bo, src->mem, &src_mm,
 322					  0, ring, tmz, &cur_size, &from);
 
 323		if (r)
 324			goto error;
 325
 326		r = amdgpu_ttm_map_buffer(dst->bo, dst->mem, &dst_mm,
 327					  1, ring, tmz, &cur_size, &to);
 
 328		if (r)
 329			goto error;
 330
 331		r = amdgpu_copy_buffer(ring, from, to, cur_size,
 332				       resv, &next, false, true, tmz);
 333		if (r)
 334			goto error;
 335
 336		dma_fence_put(fence);
 337		fence = next;
 338
 339		amdgpu_res_next(&src_mm, cur_size);
 340		amdgpu_res_next(&dst_mm, cur_size);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 341	}
 342error:
 343	mutex_unlock(&adev->mman.gtt_window_lock);
 344	if (f)
 345		*f = dma_fence_get(fence);
 346	dma_fence_put(fence);
 347	return r;
 348}
 349
 350/*
 351 * amdgpu_move_blit - Copy an entire buffer to another buffer
 352 *
 353 * This is a helper called by amdgpu_bo_move() and amdgpu_move_vram_ram() to
 354 * help move buffers to and from VRAM.
 355 */
 356static int amdgpu_move_blit(struct ttm_buffer_object *bo,
 357			    bool evict,
 358			    struct ttm_resource *new_mem,
 359			    struct ttm_resource *old_mem)
 360{
 361	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
 362	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
 363	struct amdgpu_copy_mem src, dst;
 364	struct dma_fence *fence = NULL;
 365	int r;
 366
 367	src.bo = bo;
 368	dst.bo = bo;
 369	src.mem = old_mem;
 370	dst.mem = new_mem;
 371	src.offset = 0;
 372	dst.offset = 0;
 373
 374	r = amdgpu_ttm_copy_mem_to_mem(adev, &src, &dst,
 375				       new_mem->size,
 376				       amdgpu_bo_encrypted(abo),
 377				       bo->base.resv, &fence);
 378	if (r)
 379		goto error;
 380
 381	/* clear the space being freed */
 382	if (old_mem->mem_type == TTM_PL_VRAM &&
 383	    (abo->flags & AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE)) {
 384		struct dma_fence *wipe_fence = NULL;
 385
 386		r = amdgpu_fill_buffer(abo, AMDGPU_POISON, NULL, &wipe_fence,
 387					false);
 388		if (r) {
 389			goto error;
 390		} else if (wipe_fence) {
 391			dma_fence_put(fence);
 392			fence = wipe_fence;
 393		}
 394	}
 395
 396	/* Always block for VM page tables before committing the new location */
 397	if (bo->type == ttm_bo_type_kernel)
 398		r = ttm_bo_move_accel_cleanup(bo, fence, true, false, new_mem);
 399	else
 400		r = ttm_bo_move_accel_cleanup(bo, fence, evict, true, new_mem);
 401	dma_fence_put(fence);
 402	return r;
 403
 404error:
 405	if (fence)
 406		dma_fence_wait(fence, false);
 407	dma_fence_put(fence);
 408	return r;
 409}
 410
 411/*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 412 * amdgpu_mem_visible - Check that memory can be accessed by ttm_bo_move_memcpy
 413 *
 414 * Called by amdgpu_bo_move()
 415 */
 416static bool amdgpu_mem_visible(struct amdgpu_device *adev,
 417			       struct ttm_resource *mem)
 418{
 419	u64 mem_size = (u64)mem->size;
 420	struct amdgpu_res_cursor cursor;
 421	u64 end;
 422
 423	if (mem->mem_type == TTM_PL_SYSTEM ||
 424	    mem->mem_type == TTM_PL_TT)
 425		return true;
 426	if (mem->mem_type != TTM_PL_VRAM)
 427		return false;
 428
 429	amdgpu_res_first(mem, 0, mem_size, &cursor);
 430	end = cursor.start + cursor.size;
 431	while (cursor.remaining) {
 432		amdgpu_res_next(&cursor, cursor.size);
 433
 434		if (!cursor.remaining)
 435			break;
 436
 437		/* ttm_resource_ioremap only supports contiguous memory */
 438		if (end != cursor.start)
 439			return false;
 440
 441		end = cursor.start + cursor.size;
 442	}
 443
 444	return end <= adev->gmc.visible_vram_size;
 445}
 446
 447/*
 448 * amdgpu_bo_move - Move a buffer object to a new memory location
 449 *
 450 * Called by ttm_bo_handle_move_mem()
 451 */
 452static int amdgpu_bo_move(struct ttm_buffer_object *bo, bool evict,
 453			  struct ttm_operation_ctx *ctx,
 454			  struct ttm_resource *new_mem,
 455			  struct ttm_place *hop)
 456{
 457	struct amdgpu_device *adev;
 458	struct amdgpu_bo *abo;
 459	struct ttm_resource *old_mem = bo->resource;
 460	int r;
 461
 462	if (new_mem->mem_type == TTM_PL_TT ||
 463	    new_mem->mem_type == AMDGPU_PL_PREEMPT) {
 464		r = amdgpu_ttm_backend_bind(bo->bdev, bo->ttm, new_mem);
 465		if (r)
 466			return r;
 467	}
 468
 469	abo = ttm_to_amdgpu_bo(bo);
 470	adev = amdgpu_ttm_adev(bo->bdev);
 471
 472	if (!old_mem || (old_mem->mem_type == TTM_PL_SYSTEM &&
 473			 bo->ttm == NULL)) {
 474		ttm_bo_move_null(bo, new_mem);
 475		goto out;
 476	}
 477	if (old_mem->mem_type == TTM_PL_SYSTEM &&
 478	    (new_mem->mem_type == TTM_PL_TT ||
 479	     new_mem->mem_type == AMDGPU_PL_PREEMPT)) {
 480		ttm_bo_move_null(bo, new_mem);
 481		goto out;
 482	}
 483	if ((old_mem->mem_type == TTM_PL_TT ||
 484	     old_mem->mem_type == AMDGPU_PL_PREEMPT) &&
 485	    new_mem->mem_type == TTM_PL_SYSTEM) {
 486		r = ttm_bo_wait_ctx(bo, ctx);
 487		if (r)
 488			return r;
 489
 490		amdgpu_ttm_backend_unbind(bo->bdev, bo->ttm);
 491		ttm_resource_free(bo, &bo->resource);
 492		ttm_bo_assign_mem(bo, new_mem);
 493		goto out;
 494	}
 495
 496	if (old_mem->mem_type == AMDGPU_PL_GDS ||
 497	    old_mem->mem_type == AMDGPU_PL_GWS ||
 498	    old_mem->mem_type == AMDGPU_PL_OA ||
 499	    old_mem->mem_type == AMDGPU_PL_DOORBELL ||
 500	    new_mem->mem_type == AMDGPU_PL_GDS ||
 501	    new_mem->mem_type == AMDGPU_PL_GWS ||
 502	    new_mem->mem_type == AMDGPU_PL_OA ||
 503	    new_mem->mem_type == AMDGPU_PL_DOORBELL) {
 504		/* Nothing to save here */
 505		ttm_bo_move_null(bo, new_mem);
 506		goto out;
 507	}
 508
 509	if (bo->type == ttm_bo_type_device &&
 510	    new_mem->mem_type == TTM_PL_VRAM &&
 511	    old_mem->mem_type != TTM_PL_VRAM) {
 512		/* amdgpu_bo_fault_reserve_notify will re-set this if the CPU
 513		 * accesses the BO after it's moved.
 514		 */
 515		abo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
 516	}
 517
 518	if (adev->mman.buffer_funcs_enabled) {
 519		if (((old_mem->mem_type == TTM_PL_SYSTEM &&
 520		      new_mem->mem_type == TTM_PL_VRAM) ||
 521		     (old_mem->mem_type == TTM_PL_VRAM &&
 522		      new_mem->mem_type == TTM_PL_SYSTEM))) {
 523			hop->fpfn = 0;
 524			hop->lpfn = 0;
 525			hop->mem_type = TTM_PL_TT;
 526			hop->flags = TTM_PL_FLAG_TEMPORARY;
 527			return -EMULTIHOP;
 528		}
 529
 530		r = amdgpu_move_blit(bo, evict, new_mem, old_mem);
 531	} else {
 532		r = -ENODEV;
 
 533	}
 534
 535	if (r) {
 
 536		/* Check that all memory is CPU accessible */
 537		if (!amdgpu_mem_visible(adev, old_mem) ||
 538		    !amdgpu_mem_visible(adev, new_mem)) {
 539			pr_err("Move buffer fallback to memcpy unavailable\n");
 540			return r;
 541		}
 542
 543		r = ttm_bo_move_memcpy(bo, ctx, new_mem);
 544		if (r)
 545			return r;
 546	}
 547
 548	trace_amdgpu_bo_move(abo, new_mem->mem_type, old_mem->mem_type);
 549out:
 
 
 
 
 
 
 
 550	/* update statistics */
 551	atomic64_add(bo->base.size, &adev->num_bytes_moved);
 552	amdgpu_bo_move_notify(bo, evict);
 553	return 0;
 554}
 555
 556/*
 557 * amdgpu_ttm_io_mem_reserve - Reserve a block of memory during a fault
 558 *
 559 * Called by ttm_mem_io_reserve() ultimately via ttm_bo_vm_fault()
 560 */
 561static int amdgpu_ttm_io_mem_reserve(struct ttm_device *bdev,
 562				     struct ttm_resource *mem)
 563{
 
 564	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
 565	size_t bus_size = (size_t)mem->size;
 566
 
 
 
 
 
 
 
 567	switch (mem->mem_type) {
 568	case TTM_PL_SYSTEM:
 569		/* system memory */
 570		return 0;
 571	case TTM_PL_TT:
 572	case AMDGPU_PL_PREEMPT:
 573		break;
 574	case TTM_PL_VRAM:
 575		mem->bus.offset = mem->start << PAGE_SHIFT;
 576		/* check if it's visible */
 577		if ((mem->bus.offset + bus_size) > adev->gmc.visible_vram_size)
 578			return -EINVAL;
 579
 
 
 
 580		if (adev->mman.aper_base_kaddr &&
 581		    mem->placement & TTM_PL_FLAG_CONTIGUOUS)
 582			mem->bus.addr = (u8 *)adev->mman.aper_base_kaddr +
 583					mem->bus.offset;
 584
 585		mem->bus.offset += adev->gmc.aper_base;
 586		mem->bus.is_iomem = true;
 587		break;
 588	case AMDGPU_PL_DOORBELL:
 589		mem->bus.offset = mem->start << PAGE_SHIFT;
 590		mem->bus.offset += adev->doorbell.base;
 591		mem->bus.is_iomem = true;
 592		mem->bus.caching = ttm_uncached;
 593		break;
 594	default:
 595		return -EINVAL;
 596	}
 597	return 0;
 598}
 599
 600static unsigned long amdgpu_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
 601					   unsigned long page_offset)
 602{
 603	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
 604	struct amdgpu_res_cursor cursor;
 605
 606	amdgpu_res_first(bo->resource, (u64)page_offset << PAGE_SHIFT, 0,
 607			 &cursor);
 608
 609	if (bo->resource->mem_type == AMDGPU_PL_DOORBELL)
 610		return ((uint64_t)(adev->doorbell.base + cursor.start)) >> PAGE_SHIFT;
 611
 612	return (adev->gmc.aper_base + cursor.start) >> PAGE_SHIFT;
 613}
 614
 615/**
 616 * amdgpu_ttm_domain_start - Returns GPU start address
 617 * @adev: amdgpu device object
 618 * @type: type of the memory
 619 *
 620 * Returns:
 621 * GPU start address of a memory domain
 622 */
 623
 624uint64_t amdgpu_ttm_domain_start(struct amdgpu_device *adev, uint32_t type)
 625{
 626	switch (type) {
 627	case TTM_PL_TT:
 628		return adev->gmc.gart_start;
 629	case TTM_PL_VRAM:
 630		return adev->gmc.vram_start;
 631	}
 632
 633	return 0;
 634}
 635
 636/*
 637 * TTM backend functions.
 638 */
 639struct amdgpu_ttm_tt {
 640	struct ttm_tt	ttm;
 641	struct drm_gem_object	*gobj;
 642	u64			offset;
 643	uint64_t		userptr;
 644	struct task_struct	*usertask;
 645	uint32_t		userflags;
 646	bool			bound;
 647	int32_t			pool_id;
 
 648};
 649
 650#define ttm_to_amdgpu_ttm_tt(ptr)	container_of(ptr, struct amdgpu_ttm_tt, ttm)
 651
 652#ifdef CONFIG_DRM_AMDGPU_USERPTR
 653/*
 654 * amdgpu_ttm_tt_get_user_pages - get device accessible pages that back user
 655 * memory and start HMM tracking CPU page table update
 656 *
 657 * Calling function must call amdgpu_ttm_tt_userptr_range_done() once and only
 658 * once afterwards to stop HMM tracking
 659 */
 660int amdgpu_ttm_tt_get_user_pages(struct amdgpu_bo *bo, struct page **pages,
 661				 struct hmm_range **range)
 662{
 663	struct ttm_tt *ttm = bo->tbo.ttm;
 664	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
 665	unsigned long start = gtt->userptr;
 666	struct vm_area_struct *vma;
 
 
 667	struct mm_struct *mm;
 668	bool readonly;
 669	int r = 0;
 670
 671	/* Make sure get_user_pages_done() can cleanup gracefully */
 672	*range = NULL;
 673
 674	mm = bo->notifier.mm;
 675	if (unlikely(!mm)) {
 676		DRM_DEBUG_DRIVER("BO is not registered?\n");
 677		return -EFAULT;
 678	}
 679
 
 
 
 
 680	if (!mmget_not_zero(mm)) /* Happens during process shutdown */
 681		return -ESRCH;
 682
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 683	mmap_read_lock(mm);
 684	vma = vma_lookup(mm, start);
 685	if (unlikely(!vma)) {
 686		r = -EFAULT;
 687		goto out_unlock;
 688	}
 689	if (unlikely((gtt->userflags & AMDGPU_GEM_USERPTR_ANONONLY) &&
 690		vma->vm_file)) {
 691		r = -EPERM;
 692		goto out_unlock;
 693	}
 
 
 
 
 
 694
 695	readonly = amdgpu_ttm_tt_is_readonly(ttm);
 696	r = amdgpu_hmm_range_get_pages(&bo->notifier, start, ttm->num_pages,
 697				       readonly, NULL, pages, range);
 698out_unlock:
 699	mmap_read_unlock(mm);
 700	if (r)
 701		pr_debug("failed %d to get user pages 0x%lx\n", r, start);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 702
 
 703	mmput(mm);
 704
 
 
 
 
 
 
 
 
 
 
 705	return r;
 706}
 707
 708/* amdgpu_ttm_tt_discard_user_pages - Discard range and pfn array allocations
 709 */
 710void amdgpu_ttm_tt_discard_user_pages(struct ttm_tt *ttm,
 711				      struct hmm_range *range)
 712{
 713	struct amdgpu_ttm_tt *gtt = (void *)ttm;
 714
 715	if (gtt && gtt->userptr && range)
 716		amdgpu_hmm_range_get_pages_done(range);
 717}
 718
 719/*
 720 * amdgpu_ttm_tt_get_user_pages_done - stop HMM track the CPU page table change
 721 * Check if the pages backing this ttm range have been invalidated
 722 *
 723 * Returns: true if pages are still valid
 724 */
 725bool amdgpu_ttm_tt_get_user_pages_done(struct ttm_tt *ttm,
 726				       struct hmm_range *range)
 727{
 728	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
 
 729
 730	if (!gtt || !gtt->userptr || !range)
 731		return false;
 732
 733	DRM_DEBUG_DRIVER("user_pages_done 0x%llx pages 0x%x\n",
 734		gtt->userptr, ttm->num_pages);
 735
 736	WARN_ONCE(!range->hmm_pfns, "No user pages to check\n");
 
 
 
 
 
 
 
 
 
 
 
 
 
 737
 738	return !amdgpu_hmm_range_get_pages_done(range);
 739}
 740#endif
 741
 742/*
 743 * amdgpu_ttm_tt_set_user_pages - Copy pages in, putting old pages as necessary.
 744 *
 745 * Called by amdgpu_cs_list_validate(). This creates the page list
 746 * that backs user memory and will ultimately be mapped into the device
 747 * address space.
 748 */
 749void amdgpu_ttm_tt_set_user_pages(struct ttm_tt *ttm, struct page **pages)
 750{
 751	unsigned long i;
 752
 753	for (i = 0; i < ttm->num_pages; ++i)
 754		ttm->pages[i] = pages ? pages[i] : NULL;
 755}
 756
 757/*
 758 * amdgpu_ttm_tt_pin_userptr - prepare the sg table with the user pages
 759 *
 760 * Called by amdgpu_ttm_backend_bind()
 761 **/
 762static int amdgpu_ttm_tt_pin_userptr(struct ttm_device *bdev,
 763				     struct ttm_tt *ttm)
 764{
 765	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
 766	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
 
 
 767	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
 768	enum dma_data_direction direction = write ?
 769		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
 770	int r;
 771
 772	/* Allocate an SG array and squash pages into it */
 773	r = sg_alloc_table_from_pages(ttm->sg, ttm->pages, ttm->num_pages, 0,
 774				      (u64)ttm->num_pages << PAGE_SHIFT,
 775				      GFP_KERNEL);
 776	if (r)
 777		goto release_sg;
 778
 779	/* Map SG to device */
 780	r = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
 781	if (r)
 782		goto release_sg;
 783
 784	/* convert SG to linear array of pages and dma addresses */
 785	drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
 786				       ttm->num_pages);
 787
 788	return 0;
 789
 790release_sg:
 791	kfree(ttm->sg);
 792	ttm->sg = NULL;
 793	return r;
 794}
 795
 796/*
 797 * amdgpu_ttm_tt_unpin_userptr - Unpin and unmap userptr pages
 798 */
 799static void amdgpu_ttm_tt_unpin_userptr(struct ttm_device *bdev,
 800					struct ttm_tt *ttm)
 801{
 802	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
 803	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
 
 804	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
 805	enum dma_data_direction direction = write ?
 806		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
 807
 808	/* double check that we don't free the table twice */
 809	if (!ttm->sg || !ttm->sg->sgl)
 810		return;
 811
 812	/* unmap the pages mapped to the device */
 813	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
 814	sg_free_table(ttm->sg);
 815}
 816
 817/*
 818 * total_pages is constructed as MQD0+CtrlStack0 + MQD1+CtrlStack1 + ...
 819 * MQDn+CtrlStackn where n is the number of XCCs per partition.
 820 * pages_per_xcc is the size of one MQD+CtrlStack. The first page is MQD
 821 * and uses memory type default, UC. The rest of pages_per_xcc are
 822 * Ctrl stack and modify their memory type to NC.
 823 */
 824static void amdgpu_ttm_gart_bind_gfx9_mqd(struct amdgpu_device *adev,
 825				struct ttm_tt *ttm, uint64_t flags)
 826{
 827	struct amdgpu_ttm_tt *gtt = (void *)ttm;
 828	uint64_t total_pages = ttm->num_pages;
 829	int num_xcc = max(1U, adev->gfx.num_xcc_per_xcp);
 830	uint64_t page_idx, pages_per_xcc;
 831	int i;
 832	uint64_t ctrl_flags = (flags & ~AMDGPU_PTE_MTYPE_VG10_MASK) |
 833			AMDGPU_PTE_MTYPE_VG10(AMDGPU_MTYPE_NC);
 834
 835	pages_per_xcc = total_pages;
 836	do_div(pages_per_xcc, num_xcc);
 837
 838	for (i = 0, page_idx = 0; i < num_xcc; i++, page_idx += pages_per_xcc) {
 839		/* MQD page: use default flags */
 840		amdgpu_gart_bind(adev,
 841				gtt->offset + (page_idx << PAGE_SHIFT),
 842				1, &gtt->ttm.dma_address[page_idx], flags);
 843		/*
 844		 * Ctrl pages - modify the memory type to NC (ctrl_flags) from
 845		 * the second page of the BO onward.
 846		 */
 847		amdgpu_gart_bind(adev,
 848				gtt->offset + ((page_idx + 1) << PAGE_SHIFT),
 849				pages_per_xcc - 1,
 850				&gtt->ttm.dma_address[page_idx + 1],
 851				ctrl_flags);
 852	}
 
 853}
 854
 855static void amdgpu_ttm_gart_bind(struct amdgpu_device *adev,
 856				 struct ttm_buffer_object *tbo,
 857				 uint64_t flags)
 858{
 859	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(tbo);
 860	struct ttm_tt *ttm = tbo->ttm;
 861	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
 
 862
 863	if (amdgpu_bo_encrypted(abo))
 864		flags |= AMDGPU_PTE_TMZ;
 865
 866	if (abo->flags & AMDGPU_GEM_CREATE_CP_MQD_GFX9) {
 867		amdgpu_ttm_gart_bind_gfx9_mqd(adev, ttm, flags);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 868	} else {
 869		amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
 870				 gtt->ttm.dma_address, flags);
 871	}
 
 
 
 
 
 
 
 872}
 873
 874/*
 875 * amdgpu_ttm_backend_bind - Bind GTT memory
 876 *
 877 * Called by ttm_tt_bind() on behalf of ttm_bo_handle_move_mem().
 878 * This handles binding GTT memory to the device address space.
 879 */
 880static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
 881				   struct ttm_tt *ttm,
 882				   struct ttm_resource *bo_mem)
 883{
 884	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
 885	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
 886	uint64_t flags;
 887	int r;
 888
 889	if (!bo_mem)
 890		return -EINVAL;
 891
 892	if (gtt->bound)
 893		return 0;
 894
 895	if (gtt->userptr) {
 896		r = amdgpu_ttm_tt_pin_userptr(bdev, ttm);
 897		if (r) {
 898			DRM_ERROR("failed to pin userptr\n");
 899			return r;
 900		}
 901	} else if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL) {
 902		if (!ttm->sg) {
 903			struct dma_buf_attachment *attach;
 904			struct sg_table *sgt;
 905
 906			attach = gtt->gobj->import_attach;
 907			sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
 908			if (IS_ERR(sgt))
 909				return PTR_ERR(sgt);
 910
 911			ttm->sg = sgt;
 912		}
 913
 914		drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
 915					       ttm->num_pages);
 916	}
 917
 918	if (!ttm->num_pages) {
 919		WARN(1, "nothing to bind %u pages for mreg %p back %p!\n",
 920		     ttm->num_pages, bo_mem, ttm);
 921	}
 922
 923	if (bo_mem->mem_type != TTM_PL_TT ||
 924	    !amdgpu_gtt_mgr_has_gart_addr(bo_mem)) {
 
 
 
 
 925		gtt->offset = AMDGPU_BO_INVALID_OFFSET;
 926		return 0;
 927	}
 928
 929	/* compute PTE flags relevant to this BO memory */
 930	flags = amdgpu_ttm_tt_pte_flags(adev, ttm, bo_mem);
 931
 932	/* bind pages into GART page tables */
 933	gtt->offset = (u64)bo_mem->start << PAGE_SHIFT;
 934	amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
 935			 gtt->ttm.dma_address, flags);
 936	gtt->bound = true;
 937	return 0;
 
 
 
 938}
 939
 940/*
 941 * amdgpu_ttm_alloc_gart - Make sure buffer object is accessible either
 942 * through AGP or GART aperture.
 943 *
 944 * If bo is accessible through AGP aperture, then use AGP aperture
 945 * to access bo; otherwise allocate logical space in GART aperture
 946 * and map bo to GART aperture.
 947 */
 948int amdgpu_ttm_alloc_gart(struct ttm_buffer_object *bo)
 949{
 950	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
 951	struct ttm_operation_ctx ctx = { false, false };
 952	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(bo->ttm);
 
 953	struct ttm_placement placement;
 954	struct ttm_place placements;
 955	struct ttm_resource *tmp;
 956	uint64_t addr, flags;
 957	int r;
 958
 959	if (bo->resource->start != AMDGPU_BO_INVALID_OFFSET)
 960		return 0;
 961
 962	addr = amdgpu_gmc_agp_addr(bo);
 963	if (addr != AMDGPU_BO_INVALID_OFFSET)
 964		return 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 965
 966	/* allocate GART space */
 967	placement.num_placement = 1;
 968	placement.placement = &placements;
 969	placement.num_busy_placement = 1;
 970	placement.busy_placement = &placements;
 971	placements.fpfn = 0;
 972	placements.lpfn = adev->gmc.gart_size >> PAGE_SHIFT;
 973	placements.mem_type = TTM_PL_TT;
 974	placements.flags = bo->resource->placement;
 975
 976	r = ttm_bo_mem_space(bo, &placement, &tmp, &ctx);
 977	if (unlikely(r))
 978		return r;
 979
 980	/* compute PTE flags for this buffer object */
 981	flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, tmp);
 
 
 
 
 
 982
 983	/* Bind pages */
 984	gtt->offset = (u64)tmp->start << PAGE_SHIFT;
 985	amdgpu_ttm_gart_bind(adev, bo, flags);
 986	amdgpu_gart_invalidate_tlb(adev);
 987	ttm_resource_free(bo, &bo->resource);
 988	ttm_bo_assign_mem(bo, tmp);
 989
 990	return 0;
 991}
 992
 993/*
 994 * amdgpu_ttm_recover_gart - Rebind GTT pages
 995 *
 996 * Called by amdgpu_gtt_mgr_recover() from amdgpu_device_reset() to
 997 * rebind GTT pages during a GPU reset.
 998 */
 999void amdgpu_ttm_recover_gart(struct ttm_buffer_object *tbo)
1000{
1001	struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
1002	uint64_t flags;
 
1003
1004	if (!tbo->ttm)
1005		return;
 
 
 
1006
1007	flags = amdgpu_ttm_tt_pte_flags(adev, tbo->ttm, tbo->resource);
1008	amdgpu_ttm_gart_bind(adev, tbo, flags);
1009}
1010
1011/*
1012 * amdgpu_ttm_backend_unbind - Unbind GTT mapped pages
1013 *
1014 * Called by ttm_tt_unbind() on behalf of ttm_bo_move_ttm() and
1015 * ttm_tt_destroy().
1016 */
1017static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
1018				      struct ttm_tt *ttm)
1019{
1020	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1021	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
 
1022
1023	/* if the pages have userptr pinning then clear that first */
1024	if (gtt->userptr) {
1025		amdgpu_ttm_tt_unpin_userptr(bdev, ttm);
1026	} else if (ttm->sg && gtt->gobj->import_attach) {
1027		struct dma_buf_attachment *attach;
1028
1029		attach = gtt->gobj->import_attach;
1030		dma_buf_unmap_attachment(attach, ttm->sg, DMA_BIDIRECTIONAL);
1031		ttm->sg = NULL;
1032	}
1033
1034	if (!gtt->bound)
1035		return;
1036
1037	if (gtt->offset == AMDGPU_BO_INVALID_OFFSET)
1038		return;
1039
1040	/* unbind shouldn't be done for GDS/GWS/OA in ttm_bo_clean_mm */
1041	amdgpu_gart_unbind(adev, gtt->offset, ttm->num_pages);
1042	gtt->bound = false;
 
 
1043}
1044
1045static void amdgpu_ttm_backend_destroy(struct ttm_device *bdev,
1046				       struct ttm_tt *ttm)
1047{
1048	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1049
1050	if (gtt->usertask)
1051		put_task_struct(gtt->usertask);
1052
1053	ttm_tt_fini(&gtt->ttm);
1054	kfree(gtt);
1055}
1056
 
 
 
 
 
 
1057/**
1058 * amdgpu_ttm_tt_create - Create a ttm_tt object for a given BO
1059 *
1060 * @bo: The buffer object to create a GTT ttm_tt object around
1061 * @page_flags: Page flags to be added to the ttm_tt object
1062 *
1063 * Called by ttm_tt_create().
1064 */
1065static struct ttm_tt *amdgpu_ttm_tt_create(struct ttm_buffer_object *bo,
1066					   uint32_t page_flags)
1067{
1068	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1069	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1070	struct amdgpu_ttm_tt *gtt;
1071	enum ttm_caching caching;
1072
1073	gtt = kzalloc(sizeof(struct amdgpu_ttm_tt), GFP_KERNEL);
1074	if (!gtt)
1075		return NULL;
1076
 
1077	gtt->gobj = &bo->base;
1078	if (adev->gmc.mem_partitions && abo->xcp_id >= 0)
1079		gtt->pool_id = KFD_XCP_MEM_ID(adev, abo->xcp_id);
1080	else
1081		gtt->pool_id = abo->xcp_id;
1082
1083	if (abo->flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
1084		caching = ttm_write_combined;
1085	else
1086		caching = ttm_cached;
1087
1088	/* allocate space for the uninitialized page entries */
1089	if (ttm_sg_tt_init(&gtt->ttm, bo, page_flags, caching)) {
1090		kfree(gtt);
1091		return NULL;
1092	}
1093	return &gtt->ttm;
1094}
1095
1096/*
1097 * amdgpu_ttm_tt_populate - Map GTT pages visible to the device
1098 *
1099 * Map the pages of a ttm_tt object to an address space visible
1100 * to the underlying device.
1101 */
1102static int amdgpu_ttm_tt_populate(struct ttm_device *bdev,
1103				  struct ttm_tt *ttm,
1104				  struct ttm_operation_ctx *ctx)
1105{
1106	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1107	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1108	struct ttm_pool *pool;
1109	pgoff_t i;
1110	int ret;
1111
1112	/* user pages are bound by amdgpu_ttm_tt_pin_userptr() */
1113	if (gtt->userptr) {
1114		ttm->sg = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
1115		if (!ttm->sg)
1116			return -ENOMEM;
 
 
 
1117		return 0;
1118	}
1119
1120	if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1121		return 0;
 
1122
1123	if (adev->mman.ttm_pools && gtt->pool_id >= 0)
1124		pool = &adev->mman.ttm_pools[gtt->pool_id];
1125	else
1126		pool = &adev->mman.bdev.pool;
1127	ret = ttm_pool_alloc(pool, ttm, ctx);
1128	if (ret)
1129		return ret;
1130
1131	for (i = 0; i < ttm->num_pages; ++i)
1132		ttm->pages[i]->mapping = bdev->dev_mapping;
1133
1134	return 0;
 
 
1135}
1136
1137/*
1138 * amdgpu_ttm_tt_unpopulate - unmap GTT pages and unpopulate page arrays
1139 *
1140 * Unmaps pages of a ttm_tt object from the device address space and
1141 * unpopulates the page array backing it.
1142 */
1143static void amdgpu_ttm_tt_unpopulate(struct ttm_device *bdev,
1144				     struct ttm_tt *ttm)
1145{
1146	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1147	struct amdgpu_device *adev;
1148	struct ttm_pool *pool;
1149	pgoff_t i;
1150
1151	amdgpu_ttm_backend_unbind(bdev, ttm);
1152
1153	if (gtt->userptr) {
1154		amdgpu_ttm_tt_set_user_pages(ttm, NULL);
1155		kfree(ttm->sg);
 
 
 
 
 
 
 
 
 
1156		ttm->sg = NULL;
1157		return;
1158	}
1159
1160	if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
1161		return;
1162
1163	for (i = 0; i < ttm->num_pages; ++i)
1164		ttm->pages[i]->mapping = NULL;
1165
1166	adev = amdgpu_ttm_adev(bdev);
 
 
 
 
 
1167
1168	if (adev->mman.ttm_pools && gtt->pool_id >= 0)
1169		pool = &adev->mman.ttm_pools[gtt->pool_id];
1170	else
1171		pool = &adev->mman.bdev.pool;
1172
1173	return ttm_pool_free(pool, ttm);
1174}
1175
1176/**
1177 * amdgpu_ttm_tt_get_userptr - Return the userptr GTT ttm_tt for the current
1178 * task
1179 *
1180 * @tbo: The ttm_buffer_object that contains the userptr
1181 * @user_addr:  The returned value
1182 */
1183int amdgpu_ttm_tt_get_userptr(const struct ttm_buffer_object *tbo,
1184			      uint64_t *user_addr)
1185{
1186	struct amdgpu_ttm_tt *gtt;
1187
1188	if (!tbo->ttm)
1189		return -EINVAL;
1190
1191	gtt = (void *)tbo->ttm;
1192	*user_addr = gtt->userptr;
1193	return 0;
1194}
1195
1196/**
1197 * amdgpu_ttm_tt_set_userptr - Initialize userptr GTT ttm_tt for the current
1198 * task
1199 *
1200 * @bo: The ttm_buffer_object to bind this userptr to
1201 * @addr:  The address in the current tasks VM space to use
1202 * @flags: Requirements of userptr object.
1203 *
1204 * Called by amdgpu_gem_userptr_ioctl() and kfd_ioctl_alloc_memory_of_gpu() to
1205 * bind userptr pages to current task and by kfd_ioctl_acquire_vm() to
1206 * initialize GPU VM for a KFD process.
1207 */
1208int amdgpu_ttm_tt_set_userptr(struct ttm_buffer_object *bo,
1209			      uint64_t addr, uint32_t flags)
1210{
1211	struct amdgpu_ttm_tt *gtt;
1212
1213	if (!bo->ttm) {
1214		/* TODO: We want a separate TTM object type for userptrs */
1215		bo->ttm = amdgpu_ttm_tt_create(bo, 0);
1216		if (bo->ttm == NULL)
1217			return -ENOMEM;
1218	}
1219
1220	/* Set TTM_TT_FLAG_EXTERNAL before populate but after create. */
1221	bo->ttm->page_flags |= TTM_TT_FLAG_EXTERNAL;
1222
1223	gtt = ttm_to_amdgpu_ttm_tt(bo->ttm);
1224	gtt->userptr = addr;
1225	gtt->userflags = flags;
1226
1227	if (gtt->usertask)
1228		put_task_struct(gtt->usertask);
1229	gtt->usertask = current->group_leader;
1230	get_task_struct(gtt->usertask);
1231
1232	return 0;
1233}
1234
1235/*
1236 * amdgpu_ttm_tt_get_usermm - Return memory manager for ttm_tt object
1237 */
1238struct mm_struct *amdgpu_ttm_tt_get_usermm(struct ttm_tt *ttm)
1239{
1240	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1241
1242	if (gtt == NULL)
1243		return NULL;
1244
1245	if (gtt->usertask == NULL)
1246		return NULL;
1247
1248	return gtt->usertask->mm;
1249}
1250
1251/*
1252 * amdgpu_ttm_tt_affect_userptr - Determine if a ttm_tt object lays inside an
1253 * address range for the current task.
1254 *
1255 */
1256bool amdgpu_ttm_tt_affect_userptr(struct ttm_tt *ttm, unsigned long start,
1257				  unsigned long end, unsigned long *userptr)
1258{
1259	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1260	unsigned long size;
1261
1262	if (gtt == NULL || !gtt->userptr)
1263		return false;
1264
1265	/* Return false if no part of the ttm_tt object lies within
1266	 * the range
1267	 */
1268	size = (unsigned long)gtt->ttm.num_pages * PAGE_SIZE;
1269	if (gtt->userptr > end || gtt->userptr + size <= start)
1270		return false;
1271
1272	if (userptr)
1273		*userptr = gtt->userptr;
1274	return true;
1275}
1276
1277/*
1278 * amdgpu_ttm_tt_is_userptr - Have the pages backing by userptr?
1279 */
1280bool amdgpu_ttm_tt_is_userptr(struct ttm_tt *ttm)
1281{
1282	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1283
1284	if (gtt == NULL || !gtt->userptr)
1285		return false;
1286
1287	return true;
1288}
1289
1290/*
1291 * amdgpu_ttm_tt_is_readonly - Is the ttm_tt object read only?
1292 */
1293bool amdgpu_ttm_tt_is_readonly(struct ttm_tt *ttm)
1294{
1295	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1296
1297	if (gtt == NULL)
1298		return false;
1299
1300	return !!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1301}
1302
1303/**
1304 * amdgpu_ttm_tt_pde_flags - Compute PDE flags for ttm_tt object
1305 *
1306 * @ttm: The ttm_tt object to compute the flags for
1307 * @mem: The memory registry backing this ttm_tt object
1308 *
1309 * Figure out the flags to use for a VM PDE (Page Directory Entry).
1310 */
1311uint64_t amdgpu_ttm_tt_pde_flags(struct ttm_tt *ttm, struct ttm_resource *mem)
1312{
1313	uint64_t flags = 0;
1314
1315	if (mem && mem->mem_type != TTM_PL_SYSTEM)
1316		flags |= AMDGPU_PTE_VALID;
1317
1318	if (mem && (mem->mem_type == TTM_PL_TT ||
1319		    mem->mem_type == AMDGPU_PL_DOORBELL ||
1320		    mem->mem_type == AMDGPU_PL_PREEMPT)) {
1321		flags |= AMDGPU_PTE_SYSTEM;
1322
1323		if (ttm->caching == ttm_cached)
1324			flags |= AMDGPU_PTE_SNOOPED;
1325	}
1326
1327	if (mem && mem->mem_type == TTM_PL_VRAM &&
1328			mem->bus.caching == ttm_cached)
1329		flags |= AMDGPU_PTE_SNOOPED;
1330
1331	return flags;
1332}
1333
1334/**
1335 * amdgpu_ttm_tt_pte_flags - Compute PTE flags for ttm_tt object
1336 *
1337 * @adev: amdgpu_device pointer
1338 * @ttm: The ttm_tt object to compute the flags for
1339 * @mem: The memory registry backing this ttm_tt object
1340 *
1341 * Figure out the flags to use for a VM PTE (Page Table Entry).
1342 */
1343uint64_t amdgpu_ttm_tt_pte_flags(struct amdgpu_device *adev, struct ttm_tt *ttm,
1344				 struct ttm_resource *mem)
1345{
1346	uint64_t flags = amdgpu_ttm_tt_pde_flags(ttm, mem);
1347
1348	flags |= adev->gart.gart_pte_flags;
1349	flags |= AMDGPU_PTE_READABLE;
1350
1351	if (!amdgpu_ttm_tt_is_readonly(ttm))
1352		flags |= AMDGPU_PTE_WRITEABLE;
1353
1354	return flags;
1355}
1356
1357/*
1358 * amdgpu_ttm_bo_eviction_valuable - Check to see if we can evict a buffer
1359 * object.
1360 *
1361 * Return true if eviction is sensible. Called by ttm_mem_evict_first() on
1362 * behalf of ttm_bo_mem_force_space() which tries to evict buffer objects until
1363 * it can find space for a new object and by ttm_bo_force_list_clean() which is
1364 * used to clean out a memory space.
1365 */
1366static bool amdgpu_ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
1367					    const struct ttm_place *place)
1368{
1369	struct dma_resv_iter resv_cursor;
 
 
1370	struct dma_fence *f;
1371
1372	if (!amdgpu_bo_is_amdgpu_bo(bo))
1373		return ttm_bo_eviction_valuable(bo, place);
1374
1375	/* Swapout? */
1376	if (bo->resource->mem_type == TTM_PL_SYSTEM)
1377		return true;
1378
1379	if (bo->type == ttm_bo_type_kernel &&
1380	    !amdgpu_vm_evictable(ttm_to_amdgpu_bo(bo)))
1381		return false;
1382
1383	/* If bo is a KFD BO, check if the bo belongs to the current process.
1384	 * If true, then return false as any KFD process needs all its BOs to
1385	 * be resident to run successfully
1386	 */
1387	dma_resv_for_each_fence(&resv_cursor, bo->base.resv,
1388				DMA_RESV_USAGE_BOOKKEEP, f) {
1389		if (amdkfd_fence_check_mm(f, current->mm))
1390			return false;
 
 
 
 
1391	}
1392
1393	/* Preemptible BOs don't own system resources managed by the
1394	 * driver (pages, VRAM, GART space). They point to resources
1395	 * owned by someone else (e.g. pageable memory in user mode
1396	 * or a DMABuf). They are used in a preemptible context so we
1397	 * can guarantee no deadlocks and good QoS in case of MMU
1398	 * notifiers or DMABuf move notifiers from the resource owner.
1399	 */
1400	if (bo->resource->mem_type == AMDGPU_PL_PREEMPT)
1401		return false;
1402
1403	if (bo->resource->mem_type == TTM_PL_TT &&
1404	    amdgpu_bo_encrypted(ttm_to_amdgpu_bo(bo)))
1405		return false;
1406
1407	return ttm_bo_eviction_valuable(bo, place);
1408}
1409
1410static void amdgpu_ttm_vram_mm_access(struct amdgpu_device *adev, loff_t pos,
1411				      void *buf, size_t size, bool write)
1412{
1413	while (size) {
1414		uint64_t aligned_pos = ALIGN_DOWN(pos, 4);
1415		uint64_t bytes = 4 - (pos & 0x3);
1416		uint32_t shift = (pos & 0x3) * 8;
1417		uint32_t mask = 0xffffffff << shift;
1418		uint32_t value = 0;
1419
1420		if (size < bytes) {
1421			mask &= 0xffffffff >> (bytes - size) * 8;
1422			bytes = size;
1423		}
 
1424
1425		if (mask != 0xffffffff) {
1426			amdgpu_device_mm_access(adev, aligned_pos, &value, 4, false);
1427			if (write) {
1428				value &= ~mask;
1429				value |= (*(uint32_t *)buf << shift) & mask;
1430				amdgpu_device_mm_access(adev, aligned_pos, &value, 4, true);
1431			} else {
1432				value = (value & mask) >> shift;
1433				memcpy(buf, &value, bytes);
1434			}
1435		} else {
1436			amdgpu_device_mm_access(adev, aligned_pos, buf, 4, write);
1437		}
1438
1439		pos += bytes;
1440		buf += bytes;
1441		size -= bytes;
1442	}
1443}
1444
1445static int amdgpu_ttm_access_memory_sdma(struct ttm_buffer_object *bo,
1446					unsigned long offset, void *buf,
1447					int len, int write)
1448{
1449	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1450	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1451	struct amdgpu_res_cursor src_mm;
1452	struct amdgpu_job *job;
1453	struct dma_fence *fence;
1454	uint64_t src_addr, dst_addr;
1455	unsigned int num_dw;
1456	int r, idx;
1457
1458	if (len != PAGE_SIZE)
1459		return -EINVAL;
1460
1461	if (!adev->mman.sdma_access_ptr)
1462		return -EACCES;
1463
1464	if (!drm_dev_enter(adev_to_drm(adev), &idx))
1465		return -ENODEV;
1466
1467	if (write)
1468		memcpy(adev->mman.sdma_access_ptr, buf, len);
1469
1470	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
1471	r = amdgpu_job_alloc_with_ib(adev, &adev->mman.high_pr,
1472				     AMDGPU_FENCE_OWNER_UNDEFINED,
1473				     num_dw * 4, AMDGPU_IB_POOL_DELAYED,
1474				     &job);
1475	if (r)
1476		goto out;
1477
1478	amdgpu_res_first(abo->tbo.resource, offset, len, &src_mm);
1479	src_addr = amdgpu_ttm_domain_start(adev, bo->resource->mem_type) +
1480		src_mm.start;
1481	dst_addr = amdgpu_bo_gpu_offset(adev->mman.sdma_access_bo);
1482	if (write)
1483		swap(src_addr, dst_addr);
1484
1485	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr, dst_addr,
1486				PAGE_SIZE, false);
1487
1488	amdgpu_ring_pad_ib(adev->mman.buffer_funcs_ring, &job->ibs[0]);
1489	WARN_ON(job->ibs[0].length_dw > num_dw);
1490
1491	fence = amdgpu_job_submit(job);
1492
1493	if (!dma_fence_wait_timeout(fence, false, adev->sdma_timeout))
1494		r = -ETIMEDOUT;
1495	dma_fence_put(fence);
1496
1497	if (!(r || write))
1498		memcpy(buf, adev->mman.sdma_access_ptr, len);
1499out:
1500	drm_dev_exit(idx);
1501	return r;
1502}
1503
1504/**
1505 * amdgpu_ttm_access_memory - Read or Write memory that backs a buffer object.
1506 *
1507 * @bo:  The buffer object to read/write
1508 * @offset:  Offset into buffer object
1509 * @buf:  Secondary buffer to write/read from
1510 * @len: Length in bytes of access
1511 * @write:  true if writing
1512 *
1513 * This is used to access VRAM that backs a buffer object via MMIO
1514 * access for debugging purposes.
1515 */
1516static int amdgpu_ttm_access_memory(struct ttm_buffer_object *bo,
1517				    unsigned long offset, void *buf, int len,
1518				    int write)
1519{
1520	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1521	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1522	struct amdgpu_res_cursor cursor;
 
1523	int ret = 0;
 
 
1524
1525	if (bo->resource->mem_type != TTM_PL_VRAM)
1526		return -EIO;
1527
1528	if (amdgpu_device_has_timeouts_enabled(adev) &&
1529			!amdgpu_ttm_access_memory_sdma(bo, offset, buf, len, write))
1530		return len;
1531
1532	amdgpu_res_first(bo->resource, offset, len, &cursor);
1533	while (cursor.remaining) {
1534		size_t count, size = cursor.size;
1535		loff_t pos = cursor.start;
1536
1537		count = amdgpu_device_aper_access(adev, pos, buf, size, write);
1538		size -= count;
1539		if (size) {
1540			/* using MM to access rest vram and handle un-aligned address */
1541			pos += count;
1542			buf += count;
1543			amdgpu_ttm_vram_mm_access(adev, pos, buf, size, write);
1544		}
1545
1546		ret += cursor.size;
1547		buf += cursor.size;
1548		amdgpu_res_next(&cursor, cursor.size);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1549	}
1550
1551	return ret;
1552}
1553
1554static void
1555amdgpu_bo_delete_mem_notify(struct ttm_buffer_object *bo)
1556{
1557	amdgpu_bo_move_notify(bo, false);
1558}
1559
1560static struct ttm_device_funcs amdgpu_bo_driver = {
1561	.ttm_tt_create = &amdgpu_ttm_tt_create,
1562	.ttm_tt_populate = &amdgpu_ttm_tt_populate,
1563	.ttm_tt_unpopulate = &amdgpu_ttm_tt_unpopulate,
1564	.ttm_tt_destroy = &amdgpu_ttm_backend_destroy,
1565	.eviction_valuable = amdgpu_ttm_bo_eviction_valuable,
1566	.evict_flags = &amdgpu_evict_flags,
1567	.move = &amdgpu_bo_move,
1568	.delete_mem_notify = &amdgpu_bo_delete_mem_notify,
 
1569	.release_notify = &amdgpu_bo_release_notify,
 
1570	.io_mem_reserve = &amdgpu_ttm_io_mem_reserve,
1571	.io_mem_pfn = amdgpu_ttm_io_mem_pfn,
1572	.access_memory = &amdgpu_ttm_access_memory,
 
1573};
1574
1575/*
1576 * Firmware Reservation functions
1577 */
1578/**
1579 * amdgpu_ttm_fw_reserve_vram_fini - free fw reserved vram
1580 *
1581 * @adev: amdgpu_device pointer
1582 *
1583 * free fw reserved vram if it has been reserved.
1584 */
1585static void amdgpu_ttm_fw_reserve_vram_fini(struct amdgpu_device *adev)
1586{
1587	amdgpu_bo_free_kernel(&adev->mman.fw_vram_usage_reserved_bo,
1588		NULL, &adev->mman.fw_vram_usage_va);
1589}
1590
1591/*
1592 * Driver Reservation functions
1593 */
1594/**
1595 * amdgpu_ttm_drv_reserve_vram_fini - free drv reserved vram
1596 *
1597 * @adev: amdgpu_device pointer
1598 *
1599 * free drv reserved vram if it has been reserved.
1600 */
1601static void amdgpu_ttm_drv_reserve_vram_fini(struct amdgpu_device *adev)
1602{
1603	amdgpu_bo_free_kernel(&adev->mman.drv_vram_usage_reserved_bo,
1604						  NULL,
1605						  &adev->mman.drv_vram_usage_va);
1606}
1607
1608/**
1609 * amdgpu_ttm_fw_reserve_vram_init - create bo vram reservation from fw
1610 *
1611 * @adev: amdgpu_device pointer
1612 *
1613 * create bo vram reservation from fw.
1614 */
1615static int amdgpu_ttm_fw_reserve_vram_init(struct amdgpu_device *adev)
1616{
1617	uint64_t vram_size = adev->gmc.visible_vram_size;
1618
1619	adev->mman.fw_vram_usage_va = NULL;
1620	adev->mman.fw_vram_usage_reserved_bo = NULL;
1621
1622	if (adev->mman.fw_vram_usage_size == 0 ||
1623	    adev->mman.fw_vram_usage_size > vram_size)
1624		return 0;
1625
1626	return amdgpu_bo_create_kernel_at(adev,
1627					  adev->mman.fw_vram_usage_start_offset,
1628					  adev->mman.fw_vram_usage_size,
1629					  &adev->mman.fw_vram_usage_reserved_bo,
1630					  &adev->mman.fw_vram_usage_va);
1631}
1632
1633/**
1634 * amdgpu_ttm_drv_reserve_vram_init - create bo vram reservation from driver
1635 *
1636 * @adev: amdgpu_device pointer
1637 *
1638 * create bo vram reservation from drv.
1639 */
1640static int amdgpu_ttm_drv_reserve_vram_init(struct amdgpu_device *adev)
1641{
1642	u64 vram_size = adev->gmc.visible_vram_size;
1643
1644	adev->mman.drv_vram_usage_va = NULL;
1645	adev->mman.drv_vram_usage_reserved_bo = NULL;
1646
1647	if (adev->mman.drv_vram_usage_size == 0 ||
1648	    adev->mman.drv_vram_usage_size > vram_size)
1649		return 0;
1650
1651	return amdgpu_bo_create_kernel_at(adev,
1652					  adev->mman.drv_vram_usage_start_offset,
1653					  adev->mman.drv_vram_usage_size,
1654					  &adev->mman.drv_vram_usage_reserved_bo,
1655					  &adev->mman.drv_vram_usage_va);
1656}
1657
1658/*
1659 * Memoy training reservation functions
1660 */
1661
1662/**
1663 * amdgpu_ttm_training_reserve_vram_fini - free memory training reserved vram
1664 *
1665 * @adev: amdgpu_device pointer
1666 *
1667 * free memory training reserved vram if it has been reserved.
1668 */
1669static int amdgpu_ttm_training_reserve_vram_fini(struct amdgpu_device *adev)
1670{
1671	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1672
1673	ctx->init = PSP_MEM_TRAIN_NOT_SUPPORT;
1674	amdgpu_bo_free_kernel(&ctx->c2p_bo, NULL, NULL);
1675	ctx->c2p_bo = NULL;
1676
1677	return 0;
1678}
1679
1680static void amdgpu_ttm_training_data_block_init(struct amdgpu_device *adev,
1681						uint32_t reserve_size)
1682{
1683	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1684
1685	memset(ctx, 0, sizeof(*ctx));
1686
1687	ctx->c2p_train_data_offset =
1688		ALIGN((adev->gmc.mc_vram_size - reserve_size - SZ_1M), SZ_1M);
1689	ctx->p2c_train_data_offset =
1690		(adev->gmc.mc_vram_size - GDDR6_MEM_TRAINING_OFFSET);
1691	ctx->train_data_size =
1692		GDDR6_MEM_TRAINING_DATA_SIZE_IN_BYTES;
1693
1694	DRM_DEBUG("train_data_size:%llx,p2c_train_data_offset:%llx,c2p_train_data_offset:%llx.\n",
1695			ctx->train_data_size,
1696			ctx->p2c_train_data_offset,
1697			ctx->c2p_train_data_offset);
1698}
1699
1700/*
1701 * reserve TMR memory at the top of VRAM which holds
1702 * IP Discovery data and is protected by PSP.
1703 */
1704static int amdgpu_ttm_reserve_tmr(struct amdgpu_device *adev)
1705{
 
1706	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1707	bool mem_train_support = false;
1708	uint32_t reserve_size = 0;
1709	int ret;
1710
1711	if (adev->bios && !amdgpu_sriov_vf(adev)) {
1712		if (amdgpu_atomfirmware_mem_training_supported(adev))
 
1713			mem_train_support = true;
 
 
1714		else
1715			DRM_DEBUG("memory training does not support!\n");
1716	}
1717
1718	/*
1719	 * Query reserved tmr size through atom firmwareinfo for Sienna_Cichlid and onwards for all
1720	 * the use cases (IP discovery/G6 memory training/profiling/diagnostic data.etc)
1721	 *
1722	 * Otherwise, fallback to legacy approach to check and reserve tmr block for ip
1723	 * discovery data and G6 memory training data respectively
1724	 */
1725	if (adev->bios)
1726		reserve_size =
1727			amdgpu_atomfirmware_get_fw_reserved_fb_size(adev);
1728
1729	if (!adev->bios &&
1730	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3))
1731		reserve_size = max(reserve_size, (uint32_t)280 << 20);
1732	else if (!reserve_size)
1733		reserve_size = DISCOVERY_TMR_OFFSET;
1734
1735	if (mem_train_support) {
1736		/* reserve vram for mem train according to TMR location */
1737		amdgpu_ttm_training_data_block_init(adev, reserve_size);
1738		ret = amdgpu_bo_create_kernel_at(adev,
1739						 ctx->c2p_train_data_offset,
1740						 ctx->train_data_size,
1741						 &ctx->c2p_bo,
1742						 NULL);
 
1743		if (ret) {
1744			DRM_ERROR("alloc c2p_bo failed(%d)!\n", ret);
1745			amdgpu_ttm_training_reserve_vram_fini(adev);
1746			return ret;
1747		}
1748		ctx->init = PSP_MEM_TRAIN_RESERVE_SUCCESS;
1749	}
1750
1751	if (!adev->gmc.is_app_apu) {
1752		ret = amdgpu_bo_create_kernel_at(
1753			adev, adev->gmc.real_vram_size - reserve_size,
1754			reserve_size, &adev->mman.fw_reserved_memory, NULL);
1755		if (ret) {
1756			DRM_ERROR("alloc tmr failed(%d)!\n", ret);
1757			amdgpu_bo_free_kernel(&adev->mman.fw_reserved_memory,
1758					      NULL, NULL);
1759			return ret;
1760		}
1761	} else {
1762		DRM_DEBUG_DRIVER("backdoor fw loading path for PSP TMR, no reservation needed\n");
1763	}
1764
1765	return 0;
1766}
1767
1768static int amdgpu_ttm_pools_init(struct amdgpu_device *adev)
1769{
1770	int i;
1771
1772	if (!adev->gmc.is_app_apu || !adev->gmc.num_mem_partitions)
1773		return 0;
1774
1775	adev->mman.ttm_pools = kcalloc(adev->gmc.num_mem_partitions,
1776				       sizeof(*adev->mman.ttm_pools),
1777				       GFP_KERNEL);
1778	if (!adev->mman.ttm_pools)
1779		return -ENOMEM;
1780
1781	for (i = 0; i < adev->gmc.num_mem_partitions; i++) {
1782		ttm_pool_init(&adev->mman.ttm_pools[i], adev->dev,
1783			      adev->gmc.mem_partitions[i].numa.node,
1784			      false, false);
1785	}
1786	return 0;
1787}
1788
1789static void amdgpu_ttm_pools_fini(struct amdgpu_device *adev)
1790{
1791	int i;
1792
1793	if (!adev->gmc.is_app_apu || !adev->mman.ttm_pools)
1794		return;
1795
1796	for (i = 0; i < adev->gmc.num_mem_partitions; i++)
1797		ttm_pool_fini(&adev->mman.ttm_pools[i]);
1798
1799	kfree(adev->mman.ttm_pools);
1800	adev->mman.ttm_pools = NULL;
1801}
1802
1803/*
1804 * amdgpu_ttm_init - Init the memory management (ttm) as well as various
1805 * gtt/vram related fields.
1806 *
1807 * This initializes all of the memory space pools that the TTM layer
1808 * will need such as the GTT space (system memory mapped to the device),
1809 * VRAM (on-board memory), and on-chip memories (GDS, GWS, OA) which
1810 * can be mapped per VMID.
1811 */
1812int amdgpu_ttm_init(struct amdgpu_device *adev)
1813{
1814	uint64_t gtt_size;
1815	int r;
 
 
1816
1817	mutex_init(&adev->mman.gtt_window_lock);
1818
1819	/* No others user of address space so set it to 0 */
1820	r = ttm_device_init(&adev->mman.bdev, &amdgpu_bo_driver, adev->dev,
1821			       adev_to_drm(adev)->anon_inode->i_mapping,
1822			       adev_to_drm(adev)->vma_offset_manager,
1823			       adev->need_swiotlb,
1824			       dma_addressing_limited(adev->dev));
1825	if (r) {
1826		DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
1827		return r;
1828	}
 
1829
1830	r = amdgpu_ttm_pools_init(adev);
1831	if (r) {
1832		DRM_ERROR("failed to init ttm pools(%d).\n", r);
1833		return r;
1834	}
1835	adev->mman.initialized = true;
1836
1837	/* Initialize VRAM pool with all of VRAM divided into pages */
1838	r = amdgpu_vram_mgr_init(adev);
 
1839	if (r) {
1840		DRM_ERROR("Failed initializing VRAM heap.\n");
1841		return r;
1842	}
1843
 
 
 
 
 
 
1844	/* Change the size here instead of the init above so only lpfn is affected */
1845	amdgpu_ttm_set_buffer_funcs_status(adev, false);
1846#ifdef CONFIG_64BIT
1847#ifdef CONFIG_X86
1848	if (adev->gmc.xgmi.connected_to_cpu)
1849		adev->mman.aper_base_kaddr = ioremap_cache(adev->gmc.aper_base,
1850				adev->gmc.visible_vram_size);
1851
1852	else if (adev->gmc.is_app_apu)
1853		DRM_DEBUG_DRIVER(
1854			"No need to ioremap when real vram size is 0\n");
1855	else
1856#endif
1857		adev->mman.aper_base_kaddr = ioremap_wc(adev->gmc.aper_base,
1858				adev->gmc.visible_vram_size);
1859#endif
1860
1861	/*
1862	 *The reserved vram for firmware must be pinned to the specified
1863	 *place on the VRAM, so reserve it early.
1864	 */
1865	r = amdgpu_ttm_fw_reserve_vram_init(adev);
1866	if (r)
1867		return r;
1868
1869	/*
1870	 *The reserved vram for driver must be pinned to the specified
1871	 *place on the VRAM, so reserve it early.
1872	 */
1873	r = amdgpu_ttm_drv_reserve_vram_init(adev);
1874	if (r)
1875		return r;
 
1876
1877	/*
1878	 * only NAVI10 and onwards ASIC support for IP discovery.
1879	 * If IP discovery enabled, a block of memory should be
1880	 * reserved for IP discovey.
1881	 */
1882	if (adev->mman.discovery_bin) {
1883		r = amdgpu_ttm_reserve_tmr(adev);
1884		if (r)
1885			return r;
1886	}
1887
1888	/* allocate memory as required for VGA
1889	 * This is used for VGA emulation and pre-OS scanout buffers to
1890	 * avoid display artifacts while transitioning between pre-OS
1891	 * and driver.
1892	 */
1893	if (!adev->gmc.is_app_apu) {
1894		r = amdgpu_bo_create_kernel_at(adev, 0,
1895					       adev->mman.stolen_vga_size,
1896					       &adev->mman.stolen_vga_memory,
1897					       NULL);
1898		if (r)
1899			return r;
1900
1901		r = amdgpu_bo_create_kernel_at(adev, adev->mman.stolen_vga_size,
1902					       adev->mman.stolen_extended_size,
1903					       &adev->mman.stolen_extended_memory,
1904					       NULL);
1905
1906		if (r)
1907			return r;
1908
1909		r = amdgpu_bo_create_kernel_at(adev,
1910					       adev->mman.stolen_reserved_offset,
1911					       adev->mman.stolen_reserved_size,
1912					       &adev->mman.stolen_reserved_memory,
1913					       NULL);
1914		if (r)
1915			return r;
1916	} else {
1917		DRM_DEBUG_DRIVER("Skipped stolen memory reservation\n");
1918	}
1919
1920	DRM_INFO("amdgpu: %uM of VRAM memory ready\n",
1921		 (unsigned int)(adev->gmc.real_vram_size / (1024 * 1024)));
1922
1923	/* Compute GTT size, either based on TTM limit
1924	 * or whatever the user passed on module init.
1925	 */
1926	if (amdgpu_gtt_size == -1)
1927		gtt_size = ttm_tt_pages_limit() << PAGE_SHIFT;
1928	else
1929		gtt_size = (uint64_t)amdgpu_gtt_size << 20;
1930
1931	/* Initialize GTT memory pool */
1932	r = amdgpu_gtt_mgr_init(adev, gtt_size);
1933	if (r) {
1934		DRM_ERROR("Failed initializing GTT heap.\n");
1935		return r;
1936	}
1937	DRM_INFO("amdgpu: %uM of GTT memory ready.\n",
1938		 (unsigned int)(gtt_size / (1024 * 1024)));
1939
1940	/* Initiailize doorbell pool on PCI BAR */
1941	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_DOORBELL, adev->doorbell.size / PAGE_SIZE);
1942	if (r) {
1943		DRM_ERROR("Failed initializing doorbell heap.\n");
1944		return r;
1945	}
1946
1947	/* Create a boorbell page for kernel usages */
1948	r = amdgpu_doorbell_create_kernel_doorbells(adev);
1949	if (r) {
1950		DRM_ERROR("Failed to initialize kernel doorbells.\n");
1951		return r;
1952	}
1953
1954	/* Initialize preemptible memory pool */
1955	r = amdgpu_preempt_mgr_init(adev);
1956	if (r) {
1957		DRM_ERROR("Failed initializing PREEMPT heap.\n");
1958		return r;
1959	}
1960
1961	/* Initialize various on-chip memory pools */
1962	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GDS, adev->gds.gds_size);
 
1963	if (r) {
1964		DRM_ERROR("Failed initializing GDS heap.\n");
1965		return r;
1966	}
1967
1968	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GWS, adev->gds.gws_size);
 
1969	if (r) {
1970		DRM_ERROR("Failed initializing gws heap.\n");
1971		return r;
1972	}
1973
1974	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_OA, adev->gds.oa_size);
 
1975	if (r) {
1976		DRM_ERROR("Failed initializing oa heap.\n");
1977		return r;
1978	}
1979	if (amdgpu_bo_create_kernel(adev, PAGE_SIZE, PAGE_SIZE,
1980				AMDGPU_GEM_DOMAIN_GTT,
1981				&adev->mman.sdma_access_bo, NULL,
1982				&adev->mman.sdma_access_ptr))
1983		DRM_WARN("Debug VRAM access will use slowpath MM access\n");
1984
1985	return 0;
1986}
1987
1988/*
 
 
 
 
 
 
 
 
 
 
1989 * amdgpu_ttm_fini - De-initialize the TTM memory pools
1990 */
1991void amdgpu_ttm_fini(struct amdgpu_device *adev)
1992{
1993	int idx;
1994
1995	if (!adev->mman.initialized)
1996		return;
1997
1998	amdgpu_ttm_pools_fini(adev);
1999
2000	amdgpu_ttm_training_reserve_vram_fini(adev);
2001	/* return the stolen vga memory back to VRAM */
2002	if (!adev->gmc.is_app_apu) {
2003		amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
2004		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
2005		/* return the FW reserved memory back to VRAM */
2006		amdgpu_bo_free_kernel(&adev->mman.fw_reserved_memory, NULL,
2007				      NULL);
2008		if (adev->mman.stolen_reserved_size)
2009			amdgpu_bo_free_kernel(&adev->mman.stolen_reserved_memory,
2010					      NULL, NULL);
2011	}
2012	amdgpu_bo_free_kernel(&adev->mman.sdma_access_bo, NULL,
2013					&adev->mman.sdma_access_ptr);
2014	amdgpu_ttm_fw_reserve_vram_fini(adev);
2015	amdgpu_ttm_drv_reserve_vram_fini(adev);
2016
2017	if (drm_dev_enter(adev_to_drm(adev), &idx)) {
2018
2019		if (adev->mman.aper_base_kaddr)
2020			iounmap(adev->mman.aper_base_kaddr);
2021		adev->mman.aper_base_kaddr = NULL;
2022
2023		drm_dev_exit(idx);
2024	}
2025
2026	amdgpu_vram_mgr_fini(adev);
2027	amdgpu_gtt_mgr_fini(adev);
2028	amdgpu_preempt_mgr_fini(adev);
2029	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GDS);
2030	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GWS);
2031	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_OA);
2032	ttm_device_fini(&adev->mman.bdev);
2033	adev->mman.initialized = false;
2034	DRM_INFO("amdgpu: ttm finalized\n");
2035}
2036
2037/**
2038 * amdgpu_ttm_set_buffer_funcs_status - enable/disable use of buffer functions
2039 *
2040 * @adev: amdgpu_device pointer
2041 * @enable: true when we can use buffer functions.
2042 *
2043 * Enable/disable use of buffer functions during suspend/resume. This should
2044 * only be called at bootup or when userspace isn't running.
2045 */
2046void amdgpu_ttm_set_buffer_funcs_status(struct amdgpu_device *adev, bool enable)
2047{
2048	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM);
2049	uint64_t size;
2050	int r;
2051
2052	if (!adev->mman.initialized || amdgpu_in_reset(adev) ||
2053	    adev->mman.buffer_funcs_enabled == enable || adev->gmc.is_app_apu)
2054		return;
2055
2056	if (enable) {
2057		struct amdgpu_ring *ring;
2058		struct drm_gpu_scheduler *sched;
2059
2060		ring = adev->mman.buffer_funcs_ring;
2061		sched = &ring->sched;
2062		r = drm_sched_entity_init(&adev->mman.high_pr,
2063					  DRM_SCHED_PRIORITY_KERNEL, &sched,
2064					  1, NULL);
2065		if (r) {
2066			DRM_ERROR("Failed setting up TTM BO move entity (%d)\n",
2067				  r);
2068			return;
2069		}
2070
2071		r = drm_sched_entity_init(&adev->mman.low_pr,
2072					  DRM_SCHED_PRIORITY_NORMAL, &sched,
2073					  1, NULL);
2074		if (r) {
2075			DRM_ERROR("Failed setting up TTM BO move entity (%d)\n",
2076				  r);
2077			goto error_free_entity;
2078		}
2079	} else {
2080		drm_sched_entity_destroy(&adev->mman.high_pr);
2081		drm_sched_entity_destroy(&adev->mman.low_pr);
2082		dma_fence_put(man->move);
2083		man->move = NULL;
2084	}
2085
2086	/* this just adjusts TTM size idea, which sets lpfn to the correct value */
2087	if (enable)
2088		size = adev->gmc.real_vram_size;
2089	else
2090		size = adev->gmc.visible_vram_size;
2091	man->size = size;
2092	adev->mman.buffer_funcs_enabled = enable;
2093
2094	return;
2095
2096error_free_entity:
2097	drm_sched_entity_destroy(&adev->mman.high_pr);
2098}
2099
2100static int amdgpu_ttm_prepare_job(struct amdgpu_device *adev,
2101				  bool direct_submit,
2102				  unsigned int num_dw,
2103				  struct dma_resv *resv,
2104				  bool vm_needs_flush,
2105				  struct amdgpu_job **job,
2106				  bool delayed)
2107{
2108	enum amdgpu_ib_pool_type pool = direct_submit ?
2109		AMDGPU_IB_POOL_DIRECT :
2110		AMDGPU_IB_POOL_DELAYED;
2111	int r;
2112	struct drm_sched_entity *entity = delayed ? &adev->mman.low_pr :
2113						    &adev->mman.high_pr;
2114	r = amdgpu_job_alloc_with_ib(adev, entity,
2115				     AMDGPU_FENCE_OWNER_UNDEFINED,
2116				     num_dw * 4, pool, job);
2117	if (r)
2118		return r;
2119
2120	if (vm_needs_flush) {
2121		(*job)->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gmc.pdb0_bo ?
2122							adev->gmc.pdb0_bo :
2123							adev->gart.bo);
2124		(*job)->vm_needs_flush = true;
2125	}
2126	if (!resv)
2127		return 0;
2128
2129	return drm_sched_job_add_resv_dependencies(&(*job)->base, resv,
2130						   DMA_RESV_USAGE_BOOKKEEP);
2131}
2132
2133int amdgpu_copy_buffer(struct amdgpu_ring *ring, uint64_t src_offset,
2134		       uint64_t dst_offset, uint32_t byte_count,
2135		       struct dma_resv *resv,
2136		       struct dma_fence **fence, bool direct_submit,
2137		       bool vm_needs_flush, bool tmz)
2138{
 
 
2139	struct amdgpu_device *adev = ring->adev;
2140	unsigned int num_loops, num_dw;
2141	struct amdgpu_job *job;
 
2142	uint32_t max_bytes;
2143	unsigned int i;
 
2144	int r;
2145
2146	if (!direct_submit && !ring->sched.ready) {
2147		DRM_ERROR("Trying to move memory with ring turned off.\n");
2148		return -EINVAL;
2149	}
2150
2151	max_bytes = adev->mman.buffer_funcs->copy_max_bytes;
2152	num_loops = DIV_ROUND_UP(byte_count, max_bytes);
2153	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->copy_num_dw, 8);
2154	r = amdgpu_ttm_prepare_job(adev, direct_submit, num_dw,
2155				   resv, vm_needs_flush, &job, false);
2156	if (r)
2157		return r;
2158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2159	for (i = 0; i < num_loops; i++) {
2160		uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
2161
2162		amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
2163					dst_offset, cur_size_in_bytes, tmz);
2164
2165		src_offset += cur_size_in_bytes;
2166		dst_offset += cur_size_in_bytes;
2167		byte_count -= cur_size_in_bytes;
2168	}
2169
2170	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2171	WARN_ON(job->ibs[0].length_dw > num_dw);
2172	if (direct_submit)
2173		r = amdgpu_job_submit_direct(job, ring, fence);
2174	else
2175		*fence = amdgpu_job_submit(job);
 
2176	if (r)
2177		goto error_free;
2178
2179	return r;
2180
2181error_free:
2182	amdgpu_job_free(job);
2183	DRM_ERROR("Error scheduling IBs (%d)\n", r);
2184	return r;
2185}
2186
2187static int amdgpu_ttm_fill_mem(struct amdgpu_ring *ring, uint32_t src_data,
2188			       uint64_t dst_addr, uint32_t byte_count,
2189			       struct dma_resv *resv,
2190			       struct dma_fence **fence,
2191			       bool vm_needs_flush, bool delayed)
2192{
2193	struct amdgpu_device *adev = ring->adev;
 
 
 
 
 
2194	unsigned int num_loops, num_dw;
 
2195	struct amdgpu_job *job;
2196	uint32_t max_bytes;
2197	unsigned int i;
2198	int r;
2199
2200	max_bytes = adev->mman.buffer_funcs->fill_max_bytes;
2201	num_loops = DIV_ROUND_UP_ULL(byte_count, max_bytes);
2202	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->fill_num_dw, 8);
2203	r = amdgpu_ttm_prepare_job(adev, false, num_dw, resv, vm_needs_flush,
2204				   &job, delayed);
2205	if (r)
2206		return r;
2207
2208	for (i = 0; i < num_loops; i++) {
2209		uint32_t cur_size = min(byte_count, max_bytes);
2210
2211		amdgpu_emit_fill_buffer(adev, &job->ibs[0], src_data, dst_addr,
2212					cur_size);
2213
2214		dst_addr += cur_size;
2215		byte_count -= cur_size;
 
 
 
 
 
 
 
2216	}
 
2217
2218	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2219	WARN_ON(job->ibs[0].length_dw > num_dw);
2220	*fence = amdgpu_job_submit(job);
2221	return 0;
2222}
2223
2224int amdgpu_fill_buffer(struct amdgpu_bo *bo,
2225			uint32_t src_data,
2226			struct dma_resv *resv,
2227			struct dma_fence **f,
2228			bool delayed)
2229{
2230	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
2231	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
2232	struct dma_fence *fence = NULL;
2233	struct amdgpu_res_cursor dst;
2234	int r;
2235
2236	if (!adev->mman.buffer_funcs_enabled) {
2237		DRM_ERROR("Trying to clear memory with ring turned off.\n");
2238		return -EINVAL;
 
 
 
 
 
2239	}
2240
2241	amdgpu_res_first(bo->tbo.resource, 0, amdgpu_bo_size(bo), &dst);
 
2242
2243	mutex_lock(&adev->mman.gtt_window_lock);
2244	while (dst.remaining) {
2245		struct dma_fence *next;
2246		uint64_t cur_size, to;
 
 
 
 
2247
2248		/* Never fill more than 256MiB at once to avoid timeouts */
2249		cur_size = min(dst.size, 256ULL << 20);
2250
2251		r = amdgpu_ttm_map_buffer(&bo->tbo, bo->tbo.resource, &dst,
2252					  1, ring, false, &cur_size, &to);
2253		if (r)
2254			goto error;
2255
2256		r = amdgpu_ttm_fill_mem(ring, src_data, to, cur_size, resv,
2257					&next, true, delayed);
2258		if (r)
2259			goto error;
2260
2261		dma_fence_put(fence);
2262		fence = next;
2263
2264		amdgpu_res_next(&dst, cur_size);
2265	}
2266error:
2267	mutex_unlock(&adev->mman.gtt_window_lock);
2268	if (f)
2269		*f = dma_fence_get(fence);
2270	dma_fence_put(fence);
2271	return r;
2272}
2273
2274/**
2275 * amdgpu_ttm_evict_resources - evict memory buffers
2276 * @adev: amdgpu device object
2277 * @mem_type: evicted BO's memory type
2278 *
2279 * Evicts all @mem_type buffers on the lru list of the memory type.
2280 *
2281 * Returns:
2282 * 0 for success or a negative error code on failure.
2283 */
2284int amdgpu_ttm_evict_resources(struct amdgpu_device *adev, int mem_type)
2285{
2286	struct ttm_resource_manager *man;
2287
2288	switch (mem_type) {
2289	case TTM_PL_VRAM:
2290	case TTM_PL_TT:
2291	case AMDGPU_PL_GWS:
2292	case AMDGPU_PL_GDS:
2293	case AMDGPU_PL_OA:
2294		man = ttm_manager_type(&adev->mman.bdev, mem_type);
2295		break;
2296	default:
2297		DRM_ERROR("Trying to evict invalid memory type\n");
2298		return -EINVAL;
2299	}
2300
2301	return ttm_resource_manager_evict_all(&adev->mman.bdev, man);
 
 
2302}
2303
2304#if defined(CONFIG_DEBUG_FS)
2305
2306static int amdgpu_ttm_page_pool_show(struct seq_file *m, void *unused)
2307{
2308	struct amdgpu_device *adev = m->private;
 
 
 
 
 
2309
2310	return ttm_pool_debugfs(&adev->mman.bdev.pool, m);
 
2311}
2312
2313DEFINE_SHOW_ATTRIBUTE(amdgpu_ttm_page_pool);
 
 
 
 
 
 
 
 
 
 
2314
2315/*
2316 * amdgpu_ttm_vram_read - Linear read access to VRAM
2317 *
2318 * Accesses VRAM via MMIO for debugging purposes.
2319 */
2320static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
2321				    size_t size, loff_t *pos)
2322{
2323	struct amdgpu_device *adev = file_inode(f)->i_private;
2324	ssize_t result = 0;
2325
2326	if (size & 0x3 || *pos & 0x3)
2327		return -EINVAL;
2328
2329	if (*pos >= adev->gmc.mc_vram_size)
2330		return -ENXIO;
2331
2332	size = min(size, (size_t)(adev->gmc.mc_vram_size - *pos));
2333	while (size) {
2334		size_t bytes = min(size, AMDGPU_TTM_VRAM_MAX_DW_READ * 4);
2335		uint32_t value[AMDGPU_TTM_VRAM_MAX_DW_READ];
2336
2337		amdgpu_device_vram_access(adev, *pos, value, bytes, false);
2338		if (copy_to_user(buf, value, bytes))
2339			return -EFAULT;
2340
2341		result += bytes;
2342		buf += bytes;
2343		*pos += bytes;
2344		size -= bytes;
2345	}
2346
2347	return result;
2348}
2349
2350/*
2351 * amdgpu_ttm_vram_write - Linear write access to VRAM
2352 *
2353 * Accesses VRAM via MMIO for debugging purposes.
2354 */
2355static ssize_t amdgpu_ttm_vram_write(struct file *f, const char __user *buf,
2356				    size_t size, loff_t *pos)
2357{
2358	struct amdgpu_device *adev = file_inode(f)->i_private;
2359	ssize_t result = 0;
2360	int r;
2361
2362	if (size & 0x3 || *pos & 0x3)
2363		return -EINVAL;
2364
2365	if (*pos >= adev->gmc.mc_vram_size)
2366		return -ENXIO;
2367
2368	while (size) {
 
2369		uint32_t value;
2370
2371		if (*pos >= adev->gmc.mc_vram_size)
2372			return result;
2373
2374		r = get_user(value, (uint32_t *)buf);
2375		if (r)
2376			return r;
2377
2378		amdgpu_device_mm_access(adev, *pos, &value, 4, true);
 
 
 
 
2379
2380		result += 4;
2381		buf += 4;
2382		*pos += 4;
2383		size -= 4;
2384	}
2385
2386	return result;
2387}
2388
2389static const struct file_operations amdgpu_ttm_vram_fops = {
2390	.owner = THIS_MODULE,
2391	.read = amdgpu_ttm_vram_read,
2392	.write = amdgpu_ttm_vram_write,
2393	.llseek = default_llseek,
2394};
2395
2396/*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2397 * amdgpu_iomem_read - Virtual read access to GPU mapped memory
2398 *
2399 * This function is used to read memory that has been mapped to the
2400 * GPU and the known addresses are not physical addresses but instead
2401 * bus addresses (e.g., what you'd put in an IB or ring buffer).
2402 */
2403static ssize_t amdgpu_iomem_read(struct file *f, char __user *buf,
2404				 size_t size, loff_t *pos)
2405{
2406	struct amdgpu_device *adev = file_inode(f)->i_private;
2407	struct iommu_domain *dom;
2408	ssize_t result = 0;
2409	int r;
2410
2411	/* retrieve the IOMMU domain if any for this device */
2412	dom = iommu_get_domain_for_dev(adev->dev);
2413
2414	while (size) {
2415		phys_addr_t addr = *pos & PAGE_MASK;
2416		loff_t off = *pos & ~PAGE_MASK;
2417		size_t bytes = PAGE_SIZE - off;
2418		unsigned long pfn;
2419		struct page *p;
2420		void *ptr;
2421
2422		bytes = min(bytes, size);
2423
2424		/* Translate the bus address to a physical address.  If
2425		 * the domain is NULL it means there is no IOMMU active
2426		 * and the address translation is the identity
2427		 */
2428		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2429
2430		pfn = addr >> PAGE_SHIFT;
2431		if (!pfn_valid(pfn))
2432			return -EPERM;
2433
2434		p = pfn_to_page(pfn);
2435		if (p->mapping != adev->mman.bdev.dev_mapping)
2436			return -EPERM;
2437
2438		ptr = kmap_local_page(p);
2439		r = copy_to_user(buf, ptr + off, bytes);
2440		kunmap_local(ptr);
2441		if (r)
2442			return -EFAULT;
2443
2444		size -= bytes;
2445		*pos += bytes;
2446		result += bytes;
2447	}
2448
2449	return result;
2450}
2451
2452/*
2453 * amdgpu_iomem_write - Virtual write access to GPU mapped memory
2454 *
2455 * This function is used to write memory that has been mapped to the
2456 * GPU and the known addresses are not physical addresses but instead
2457 * bus addresses (e.g., what you'd put in an IB or ring buffer).
2458 */
2459static ssize_t amdgpu_iomem_write(struct file *f, const char __user *buf,
2460				 size_t size, loff_t *pos)
2461{
2462	struct amdgpu_device *adev = file_inode(f)->i_private;
2463	struct iommu_domain *dom;
2464	ssize_t result = 0;
2465	int r;
2466
2467	dom = iommu_get_domain_for_dev(adev->dev);
2468
2469	while (size) {
2470		phys_addr_t addr = *pos & PAGE_MASK;
2471		loff_t off = *pos & ~PAGE_MASK;
2472		size_t bytes = PAGE_SIZE - off;
2473		unsigned long pfn;
2474		struct page *p;
2475		void *ptr;
2476
2477		bytes = min(bytes, size);
2478
2479		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2480
2481		pfn = addr >> PAGE_SHIFT;
2482		if (!pfn_valid(pfn))
2483			return -EPERM;
2484
2485		p = pfn_to_page(pfn);
2486		if (p->mapping != adev->mman.bdev.dev_mapping)
2487			return -EPERM;
2488
2489		ptr = kmap_local_page(p);
2490		r = copy_from_user(ptr + off, buf, bytes);
2491		kunmap_local(ptr);
2492		if (r)
2493			return -EFAULT;
2494
2495		size -= bytes;
2496		*pos += bytes;
2497		result += bytes;
2498	}
2499
2500	return result;
2501}
2502
2503static const struct file_operations amdgpu_ttm_iomem_fops = {
2504	.owner = THIS_MODULE,
2505	.read = amdgpu_iomem_read,
2506	.write = amdgpu_iomem_write,
2507	.llseek = default_llseek
2508};
2509
 
 
 
 
 
 
 
 
 
 
 
 
2510#endif
2511
2512void amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
2513{
2514#if defined(CONFIG_DEBUG_FS)
2515	struct drm_minor *minor = adev_to_drm(adev)->primary;
2516	struct dentry *root = minor->debugfs_root;
2517
2518	debugfs_create_file_size("amdgpu_vram", 0444, root, adev,
2519				 &amdgpu_ttm_vram_fops, adev->gmc.mc_vram_size);
2520	debugfs_create_file("amdgpu_iomem", 0444, root, adev,
2521			    &amdgpu_ttm_iomem_fops);
2522	debugfs_create_file("ttm_page_pool", 0444, root, adev,
2523			    &amdgpu_ttm_page_pool_fops);
2524	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
2525							     TTM_PL_VRAM),
2526					    root, "amdgpu_vram_mm");
2527	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
2528							     TTM_PL_TT),
2529					    root, "amdgpu_gtt_mm");
2530	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
2531							     AMDGPU_PL_GDS),
2532					    root, "amdgpu_gds_mm");
2533	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
2534							     AMDGPU_PL_GWS),
2535					    root, "amdgpu_gws_mm");
2536	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
2537							     AMDGPU_PL_OA),
2538					    root, "amdgpu_oa_mm");
2539
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2540#endif
2541}