xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c (revision 89abac69b89bcb7c11c0bb4038e012a8c03d590b)
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_ras_mgr.h"
60 #include "amdgpu_hmm.h"
61 #include "amdgpu_atomfirmware.h"
62 #include "amdgpu_res_cursor.h"
63 #include "bif/bif_4_1_d.h"
64 #include "kfd_svm.h"
65 
66 MODULE_IMPORT_NS("DMA_BUF");
67 
68 #define AMDGPU_TTM_VRAM_MAX_DW_READ	((size_t)128)
69 
70 static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
71 				   struct ttm_tt *ttm,
72 				   struct ttm_resource *bo_mem);
73 static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
74 				      struct ttm_tt *ttm);
75 
76 static int amdgpu_ttm_init_on_chip(struct amdgpu_device *adev,
77 				    unsigned int type,
78 				    uint64_t size_in_page)
79 {
80 	if (!size_in_page)
81 		return 0;
82 
83 	return ttm_range_man_init(&adev->mman.bdev, type,
84 				  false, size_in_page);
85 }
86 
87 /**
88  * amdgpu_evict_flags - Compute placement flags
89  *
90  * @bo: The buffer object to evict
91  * @placement: Possible destination(s) for evicted BO
92  *
93  * Fill in placement data when ttm_bo_evict() is called
94  */
95 static void amdgpu_evict_flags(struct ttm_buffer_object *bo,
96 				struct ttm_placement *placement)
97 {
98 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
99 	struct amdgpu_bo *abo;
100 	static const struct ttm_place placements = {
101 		.fpfn = 0,
102 		.lpfn = 0,
103 		.mem_type = TTM_PL_SYSTEM,
104 		.flags = 0
105 	};
106 
107 	/* Don't handle scatter gather BOs */
108 	if (bo->type == ttm_bo_type_sg) {
109 		placement->num_placement = 0;
110 		return;
111 	}
112 
113 	/* Object isn't an AMDGPU object so ignore */
114 	if (!amdgpu_bo_is_amdgpu_bo(bo)) {
115 		placement->placement = &placements;
116 		placement->num_placement = 1;
117 		return;
118 	}
119 
120 	abo = ttm_to_amdgpu_bo(bo);
121 	if (abo->flags & AMDGPU_GEM_CREATE_DISCARDABLE) {
122 		placement->num_placement = 0;
123 		return;
124 	}
125 
126 	switch (bo->resource->mem_type) {
127 	case AMDGPU_PL_GDS:
128 	case AMDGPU_PL_GWS:
129 	case AMDGPU_PL_OA:
130 	case AMDGPU_PL_DOORBELL:
131 	case AMDGPU_PL_MMIO_REMAP:
132 	case AMDGPU_PL_NPA:
133 		placement->num_placement = 0;
134 		return;
135 
136 	case TTM_PL_VRAM:
137 		if (!adev->mman.buffer_funcs_enabled) {
138 			/* Move to system memory */
139 			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
140 
141 		} else if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
142 			   !(abo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) &&
143 			   amdgpu_res_cpu_visible(adev, bo->resource)) {
144 
145 			/* Try evicting to the CPU inaccessible part of VRAM
146 			 * first, but only set GTT as busy placement, so this
147 			 * BO will be evicted to GTT rather than causing other
148 			 * BOs to be evicted from VRAM
149 			 */
150 			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
151 							AMDGPU_GEM_DOMAIN_GTT |
152 							AMDGPU_GEM_DOMAIN_CPU);
153 			abo->placements[0].fpfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
154 			abo->placements[0].lpfn = 0;
155 			abo->placements[0].flags |= TTM_PL_FLAG_DESIRED;
156 		} else {
157 			/* Move to GTT memory */
158 			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_GTT |
159 							AMDGPU_GEM_DOMAIN_CPU);
160 		}
161 		break;
162 	case TTM_PL_TT:
163 	case AMDGPU_PL_PREEMPT:
164 	default:
165 		amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
166 		break;
167 	}
168 	*placement = abo->placement;
169 }
170 
171 static struct dma_fence *
172 amdgpu_ttm_job_submit(struct amdgpu_device *adev, struct amdgpu_ttm_buffer_entity *entity,
173 		      struct amdgpu_job *job, u32 num_dw)
174 {
175 	struct amdgpu_ring *ring;
176 
177 	ring = to_amdgpu_ring(adev->mman.buffer_funcs_scheds[0]);
178 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
179 	WARN_ON(job->ibs[0].length_dw > num_dw);
180 
181 	lockdep_assert_held(&entity->lock);
182 
183 	return amdgpu_job_submit(job);
184 }
185 
186 /**
187  * amdgpu_ttm_map_buffer - Map memory into the GART windows
188  * @entity: entity to run the window setup job
189  * @bo: buffer object to map
190  * @mem: memory object to map
191  * @mm_cur: range to map
192  * @window: which GART window to use
193  * @tmz: if we should setup a TMZ enabled mapping
194  * @size: in number of bytes to map, out number of bytes mapped
195  * @addr: resulting address inside the MC address space
196  * @vm_needs_flush: out, set true if a GART window was programmed (VMID 0 flush
197  *		    needed) or false for a direct address
198  *
199  * Setup one of the GART windows to access a specific piece of memory or return
200  * the physical address for local memory.
201  */
202 static int amdgpu_ttm_map_buffer(struct amdgpu_ttm_buffer_entity *entity,
203 				 struct ttm_buffer_object *bo,
204 				 struct ttm_resource *mem,
205 				 struct amdgpu_res_cursor *mm_cur,
206 				 unsigned int window,
207 				 bool tmz, uint64_t *size, uint64_t *addr,
208 				 bool *vm_needs_flush,
209 				 bool readonly)
210 {
211 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
212 	unsigned int offset, num_pages, num_dw, num_bytes;
213 	uint64_t src_addr, dst_addr;
214 	struct amdgpu_job *job;
215 	void *cpu_addr;
216 	uint64_t flags;
217 	int r;
218 	const u64 GTT_MAX_PAGES = (AMDGPU_GTT_MAX_TRANSFER_SIZE >> PAGE_SHIFT);
219 
220 	BUG_ON(adev->mman.buffer_funcs->copy_max_bytes <
221 	       GTT_MAX_PAGES * AMDGPU_GPU_PAGES_IN_CPU_PAGE * 8);
222 
223 	if (WARN_ON(mem->mem_type == AMDGPU_PL_PREEMPT))
224 		return -EINVAL;
225 
226 	/* Map only what can't be accessed directly */
227 	if (!tmz && mem->start != AMDGPU_BO_INVALID_OFFSET) {
228 		*addr = amdgpu_ttm_domain_start(adev, mem->mem_type) +
229 			mm_cur->start;
230 		*vm_needs_flush = false;
231 		return 0;
232 	}
233 
234 	/* A GART window is programmed below, so its VMID 0 TLB needs a flush */
235 	*vm_needs_flush = true;
236 
237 	/*
238 	 * If start begins at an offset inside the page, then adjust the size
239 	 * and addr accordingly
240 	 */
241 	offset = mm_cur->start & ~PAGE_MASK;
242 
243 	num_pages = PFN_UP(*size + offset);
244 	num_pages = min_t(uint32_t, num_pages, GTT_MAX_PAGES);
245 
246 	*size = min(*size, (uint64_t)num_pages * PAGE_SIZE - offset);
247 
248 	*addr = amdgpu_compute_gart_address(&adev->gmc, entity, window);
249 	*addr += offset;
250 
251 	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
252 	num_bytes = num_pages * 8 * AMDGPU_GPU_PAGES_IN_CPU_PAGE;
253 
254 	r = amdgpu_job_alloc_with_ib(adev, &entity->base,
255 				     AMDGPU_FENCE_OWNER_UNDEFINED,
256 				     num_dw * 4 + num_bytes,
257 				     AMDGPU_IB_POOL_DELAYED,
258 				     AMDGPU_KERNEL_JOB_ID_TTM_MAP_BUFFER,
259 				     &job);
260 	if (r)
261 		return r;
262 
263 	src_addr = num_dw * 4;
264 	src_addr += job->ibs[0].gpu_addr;
265 
266 	dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
267 	dst_addr += (entity->gart_window_offs[window] >> AMDGPU_GPU_PAGE_SHIFT) * 8;
268 	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
269 				dst_addr, num_bytes, 0);
270 
271 	flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, mem);
272 	if (tmz)
273 		flags |= AMDGPU_PTE_TMZ;
274 	if (readonly)
275 		flags &= ~AMDGPU_PTE_WRITEABLE;
276 
277 	cpu_addr = &job->ibs[0].ptr[num_dw];
278 
279 	if (mem->mem_type == TTM_PL_TT) {
280 		dma_addr_t *dma_addr;
281 
282 		dma_addr = &bo->ttm->dma_address[mm_cur->start >> PAGE_SHIFT];
283 		amdgpu_gart_map(adev, 0, num_pages, dma_addr, flags, cpu_addr);
284 	} else {
285 		u64 pa = mm_cur->start + adev->vm_manager.vram_base_offset;
286 
287 		amdgpu_gart_map_vram_range(adev, pa, 0, num_pages, flags, cpu_addr);
288 	}
289 
290 	dma_fence_put(amdgpu_ttm_job_submit(adev, entity, job, num_dw));
291 	return 0;
292 }
293 
294 /**
295  * amdgpu_ttm_copy_mem_to_mem - Helper function for copy
296  * @adev: amdgpu device
297  * @entity: entity to run the jobs
298  * @src: buffer/address where to read from
299  * @dst: buffer/address where to write to
300  * @size: number of bytes to copy
301  * @tmz: if a secure copy should be used
302  * @resv: resv object to sync to
303  * @f: Returns the last fence if multiple jobs are submitted.
304  *
305  * The function copies @size bytes from {src->mem + src->offset} to
306  * {dst->mem + dst->offset}. src->bo and dst->bo could be same BO for a
307  * move and different for a BO to BO copy.
308  *
309  */
310 __attribute__((nonnull))
311 static int amdgpu_ttm_copy_mem_to_mem(struct amdgpu_device *adev,
312 				      struct amdgpu_ttm_buffer_entity *entity,
313 				      const struct amdgpu_copy_mem *src,
314 				      const struct amdgpu_copy_mem *dst,
315 				      uint64_t size, bool tmz,
316 				      struct dma_resv *resv,
317 				      struct dma_fence **f)
318 {
319 	struct amdgpu_res_cursor src_mm, dst_mm;
320 	struct dma_fence *fence = NULL;
321 	int r = 0;
322 	uint32_t copy_flags = 0;
323 	struct amdgpu_bo *abo_src, *abo_dst;
324 
325 	if (!adev->mman.buffer_funcs_enabled) {
326 		dev_err(adev->dev,
327 			"Trying to move memory with ring turned off.\n");
328 		return -EINVAL;
329 	}
330 
331 	amdgpu_res_first(src->mem, src->offset, size, &src_mm);
332 	amdgpu_res_first(dst->mem, dst->offset, size, &dst_mm);
333 
334 	mutex_lock(&entity->lock);
335 	while (src_mm.remaining) {
336 		uint64_t from, to, cur_size, tiling_flags;
337 		uint32_t num_type, data_format, max_com, write_compress_disable;
338 		bool src_vm_flush, dst_vm_flush;
339 		struct dma_fence *next;
340 
341 		/* Never copy more than 256MiB at once to avoid a timeout */
342 		cur_size = min3(src_mm.size, dst_mm.size, 256ULL << 20);
343 
344 		/* Map src to window 0 and dst to window 1. */
345 		r = amdgpu_ttm_map_buffer(entity, src->bo, src->mem, &src_mm,
346 					  0, tmz, &cur_size, &from, &src_vm_flush, true);
347 		if (r)
348 			goto error;
349 
350 		r = amdgpu_ttm_map_buffer(entity, dst->bo, dst->mem, &dst_mm,
351 					  1, tmz, &cur_size, &to, &dst_vm_flush, false);
352 		if (r)
353 			goto error;
354 
355 		abo_src = ttm_to_amdgpu_bo(src->bo);
356 		abo_dst = ttm_to_amdgpu_bo(dst->bo);
357 		if (tmz)
358 			copy_flags |= AMDGPU_COPY_FLAGS_TMZ;
359 		if ((abo_src->flags & AMDGPU_GEM_CREATE_GFX12_DCC) &&
360 		    (abo_src->tbo.resource->mem_type == TTM_PL_VRAM))
361 			copy_flags |= AMDGPU_COPY_FLAGS_READ_DECOMPRESSED;
362 		if ((abo_dst->flags & AMDGPU_GEM_CREATE_GFX12_DCC) &&
363 		    (dst->mem->mem_type == TTM_PL_VRAM)) {
364 			copy_flags |= AMDGPU_COPY_FLAGS_WRITE_COMPRESSED;
365 			amdgpu_bo_get_tiling_flags(abo_dst, &tiling_flags);
366 			max_com = AMDGPU_TILING_GET(tiling_flags, GFX12_DCC_MAX_COMPRESSED_BLOCK);
367 			num_type = AMDGPU_TILING_GET(tiling_flags, GFX12_DCC_NUMBER_TYPE);
368 			data_format = AMDGPU_TILING_GET(tiling_flags, GFX12_DCC_DATA_FORMAT);
369 			write_compress_disable =
370 				AMDGPU_TILING_GET(tiling_flags, GFX12_DCC_WRITE_COMPRESS_DISABLE);
371 			copy_flags |= (AMDGPU_COPY_FLAGS_SET(MAX_COMPRESSED, max_com) |
372 				       AMDGPU_COPY_FLAGS_SET(NUMBER_TYPE, num_type) |
373 				       AMDGPU_COPY_FLAGS_SET(DATA_FORMAT, data_format) |
374 				       AMDGPU_COPY_FLAGS_SET(WRITE_COMPRESS_DISABLE,
375 							     write_compress_disable));
376 		}
377 
378 		r = amdgpu_copy_buffer(adev, entity, from, to, cur_size, resv,
379 				       &next, src_vm_flush || dst_vm_flush, copy_flags);
380 		if (r)
381 			goto error;
382 
383 		dma_fence_put(fence);
384 		fence = next;
385 
386 		amdgpu_res_next(&src_mm, cur_size);
387 		amdgpu_res_next(&dst_mm, cur_size);
388 	}
389 error:
390 	mutex_unlock(&entity->lock);
391 	*f = fence;
392 	return r;
393 }
394 
395 /*
396  * amdgpu_move_blit - Copy an entire buffer to another buffer
397  *
398  * This is a helper called by amdgpu_bo_move() and amdgpu_move_vram_ram() to
399  * help move buffers to and from VRAM.
400  */
401 static int amdgpu_move_blit(struct ttm_buffer_object *bo,
402 			    bool evict,
403 			    struct ttm_resource *new_mem,
404 			    struct ttm_resource *old_mem)
405 {
406 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
407 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
408 	struct amdgpu_ttm_buffer_entity *entity;
409 	struct amdgpu_copy_mem src, dst;
410 	struct dma_fence *fence = NULL;
411 	int r;
412 	u32 e;
413 
414 	src.bo = bo;
415 	dst.bo = bo;
416 	src.mem = old_mem;
417 	dst.mem = new_mem;
418 	src.offset = 0;
419 	dst.offset = 0;
420 
421 	e = atomic_inc_return(&adev->mman.next_move_entity) %
422 			      adev->mman.num_move_entities;
423 	entity = &adev->mman.move_entities[e];
424 
425 	r = amdgpu_ttm_copy_mem_to_mem(adev,
426 				       entity,
427 				       &src, &dst,
428 				       new_mem->size,
429 				       amdgpu_bo_encrypted(abo),
430 				       bo->base.resv, &fence);
431 	if (r)
432 		goto error;
433 
434 	/* clear the space being freed */
435 	if (old_mem->mem_type == TTM_PL_VRAM &&
436 	    (abo->flags & AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE)) {
437 		struct dma_fence *wipe_fence = NULL;
438 		r = amdgpu_ttm_clear_buffer(entity, abo, NULL, &wipe_fence,
439 					    false, AMDGPU_KERNEL_JOB_ID_MOVE_BLIT);
440 		if (r) {
441 			goto error;
442 		} else if (wipe_fence) {
443 			amdgpu_vram_mgr_set_cleared(bo->resource);
444 			dma_fence_put(fence);
445 			fence = wipe_fence;
446 		}
447 	}
448 
449 	/* Always block for VM page tables before committing the new location */
450 	if (bo->type == ttm_bo_type_kernel)
451 		r = ttm_bo_move_accel_cleanup(bo, fence, true, false, new_mem);
452 	else
453 		r = ttm_bo_move_accel_cleanup(bo, fence, evict, true, new_mem);
454 	dma_fence_put(fence);
455 	return r;
456 
457 error:
458 	if (fence)
459 		dma_fence_wait(fence, false);
460 	dma_fence_put(fence);
461 	return r;
462 }
463 
464 /**
465  * amdgpu_res_cpu_visible - Check that resource can be accessed by CPU
466  * @adev: amdgpu device
467  * @res: the resource to check
468  *
469  * Returns: true if the full resource is CPU visible, false otherwise.
470  */
471 bool amdgpu_res_cpu_visible(struct amdgpu_device *adev,
472 			    struct ttm_resource *res)
473 {
474 	struct amdgpu_res_cursor cursor;
475 
476 	if (!res)
477 		return false;
478 
479 	if (res->mem_type == TTM_PL_SYSTEM || res->mem_type == TTM_PL_TT ||
480 	    res->mem_type == AMDGPU_PL_PREEMPT || res->mem_type == AMDGPU_PL_DOORBELL ||
481 	    res->mem_type == AMDGPU_PL_MMIO_REMAP)
482 		return true;
483 
484 	if (res->mem_type != TTM_PL_VRAM)
485 		return false;
486 
487 	amdgpu_res_first(res, 0, res->size, &cursor);
488 	while (cursor.remaining) {
489 		if ((cursor.start + cursor.size) > adev->gmc.visible_vram_size)
490 			return false;
491 		amdgpu_res_next(&cursor, cursor.size);
492 	}
493 
494 	return true;
495 }
496 
497 /*
498  * amdgpu_res_copyable - Check that memory can be accessed by ttm_bo_move_memcpy
499  *
500  * Called by amdgpu_bo_move()
501  */
502 static bool amdgpu_res_copyable(struct amdgpu_device *adev,
503 				struct ttm_resource *mem)
504 {
505 	if (!amdgpu_res_cpu_visible(adev, mem))
506 		return false;
507 
508 	/* ttm_resource_ioremap only supports contiguous memory */
509 	if (mem->mem_type == TTM_PL_VRAM &&
510 	    !(mem->placement & TTM_PL_FLAG_CONTIGUOUS))
511 		return false;
512 
513 	return true;
514 }
515 
516 /*
517  * amdgpu_bo_move - Move a buffer object to a new memory location
518  *
519  * Called by ttm_bo_handle_move_mem()
520  */
521 static int amdgpu_bo_move(struct ttm_buffer_object *bo, bool evict,
522 			  struct ttm_operation_ctx *ctx,
523 			  struct ttm_resource *new_mem,
524 			  struct ttm_place *hop)
525 {
526 	struct amdgpu_device *adev;
527 	struct amdgpu_bo *abo;
528 	struct ttm_resource *old_mem = bo->resource;
529 	int r;
530 
531 	if (new_mem->mem_type == TTM_PL_TT ||
532 	    new_mem->mem_type == AMDGPU_PL_PREEMPT) {
533 		if (old_mem && (old_mem->mem_type == TTM_PL_TT ||
534 				old_mem->mem_type == AMDGPU_PL_PREEMPT)) {
535 			r = ttm_bo_wait_ctx(bo, ctx);
536 			if (r)
537 				return r;
538 
539 			amdgpu_ttm_backend_unbind(bo->bdev, bo->ttm);
540 		}
541 
542 		r = amdgpu_ttm_backend_bind(bo->bdev, bo->ttm, new_mem);
543 		if (r)
544 			return r;
545 	}
546 
547 	abo = ttm_to_amdgpu_bo(bo);
548 	adev = amdgpu_ttm_adev(bo->bdev);
549 
550 	if (!old_mem || (old_mem->mem_type == TTM_PL_SYSTEM &&
551 			 bo->ttm == NULL)) {
552 		amdgpu_bo_move_notify(bo, evict, new_mem);
553 		ttm_bo_move_null(bo, new_mem);
554 		return 0;
555 	}
556 	if (old_mem->mem_type == TTM_PL_SYSTEM &&
557 	    (new_mem->mem_type == TTM_PL_TT ||
558 	     new_mem->mem_type == AMDGPU_PL_PREEMPT)) {
559 		amdgpu_bo_move_notify(bo, evict, new_mem);
560 		ttm_bo_move_null(bo, new_mem);
561 		return 0;
562 	}
563 	if ((old_mem->mem_type == TTM_PL_TT ||
564 	     old_mem->mem_type == AMDGPU_PL_PREEMPT) &&
565 	    new_mem->mem_type == TTM_PL_SYSTEM) {
566 		r = ttm_bo_wait_ctx(bo, ctx);
567 		if (r)
568 			return r;
569 
570 		amdgpu_ttm_backend_unbind(bo->bdev, bo->ttm);
571 		amdgpu_bo_move_notify(bo, evict, new_mem);
572 		ttm_resource_free(bo, &bo->resource);
573 		ttm_bo_assign_mem(bo, new_mem);
574 		return 0;
575 	}
576 	if ((old_mem->mem_type == TTM_PL_TT ||
577 	     old_mem->mem_type == AMDGPU_PL_PREEMPT) &&
578 	    (new_mem->mem_type == TTM_PL_TT ||
579 	     new_mem->mem_type == AMDGPU_PL_PREEMPT)) {
580 		amdgpu_bo_move_notify(bo, evict, new_mem);
581 		ttm_resource_free(bo, &bo->resource);
582 		ttm_bo_assign_mem(bo, new_mem);
583 		return 0;
584 	}
585 
586 	if (old_mem->mem_type == AMDGPU_PL_GDS ||
587 	    old_mem->mem_type == AMDGPU_PL_GWS ||
588 	    old_mem->mem_type == AMDGPU_PL_OA ||
589 	    old_mem->mem_type == AMDGPU_PL_DOORBELL ||
590 	    old_mem->mem_type == AMDGPU_PL_MMIO_REMAP ||
591 	    old_mem->mem_type == AMDGPU_PL_NPA ||
592 	    new_mem->mem_type == AMDGPU_PL_GDS ||
593 	    new_mem->mem_type == AMDGPU_PL_GWS ||
594 	    new_mem->mem_type == AMDGPU_PL_OA ||
595 	    new_mem->mem_type == AMDGPU_PL_DOORBELL ||
596 	    new_mem->mem_type == AMDGPU_PL_MMIO_REMAP ||
597 	    new_mem->mem_type == AMDGPU_PL_NPA) {
598 		/* Nothing to save here */
599 		amdgpu_bo_move_notify(bo, evict, new_mem);
600 		ttm_bo_move_null(bo, new_mem);
601 		return 0;
602 	}
603 
604 	if (bo->type == ttm_bo_type_device &&
605 	    new_mem->mem_type == TTM_PL_VRAM &&
606 	    old_mem->mem_type != TTM_PL_VRAM) {
607 		/* amdgpu_bo_fault_reserve_notify will re-set this if the CPU
608 		 * accesses the BO after it's moved.
609 		 */
610 		abo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
611 	}
612 
613 	if (adev->mman.buffer_funcs_enabled &&
614 	    ((old_mem->mem_type == TTM_PL_SYSTEM &&
615 	      new_mem->mem_type == TTM_PL_VRAM) ||
616 	     (old_mem->mem_type == TTM_PL_VRAM &&
617 	      new_mem->mem_type == TTM_PL_SYSTEM))) {
618 		hop->fpfn = 0;
619 		hop->lpfn = 0;
620 		hop->mem_type = TTM_PL_TT;
621 		hop->flags = TTM_PL_FLAG_TEMPORARY;
622 		return -EMULTIHOP;
623 	}
624 
625 	amdgpu_bo_move_notify(bo, evict, new_mem);
626 	if (adev->mman.buffer_funcs_enabled)
627 		r = amdgpu_move_blit(bo, evict, new_mem, old_mem);
628 	else
629 		r = -ENODEV;
630 
631 	if (r) {
632 		/* Check that all memory is CPU accessible */
633 		if (!amdgpu_res_copyable(adev, old_mem) ||
634 		    !amdgpu_res_copyable(adev, new_mem)) {
635 			pr_err("Move buffer fallback to memcpy unavailable\n");
636 			return r;
637 		}
638 
639 		r = ttm_bo_move_memcpy(bo, ctx, new_mem);
640 		if (r)
641 			return r;
642 	}
643 
644 	/* update statistics after the move */
645 	if (evict)
646 		atomic64_inc(&adev->num_evictions);
647 	atomic64_add(bo->base.size, &adev->num_bytes_moved);
648 	return 0;
649 }
650 
651 /*
652  * amdgpu_ttm_io_mem_reserve - Reserve a block of memory during a fault
653  *
654  * Called by ttm_mem_io_reserve() ultimately via ttm_bo_vm_fault()
655  */
656 static int amdgpu_ttm_io_mem_reserve(struct ttm_device *bdev,
657 				     struct ttm_resource *mem)
658 {
659 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
660 
661 	switch (mem->mem_type) {
662 	case TTM_PL_SYSTEM:
663 		/* system memory */
664 		return 0;
665 	case TTM_PL_TT:
666 	case AMDGPU_PL_PREEMPT:
667 		break;
668 	case TTM_PL_VRAM:
669 		mem->bus.offset = mem->start << PAGE_SHIFT;
670 
671 		if (adev->mman.aper_base_kaddr &&
672 		    mem->placement & TTM_PL_FLAG_CONTIGUOUS)
673 			mem->bus.addr = (u8 *)adev->mman.aper_base_kaddr +
674 					mem->bus.offset;
675 
676 		mem->bus.offset += adev->gmc.aper_base;
677 		mem->bus.is_iomem = true;
678 		break;
679 	case AMDGPU_PL_DOORBELL:
680 		mem->bus.offset = mem->start << PAGE_SHIFT;
681 		mem->bus.offset += adev->doorbell.base;
682 		mem->bus.is_iomem = true;
683 		mem->bus.caching = ttm_uncached;
684 		break;
685 	case AMDGPU_PL_MMIO_REMAP:
686 		mem->bus.offset = mem->start << PAGE_SHIFT;
687 		mem->bus.offset += adev->rmmio_remap.bus_addr;
688 		mem->bus.is_iomem = true;
689 		mem->bus.caching = ttm_uncached;
690 		break;
691 	default:
692 		return -EINVAL;
693 	}
694 	return 0;
695 }
696 
697 static unsigned long amdgpu_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
698 					   unsigned long page_offset)
699 {
700 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
701 	struct amdgpu_res_cursor cursor;
702 
703 	amdgpu_res_first(bo->resource, (u64)page_offset << PAGE_SHIFT, 0,
704 			 &cursor);
705 
706 	if (bo->resource->mem_type == AMDGPU_PL_DOORBELL)
707 		return ((uint64_t)(adev->doorbell.base + cursor.start)) >> PAGE_SHIFT;
708 	else if (bo->resource->mem_type == AMDGPU_PL_MMIO_REMAP)
709 		return ((uint64_t)(adev->rmmio_remap.bus_addr + cursor.start)) >> PAGE_SHIFT;
710 
711 	return (adev->gmc.aper_base + cursor.start) >> PAGE_SHIFT;
712 }
713 
714 /**
715  * amdgpu_ttm_domain_start - Returns GPU start address
716  * @adev: amdgpu device object
717  * @type: type of the memory
718  *
719  * Returns:
720  * GPU start address of a memory domain
721  */
722 
723 uint64_t amdgpu_ttm_domain_start(struct amdgpu_device *adev, uint32_t type)
724 {
725 	switch (type) {
726 	case TTM_PL_TT:
727 		return adev->gmc.gart_start;
728 	case TTM_PL_VRAM:
729 		return adev->gmc.vram_start;
730 	}
731 
732 	return 0;
733 }
734 
735 /*
736  * TTM backend functions.
737  */
738 struct amdgpu_ttm_tt {
739 	struct ttm_tt	ttm;
740 	struct drm_gem_object	*gobj;
741 	u64			offset;
742 	uint64_t		userptr;
743 	struct task_struct	*usertask;
744 	uint32_t		userflags;
745 	bool			bound;
746 	int32_t			pool_id;
747 };
748 
749 #define ttm_to_amdgpu_ttm_tt(ptr)	container_of(ptr, struct amdgpu_ttm_tt, ttm)
750 
751 #ifdef CONFIG_DRM_AMDGPU_USERPTR
752 /*
753  * amdgpu_ttm_tt_get_user_pages - get device accessible pages that back user
754  * memory and start HMM tracking CPU page table update
755  *
756  * Calling function must call amdgpu_ttm_tt_userptr_range_done() once and only
757  * once afterwards to stop HMM tracking. Its the caller responsibility to ensure
758  * that range is a valid memory and it is freed too.
759  */
760 int amdgpu_ttm_tt_get_user_pages(struct amdgpu_bo *bo,
761 				 struct amdgpu_hmm_range *range)
762 {
763 	struct ttm_tt *ttm = bo->tbo.ttm;
764 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
765 	unsigned long start = gtt->userptr;
766 	struct vm_area_struct *vma;
767 	struct mm_struct *mm;
768 	bool readonly;
769 	int r = 0;
770 
771 	mm = bo->notifier.mm;
772 	if (unlikely(!mm)) {
773 		DRM_DEBUG_DRIVER("BO is not registered?\n");
774 		return -EFAULT;
775 	}
776 
777 	if (!mmget_not_zero(mm)) /* Happens during process shutdown */
778 		return -ESRCH;
779 
780 	mmap_read_lock(mm);
781 	vma = vma_lookup(mm, start);
782 	if (unlikely(!vma)) {
783 		r = -EFAULT;
784 		goto out_unlock;
785 	}
786 	if (unlikely((gtt->userflags & AMDGPU_GEM_USERPTR_ANONONLY) &&
787 		     (vma->vm_file ||
788 		      vma->vm_end < start + (u64)ttm->num_pages * PAGE_SIZE))) {
789 		r = -EPERM;
790 		goto out_unlock;
791 	}
792 
793 	readonly = amdgpu_ttm_tt_is_readonly(ttm);
794 	r = amdgpu_hmm_range_get_pages(&bo->notifier, start, ttm->num_pages,
795 				       readonly, NULL, range);
796 out_unlock:
797 	mmap_read_unlock(mm);
798 	if (r)
799 		pr_debug("failed %d to get user pages 0x%lx\n", r, start);
800 
801 	mmput(mm);
802 
803 	return r;
804 }
805 
806 #endif
807 
808 /*
809  * amdgpu_ttm_tt_set_user_pages - Copy pages in, putting old pages as necessary.
810  *
811  * Called by amdgpu_cs_list_validate(). This creates the page list
812  * that backs user memory and will ultimately be mapped into the device
813  * address space.
814  */
815 void amdgpu_ttm_tt_set_user_pages(struct ttm_tt *ttm, struct amdgpu_hmm_range *range)
816 {
817 	unsigned long i;
818 
819 	for (i = 0; i < ttm->num_pages; ++i)
820 		ttm->pages[i] = range ? hmm_pfn_to_page(range->hmm_range.hmm_pfns[i]) : NULL;
821 }
822 
823 /*
824  * amdgpu_ttm_tt_pin_userptr - prepare the sg table with the user pages
825  *
826  * Called by amdgpu_ttm_backend_bind()
827  **/
828 static int amdgpu_ttm_tt_pin_userptr(struct ttm_device *bdev,
829 				     struct ttm_tt *ttm)
830 {
831 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
832 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
833 	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
834 	enum dma_data_direction direction = write ?
835 		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
836 	int r;
837 
838 	/* Allocate an SG array and squash pages into it */
839 	r = sg_alloc_table_from_pages(ttm->sg, ttm->pages, ttm->num_pages, 0,
840 				      (u64)ttm->num_pages << PAGE_SHIFT,
841 				      GFP_KERNEL);
842 	if (r)
843 		goto release_sg;
844 
845 	/* Map SG to device */
846 	r = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
847 	if (r)
848 		goto release_sg_table;
849 
850 	/* convert SG to linear array of pages and dma addresses */
851 	drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
852 				       ttm->num_pages);
853 
854 	return 0;
855 
856 release_sg_table:
857 	sg_free_table(ttm->sg);
858 release_sg:
859 	kfree(ttm->sg);
860 	ttm->sg = NULL;
861 	return r;
862 }
863 
864 /*
865  * amdgpu_ttm_tt_unpin_userptr - Unpin and unmap userptr pages
866  */
867 static void amdgpu_ttm_tt_unpin_userptr(struct ttm_device *bdev,
868 					struct ttm_tt *ttm)
869 {
870 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
871 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
872 	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
873 	enum dma_data_direction direction = write ?
874 		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
875 
876 	/* double check that we don't free the table twice */
877 	if (!ttm->sg || !ttm->sg->sgl)
878 		return;
879 
880 	/* unmap the pages mapped to the device */
881 	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
882 	sg_free_table(ttm->sg);
883 }
884 
885 /*
886  * total_pages is constructed as MQD0+CtrlStack0 + MQD1+CtrlStack1 + ...
887  * MQDn+CtrlStackn where n is the number of XCCs per partition.
888  * pages_per_xcc is the size of one MQD+CtrlStack. The first page is MQD
889  * and uses memory type default, UC. The rest of pages_per_xcc are
890  * Ctrl stack and modify their memory type to NC.
891  */
892 static void amdgpu_ttm_gart_bind_gfx9_mqd(struct amdgpu_device *adev,
893 				struct ttm_tt *ttm, uint64_t flags)
894 {
895 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
896 	uint64_t total_pages = ttm->num_pages;
897 	int num_xcc = max(1U, adev->gfx.num_xcc_per_xcp);
898 	uint64_t page_idx, pages_per_xcc;
899 	int i;
900 
901 	pages_per_xcc = total_pages;
902 	do_div(pages_per_xcc, num_xcc);
903 
904 	for (i = 0, page_idx = 0; i < num_xcc; i++, page_idx += pages_per_xcc) {
905 		amdgpu_gart_map_gfx9_mqd(adev,
906 				gtt->offset + (page_idx << PAGE_SHIFT),
907 				pages_per_xcc, &gtt->ttm.dma_address[page_idx],
908 				flags);
909 	}
910 }
911 
912 static void amdgpu_ttm_gart_bind(struct amdgpu_device *adev,
913 				 struct ttm_buffer_object *tbo,
914 				 uint64_t flags)
915 {
916 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(tbo);
917 	struct ttm_tt *ttm = tbo->ttm;
918 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
919 
920 	if (amdgpu_bo_encrypted(abo))
921 		flags |= AMDGPU_PTE_TMZ;
922 
923 	if (abo->flags & AMDGPU_GEM_CREATE_CP_MQD_GFX9) {
924 		amdgpu_ttm_gart_bind_gfx9_mqd(adev, ttm, flags);
925 	} else {
926 		amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
927 				 gtt->ttm.dma_address, flags);
928 	}
929 	gtt->bound = true;
930 }
931 
932 /*
933  * amdgpu_ttm_backend_bind - Bind GTT memory
934  *
935  * Called by ttm_tt_bind() on behalf of ttm_bo_handle_move_mem().
936  * This handles binding GTT memory to the device address space.
937  */
938 static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
939 				   struct ttm_tt *ttm,
940 				   struct ttm_resource *bo_mem)
941 {
942 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
943 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
944 	uint64_t flags;
945 	int r;
946 
947 	if (!bo_mem)
948 		return -EINVAL;
949 
950 	if (gtt->bound)
951 		return 0;
952 
953 	if (gtt->userptr) {
954 		r = amdgpu_ttm_tt_pin_userptr(bdev, ttm);
955 		if (r) {
956 			dev_err(adev->dev, "failed to pin userptr\n");
957 			return r;
958 		}
959 	} else if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL) {
960 		if (!ttm->sg) {
961 			struct dma_buf_attachment *attach;
962 			struct sg_table *sgt;
963 
964 			attach = gtt->gobj->import_attach;
965 			sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
966 			if (IS_ERR(sgt))
967 				return PTR_ERR(sgt);
968 
969 			ttm->sg = sgt;
970 		}
971 
972 		drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
973 					       ttm->num_pages);
974 	}
975 
976 	if (!ttm->num_pages) {
977 		WARN(1, "nothing to bind %u pages for mreg %p back %p!\n",
978 		     ttm->num_pages, bo_mem, ttm);
979 	}
980 
981 	if (bo_mem->mem_type != TTM_PL_TT ||
982 	    !amdgpu_gtt_mgr_has_gart_addr(bo_mem)) {
983 		gtt->offset = AMDGPU_BO_INVALID_OFFSET;
984 		return 0;
985 	}
986 
987 	/* compute PTE flags relevant to this BO memory */
988 	flags = amdgpu_ttm_tt_pte_flags(adev, ttm, bo_mem);
989 
990 	/* bind pages into GART page tables */
991 	gtt->offset = (u64)bo_mem->start << PAGE_SHIFT;
992 	amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
993 			 gtt->ttm.dma_address, flags);
994 	gtt->bound = true;
995 	return 0;
996 }
997 
998 /*
999  * amdgpu_ttm_alloc_gart - Make sure buffer object is accessible either
1000  * through AGP or GART aperture.
1001  *
1002  * If bo is accessible through AGP aperture, then use AGP aperture
1003  * to access bo; otherwise allocate logical space in GART aperture
1004  * and map bo to GART aperture.
1005  */
1006 int amdgpu_ttm_alloc_gart(struct ttm_buffer_object *bo)
1007 {
1008 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1009 	struct ttm_operation_ctx ctx = { false, false };
1010 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(bo->ttm);
1011 	struct ttm_placement placement;
1012 	struct ttm_place placements;
1013 	struct ttm_resource *tmp;
1014 	uint64_t addr, flags;
1015 	int r;
1016 
1017 	if (bo->resource->start != AMDGPU_BO_INVALID_OFFSET)
1018 		return 0;
1019 
1020 	addr = amdgpu_gmc_agp_addr(bo);
1021 	if (addr != AMDGPU_BO_INVALID_OFFSET)
1022 		return 0;
1023 
1024 	/* allocate GART space */
1025 	placement.num_placement = 1;
1026 	placement.placement = &placements;
1027 	placements.fpfn = 0;
1028 	placements.lpfn = adev->gmc.gart_size >> PAGE_SHIFT;
1029 	placements.mem_type = TTM_PL_TT;
1030 	placements.flags = bo->resource->placement;
1031 
1032 	r = ttm_bo_mem_space(bo, &placement, &tmp, &ctx);
1033 	if (unlikely(r))
1034 		return r;
1035 
1036 	/* compute PTE flags for this buffer object */
1037 	flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, tmp);
1038 
1039 	/* Bind pages */
1040 	gtt->offset = (u64)tmp->start << PAGE_SHIFT;
1041 	amdgpu_ttm_gart_bind(adev, bo, flags);
1042 	amdgpu_gart_invalidate_tlb(adev);
1043 	ttm_resource_free(bo, &bo->resource);
1044 	ttm_bo_assign_mem(bo, tmp);
1045 
1046 	return 0;
1047 }
1048 
1049 /*
1050  * amdgpu_ttm_recover_gart - Rebind GTT pages
1051  *
1052  * Called by amdgpu_gtt_mgr_recover() from amdgpu_device_reset() to
1053  * rebind GTT pages during a GPU reset.
1054  */
1055 void amdgpu_ttm_recover_gart(struct ttm_buffer_object *tbo)
1056 {
1057 	struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
1058 	uint64_t flags;
1059 
1060 	if (!tbo->ttm)
1061 		return;
1062 
1063 	flags = amdgpu_ttm_tt_pte_flags(adev, tbo->ttm, tbo->resource);
1064 	amdgpu_ttm_gart_bind(adev, tbo, flags);
1065 }
1066 
1067 /*
1068  * amdgpu_ttm_backend_unbind - Unbind GTT mapped pages
1069  *
1070  * Called by ttm_tt_unbind() on behalf of ttm_bo_move_ttm() and
1071  * ttm_tt_destroy().
1072  */
1073 static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
1074 				      struct ttm_tt *ttm)
1075 {
1076 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1077 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1078 
1079 	/* if the pages have userptr pinning then clear that first */
1080 	if (gtt->userptr) {
1081 		amdgpu_ttm_tt_unpin_userptr(bdev, ttm);
1082 	} else if (ttm->sg && drm_gem_is_imported(gtt->gobj)) {
1083 		struct dma_buf_attachment *attach;
1084 
1085 		attach = gtt->gobj->import_attach;
1086 		dma_buf_unmap_attachment(attach, ttm->sg, DMA_BIDIRECTIONAL);
1087 		ttm->sg = NULL;
1088 	}
1089 
1090 	if (!gtt->bound)
1091 		return;
1092 
1093 	if (gtt->offset == AMDGPU_BO_INVALID_OFFSET)
1094 		return;
1095 
1096 	/* unbind shouldn't be done for GDS/GWS/OA in ttm_bo_clean_mm */
1097 	amdgpu_gart_unbind(adev, gtt->offset, ttm->num_pages);
1098 	gtt->bound = false;
1099 }
1100 
1101 static void amdgpu_ttm_backend_destroy(struct ttm_device *bdev,
1102 				       struct ttm_tt *ttm)
1103 {
1104 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1105 
1106 	if (gtt->usertask)
1107 		put_task_struct(gtt->usertask);
1108 
1109 	ttm_tt_fini(&gtt->ttm);
1110 	kfree(gtt);
1111 }
1112 
1113 /**
1114  * amdgpu_ttm_mmio_remap_alloc_sgt - build an sg_table for MMIO_REMAP I/O aperture
1115  * @adev: amdgpu device providing the remap BAR base (adev->rmmio_remap.bus_addr)
1116  * @res:  TTM resource of the BO to export; expected to live in AMDGPU_PL_MMIO_REMAP
1117  * @dev:  importing device to map for (typically @attach->dev in dma-buf paths)
1118  * @dir:  DMA data direction for the importer (passed to dma_map_resource())
1119  * @sgt:  output; on success, set to a newly allocated sg_table describing the I/O span
1120  *
1121  * The HDP flush page (AMDGPU_PL_MMIO_REMAP) is a fixed hardware I/O window in a PCI
1122  * BAR—there are no struct pages to back it. Importers still need a DMA address list,
1123  * so we synthesize a minimal sg_table and populate it from dma_map_resource(), not
1124  * from pages. Using the common amdgpu_res_cursor walker keeps the offset/size math
1125  * consistent with other TTM/manager users.
1126  *
1127  * - @res is assumed to be a small, contiguous I/O region (typically a single 4 KiB
1128  *   page) in AMDGPU_PL_MMIO_REMAP. Callers should validate placement before calling.
1129  * - The sg entry is created with sg_set_page(sg, NULL, …) to reflect I/O space.
1130  * - The mapping uses DMA_ATTR_SKIP_CPU_SYNC because this is MMIO, not cacheable RAM.
1131  * - Peer reachability / p2pdma policy checks must be done by the caller.
1132  *
1133  * Return:
1134  * * 0 on success, with *@sgt set to a valid table that must be freed via
1135  *   amdgpu_ttm_mmio_remap_free_sgt().
1136  * * -ENOMEM if allocation of the sg_table fails.
1137  * * -EIO if dma_map_resource() fails.
1138  *
1139  */
1140 int amdgpu_ttm_mmio_remap_alloc_sgt(struct amdgpu_device *adev,
1141 				    struct ttm_resource *res,
1142 				    struct device *dev,
1143 				    enum dma_data_direction dir,
1144 				    struct sg_table **sgt)
1145 {
1146 	struct amdgpu_res_cursor cur;
1147 	dma_addr_t dma;
1148 	resource_size_t phys;
1149 	struct scatterlist *sg;
1150 	int r;
1151 
1152 	/* Walk the resource once; MMIO_REMAP is expected to be contiguous+small. */
1153 	amdgpu_res_first(res, 0, res->size, &cur);
1154 
1155 	/* Translate byte offset in the remap window into a host physical BAR address. */
1156 	phys = adev->rmmio_remap.bus_addr + cur.start;
1157 
1158 	/* Build a single-entry sg_table mapped as I/O (no struct page backing). */
1159 	*sgt = kzalloc_obj(**sgt);
1160 	if (!*sgt)
1161 		return -ENOMEM;
1162 	r = sg_alloc_table(*sgt, 1, GFP_KERNEL);
1163 	if (r) {
1164 		kfree(*sgt);
1165 		return r;
1166 	}
1167 	sg = (*sgt)->sgl;
1168 	sg_set_page(sg, NULL, cur.size, 0);  /* WHY: I/O space → no pages */
1169 
1170 	dma = dma_map_resource(dev, phys, cur.size, dir, DMA_ATTR_SKIP_CPU_SYNC);
1171 	if (dma_mapping_error(dev, dma)) {
1172 		sg_free_table(*sgt);
1173 		kfree(*sgt);
1174 		return -EIO;
1175 	}
1176 	sg_dma_address(sg) = dma;
1177 	sg_dma_len(sg) = cur.size;
1178 	return 0;
1179 }
1180 
1181 void amdgpu_ttm_mmio_remap_free_sgt(struct device *dev,
1182 				    enum dma_data_direction dir,
1183 				    struct sg_table *sgt)
1184 {
1185 	struct scatterlist *sg = sgt->sgl;
1186 
1187 	dma_unmap_resource(dev, sg_dma_address(sg), sg_dma_len(sg),
1188 			   dir, DMA_ATTR_SKIP_CPU_SYNC);
1189 	sg_free_table(sgt);
1190 	kfree(sgt);
1191 }
1192 
1193 /**
1194  * amdgpu_ttm_tt_create - Create a ttm_tt object for a given BO
1195  *
1196  * @bo: The buffer object to create a GTT ttm_tt object around
1197  * @page_flags: Page flags to be added to the ttm_tt object
1198  *
1199  * Called by ttm_tt_create().
1200  */
1201 static struct ttm_tt *amdgpu_ttm_tt_create(struct ttm_buffer_object *bo,
1202 					   uint32_t page_flags)
1203 {
1204 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1205 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1206 	struct amdgpu_ttm_tt *gtt;
1207 	enum ttm_caching caching;
1208 
1209 	gtt = kzalloc_obj(struct amdgpu_ttm_tt);
1210 	if (!gtt)
1211 		return NULL;
1212 
1213 	gtt->gobj = &bo->base;
1214 	if (adev->gmc.mem_partitions && abo->xcp_id >= 0)
1215 		gtt->pool_id = KFD_XCP_MEM_ID(adev, abo->xcp_id);
1216 	else
1217 		gtt->pool_id = abo->xcp_id;
1218 
1219 	if (abo->flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
1220 		caching = ttm_write_combined;
1221 	else
1222 		caching = ttm_cached;
1223 
1224 	/* allocate space for the uninitialized page entries */
1225 	if (ttm_sg_tt_init(&gtt->ttm, bo, page_flags, caching)) {
1226 		kfree(gtt);
1227 		return NULL;
1228 	}
1229 	return &gtt->ttm;
1230 }
1231 
1232 /*
1233  * amdgpu_ttm_tt_populate - Map GTT pages visible to the device
1234  *
1235  * Map the pages of a ttm_tt object to an address space visible
1236  * to the underlying device.
1237  */
1238 static int amdgpu_ttm_tt_populate(struct ttm_device *bdev,
1239 				  struct ttm_tt *ttm,
1240 				  struct ttm_operation_ctx *ctx)
1241 {
1242 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1243 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1244 	struct ttm_pool *pool;
1245 	pgoff_t i;
1246 	int ret;
1247 
1248 	/* user pages are bound by amdgpu_ttm_tt_pin_userptr() */
1249 	if (gtt->userptr) {
1250 		ttm->sg = kzalloc_obj(struct sg_table);
1251 		if (!ttm->sg)
1252 			return -ENOMEM;
1253 		return 0;
1254 	}
1255 
1256 	if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
1257 		return 0;
1258 
1259 	if (adev->mman.ttm_pools && gtt->pool_id >= 0)
1260 		pool = &adev->mman.ttm_pools[gtt->pool_id];
1261 	else
1262 		pool = &adev->mman.bdev.pool;
1263 	ret = ttm_pool_alloc(pool, ttm, ctx);
1264 	if (ret)
1265 		return ret;
1266 
1267 	for (i = 0; i < ttm->num_pages; ++i)
1268 		ttm->pages[i]->mapping = bdev->dev_mapping;
1269 
1270 	return 0;
1271 }
1272 
1273 /*
1274  * amdgpu_ttm_tt_unpopulate - unmap GTT pages and unpopulate page arrays
1275  *
1276  * Unmaps pages of a ttm_tt object from the device address space and
1277  * unpopulates the page array backing it.
1278  */
1279 static void amdgpu_ttm_tt_unpopulate(struct ttm_device *bdev,
1280 				     struct ttm_tt *ttm)
1281 {
1282 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1283 	struct amdgpu_device *adev;
1284 	struct ttm_pool *pool;
1285 	pgoff_t i;
1286 
1287 	amdgpu_ttm_backend_unbind(bdev, ttm);
1288 
1289 	if (gtt->userptr) {
1290 		amdgpu_ttm_tt_set_user_pages(ttm, NULL);
1291 		kfree(ttm->sg);
1292 		ttm->sg = NULL;
1293 		return;
1294 	}
1295 
1296 	if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
1297 		return;
1298 
1299 	for (i = 0; i < ttm->num_pages; ++i)
1300 		ttm->pages[i]->mapping = NULL;
1301 
1302 	adev = amdgpu_ttm_adev(bdev);
1303 
1304 	if (adev->mman.ttm_pools && gtt->pool_id >= 0)
1305 		pool = &adev->mman.ttm_pools[gtt->pool_id];
1306 	else
1307 		pool = &adev->mman.bdev.pool;
1308 
1309 	return ttm_pool_free(pool, ttm);
1310 }
1311 
1312 /**
1313  * amdgpu_ttm_tt_get_userptr - Return the userptr GTT ttm_tt for the current
1314  * task
1315  *
1316  * @tbo: The ttm_buffer_object that contains the userptr
1317  * @user_addr:  The returned value
1318  */
1319 int amdgpu_ttm_tt_get_userptr(const struct ttm_buffer_object *tbo,
1320 			      uint64_t *user_addr)
1321 {
1322 	struct amdgpu_ttm_tt *gtt;
1323 
1324 	if (!tbo->ttm)
1325 		return -EINVAL;
1326 
1327 	gtt = (void *)tbo->ttm;
1328 	*user_addr = gtt->userptr;
1329 	return 0;
1330 }
1331 
1332 /**
1333  * amdgpu_ttm_tt_set_userptr - Initialize userptr GTT ttm_tt for the current
1334  * task
1335  *
1336  * @bo: The ttm_buffer_object to bind this userptr to
1337  * @addr:  The address in the current tasks VM space to use
1338  * @flags: Requirements of userptr object.
1339  *
1340  * Called by amdgpu_gem_userptr_ioctl() and kfd_ioctl_alloc_memory_of_gpu() to
1341  * bind userptr pages to current task and by kfd_ioctl_acquire_vm() to
1342  * initialize GPU VM for a KFD process.
1343  */
1344 int amdgpu_ttm_tt_set_userptr(struct ttm_buffer_object *bo,
1345 			      uint64_t addr, uint32_t flags)
1346 {
1347 	struct amdgpu_ttm_tt *gtt;
1348 
1349 	if (!bo->ttm) {
1350 		/* TODO: We want a separate TTM object type for userptrs */
1351 		bo->ttm = amdgpu_ttm_tt_create(bo, 0);
1352 		if (bo->ttm == NULL)
1353 			return -ENOMEM;
1354 	}
1355 
1356 	/* Set TTM_TT_FLAG_EXTERNAL before populate but after create. */
1357 	bo->ttm->page_flags |= TTM_TT_FLAG_EXTERNAL;
1358 
1359 	gtt = ttm_to_amdgpu_ttm_tt(bo->ttm);
1360 	gtt->userptr = addr;
1361 	gtt->userflags = flags;
1362 
1363 	if (gtt->usertask)
1364 		put_task_struct(gtt->usertask);
1365 	gtt->usertask = current->group_leader;
1366 	get_task_struct(gtt->usertask);
1367 
1368 	return 0;
1369 }
1370 
1371 /*
1372  * amdgpu_ttm_tt_get_usermm - Return memory manager for ttm_tt object
1373  */
1374 struct mm_struct *amdgpu_ttm_tt_get_usermm(struct ttm_tt *ttm)
1375 {
1376 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1377 
1378 	if (gtt == NULL)
1379 		return NULL;
1380 
1381 	if (gtt->usertask == NULL)
1382 		return NULL;
1383 
1384 	return gtt->usertask->mm;
1385 }
1386 
1387 /*
1388  * amdgpu_ttm_tt_affect_userptr - Determine if a ttm_tt object lays inside an
1389  * address range for the current task.
1390  *
1391  */
1392 bool amdgpu_ttm_tt_affect_userptr(struct ttm_tt *ttm, unsigned long start,
1393 				  unsigned long end, unsigned long *userptr)
1394 {
1395 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1396 	unsigned long size;
1397 
1398 	if (gtt == NULL || !gtt->userptr)
1399 		return false;
1400 
1401 	/* Return false if no part of the ttm_tt object lies within
1402 	 * the range
1403 	 */
1404 	size = (unsigned long)gtt->ttm.num_pages * PAGE_SIZE;
1405 	if (gtt->userptr > end || gtt->userptr + size <= start)
1406 		return false;
1407 
1408 	if (userptr)
1409 		*userptr = gtt->userptr;
1410 	return true;
1411 }
1412 
1413 /*
1414  * amdgpu_ttm_tt_is_userptr - Have the pages backing by userptr?
1415  */
1416 bool amdgpu_ttm_tt_is_userptr(struct ttm_tt *ttm)
1417 {
1418 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1419 
1420 	if (gtt == NULL || !gtt->userptr)
1421 		return false;
1422 
1423 	return true;
1424 }
1425 
1426 /*
1427  * amdgpu_ttm_tt_is_readonly - Is the ttm_tt object read only?
1428  */
1429 bool amdgpu_ttm_tt_is_readonly(struct ttm_tt *ttm)
1430 {
1431 	struct amdgpu_ttm_tt *gtt = ttm_to_amdgpu_ttm_tt(ttm);
1432 
1433 	if (gtt == NULL)
1434 		return false;
1435 
1436 	return !!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1437 }
1438 
1439 /**
1440  * amdgpu_ttm_tt_pde_flags - Compute PDE flags for ttm_tt object
1441  *
1442  * @ttm: The ttm_tt object to compute the flags for
1443  * @mem: The memory registry backing this ttm_tt object
1444  *
1445  * Figure out the flags to use for a VM PDE (Page Directory Entry).
1446  */
1447 uint64_t amdgpu_ttm_tt_pde_flags(struct ttm_tt *ttm, struct ttm_resource *mem)
1448 {
1449 	uint64_t flags = 0;
1450 
1451 	if (mem && mem->mem_type != TTM_PL_SYSTEM)
1452 		flags |= AMDGPU_PTE_VALID;
1453 
1454 	if (mem && (mem->mem_type == TTM_PL_TT ||
1455 		    mem->mem_type == AMDGPU_PL_DOORBELL ||
1456 		    mem->mem_type == AMDGPU_PL_PREEMPT ||
1457 		    mem->mem_type == AMDGPU_PL_MMIO_REMAP)) {
1458 		flags |= AMDGPU_PTE_SYSTEM;
1459 
1460 		if (ttm && ttm->caching == ttm_cached)
1461 			flags |= AMDGPU_PTE_SNOOPED;
1462 	}
1463 
1464 	if (mem && mem->mem_type == TTM_PL_VRAM) {
1465 		if (mem->bo) {
1466 			struct amdgpu_device *adev = amdgpu_ttm_adev(mem->bo->bdev);
1467 
1468 			if (amdgpu_virt_vram_is_spm(adev))
1469 				flags |= AMDGPU_PTE_SYSTEM;
1470 		}
1471 
1472 		if (mem->bus.caching == ttm_cached)
1473 			flags |= AMDGPU_PTE_SNOOPED;
1474 	}
1475 
1476 	return flags;
1477 }
1478 
1479 /**
1480  * amdgpu_ttm_tt_pte_flags - Compute PTE flags for ttm_tt object
1481  *
1482  * @adev: amdgpu_device pointer
1483  * @ttm: The ttm_tt object to compute the flags for
1484  * @mem: The memory registry backing this ttm_tt object
1485  *
1486  * Figure out the flags to use for a VM PTE (Page Table Entry).
1487  */
1488 uint64_t amdgpu_ttm_tt_pte_flags(struct amdgpu_device *adev, struct ttm_tt *ttm,
1489 				 struct ttm_resource *mem)
1490 {
1491 	uint64_t flags = amdgpu_ttm_tt_pde_flags(ttm, mem);
1492 
1493 	flags |= adev->gart.gart_pte_flags;
1494 	flags |= AMDGPU_PTE_READABLE;
1495 
1496 	if (!amdgpu_ttm_tt_is_readonly(ttm))
1497 		flags |= AMDGPU_PTE_WRITEABLE;
1498 
1499 	return flags;
1500 }
1501 
1502 /*
1503  * amdgpu_ttm_bo_eviction_valuable - Check to see if we can evict a buffer
1504  * object.
1505  *
1506  * Return true if eviction is sensible. Called by ttm_mem_evict_first() on
1507  * behalf of ttm_bo_mem_force_space() which tries to evict buffer objects until
1508  * it can find space for a new object and by ttm_bo_force_list_clean() which is
1509  * used to clean out a memory space.
1510  */
1511 static bool amdgpu_ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
1512 					    const struct ttm_place *place)
1513 {
1514 	struct dma_resv_iter resv_cursor;
1515 	struct amdgpu_bo *abo;
1516 	struct dma_fence *f;
1517 
1518 	if (!amdgpu_bo_is_amdgpu_bo(bo))
1519 		return ttm_bo_eviction_valuable(bo, place);
1520 
1521 	/* Swapout? */
1522 	if (bo->resource->mem_type == TTM_PL_SYSTEM)
1523 		return true;
1524 
1525 	abo = ttm_to_amdgpu_bo(bo);
1526 	if ((abo->flags & AMDGPU_GEM_CREATE_DISCARDABLE) &&
1527 	    bo->destroy == &svm_range_bo_destroy) {
1528 		/*
1529 		 * SVM BOs are migrated to system memory synchronously in this
1530 		 * TTM eviction context. The migration needs the owning
1531 		 * process's mmap lock, but the normal lock order is
1532 		 * mmap_lock -> BO reservation and the BO is already reserved
1533 		 * here. svm_range_evict_svm_bo() only trylocks the mmap lock;
1534 		 * if the eviction fails for any reason, we return false so TTM
1535 		 * skips this BO instead of risking a deadlock.
1536 		 */
1537 		if (svm_range_evict_svm_bo(abo) < 0)
1538 			return false;
1539 	}
1540 
1541 	if (bo->type == ttm_bo_type_kernel &&
1542 	    !amdgpu_vm_evictable(ttm_to_amdgpu_bo(bo)))
1543 		return false;
1544 
1545 	/* If bo is a KFD BO, check if the bo belongs to the current process.
1546 	 * If true, then return false as any KFD process needs all its BOs to
1547 	 * be resident to run successfully
1548 	 */
1549 	dma_resv_for_each_fence(&resv_cursor, bo->base.resv,
1550 				DMA_RESV_USAGE_BOOKKEEP, f) {
1551 		if (amdkfd_fence_check_mm(f, current->mm) &&
1552 		    !(place && (place->flags & TTM_PL_FLAG_CONTIGUOUS)))
1553 			return false;
1554 	}
1555 
1556 	/* Preemptible BOs don't own system resources managed by the
1557 	 * driver (pages, VRAM, GART space). They point to resources
1558 	 * owned by someone else (e.g. pageable memory in user mode
1559 	 * or a DMABuf). They are used in a preemptible context so we
1560 	 * can guarantee no deadlocks and good QoS in case of MMU
1561 	 * notifiers or DMABuf move notifiers from the resource owner.
1562 	 */
1563 	if (bo->resource->mem_type == AMDGPU_PL_PREEMPT)
1564 		return false;
1565 
1566 	if (bo->resource->mem_type == TTM_PL_TT &&
1567 	    amdgpu_bo_encrypted(ttm_to_amdgpu_bo(bo)))
1568 		return false;
1569 
1570 	return ttm_bo_eviction_valuable(bo, place);
1571 }
1572 
1573 static void amdgpu_ttm_vram_mm_access(struct amdgpu_device *adev, loff_t pos,
1574 				      void *buf, size_t size, bool write)
1575 {
1576 	while (size) {
1577 		uint64_t aligned_pos = ALIGN_DOWN(pos, 4);
1578 		uint64_t bytes = 4 - (pos & 0x3);
1579 		uint32_t shift = (pos & 0x3) * 8;
1580 		uint32_t mask = 0xffffffff << shift;
1581 		uint32_t value = 0;
1582 
1583 		if (size < bytes) {
1584 			mask &= 0xffffffff >> (bytes - size) * 8;
1585 			bytes = size;
1586 		}
1587 
1588 		if (mask != 0xffffffff) {
1589 			amdgpu_device_mm_access(adev, aligned_pos, &value, 4, false);
1590 			if (write) {
1591 				value &= ~mask;
1592 				value |= (*(uint32_t *)buf << shift) & mask;
1593 				amdgpu_device_mm_access(adev, aligned_pos, &value, 4, true);
1594 			} else {
1595 				value = (value & mask) >> shift;
1596 				memcpy(buf, &value, bytes);
1597 			}
1598 		} else {
1599 			amdgpu_device_mm_access(adev, aligned_pos, buf, 4, write);
1600 		}
1601 
1602 		pos += bytes;
1603 		buf += bytes;
1604 		size -= bytes;
1605 	}
1606 }
1607 
1608 static int amdgpu_ttm_access_memory_sdma(struct ttm_buffer_object *bo,
1609 					unsigned long offset, void *buf,
1610 					int len, int write)
1611 {
1612 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1613 	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1614 	struct amdgpu_res_cursor src_mm;
1615 	struct amdgpu_job *job;
1616 	struct dma_fence *fence;
1617 	uint64_t src_addr, dst_addr;
1618 	unsigned int num_dw;
1619 	int r, idx;
1620 
1621 	if (len != PAGE_SIZE)
1622 		return -EINVAL;
1623 
1624 	if (!adev->mman.sdma_access_ptr)
1625 		return -EACCES;
1626 
1627 	if (!adev->mman.buffer_funcs_enabled || !drm_dev_enter(adev_to_drm(adev), &idx))
1628 		return -ENODEV;
1629 
1630 	if (write)
1631 		memcpy(adev->mman.sdma_access_ptr, buf, len);
1632 
1633 	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
1634 	r = amdgpu_job_alloc_with_ib(adev, &adev->mman.default_entity.base,
1635 				     AMDGPU_FENCE_OWNER_UNDEFINED,
1636 				     num_dw * 4, AMDGPU_IB_POOL_DELAYED,
1637 				     AMDGPU_KERNEL_JOB_ID_TTM_ACCESS_MEMORY_SDMA,
1638 				     &job);
1639 	if (r)
1640 		goto out;
1641 
1642 	mutex_lock(&adev->mman.default_entity.lock);
1643 	amdgpu_res_first(abo->tbo.resource, offset, len, &src_mm);
1644 	src_addr = amdgpu_ttm_domain_start(adev, bo->resource->mem_type) +
1645 		src_mm.start;
1646 	dst_addr = amdgpu_bo_gpu_offset(adev->mman.sdma_access_bo);
1647 	if (write)
1648 		swap(src_addr, dst_addr);
1649 
1650 	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr, dst_addr,
1651 				PAGE_SIZE, 0);
1652 
1653 	fence = amdgpu_ttm_job_submit(adev, &adev->mman.default_entity, job, num_dw);
1654 	mutex_unlock(&adev->mman.default_entity.lock);
1655 
1656 	if (!dma_fence_wait_timeout(fence, false, adev->sdma_timeout))
1657 		r = -ETIMEDOUT;
1658 	dma_fence_put(fence);
1659 
1660 	if (!(r || write))
1661 		memcpy(buf, adev->mman.sdma_access_ptr, len);
1662 out:
1663 	drm_dev_exit(idx);
1664 	return r;
1665 }
1666 
1667 /**
1668  * amdgpu_ttm_access_memory - Read or Write memory that backs a buffer object.
1669  *
1670  * @bo:  The buffer object to read/write
1671  * @offset:  Offset into buffer object
1672  * @buf:  Secondary buffer to write/read from
1673  * @len: Length in bytes of access
1674  * @write:  true if writing
1675  *
1676  * This is used to access VRAM that backs a buffer object via MMIO
1677  * access for debugging purposes.
1678  */
1679 static int amdgpu_ttm_access_memory(struct ttm_buffer_object *bo,
1680 				    unsigned long offset, void *buf, int len,
1681 				    int write)
1682 {
1683 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1684 	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1685 	struct amdgpu_res_cursor cursor;
1686 	int ret = 0;
1687 
1688 	if (bo->resource->mem_type != TTM_PL_VRAM)
1689 		return -EIO;
1690 
1691 	if (amdgpu_device_has_timeouts_enabled(adev) &&
1692 			!amdgpu_ttm_access_memory_sdma(bo, offset, buf, len, write))
1693 		return len;
1694 
1695 	amdgpu_res_first(bo->resource, offset, len, &cursor);
1696 	while (cursor.remaining) {
1697 		size_t count, size = cursor.size;
1698 		loff_t pos = cursor.start;
1699 
1700 		count = amdgpu_device_aper_access(adev, pos, buf, size, write);
1701 		size -= count;
1702 		if (size) {
1703 			/* using MM to access rest vram and handle un-aligned address */
1704 			pos += count;
1705 			buf += count;
1706 			amdgpu_ttm_vram_mm_access(adev, pos, buf, size, write);
1707 		}
1708 
1709 		ret += cursor.size;
1710 		buf += cursor.size;
1711 		amdgpu_res_next(&cursor, cursor.size);
1712 	}
1713 
1714 	return ret;
1715 }
1716 
1717 static void
1718 amdgpu_bo_delete_mem_notify(struct ttm_buffer_object *bo)
1719 {
1720 	if (bo->resource && bo->resource->mem_type == TTM_PL_TT)
1721 		amdgpu_gtt_mgr_mark_bo_teardown(bo);
1722 
1723 	amdgpu_bo_move_notify(bo, false, NULL);
1724 }
1725 
1726 static struct ttm_device_funcs amdgpu_bo_driver = {
1727 	.ttm_tt_create = &amdgpu_ttm_tt_create,
1728 	.ttm_tt_populate = &amdgpu_ttm_tt_populate,
1729 	.ttm_tt_unpopulate = &amdgpu_ttm_tt_unpopulate,
1730 	.ttm_tt_destroy = &amdgpu_ttm_backend_destroy,
1731 	.eviction_valuable = amdgpu_ttm_bo_eviction_valuable,
1732 	.evict_flags = &amdgpu_evict_flags,
1733 	.move = &amdgpu_bo_move,
1734 	.delete_mem_notify = &amdgpu_bo_delete_mem_notify,
1735 	.release_notify = &amdgpu_bo_release_notify,
1736 	.io_mem_reserve = &amdgpu_ttm_io_mem_reserve,
1737 	.io_mem_pfn = amdgpu_ttm_io_mem_pfn,
1738 	.access_memory = &amdgpu_ttm_access_memory,
1739 };
1740 
1741 void amdgpu_ttm_init_vram_resv(struct amdgpu_device *adev,
1742 				enum amdgpu_resv_region_id id,
1743 				uint64_t offset, uint64_t size,
1744 				bool needs_cpu_map)
1745 {
1746 	struct amdgpu_vram_resv *resv;
1747 
1748 	if (id >= AMDGPU_RESV_MAX)
1749 		return;
1750 
1751 	resv = &adev->mman.resv_region[id];
1752 	resv->offset = offset;
1753 	resv->size = size;
1754 	resv->needs_cpu_map = needs_cpu_map;
1755 }
1756 
1757 static void amdgpu_ttm_init_fw_resv_region(struct amdgpu_device *adev)
1758 {
1759 	u64 reserve_size = 0, offset = 0;
1760 
1761 	if (!adev->discovery.reserve_tmr)
1762 		return;
1763 
1764 	/*
1765 	 * Query reserved tmr size through atom firmwareinfo for Sienna_Cichlid and onwards for all
1766 	 * the use cases (IP discovery/G6 memory training/profiling/diagnostic data.etc)
1767 	 *
1768 	 * Otherwise, fallback to legacy approach to check and reserve tmr block for ip
1769 	 * discovery data and G6 memory training data respectively
1770 	 */
1771 	if (adev->bios) {
1772 		reserve_size =
1773 			amdgpu_atomfirmware_get_fw_reserved_fb_size(adev);
1774 		if (reserve_size)
1775 			offset = adev->gmc.real_vram_size - reserve_size;
1776 	}
1777 
1778 	if (!adev->bios &&
1779 	    (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3) ||
1780 	     amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 4) ||
1781 	     amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 5, 0))) {
1782 		reserve_size = (u64)280 << 20;
1783 		offset = adev->gmc.real_vram_size - reserve_size;
1784 	} else if (adev->asic_funcs && adev->asic_funcs->get_fw_reserved_info) {
1785 		dev_dbg(adev->dev, "Querying FW reserved region info through get_fw_reserved_info\n");
1786 		adev->asic_funcs->get_fw_reserved_info(adev, &reserve_size, &offset);
1787 	} else if (!reserve_size) {
1788 		reserve_size = DISCOVERY_TMR_OFFSET;
1789 		offset = adev->gmc.real_vram_size - reserve_size;
1790 	}
1791 	amdgpu_ttm_init_vram_resv(adev, AMDGPU_RESV_FW,
1792 				offset,	reserve_size, false);
1793 }
1794 
1795 static void amdgpu_ttm_init_mem_train_resv_region(struct amdgpu_device *adev)
1796 {
1797 	uint64_t reserve_size;
1798 	uint64_t offset;
1799 
1800 	if (!adev->discovery.reserve_tmr)
1801 		return;
1802 
1803 	if (!adev->bios || amdgpu_sriov_vf(adev))
1804 		return;
1805 
1806 	if (!amdgpu_atomfirmware_mem_training_supported(adev))
1807 		return;
1808 
1809 	reserve_size = adev->mman.resv_region[AMDGPU_RESV_FW].size;
1810 	offset = ALIGN((adev->gmc.mc_vram_size - reserve_size - SZ_1M), SZ_1M);
1811 	amdgpu_ttm_init_vram_resv(adev, AMDGPU_RESV_MEM_TRAIN,
1812 				  offset,
1813 				  GDDR6_MEM_TRAINING_DATA_SIZE_IN_BYTES,
1814 				  false);
1815 }
1816 
1817 static void amdgpu_ttm_init_vram_resv_regions(struct amdgpu_device *adev)
1818 {
1819 	uint64_t vram_size = adev->gmc.visible_vram_size;
1820 
1821 	/* Initialize memory reservations as required for VGA.
1822 	 * This is used for VGA emulation and pre-OS scanout buffers to
1823 	 * avoid display artifacts while transitioning between pre-OS
1824 	 * and driver.
1825 	 */
1826 	amdgpu_gmc_init_vga_resv_regions(adev);
1827 	amdgpu_ttm_init_fw_resv_region(adev);
1828 	amdgpu_ttm_init_mem_train_resv_region(adev);
1829 
1830 	if (adev->mman.resv_region[AMDGPU_RESV_FW_VRAM_USAGE].size > vram_size)
1831 		adev->mman.resv_region[AMDGPU_RESV_FW_VRAM_USAGE].size = 0;
1832 
1833 	if (adev->mman.resv_region[AMDGPU_RESV_DRV_VRAM_USAGE].size > vram_size)
1834 		adev->mman.resv_region[AMDGPU_RESV_DRV_VRAM_USAGE].size = 0;
1835 }
1836 
1837 int amdgpu_ttm_mark_vram_reserved(struct amdgpu_device *adev,
1838 				  enum amdgpu_resv_region_id id)
1839 {
1840 	struct amdgpu_vram_resv *resv;
1841 	int ret;
1842 
1843 	if (id >= AMDGPU_RESV_MAX)
1844 		return -EINVAL;
1845 
1846 	resv = &adev->mman.resv_region[id];
1847 	if (!resv->size)
1848 		return 0;
1849 
1850 	ret = amdgpu_bo_create_kernel_at(adev, resv->offset, resv->size,
1851 					 &resv->bo,
1852 					 resv->needs_cpu_map ? &resv->cpu_ptr : NULL);
1853 	if (ret) {
1854 		dev_err(adev->dev,
1855 			"reserve vram failed: id=%d offset=0x%llx size=0x%llx ret=%d\n",
1856 			id, resv->offset, resv->size, ret);
1857 		memset(resv, 0, sizeof(*resv));
1858 	}
1859 
1860 	return ret;
1861 }
1862 
1863 void amdgpu_ttm_unmark_vram_reserved(struct amdgpu_device *adev,
1864 				     enum amdgpu_resv_region_id id)
1865 {
1866 	struct amdgpu_vram_resv *resv;
1867 
1868 	if (id >= AMDGPU_RESV_MAX)
1869 		return;
1870 
1871 	resv = &adev->mman.resv_region[id];
1872 	if (!resv->bo)
1873 		return;
1874 
1875 	amdgpu_bo_free_kernel(&resv->bo, NULL,
1876 			      resv->needs_cpu_map ? &resv->cpu_ptr : NULL);
1877 	memset(resv, 0, sizeof(*resv));
1878 }
1879 
1880 /*
1881  * Reserve all regions with non-zero size. Regions whose info is not
1882  * yet available (e.g., fw extended region) may still be reserved
1883  * during runtime.
1884  */
1885 static int amdgpu_ttm_alloc_vram_resv_regions(struct amdgpu_device *adev)
1886 {
1887 	int i, r;
1888 
1889 	for (i = 0; i < AMDGPU_RESV_MAX; i++) {
1890 		r = amdgpu_ttm_mark_vram_reserved(adev, i);
1891 		if (r)
1892 			return r;
1893 	}
1894 
1895 	return 0;
1896 }
1897 
1898 /*
1899  * Memoy training reservation functions
1900  */
1901 
1902 /**
1903  * amdgpu_ttm_training_reserve_vram_fini - free memory training reserved vram
1904  *
1905  * @adev: amdgpu_device pointer
1906  *
1907  * free memory training reserved vram if it has been reserved.
1908  */
1909 static int amdgpu_ttm_training_reserve_vram_fini(struct amdgpu_device *adev)
1910 {
1911 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1912 
1913 	ctx->init = PSP_MEM_TRAIN_NOT_SUPPORT;
1914 	amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_MEM_TRAIN);
1915 
1916 	return 0;
1917 }
1918 
1919 static void amdgpu_ttm_training_data_block_init(struct amdgpu_device *adev)
1920 {
1921 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1922 	struct amdgpu_vram_resv *resv =
1923 			&adev->mman.resv_region[AMDGPU_RESV_MEM_TRAIN];
1924 
1925 	memset(ctx, 0, sizeof(*ctx));
1926 
1927 	ctx->c2p_train_data_offset = resv->offset;
1928 	ctx->p2c_train_data_offset =
1929 		(adev->gmc.mc_vram_size - GDDR6_MEM_TRAINING_OFFSET);
1930 	ctx->train_data_size = resv->size;
1931 
1932 	DRM_DEBUG("train_data_size:%llx,p2c_train_data_offset:%llx,c2p_train_data_offset:%llx.\n",
1933 			ctx->train_data_size,
1934 			ctx->p2c_train_data_offset,
1935 			ctx->c2p_train_data_offset);
1936 }
1937 
1938 static int amdgpu_ttm_pools_init(struct amdgpu_device *adev)
1939 {
1940 	int i;
1941 
1942 	if (!adev->gmc.is_app_apu || !adev->gmc.num_mem_partitions)
1943 		return 0;
1944 
1945 	adev->mman.ttm_pools = kzalloc_objs(*adev->mman.ttm_pools,
1946 					    adev->gmc.num_mem_partitions);
1947 	if (!adev->mman.ttm_pools)
1948 		return -ENOMEM;
1949 
1950 	for (i = 0; i < adev->gmc.num_mem_partitions; i++) {
1951 		ttm_pool_init(&adev->mman.ttm_pools[i], adev->dev,
1952 			      adev->gmc.mem_partitions[i].numa.node,
1953 			      TTM_ALLOCATION_POOL_BENEFICIAL_ORDER(get_order(SZ_2M)));
1954 	}
1955 	return 0;
1956 }
1957 
1958 static void amdgpu_ttm_pools_fini(struct amdgpu_device *adev)
1959 {
1960 	int i;
1961 
1962 	if (!adev->gmc.is_app_apu || !adev->mman.ttm_pools)
1963 		return;
1964 
1965 	for (i = 0; i < adev->gmc.num_mem_partitions; i++)
1966 		ttm_pool_fini(&adev->mman.ttm_pools[i]);
1967 
1968 	kfree(adev->mman.ttm_pools);
1969 	adev->mman.ttm_pools = NULL;
1970 }
1971 
1972 /**
1973  * amdgpu_ttm_alloc_mmio_remap_bo - Allocate the singleton MMIO_REMAP BO
1974  * @adev: amdgpu device
1975  *
1976  * Allocates a global BO with backing AMDGPU_PL_MMIO_REMAP when the
1977  * hardware exposes a remap base (adev->rmmio_remap.bus_addr) and the host
1978  * PAGE_SIZE is <= AMDGPU_GPU_PAGE_SIZE (4K). The BO is created as a regular
1979  * GEM object (amdgpu_bo_create).
1980  *
1981  * Return:
1982  *  * 0 on success or intentional skip (feature not present/unsupported)
1983  *  * negative errno on allocation failure
1984  */
1985 static int amdgpu_ttm_alloc_mmio_remap_bo(struct amdgpu_device *adev)
1986 {
1987 	struct ttm_operation_ctx ctx = { false, false };
1988 	struct ttm_placement placement;
1989 	struct ttm_buffer_object *tbo;
1990 	struct ttm_place placements;
1991 	struct amdgpu_bo_param bp;
1992 	struct ttm_resource *tmp;
1993 	int r;
1994 
1995 	/* Skip if HW doesn't expose remap, or if PAGE_SIZE > AMDGPU_GPU_PAGE_SIZE (4K). */
1996 	if (!adev->rmmio_remap.bus_addr || PAGE_SIZE > AMDGPU_GPU_PAGE_SIZE)
1997 		return 0;
1998 
1999 	/*
2000 	 * Allocate a BO first and then move it to AMDGPU_PL_MMIO_REMAP.
2001 	 * The initial TTM resource assigned by amdgpu_bo_create() is
2002 	 * replaced below with a fixed MMIO_REMAP placement.
2003 	 */
2004 	memset(&bp, 0, sizeof(bp));
2005 	bp.type        = ttm_bo_type_device;
2006 	bp.size        = AMDGPU_GPU_PAGE_SIZE;
2007 	bp.byte_align  = AMDGPU_GPU_PAGE_SIZE;
2008 	bp.domain      = 0;
2009 	bp.flags       = 0;
2010 	bp.resv        = NULL;
2011 	bp.bo_ptr_size = sizeof(struct amdgpu_bo);
2012 	r = amdgpu_bo_create(adev, &bp, &adev->rmmio_remap.bo);
2013 	if (r)
2014 		return r;
2015 
2016 	r = amdgpu_bo_reserve(adev->rmmio_remap.bo, true);
2017 	if (r)
2018 		goto err_unref;
2019 
2020 	tbo = &adev->rmmio_remap.bo->tbo;
2021 
2022 	/*
2023 	 * MMIO_REMAP is a fixed I/O placement (AMDGPU_PL_MMIO_REMAP).
2024 	 */
2025 	placement.num_placement = 1;
2026 	placement.placement = &placements;
2027 	placements.fpfn = 0;
2028 	placements.lpfn = 0;
2029 	placements.mem_type = AMDGPU_PL_MMIO_REMAP;
2030 	placements.flags = 0;
2031 	/* Force the BO into the fixed MMIO_REMAP placement */
2032 	r = ttm_bo_mem_space(tbo, &placement, &tmp, &ctx);
2033 	if (unlikely(r))
2034 		goto err_unlock;
2035 
2036 	ttm_resource_free(tbo, &tbo->resource);
2037 	ttm_bo_assign_mem(tbo, tmp);
2038 	ttm_bo_pin(tbo);
2039 
2040 	amdgpu_bo_unreserve(adev->rmmio_remap.bo);
2041 	return 0;
2042 
2043 err_unlock:
2044 	amdgpu_bo_unreserve(adev->rmmio_remap.bo);
2045 
2046 err_unref:
2047 	amdgpu_bo_unref(&adev->rmmio_remap.bo);
2048 	adev->rmmio_remap.bo = NULL;
2049 	return r;
2050 }
2051 
2052 /**
2053  * amdgpu_ttm_free_mmio_remap_bo - Free the singleton MMIO_REMAP BO
2054  * @adev: amdgpu device
2055  *
2056  * Frees the kernel-owned MMIO_REMAP BO if it was allocated by
2057  * amdgpu_ttm_mmio_remap_bo_init().
2058  */
2059 static void amdgpu_ttm_free_mmio_remap_bo(struct amdgpu_device *adev)
2060 {
2061 	if (!adev->rmmio_remap.bo)
2062 		return;
2063 
2064 	if (!amdgpu_bo_reserve(adev->rmmio_remap.bo, true)) {
2065 		ttm_bo_unpin(&adev->rmmio_remap.bo->tbo);
2066 		amdgpu_bo_unreserve(adev->rmmio_remap.bo);
2067 	}
2068 
2069     /*
2070      * At this point we rely on normal DRM teardown ordering:
2071      * no new user ioctls can access the global MMIO_REMAP BO
2072      * once TTM teardown begins.
2073      */
2074 	amdgpu_bo_unref(&adev->rmmio_remap.bo);
2075 	adev->rmmio_remap.bo = NULL;
2076 }
2077 
2078 static int amdgpu_ttm_buffer_entity_init(struct amdgpu_gtt_mgr *mgr,
2079 					 struct amdgpu_ttm_buffer_entity *entity,
2080 					 enum drm_sched_priority prio,
2081 					 struct drm_gpu_scheduler **scheds,
2082 					 int num_schedulers,
2083 					 u32 num_gart_windows)
2084 {
2085 	int i, r, num_pages;
2086 	const u64 GTT_MAX_PAGES = (AMDGPU_GTT_MAX_TRANSFER_SIZE >> PAGE_SHIFT);
2087 
2088 	if (ARRAY_SIZE(entity->gart_window_offs) < num_gart_windows)
2089 		return -EINVAL;
2090 
2091 	r = drm_sched_entity_init(&entity->base, prio, scheds, num_schedulers, NULL);
2092 	if (r)
2093 		return r;
2094 
2095 	mutex_init(&entity->lock);
2096 
2097 	if (num_gart_windows == 0)
2098 		return 0;
2099 
2100 	num_pages = num_gart_windows * GTT_MAX_PAGES;
2101 	r = amdgpu_gtt_mgr_alloc_entries(mgr, &entity->gart_node, num_pages,
2102 					 DRM_MM_INSERT_BEST);
2103 	if (r) {
2104 		mutex_destroy(&entity->lock);
2105 		drm_sched_entity_destroy(&entity->base);
2106 		return r;
2107 	}
2108 
2109 	for (i = 0; i < num_gart_windows; i++) {
2110 		entity->gart_window_offs[i] =
2111 			amdgpu_gtt_node_to_byte_offset(&entity->gart_node) +
2112 				i * GTT_MAX_PAGES * PAGE_SIZE;
2113 	}
2114 
2115 	return 0;
2116 }
2117 
2118 static void amdgpu_ttm_buffer_entity_fini(struct amdgpu_gtt_mgr *mgr,
2119 					  struct amdgpu_ttm_buffer_entity *entity)
2120 {
2121 	amdgpu_gtt_mgr_free_entries(mgr, &entity->gart_node);
2122 	mutex_destroy(&entity->lock);
2123 	drm_sched_entity_destroy(&entity->base);
2124 }
2125 
2126 /*
2127  * amdgpu_ttm_init - Init the memory management (ttm) as well as various
2128  * gtt/vram related fields.
2129  *
2130  * This initializes all of the memory space pools that the TTM layer
2131  * will need such as the GTT space (system memory mapped to the device),
2132  * VRAM (on-board memory), and on-chip memories (GDS, GWS, OA) which
2133  * can be mapped per VMID.
2134  */
2135 int amdgpu_ttm_init(struct amdgpu_device *adev)
2136 {
2137 	uint64_t gtt_size;
2138 	int r;
2139 
2140 	dma_set_max_seg_size(adev->dev, UINT_MAX);
2141 	/* No others user of address space so set it to 0 */
2142 	r = ttm_device_init(&adev->mman.bdev, &amdgpu_bo_driver, adev->dev,
2143 			       adev_to_drm(adev)->anon_inode->i_mapping,
2144 			       adev_to_drm(adev)->vma_offset_manager,
2145 			       (adev->need_swiotlb ?
2146 				TTM_ALLOCATION_POOL_USE_DMA_ALLOC : 0) |
2147 			       (dma_addressing_limited(adev->dev) ?
2148 				TTM_ALLOCATION_POOL_USE_DMA32 : 0) |
2149 			       TTM_ALLOCATION_POOL_BENEFICIAL_ORDER(get_order(SZ_2M)));
2150 	if (r) {
2151 		dev_err(adev->dev,
2152 			"failed initializing buffer object driver(%d).\n", r);
2153 		return r;
2154 	}
2155 
2156 	r = amdgpu_ttm_pools_init(adev);
2157 	if (r) {
2158 		dev_err(adev->dev, "failed to init ttm pools(%d).\n", r);
2159 		return r;
2160 	}
2161 	adev->mman.initialized = true;
2162 
2163 	if (!adev->gmc.is_app_apu) {
2164 		/* Initialize VRAM pool with all of VRAM divided into pages */
2165 		r = amdgpu_vram_mgr_init(adev);
2166 		if (r) {
2167 			dev_err(adev->dev, "Failed initializing VRAM heap.\n");
2168 			return r;
2169 		}
2170 	}
2171 
2172 	/* Change the size here instead of the init above so only lpfn is affected */
2173 	amdgpu_ttm_disable_buffer_funcs(adev);
2174 #ifdef CONFIG_64BIT
2175 #ifdef CONFIG_X86
2176 	if (adev->gmc.xgmi.connected_to_cpu)
2177 		adev->mman.aper_base_kaddr = ioremap_cache(adev->gmc.aper_base,
2178 				adev->gmc.visible_vram_size);
2179 	else if (adev->gmc.is_app_apu)
2180 		DRM_DEBUG_DRIVER(
2181 			"No need to ioremap when real vram size is 0\n");
2182 	else
2183 #endif
2184 		adev->mman.aper_base_kaddr = ioremap_wc(adev->gmc.aper_base,
2185 				adev->gmc.visible_vram_size);
2186 #endif
2187 
2188 	amdgpu_ttm_init_vram_resv_regions(adev);
2189 
2190 	r = amdgpu_ttm_alloc_vram_resv_regions(adev);
2191 	if (r)
2192 		return r;
2193 
2194 	/* RAS loads and reserves bad pages */
2195 	amdgpu_ras_mgr_early_init_service(adev);
2196 
2197 	if (adev->mman.resv_region[AMDGPU_RESV_MEM_TRAIN].size) {
2198 		struct psp_memory_training_context *ctx =
2199 					&adev->psp.mem_train_ctx;
2200 
2201 		amdgpu_ttm_training_data_block_init(adev);
2202 		ctx->init = PSP_MEM_TRAIN_RESERVE_SUCCESS;
2203 	}
2204 
2205 	dev_info(adev->dev, " %uM of VRAM memory ready\n",
2206 		 (unsigned int)(adev->gmc.real_vram_size / (1024 * 1024)));
2207 
2208 	/* Compute GTT size, either based on TTM limit
2209 	 * or whatever the user passed on module init.
2210 	 */
2211 	gtt_size = ttm_tt_pages_limit() << PAGE_SHIFT;
2212 	if (amdgpu_gtt_size != -1) {
2213 		uint64_t configured_size = (uint64_t)amdgpu_gtt_size << 20;
2214 
2215 		drm_warn(&adev->ddev,
2216 			"Configuring gttsize via module parameter is deprecated, please use ttm.pages_limit\n");
2217 		if (gtt_size != configured_size)
2218 			drm_warn(&adev->ddev,
2219 				"GTT size has been set as %llu but TTM size has been set as %llu, this is unusual\n",
2220 				configured_size, gtt_size);
2221 
2222 		gtt_size = configured_size;
2223 	}
2224 
2225 	/* Cap GTT so that it does not exceed total physical RAM. */
2226 	if (adev->flags & AMD_IS_APU) {
2227 		u64 phys_ram = (u64)totalram_pages() << PAGE_SHIFT;
2228 
2229 		if (gtt_size > phys_ram) {
2230 			gtt_size = phys_ram;
2231 			dev_info(adev->dev,
2232 				 "Capping GTT to %uM to not exceed available system memory\n",
2233 				 (unsigned int)(gtt_size / (1024 * 1024)));
2234 		}
2235 	}
2236 
2237 	/* Initialize GTT memory pool */
2238 	r = amdgpu_gtt_mgr_init(adev, gtt_size);
2239 	if (r) {
2240 		dev_err(adev->dev, "Failed initializing GTT heap.\n");
2241 		return r;
2242 	}
2243 	dev_info(adev->dev, " %uM of GTT memory ready.\n",
2244 		 (unsigned int)(gtt_size / (1024 * 1024)));
2245 
2246 	if (adev->flags & AMD_IS_APU) {
2247 		if (adev->gmc.real_vram_size < gtt_size)
2248 			adev->apu_prefer_gtt = true;
2249 	}
2250 
2251 	/* Initialize doorbell pool on PCI BAR */
2252 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_DOORBELL, adev->doorbell.size / PAGE_SIZE);
2253 	if (r) {
2254 		dev_err(adev->dev, "Failed initializing doorbell heap.\n");
2255 		return r;
2256 	}
2257 
2258 	/* Create a doorbell page for kernel usages */
2259 	r = amdgpu_doorbell_create_kernel_doorbells(adev);
2260 	if (r) {
2261 		dev_err(adev->dev, "Failed to initialize kernel doorbells.\n");
2262 		return r;
2263 	}
2264 
2265 	/* Initialize MMIO-remap pool (single page 4K) */
2266 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_MMIO_REMAP, 1);
2267 	if (r) {
2268 		dev_err(adev->dev, "Failed initializing MMIO-remap heap.\n");
2269 		return r;
2270 	}
2271 
2272 	/* Allocate the singleton MMIO_REMAP BO if supported */
2273 	r = amdgpu_ttm_alloc_mmio_remap_bo(adev);
2274 	if (r)
2275 		return r;
2276 
2277 	/* Initialize preemptible memory pool */
2278 	r = amdgpu_preempt_mgr_init(adev);
2279 	if (r) {
2280 		dev_err(adev->dev, "Failed initializing PREEMPT heap.\n");
2281 		return r;
2282 	}
2283 
2284 	/* Initialize various on-chip memory pools */
2285 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GDS, adev->gds.gds_size);
2286 	if (r) {
2287 		dev_err(adev->dev, "Failed initializing GDS heap.\n");
2288 		return r;
2289 	}
2290 
2291 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GWS, adev->gds.gws_size);
2292 	if (r) {
2293 		dev_err(adev->dev, "Failed initializing gws heap.\n");
2294 		return r;
2295 	}
2296 
2297 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_OA, adev->gds.oa_size);
2298 	if (r) {
2299 		dev_err(adev->dev, "Failed initializing oa heap.\n");
2300 		return r;
2301 	}
2302 
2303 	if (adev->ualink.npa_size) {
2304 		r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_NPA,
2305 					    adev->ualink.npa_size);
2306 		if (r) {
2307 			dev_err(adev->dev, "Failed initializing NPA heap.\n");
2308 			return r;
2309 		}
2310 	}
2311 
2312 	if (amdgpu_bo_create_kernel(adev, PAGE_SIZE, PAGE_SIZE,
2313 				AMDGPU_GEM_DOMAIN_GTT,
2314 				&adev->mman.sdma_access_bo, NULL,
2315 				&adev->mman.sdma_access_ptr))
2316 		drm_warn(adev_to_drm(adev),
2317 				"Debug VRAM access will use slowpath MM access\n");
2318 
2319 	return 0;
2320 }
2321 
2322 /*
2323  * amdgpu_ttm_fini - De-initialize the TTM memory pools
2324  */
2325 void amdgpu_ttm_fini(struct amdgpu_device *adev)
2326 {
2327 	if (!adev->mman.initialized)
2328 		return;
2329 
2330 	amdgpu_ttm_pools_fini(adev);
2331 
2332 	amdgpu_ttm_training_reserve_vram_fini(adev);
2333 	/* return the stolen vga memory back to VRAM */
2334 	if (!adev->gmc.is_app_apu) {
2335 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
2336 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
2337 		/* return the FW reserved memory back to VRAM */
2338 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_FW);
2339 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_FW_EXTEND);
2340 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_RESERVED);
2341 	}
2342 	amdgpu_bo_free_kernel(&adev->mman.sdma_access_bo, NULL,
2343 					&adev->mman.sdma_access_ptr);
2344 
2345 	amdgpu_ttm_free_mmio_remap_bo(adev);
2346 	amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_FW_VRAM_USAGE);
2347 	amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_DRV_VRAM_USAGE);
2348 
2349 	if (adev->mman.aper_base_kaddr) {
2350 		iounmap(adev->mman.aper_base_kaddr);
2351 		adev->mman.aper_base_kaddr = NULL;
2352 	}
2353 
2354 	if (!adev->gmc.is_app_apu)
2355 		amdgpu_vram_mgr_fini(adev);
2356 	amdgpu_gtt_mgr_fini(adev);
2357 	amdgpu_preempt_mgr_fini(adev);
2358 	amdgpu_doorbell_fini(adev);
2359 
2360 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GDS);
2361 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GWS);
2362 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_OA);
2363 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_DOORBELL);
2364 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_MMIO_REMAP);
2365 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_NPA);
2366 	ttm_device_fini(&adev->mman.bdev);
2367 	adev->mman.initialized = false;
2368 	dev_info(adev->dev, " ttm finalized\n");
2369 }
2370 
2371 /**
2372  * amdgpu_ttm_enable_buffer_funcs - enable use of buffer functions
2373  *
2374  * @adev: amdgpu_device pointer
2375  *
2376  * Enable use of buffer functions during suspend/resume. This should
2377  * only be called at bootup or when userspace isn't running.
2378  */
2379 void amdgpu_ttm_enable_buffer_funcs(struct amdgpu_device *adev)
2380 {
2381 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM);
2382 	u32 num_clear_entities, num_move_entities, sdma_ip_version;
2383 	int r, i, j;
2384 
2385 	if (!adev->mman.initialized || amdgpu_in_reset(adev) ||
2386 	    adev->mman.buffer_funcs_enabled || adev->gmc.is_app_apu)
2387 		return;
2388 
2389 	if (!adev->mman.num_buffer_funcs_scheds) {
2390 		dev_warn(adev->dev, "Not enabling DMA transfers for in kernel use");
2391 		return;
2392 	}
2393 
2394 	/* default_entity doesn't need multiple schedulers so pass only 1. */
2395 	r = amdgpu_ttm_buffer_entity_init(&adev->mman.gtt_mgr,
2396 						&adev->mman.default_entity,
2397 						DRM_SCHED_PRIORITY_KERNEL,
2398 						adev->mman.buffer_funcs_scheds, 1, 0);
2399 	if (r < 0) {
2400 		dev_err(adev->dev,
2401 			"Failed setting up TTM entity (%d)\n", r);
2402 		return;
2403 	}
2404 
2405 	num_clear_entities = MIN(adev->mman.num_buffer_funcs_scheds, TTM_NUM_MOVE_FENCES);
2406 	num_move_entities = MIN(adev->mman.num_buffer_funcs_scheds, TTM_NUM_MOVE_FENCES);
2407 	/* TODO: workaround for DCC corruption when moving BOs from multiple queues at
2408 	 * the same time: use a single queue until the root cause is identified and fixed.
2409 	 */
2410 	sdma_ip_version = amdgpu_ip_version(adev, SDMA0_HWIP, 0);
2411 	if (sdma_ip_version == IP_VERSION(7, 0, 0) || sdma_ip_version == IP_VERSION(7, 0, 1))
2412 		num_move_entities = 1;
2413 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 1) ||
2414 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 2) ||
2415 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 3) ||
2416 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 4, 4) ||
2417 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(9, 5, 0) ||
2418 	    amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(12, 1, 0))
2419 		num_clear_entities = 1;
2420 
2421 	adev->mman.clear_entities = kzalloc_objs(struct amdgpu_ttm_buffer_entity,
2422 						 num_clear_entities);
2423 	atomic_set(&adev->mman.next_clear_entity, 0);
2424 	if (!adev->mman.clear_entities)
2425 		goto error_free_default_entity;
2426 
2427 	adev->mman.num_clear_entities = num_clear_entities;
2428 
2429 	for (i = 0; i < num_clear_entities; i++) {
2430 		r = amdgpu_ttm_buffer_entity_init(
2431 			&adev->mman.gtt_mgr,
2432 			&adev->mman.clear_entities[i],
2433 			DRM_SCHED_PRIORITY_KERNEL,
2434 			adev->mman.buffer_funcs_scheds,
2435 			adev->mman.num_buffer_funcs_scheds, 1);
2436 
2437 		if (r < 0) {
2438 			for (j = 0; j < i; j++)
2439 				amdgpu_ttm_buffer_entity_fini(
2440 					&adev->mman.gtt_mgr, &adev->mman.clear_entities[j]);
2441 			adev->mman.num_clear_entities = 0;
2442 			kfree(adev->mman.clear_entities);
2443 			goto error_free_default_entity;
2444 		}
2445 	}
2446 
2447 	adev->mman.num_move_entities = num_move_entities;
2448 	atomic_set(&adev->mman.next_move_entity, 0);
2449 	for (i = 0; i < num_move_entities; i++) {
2450 		r = amdgpu_ttm_buffer_entity_init(
2451 			&adev->mman.gtt_mgr,
2452 			&adev->mman.move_entities[i],
2453 			DRM_SCHED_PRIORITY_KERNEL,
2454 			adev->mman.buffer_funcs_scheds,
2455 			adev->mman.num_buffer_funcs_scheds, 2);
2456 
2457 		if (r < 0) {
2458 			for (j = 0; j < i; j++)
2459 				amdgpu_ttm_buffer_entity_fini(
2460 					&adev->mman.gtt_mgr,
2461 					&adev->mman.move_entities[j]);
2462 			adev->mman.num_move_entities = 0;
2463 			goto error_free_clear_entities;
2464 		}
2465 	}
2466 
2467 	/* this just adjusts TTM size idea, which sets lpfn to the correct value */
2468 	man->size = adev->gmc.real_vram_size;
2469 	adev->mman.buffer_funcs_enabled = true;
2470 
2471 	return;
2472 
2473 error_free_clear_entities:
2474 	for (i = 0; i < adev->mman.num_clear_entities; i++)
2475 		amdgpu_ttm_buffer_entity_fini(&adev->mman.gtt_mgr,
2476 					      &adev->mman.clear_entities[i]);
2477 	kfree(adev->mman.clear_entities);
2478 	adev->mman.clear_entities = NULL;
2479 	adev->mman.num_clear_entities = 0;
2480 error_free_default_entity:
2481 	amdgpu_ttm_buffer_entity_fini(&adev->mman.gtt_mgr,
2482 				      &adev->mman.default_entity);
2483 }
2484 
2485 /**
2486  * amdgpu_ttm_disable_buffer_funcs - disable use of buffer functions
2487  *
2488  * @adev: amdgpu_device pointer
2489  */
2490 void amdgpu_ttm_disable_buffer_funcs(struct amdgpu_device *adev)
2491 {
2492 	struct ttm_resource_manager *man =
2493 		ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM);
2494 	int i;
2495 
2496 	if (!adev->mman.buffer_funcs_enabled || amdgpu_in_reset(adev))
2497 		return;
2498 
2499 	amdgpu_ttm_buffer_entity_fini(&adev->mman.gtt_mgr,
2500 				      &adev->mman.default_entity);
2501 	for (i = 0; i < adev->mman.num_move_entities; i++)
2502 		amdgpu_ttm_buffer_entity_fini(&adev->mman.gtt_mgr,
2503 					      &adev->mman.move_entities[i]);
2504 	for (i = 0; i < adev->mman.num_clear_entities; i++)
2505 		amdgpu_ttm_buffer_entity_fini(&adev->mman.gtt_mgr,
2506 					      &adev->mman.clear_entities[i]);
2507 	/* Drop all the old fences since re-creating the scheduler entities
2508 	 * will allocate new contexts.
2509 	 */
2510 	ttm_resource_manager_cleanup(man);
2511 
2512 	kfree(adev->mman.clear_entities);
2513 	adev->mman.clear_entities = NULL;
2514 	adev->mman.num_clear_entities = 0;
2515 	adev->mman.num_move_entities = 0;
2516 
2517 	man->size = adev->gmc.visible_vram_size;
2518 	adev->mman.buffer_funcs_enabled = false;
2519 }
2520 
2521 static int amdgpu_ttm_prepare_job(struct amdgpu_device *adev,
2522 				  struct amdgpu_ttm_buffer_entity *entity,
2523 				  unsigned int num_dw,
2524 				  struct dma_resv *resv,
2525 				  bool vm_needs_flush,
2526 				  struct amdgpu_job **job,
2527 				  u64 k_job_id)
2528 {
2529 	enum amdgpu_ib_pool_type pool = AMDGPU_IB_POOL_DELAYED;
2530 	int r;
2531 	r = amdgpu_job_alloc_with_ib(adev, &entity->base,
2532 				     AMDGPU_FENCE_OWNER_UNDEFINED,
2533 				     num_dw * 4, pool, k_job_id, job);
2534 	if (r)
2535 		return r;
2536 
2537 	if (vm_needs_flush) {
2538 		(*job)->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gmc.pdb0_bo ?
2539 							adev->gmc.pdb0_bo :
2540 							adev->gart.bo);
2541 		(*job)->vm_needs_flush = true;
2542 	}
2543 	if (!resv)
2544 		return 0;
2545 
2546 	return drm_sched_job_add_resv_dependencies(&(*job)->base, resv,
2547 						   DMA_RESV_USAGE_BOOKKEEP);
2548 }
2549 
2550 static int amdgpu_calc_bytes_per_packet(u32 max_bytes_per_packet,
2551 					u32 byte_count)
2552 {
2553 	/* Byte count is dword-aligned and fits a single packet */
2554 	if (!(byte_count & 0x3) && byte_count <= max_bytes_per_packet)
2555 		return max_bytes_per_packet;
2556 
2557 	/*
2558 	 * Align down maximum byte count to 256 bytes so that
2559 	 * the copy optimally uses all memory channels and
2560 	 * also to ensure that SDMA can use its dword mode, which
2561 	 * is faster.
2562 	 *
2563 	 * This assumes that the starting addresses of BOs are always
2564 	 * dword aligned, which should be the case for every copy
2565 	 * operation in the kernel, because the kernel always copies
2566 	 * pages.
2567 	 */
2568 	return ALIGN_DOWN(max_bytes_per_packet, SZ_256);
2569 }
2570 
2571 int amdgpu_copy_buffer(struct amdgpu_device *adev,
2572 		       struct amdgpu_ttm_buffer_entity *entity,
2573 		       uint64_t src_offset,
2574 		       uint64_t dst_offset, uint32_t byte_count,
2575 		       struct dma_resv *resv,
2576 		       struct dma_fence **fence,
2577 		       bool vm_needs_flush, uint32_t copy_flags)
2578 {
2579 	unsigned int num_loops, num_dw;
2580 	struct amdgpu_ring *ring;
2581 	struct amdgpu_job *job;
2582 	uint32_t max_bytes;
2583 	unsigned int i;
2584 	int r;
2585 
2586 	ring = to_amdgpu_ring(adev->mman.buffer_funcs_scheds[0]);
2587 
2588 	if (!ring->sched.ready) {
2589 		dev_err(adev->dev,
2590 			"Trying to move memory with ring turned off.\n");
2591 		return -EINVAL;
2592 	}
2593 
2594 	max_bytes = amdgpu_calc_bytes_per_packet(adev->mman.buffer_funcs->copy_max_bytes,
2595 						 byte_count);
2596 	num_loops = DIV_ROUND_UP(byte_count, max_bytes);
2597 	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->copy_num_dw, 8);
2598 	r = amdgpu_ttm_prepare_job(adev, entity, num_dw,
2599 				   resv, vm_needs_flush, &job,
2600 				   AMDGPU_KERNEL_JOB_ID_TTM_COPY_BUFFER);
2601 	if (r)
2602 		goto error_free;
2603 
2604 	for (i = 0; i < num_loops; i++) {
2605 		uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
2606 
2607 		amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
2608 					dst_offset, cur_size_in_bytes, copy_flags);
2609 		src_offset += cur_size_in_bytes;
2610 		dst_offset += cur_size_in_bytes;
2611 		byte_count -= cur_size_in_bytes;
2612 	}
2613 
2614 	*fence = amdgpu_ttm_job_submit(adev, entity, job, num_dw);
2615 
2616 	return 0;
2617 
2618 error_free:
2619 	amdgpu_job_free(job);
2620 	dev_err(adev->dev, "Error scheduling IBs (%d)\n", r);
2621 	return r;
2622 }
2623 
2624 static int amdgpu_ttm_fill_mem(struct amdgpu_device *adev,
2625 			       struct amdgpu_ttm_buffer_entity *entity,
2626 			       uint32_t src_data,
2627 			       uint64_t dst_addr, uint32_t byte_count,
2628 			       struct dma_resv *resv,
2629 			       struct dma_fence **fence,
2630 			       bool vm_needs_flush,
2631 			       u64 k_job_id)
2632 {
2633 	unsigned int num_loops, num_dw;
2634 	struct amdgpu_job *job;
2635 	uint32_t max_bytes;
2636 	unsigned int i;
2637 	int r;
2638 
2639 	max_bytes = amdgpu_calc_bytes_per_packet(adev->mman.buffer_funcs->fill_max_bytes,
2640 						 byte_count);
2641 	num_loops = DIV_ROUND_UP_ULL(byte_count, max_bytes);
2642 	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->fill_num_dw, 8);
2643 	r = amdgpu_ttm_prepare_job(adev, entity, num_dw, resv,
2644 				   vm_needs_flush, &job, k_job_id);
2645 	if (r)
2646 		return r;
2647 
2648 	for (i = 0; i < num_loops; i++) {
2649 		uint32_t cur_size = min(byte_count, max_bytes);
2650 
2651 		amdgpu_emit_fill_buffer(adev, &job->ibs[0], src_data, dst_addr,
2652 					cur_size);
2653 
2654 		dst_addr += cur_size;
2655 		byte_count -= cur_size;
2656 	}
2657 
2658 	*fence = amdgpu_ttm_job_submit(adev, entity, job, num_dw);
2659 	return 0;
2660 }
2661 
2662 /**
2663  * amdgpu_ttm_clear_buffer - fill a buffer with 0
2664  * @entity: entity to use
2665  * @bo: the bo to fill
2666  * @resv: fences contained in this reservation will be used as dependencies.
2667  * @out_fence: the fence from the last clear will be stored here. It might be
2668  *             NULL if no job was run.
2669  * @consider_clear_status: true if region reported as cleared by amdgpu_res_cleared()
2670  *                         are skipped.
2671  * @k_job_id: trace id
2672  *
2673  */
2674 int amdgpu_ttm_clear_buffer(struct amdgpu_ttm_buffer_entity *entity,
2675 			    struct amdgpu_bo *bo,
2676 			    struct dma_resv *resv,
2677 			    struct dma_fence **out_fence,
2678 			    bool consider_clear_status,
2679 			    u64 k_job_id)
2680 {
2681 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
2682 	struct dma_fence *fence = NULL;
2683 	struct amdgpu_res_cursor dst;
2684 	bool vm_needs_flush = false;
2685 	int r;
2686 
2687 	if (!entity)
2688 		return -EINVAL;
2689 
2690 	amdgpu_res_first(bo->tbo.resource, 0, amdgpu_bo_size(bo), &dst);
2691 
2692 	mutex_lock(&entity->lock);
2693 	while (dst.remaining) {
2694 		struct dma_fence *next;
2695 		uint64_t cur_size, to;
2696 
2697 		if (consider_clear_status && amdgpu_res_cleared(&dst)) {
2698 			amdgpu_res_next(&dst, dst.size);
2699 			continue;
2700 		}
2701 
2702 		/* Never fill more than 256MiB at once to avoid timeouts */
2703 		cur_size = min(dst.size, 256ULL << 20);
2704 
2705 		r = amdgpu_ttm_map_buffer(entity, &bo->tbo, bo->tbo.resource, &dst,
2706 					  0, false, &cur_size, &to, &vm_needs_flush, false);
2707 		if (r)
2708 			goto error;
2709 
2710 		r = amdgpu_ttm_fill_mem(adev, entity,
2711 					0, to, cur_size, resv,
2712 					&next, vm_needs_flush, k_job_id);
2713 		if (r)
2714 			goto error;
2715 
2716 		dma_fence_put(fence);
2717 		fence = next;
2718 
2719 		amdgpu_res_next(&dst, cur_size);
2720 	}
2721 	r = 0;
2722 
2723 error:
2724 	mutex_unlock(&entity->lock);
2725 	*out_fence = fence;
2726 	return r;
2727 }
2728 
2729 struct amdgpu_ttm_buffer_entity *
2730 amdgpu_ttm_next_clear_entity(struct amdgpu_device *adev)
2731 {
2732 	struct amdgpu_mman *mman = &adev->mman;
2733 	u32 i;
2734 
2735 	if (mman->num_clear_entities == 0)
2736 		return NULL;
2737 
2738 	i = atomic_inc_return(&mman->next_clear_entity) %
2739 			      mman->num_clear_entities;
2740 	return &mman->clear_entities[i];
2741 }
2742 
2743 /**
2744  * amdgpu_ttm_evict_resources - evict memory buffers
2745  * @adev: amdgpu device object
2746  * @mem_type: evicted BO's memory type
2747  *
2748  * Evicts all @mem_type buffers on the lru list of the memory type.
2749  *
2750  * Returns:
2751  * 0 for success or a negative error code on failure.
2752  */
2753 int amdgpu_ttm_evict_resources(struct amdgpu_device *adev, int mem_type)
2754 {
2755 	struct ttm_resource_manager *man;
2756 
2757 	switch (mem_type) {
2758 	case TTM_PL_VRAM:
2759 	case TTM_PL_TT:
2760 	case AMDGPU_PL_GWS:
2761 	case AMDGPU_PL_GDS:
2762 	case AMDGPU_PL_OA:
2763 	case AMDGPU_PL_NPA:
2764 		man = ttm_manager_type(&adev->mman.bdev, mem_type);
2765 		break;
2766 	default:
2767 		dev_err(adev->dev, "Trying to evict invalid memory type\n");
2768 		return -EINVAL;
2769 	}
2770 
2771 	return ttm_resource_manager_evict_all(&adev->mman.bdev, man);
2772 }
2773 
2774 void amdgpu_sdma_set_buffer_funcs_scheds(struct amdgpu_device *adev,
2775 					 const struct amdgpu_buffer_funcs *buffer_funcs)
2776 {
2777 	struct drm_gpu_scheduler *sched;
2778 	struct amdgpu_vmhub *hub;
2779 	int i, n;
2780 
2781 	adev->mman.buffer_funcs = buffer_funcs;
2782 
2783 	for (i = 0, n = 0; i < adev->sdma.num_instances; i++) {
2784 		if (adev->sdma.has_page_queue)
2785 			sched = &adev->sdma.instance[i].page.sched;
2786 		else
2787 			sched = &adev->sdma.instance[i].ring.sched;
2788 
2789 		if (!sched->ready)
2790 			continue;
2791 
2792 		adev->mman.buffer_funcs_scheds[n++] = sched;
2793 	}
2794 
2795 	if (n == 0) {
2796 		adev->mman.num_buffer_funcs_scheds = 0;
2797 		drm_warn(&adev->ddev, "No working sdma ring available\n");
2798 		return;
2799 	}
2800 
2801 	hub = &adev->vmhub[AMDGPU_GFXHUB(0)];
2802 
2803 	/*
2804 	 * Allow using multiple SDMA schedulers only on GPUs where
2805 	 * we are allowed to do concurrent VM flushes.
2806 	 * This consideration is necessary because all GART windows
2807 	 * are mapped in VMID 0 (the kernel VMID) so each buffer
2808 	 * entity would flush VMID 0 concurrently.
2809 	 *
2810 	 * Also consider the SDMA invalidation workaround on
2811 	 * Navi 1x GPUs, which also prevents us from using
2812 	 * multiple SDMA engines on VMID 0 at the same time.
2813 	 */
2814 	adev->mman.num_buffer_funcs_scheds =
2815 		(adev->vm_manager.concurrent_flush &&
2816 		 !hub->sdma_invalidation_workaround) ? n : 1;
2817 }
2818 
2819 #if defined(CONFIG_DEBUG_FS)
2820 
2821 static int amdgpu_ttm_page_pool_show(struct seq_file *m, void *unused)
2822 {
2823 	struct amdgpu_device *adev = m->private;
2824 
2825 	return ttm_pool_debugfs(&adev->mman.bdev.pool, m);
2826 }
2827 
2828 DEFINE_SHOW_ATTRIBUTE(amdgpu_ttm_page_pool);
2829 
2830 /*
2831  * amdgpu_ttm_vram_read - Linear read access to VRAM
2832  *
2833  * Accesses VRAM via MMIO for debugging purposes.
2834  */
2835 static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
2836 				    size_t size, loff_t *pos)
2837 {
2838 	struct amdgpu_device *adev = file_inode(f)->i_private;
2839 	ssize_t result = 0;
2840 
2841 	if (size & 0x3 || *pos & 0x3)
2842 		return -EINVAL;
2843 
2844 	if (*pos >= adev->gmc.mc_vram_size)
2845 		return -ENXIO;
2846 
2847 	size = min(size, (size_t)(adev->gmc.mc_vram_size - *pos));
2848 	while (size) {
2849 		size_t bytes = min(size, AMDGPU_TTM_VRAM_MAX_DW_READ * 4);
2850 		uint32_t value[AMDGPU_TTM_VRAM_MAX_DW_READ];
2851 
2852 		amdgpu_device_vram_access(adev, *pos, value, bytes, false);
2853 		if (copy_to_user(buf, value, bytes))
2854 			return -EFAULT;
2855 
2856 		result += bytes;
2857 		buf += bytes;
2858 		*pos += bytes;
2859 		size -= bytes;
2860 	}
2861 
2862 	return result;
2863 }
2864 
2865 /*
2866  * amdgpu_ttm_vram_write - Linear write access to VRAM
2867  *
2868  * Accesses VRAM via MMIO for debugging purposes.
2869  */
2870 static ssize_t amdgpu_ttm_vram_write(struct file *f, const char __user *buf,
2871 				    size_t size, loff_t *pos)
2872 {
2873 	struct amdgpu_device *adev = file_inode(f)->i_private;
2874 	ssize_t result = 0;
2875 	int r;
2876 
2877 	if (size & 0x3 || *pos & 0x3)
2878 		return -EINVAL;
2879 
2880 	if (*pos >= adev->gmc.mc_vram_size)
2881 		return -ENXIO;
2882 
2883 	while (size) {
2884 		uint32_t value;
2885 
2886 		if (*pos >= adev->gmc.mc_vram_size)
2887 			return result;
2888 
2889 		r = get_user(value, (uint32_t *)buf);
2890 		if (r)
2891 			return r;
2892 
2893 		amdgpu_device_mm_access(adev, *pos, &value, 4, true);
2894 
2895 		result += 4;
2896 		buf += 4;
2897 		*pos += 4;
2898 		size -= 4;
2899 	}
2900 
2901 	return result;
2902 }
2903 
2904 static const struct file_operations amdgpu_ttm_vram_fops = {
2905 	.owner = THIS_MODULE,
2906 	.read = amdgpu_ttm_vram_read,
2907 	.write = amdgpu_ttm_vram_write,
2908 	.llseek = default_llseek,
2909 };
2910 
2911 /*
2912  * amdgpu_iomem_read - Virtual read access to GPU mapped memory
2913  *
2914  * This function is used to read memory that has been mapped to the
2915  * GPU and the known addresses are not physical addresses but instead
2916  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2917  */
2918 static ssize_t amdgpu_iomem_read(struct file *f, char __user *buf,
2919 				 size_t size, loff_t *pos)
2920 {
2921 	struct amdgpu_device *adev = file_inode(f)->i_private;
2922 	struct iommu_domain *dom;
2923 	ssize_t result = 0;
2924 	int r;
2925 
2926 	/* retrieve the IOMMU domain if any for this device */
2927 	dom = iommu_get_domain_for_dev(adev->dev);
2928 
2929 	while (size) {
2930 		phys_addr_t addr = *pos & PAGE_MASK;
2931 		loff_t off = *pos & ~PAGE_MASK;
2932 		size_t bytes = PAGE_SIZE - off;
2933 		unsigned long pfn;
2934 		struct page *p;
2935 		void *ptr;
2936 
2937 		bytes = min(bytes, size);
2938 
2939 		/* Translate the bus address to a physical address.  If
2940 		 * the domain is NULL it means there is no IOMMU active
2941 		 * and the address translation is the identity
2942 		 */
2943 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2944 
2945 		pfn = addr >> PAGE_SHIFT;
2946 		if (!pfn_valid(pfn))
2947 			return -EPERM;
2948 
2949 		p = pfn_to_page(pfn);
2950 		if (p->mapping != adev->mman.bdev.dev_mapping)
2951 			return -EPERM;
2952 
2953 		ptr = kmap_local_page(p);
2954 		r = copy_to_user(buf, ptr + off, bytes);
2955 		kunmap_local(ptr);
2956 		if (r)
2957 			return -EFAULT;
2958 
2959 		size -= bytes;
2960 		*pos += bytes;
2961 		result += bytes;
2962 	}
2963 
2964 	return result;
2965 }
2966 
2967 /*
2968  * amdgpu_iomem_write - Virtual write access to GPU mapped memory
2969  *
2970  * This function is used to write memory that has been mapped to the
2971  * GPU and the known addresses are not physical addresses but instead
2972  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2973  */
2974 static ssize_t amdgpu_iomem_write(struct file *f, const char __user *buf,
2975 				 size_t size, loff_t *pos)
2976 {
2977 	struct amdgpu_device *adev = file_inode(f)->i_private;
2978 	struct iommu_domain *dom;
2979 	ssize_t result = 0;
2980 	int r;
2981 
2982 	dom = iommu_get_domain_for_dev(adev->dev);
2983 
2984 	while (size) {
2985 		phys_addr_t addr = *pos & PAGE_MASK;
2986 		loff_t off = *pos & ~PAGE_MASK;
2987 		size_t bytes = PAGE_SIZE - off;
2988 		unsigned long pfn;
2989 		struct page *p;
2990 		void *ptr;
2991 
2992 		bytes = min(bytes, size);
2993 
2994 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2995 
2996 		pfn = addr >> PAGE_SHIFT;
2997 		if (!pfn_valid(pfn))
2998 			return -EPERM;
2999 
3000 		p = pfn_to_page(pfn);
3001 		if (p->mapping != adev->mman.bdev.dev_mapping)
3002 			return -EPERM;
3003 
3004 		ptr = kmap_local_page(p);
3005 		r = copy_from_user(ptr + off, buf, bytes);
3006 		kunmap_local(ptr);
3007 		if (r)
3008 			return -EFAULT;
3009 
3010 		size -= bytes;
3011 		*pos += bytes;
3012 		result += bytes;
3013 	}
3014 
3015 	return result;
3016 }
3017 
3018 static const struct file_operations amdgpu_ttm_iomem_fops = {
3019 	.owner = THIS_MODULE,
3020 	.read = amdgpu_iomem_read,
3021 	.write = amdgpu_iomem_write,
3022 	.llseek = default_llseek
3023 };
3024 
3025 #endif
3026 
3027 void amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
3028 {
3029 #if defined(CONFIG_DEBUG_FS)
3030 	struct drm_minor *minor = adev_to_drm(adev)->primary;
3031 	struct dentry *root = minor->debugfs_root;
3032 
3033 	debugfs_create_file_size("amdgpu_vram", 0444, root, adev,
3034 				 &amdgpu_ttm_vram_fops, adev->gmc.mc_vram_size);
3035 	debugfs_create_file("amdgpu_iomem", 0444, root, adev,
3036 			    &amdgpu_ttm_iomem_fops);
3037 	debugfs_create_file("ttm_page_pool", 0444, root, adev,
3038 			    &amdgpu_ttm_page_pool_fops);
3039 	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
3040 							     TTM_PL_VRAM),
3041 					    root, "amdgpu_vram_mm");
3042 	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
3043 							     TTM_PL_TT),
3044 					    root, "amdgpu_gtt_mm");
3045 	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
3046 							     AMDGPU_PL_GDS),
3047 					    root, "amdgpu_gds_mm");
3048 	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
3049 							     AMDGPU_PL_GWS),
3050 					    root, "amdgpu_gws_mm");
3051 	ttm_resource_manager_create_debugfs(ttm_manager_type(&adev->mman.bdev,
3052 							     AMDGPU_PL_OA),
3053 					    root, "amdgpu_oa_mm");
3054 
3055 #endif
3056 }
3057