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