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