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