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