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