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