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