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