xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c (revision 15a1fbdcfb519c2bd291ed01c6c94e0b89537a77)
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 != ttm->sg->nents)
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_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 		/* Patch mtype of the second part BO */
1040 		flags &= ~AMDGPU_PTE_MTYPE_VG10_MASK;
1041 		flags |= AMDGPU_PTE_MTYPE_VG10(AMDGPU_MTYPE_NC);
1042 
1043 		r = amdgpu_gart_bind(adev,
1044 				gtt->offset + (page_idx << PAGE_SHIFT),
1045 				ttm->num_pages - page_idx,
1046 				&ttm->pages[page_idx],
1047 				&(gtt->ttm.dma_address[page_idx]), flags);
1048 	} else {
1049 		r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
1050 				     ttm->pages, gtt->ttm.dma_address, flags);
1051 	}
1052 
1053 gart_bind_fail:
1054 	if (r)
1055 		DRM_ERROR("failed to bind %lu pages at 0x%08llX\n",
1056 			  ttm->num_pages, gtt->offset);
1057 
1058 	return r;
1059 }
1060 
1061 /**
1062  * amdgpu_ttm_backend_bind - Bind GTT memory
1063  *
1064  * Called by ttm_tt_bind() on behalf of ttm_bo_handle_move_mem().
1065  * This handles binding GTT memory to the device address space.
1066  */
1067 static int amdgpu_ttm_backend_bind(struct ttm_tt *ttm,
1068 				   struct ttm_mem_reg *bo_mem)
1069 {
1070 	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1071 	struct amdgpu_ttm_tt *gtt = (void*)ttm;
1072 	uint64_t flags;
1073 	int r = 0;
1074 
1075 	if (gtt->userptr) {
1076 		r = amdgpu_ttm_tt_pin_userptr(ttm);
1077 		if (r) {
1078 			DRM_ERROR("failed to pin userptr\n");
1079 			return r;
1080 		}
1081 	}
1082 	if (!ttm->num_pages) {
1083 		WARN(1, "nothing to bind %lu pages for mreg %p back %p!\n",
1084 		     ttm->num_pages, bo_mem, ttm);
1085 	}
1086 
1087 	if (bo_mem->mem_type == AMDGPU_PL_GDS ||
1088 	    bo_mem->mem_type == AMDGPU_PL_GWS ||
1089 	    bo_mem->mem_type == AMDGPU_PL_OA)
1090 		return -EINVAL;
1091 
1092 	if (!amdgpu_gtt_mgr_has_gart_addr(bo_mem)) {
1093 		gtt->offset = AMDGPU_BO_INVALID_OFFSET;
1094 		return 0;
1095 	}
1096 
1097 	/* compute PTE flags relevant to this BO memory */
1098 	flags = amdgpu_ttm_tt_pte_flags(adev, ttm, bo_mem);
1099 
1100 	/* bind pages into GART page tables */
1101 	gtt->offset = (u64)bo_mem->start << PAGE_SHIFT;
1102 	r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
1103 		ttm->pages, gtt->ttm.dma_address, flags);
1104 
1105 	if (r)
1106 		DRM_ERROR("failed to bind %lu pages at 0x%08llX\n",
1107 			  ttm->num_pages, gtt->offset);
1108 	return r;
1109 }
1110 
1111 /**
1112  * amdgpu_ttm_alloc_gart - Allocate GART memory for buffer object
1113  */
1114 int amdgpu_ttm_alloc_gart(struct ttm_buffer_object *bo)
1115 {
1116 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1117 	struct ttm_operation_ctx ctx = { false, false };
1118 	struct amdgpu_ttm_tt *gtt = (void*)bo->ttm;
1119 	struct ttm_mem_reg tmp;
1120 	struct ttm_placement placement;
1121 	struct ttm_place placements;
1122 	uint64_t addr, flags;
1123 	int r;
1124 
1125 	if (bo->mem.start != AMDGPU_BO_INVALID_OFFSET)
1126 		return 0;
1127 
1128 	addr = amdgpu_gmc_agp_addr(bo);
1129 	if (addr != AMDGPU_BO_INVALID_OFFSET) {
1130 		bo->mem.start = addr >> PAGE_SHIFT;
1131 	} else {
1132 
1133 		/* allocate GART space */
1134 		tmp = bo->mem;
1135 		tmp.mm_node = NULL;
1136 		placement.num_placement = 1;
1137 		placement.placement = &placements;
1138 		placement.num_busy_placement = 1;
1139 		placement.busy_placement = &placements;
1140 		placements.fpfn = 0;
1141 		placements.lpfn = adev->gmc.gart_size >> PAGE_SHIFT;
1142 		placements.flags = (bo->mem.placement & ~TTM_PL_MASK_MEM) |
1143 			TTM_PL_FLAG_TT;
1144 
1145 		r = ttm_bo_mem_space(bo, &placement, &tmp, &ctx);
1146 		if (unlikely(r))
1147 			return r;
1148 
1149 		/* compute PTE flags for this buffer object */
1150 		flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, &tmp);
1151 
1152 		/* Bind pages */
1153 		gtt->offset = (u64)tmp.start << PAGE_SHIFT;
1154 		r = amdgpu_ttm_gart_bind(adev, bo, flags);
1155 		if (unlikely(r)) {
1156 			ttm_bo_mem_put(bo, &tmp);
1157 			return r;
1158 		}
1159 
1160 		ttm_bo_mem_put(bo, &bo->mem);
1161 		bo->mem = tmp;
1162 	}
1163 
1164 	bo->offset = (bo->mem.start << PAGE_SHIFT) +
1165 		bo->bdev->man[bo->mem.mem_type].gpu_offset;
1166 
1167 	return 0;
1168 }
1169 
1170 /**
1171  * amdgpu_ttm_recover_gart - Rebind GTT pages
1172  *
1173  * Called by amdgpu_gtt_mgr_recover() from amdgpu_device_reset() to
1174  * rebind GTT pages during a GPU reset.
1175  */
1176 int amdgpu_ttm_recover_gart(struct ttm_buffer_object *tbo)
1177 {
1178 	struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
1179 	uint64_t flags;
1180 	int r;
1181 
1182 	if (!tbo->ttm)
1183 		return 0;
1184 
1185 	flags = amdgpu_ttm_tt_pte_flags(adev, tbo->ttm, &tbo->mem);
1186 	r = amdgpu_ttm_gart_bind(adev, tbo, flags);
1187 
1188 	return r;
1189 }
1190 
1191 /**
1192  * amdgpu_ttm_backend_unbind - Unbind GTT mapped pages
1193  *
1194  * Called by ttm_tt_unbind() on behalf of ttm_bo_move_ttm() and
1195  * ttm_tt_destroy().
1196  */
1197 static int amdgpu_ttm_backend_unbind(struct ttm_tt *ttm)
1198 {
1199 	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1200 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1201 	int r;
1202 
1203 	/* if the pages have userptr pinning then clear that first */
1204 	if (gtt->userptr)
1205 		amdgpu_ttm_tt_unpin_userptr(ttm);
1206 
1207 	if (gtt->offset == AMDGPU_BO_INVALID_OFFSET)
1208 		return 0;
1209 
1210 	/* unbind shouldn't be done for GDS/GWS/OA in ttm_bo_clean_mm */
1211 	r = amdgpu_gart_unbind(adev, gtt->offset, ttm->num_pages);
1212 	if (r)
1213 		DRM_ERROR("failed to unbind %lu pages at 0x%08llX\n",
1214 			  gtt->ttm.ttm.num_pages, gtt->offset);
1215 	return r;
1216 }
1217 
1218 static void amdgpu_ttm_backend_destroy(struct ttm_tt *ttm)
1219 {
1220 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1221 
1222 	if (gtt->usertask)
1223 		put_task_struct(gtt->usertask);
1224 
1225 	ttm_dma_tt_fini(&gtt->ttm);
1226 	kfree(gtt);
1227 }
1228 
1229 static struct ttm_backend_func amdgpu_backend_func = {
1230 	.bind = &amdgpu_ttm_backend_bind,
1231 	.unbind = &amdgpu_ttm_backend_unbind,
1232 	.destroy = &amdgpu_ttm_backend_destroy,
1233 };
1234 
1235 /**
1236  * amdgpu_ttm_tt_create - Create a ttm_tt object for a given BO
1237  *
1238  * @bo: The buffer object to create a GTT ttm_tt object around
1239  *
1240  * Called by ttm_tt_create().
1241  */
1242 static struct ttm_tt *amdgpu_ttm_tt_create(struct ttm_buffer_object *bo,
1243 					   uint32_t page_flags)
1244 {
1245 	struct amdgpu_ttm_tt *gtt;
1246 
1247 	gtt = kzalloc(sizeof(struct amdgpu_ttm_tt), GFP_KERNEL);
1248 	if (gtt == NULL) {
1249 		return NULL;
1250 	}
1251 	gtt->ttm.ttm.func = &amdgpu_backend_func;
1252 	gtt->gobj = &bo->base;
1253 
1254 	/* allocate space for the uninitialized page entries */
1255 	if (ttm_sg_tt_init(&gtt->ttm, bo, page_flags)) {
1256 		kfree(gtt);
1257 		return NULL;
1258 	}
1259 	return &gtt->ttm.ttm;
1260 }
1261 
1262 /**
1263  * amdgpu_ttm_tt_populate - Map GTT pages visible to the device
1264  *
1265  * Map the pages of a ttm_tt object to an address space visible
1266  * to the underlying device.
1267  */
1268 static int amdgpu_ttm_tt_populate(struct ttm_tt *ttm,
1269 			struct ttm_operation_ctx *ctx)
1270 {
1271 	struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
1272 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1273 
1274 	/* user pages are bound by amdgpu_ttm_tt_pin_userptr() */
1275 	if (gtt && gtt->userptr) {
1276 		ttm->sg = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
1277 		if (!ttm->sg)
1278 			return -ENOMEM;
1279 
1280 		ttm->page_flags |= TTM_PAGE_FLAG_SG;
1281 		ttm->state = tt_unbound;
1282 		return 0;
1283 	}
1284 
1285 	if (ttm->page_flags & TTM_PAGE_FLAG_SG) {
1286 		if (!ttm->sg) {
1287 			struct dma_buf_attachment *attach;
1288 			struct sg_table *sgt;
1289 
1290 			attach = gtt->gobj->import_attach;
1291 			sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
1292 			if (IS_ERR(sgt))
1293 				return PTR_ERR(sgt);
1294 
1295 			ttm->sg = sgt;
1296 		}
1297 
1298 		drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
1299 						 gtt->ttm.dma_address,
1300 						 ttm->num_pages);
1301 		ttm->state = tt_unbound;
1302 		return 0;
1303 	}
1304 
1305 #ifdef CONFIG_SWIOTLB
1306 	if (adev->need_swiotlb && swiotlb_nr_tbl()) {
1307 		return ttm_dma_populate(&gtt->ttm, adev->dev, ctx);
1308 	}
1309 #endif
1310 
1311 	/* fall back to generic helper to populate the page array
1312 	 * and map them to the device */
1313 	return ttm_populate_and_map_pages(adev->dev, &gtt->ttm, ctx);
1314 }
1315 
1316 /**
1317  * amdgpu_ttm_tt_unpopulate - unmap GTT pages and unpopulate page arrays
1318  *
1319  * Unmaps pages of a ttm_tt object from the device address space and
1320  * unpopulates the page array backing it.
1321  */
1322 static void amdgpu_ttm_tt_unpopulate(struct ttm_tt *ttm)
1323 {
1324 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1325 	struct amdgpu_device *adev;
1326 
1327 	if (gtt && gtt->userptr) {
1328 		amdgpu_ttm_tt_set_user_pages(ttm, NULL);
1329 		kfree(ttm->sg);
1330 		ttm->page_flags &= ~TTM_PAGE_FLAG_SG;
1331 		return;
1332 	}
1333 
1334 	if (ttm->sg && gtt->gobj->import_attach) {
1335 		struct dma_buf_attachment *attach;
1336 
1337 		attach = gtt->gobj->import_attach;
1338 		dma_buf_unmap_attachment(attach, ttm->sg, DMA_BIDIRECTIONAL);
1339 		ttm->sg = NULL;
1340 		return;
1341 	}
1342 
1343 	if (ttm->page_flags & TTM_PAGE_FLAG_SG)
1344 		return;
1345 
1346 	adev = amdgpu_ttm_adev(ttm->bdev);
1347 
1348 #ifdef CONFIG_SWIOTLB
1349 	if (adev->need_swiotlb && swiotlb_nr_tbl()) {
1350 		ttm_dma_unpopulate(&gtt->ttm, adev->dev);
1351 		return;
1352 	}
1353 #endif
1354 
1355 	/* fall back to generic helper to unmap and unpopulate array */
1356 	ttm_unmap_and_unpopulate_pages(adev->dev, &gtt->ttm);
1357 }
1358 
1359 /**
1360  * amdgpu_ttm_tt_set_userptr - Initialize userptr GTT ttm_tt for the current
1361  * task
1362  *
1363  * @ttm: The ttm_tt object to bind this userptr object to
1364  * @addr:  The address in the current tasks VM space to use
1365  * @flags: Requirements of userptr object.
1366  *
1367  * Called by amdgpu_gem_userptr_ioctl() to bind userptr pages
1368  * to current task
1369  */
1370 int amdgpu_ttm_tt_set_userptr(struct ttm_tt *ttm, uint64_t addr,
1371 			      uint32_t flags)
1372 {
1373 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1374 
1375 	if (gtt == NULL)
1376 		return -EINVAL;
1377 
1378 	gtt->userptr = addr;
1379 	gtt->userflags = flags;
1380 
1381 	if (gtt->usertask)
1382 		put_task_struct(gtt->usertask);
1383 	gtt->usertask = current->group_leader;
1384 	get_task_struct(gtt->usertask);
1385 
1386 	return 0;
1387 }
1388 
1389 /**
1390  * amdgpu_ttm_tt_get_usermm - Return memory manager for ttm_tt object
1391  */
1392 struct mm_struct *amdgpu_ttm_tt_get_usermm(struct ttm_tt *ttm)
1393 {
1394 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1395 
1396 	if (gtt == NULL)
1397 		return NULL;
1398 
1399 	if (gtt->usertask == NULL)
1400 		return NULL;
1401 
1402 	return gtt->usertask->mm;
1403 }
1404 
1405 /**
1406  * amdgpu_ttm_tt_affect_userptr - Determine if a ttm_tt object lays inside an
1407  * address range for the current task.
1408  *
1409  */
1410 bool amdgpu_ttm_tt_affect_userptr(struct ttm_tt *ttm, unsigned long start,
1411 				  unsigned long end)
1412 {
1413 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1414 	unsigned long size;
1415 
1416 	if (gtt == NULL || !gtt->userptr)
1417 		return false;
1418 
1419 	/* Return false if no part of the ttm_tt object lies within
1420 	 * the range
1421 	 */
1422 	size = (unsigned long)gtt->ttm.ttm.num_pages * PAGE_SIZE;
1423 	if (gtt->userptr > end || gtt->userptr + size <= start)
1424 		return false;
1425 
1426 	return true;
1427 }
1428 
1429 /**
1430  * amdgpu_ttm_tt_is_userptr - Have the pages backing by userptr?
1431  */
1432 bool amdgpu_ttm_tt_is_userptr(struct ttm_tt *ttm)
1433 {
1434 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1435 
1436 	if (gtt == NULL || !gtt->userptr)
1437 		return false;
1438 
1439 	return true;
1440 }
1441 
1442 /**
1443  * amdgpu_ttm_tt_is_readonly - Is the ttm_tt object read only?
1444  */
1445 bool amdgpu_ttm_tt_is_readonly(struct ttm_tt *ttm)
1446 {
1447 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1448 
1449 	if (gtt == NULL)
1450 		return false;
1451 
1452 	return !!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1453 }
1454 
1455 /**
1456  * amdgpu_ttm_tt_pde_flags - Compute PDE flags for ttm_tt object
1457  *
1458  * @ttm: The ttm_tt object to compute the flags for
1459  * @mem: The memory registry backing this ttm_tt object
1460  *
1461  * Figure out the flags to use for a VM PDE (Page Directory Entry).
1462  */
1463 uint64_t amdgpu_ttm_tt_pde_flags(struct ttm_tt *ttm, struct ttm_mem_reg *mem)
1464 {
1465 	uint64_t flags = 0;
1466 
1467 	if (mem && mem->mem_type != TTM_PL_SYSTEM)
1468 		flags |= AMDGPU_PTE_VALID;
1469 
1470 	if (mem && mem->mem_type == TTM_PL_TT) {
1471 		flags |= AMDGPU_PTE_SYSTEM;
1472 
1473 		if (ttm->caching_state == tt_cached)
1474 			flags |= AMDGPU_PTE_SNOOPED;
1475 	}
1476 
1477 	return flags;
1478 }
1479 
1480 /**
1481  * amdgpu_ttm_tt_pte_flags - Compute PTE flags for ttm_tt object
1482  *
1483  * @ttm: The ttm_tt object to compute the flags for
1484  * @mem: The memory registry backing this ttm_tt object
1485 
1486  * Figure out the flags to use for a VM PTE (Page Table Entry).
1487  */
1488 uint64_t amdgpu_ttm_tt_pte_flags(struct amdgpu_device *adev, struct ttm_tt *ttm,
1489 				 struct ttm_mem_reg *mem)
1490 {
1491 	uint64_t flags = amdgpu_ttm_tt_pde_flags(ttm, mem);
1492 
1493 	flags |= adev->gart.gart_pte_flags;
1494 	flags |= AMDGPU_PTE_READABLE;
1495 
1496 	if (!amdgpu_ttm_tt_is_readonly(ttm))
1497 		flags |= AMDGPU_PTE_WRITEABLE;
1498 
1499 	return flags;
1500 }
1501 
1502 /**
1503  * amdgpu_ttm_bo_eviction_valuable - Check to see if we can evict a buffer
1504  * object.
1505  *
1506  * Return true if eviction is sensible. Called by ttm_mem_evict_first() on
1507  * behalf of ttm_bo_mem_force_space() which tries to evict buffer objects until
1508  * it can find space for a new object and by ttm_bo_force_list_clean() which is
1509  * used to clean out a memory space.
1510  */
1511 static bool amdgpu_ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
1512 					    const struct ttm_place *place)
1513 {
1514 	unsigned long num_pages = bo->mem.num_pages;
1515 	struct drm_mm_node *node = bo->mem.mm_node;
1516 	struct dma_resv_list *flist;
1517 	struct dma_fence *f;
1518 	int i;
1519 
1520 	if (bo->type == ttm_bo_type_kernel &&
1521 	    !amdgpu_vm_evictable(ttm_to_amdgpu_bo(bo)))
1522 		return false;
1523 
1524 	/* If bo is a KFD BO, check if the bo belongs to the current process.
1525 	 * If true, then return false as any KFD process needs all its BOs to
1526 	 * be resident to run successfully
1527 	 */
1528 	flist = dma_resv_get_list(bo->base.resv);
1529 	if (flist) {
1530 		for (i = 0; i < flist->shared_count; ++i) {
1531 			f = rcu_dereference_protected(flist->shared[i],
1532 				dma_resv_held(bo->base.resv));
1533 			if (amdkfd_fence_check_mm(f, current->mm))
1534 				return false;
1535 		}
1536 	}
1537 
1538 	switch (bo->mem.mem_type) {
1539 	case TTM_PL_TT:
1540 		return true;
1541 
1542 	case TTM_PL_VRAM:
1543 		/* Check each drm MM node individually */
1544 		while (num_pages) {
1545 			if (place->fpfn < (node->start + node->size) &&
1546 			    !(place->lpfn && place->lpfn <= node->start))
1547 				return true;
1548 
1549 			num_pages -= node->size;
1550 			++node;
1551 		}
1552 		return false;
1553 
1554 	default:
1555 		break;
1556 	}
1557 
1558 	return ttm_bo_eviction_valuable(bo, place);
1559 }
1560 
1561 /**
1562  * amdgpu_ttm_access_memory - Read or Write memory that backs a buffer object.
1563  *
1564  * @bo:  The buffer object to read/write
1565  * @offset:  Offset into buffer object
1566  * @buf:  Secondary buffer to write/read from
1567  * @len: Length in bytes of access
1568  * @write:  true if writing
1569  *
1570  * This is used to access VRAM that backs a buffer object via MMIO
1571  * access for debugging purposes.
1572  */
1573 static int amdgpu_ttm_access_memory(struct ttm_buffer_object *bo,
1574 				    unsigned long offset,
1575 				    void *buf, int len, int write)
1576 {
1577 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1578 	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1579 	struct drm_mm_node *nodes;
1580 	uint32_t value = 0;
1581 	int ret = 0;
1582 	uint64_t pos;
1583 	unsigned long flags;
1584 
1585 	if (bo->mem.mem_type != TTM_PL_VRAM)
1586 		return -EIO;
1587 
1588 	nodes = amdgpu_find_mm_node(&abo->tbo.mem, &offset);
1589 	pos = (nodes->start << PAGE_SHIFT) + offset;
1590 
1591 	while (len && pos < adev->gmc.mc_vram_size) {
1592 		uint64_t aligned_pos = pos & ~(uint64_t)3;
1593 		uint64_t bytes = 4 - (pos & 3);
1594 		uint32_t shift = (pos & 3) * 8;
1595 		uint32_t mask = 0xffffffff << shift;
1596 
1597 		if (len < bytes) {
1598 			mask &= 0xffffffff >> (bytes - len) * 8;
1599 			bytes = len;
1600 		}
1601 
1602 		if (mask != 0xffffffff) {
1603 			spin_lock_irqsave(&adev->mmio_idx_lock, flags);
1604 			WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)aligned_pos) | 0x80000000);
1605 			WREG32_NO_KIQ(mmMM_INDEX_HI, aligned_pos >> 31);
1606 			if (!write || mask != 0xffffffff)
1607 				value = RREG32_NO_KIQ(mmMM_DATA);
1608 			if (write) {
1609 				value &= ~mask;
1610 				value |= (*(uint32_t *)buf << shift) & mask;
1611 				WREG32_NO_KIQ(mmMM_DATA, value);
1612 			}
1613 			spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
1614 			if (!write) {
1615 				value = (value & mask) >> shift;
1616 				memcpy(buf, &value, bytes);
1617 			}
1618 		} else {
1619 			bytes = (nodes->start + nodes->size) << PAGE_SHIFT;
1620 			bytes = min(bytes - pos, (uint64_t)len & ~0x3ull);
1621 
1622 			amdgpu_device_vram_access(adev, pos, (uint32_t *)buf,
1623 						  bytes, write);
1624 		}
1625 
1626 		ret += bytes;
1627 		buf = (uint8_t *)buf + bytes;
1628 		pos += bytes;
1629 		len -= bytes;
1630 		if (pos >= (nodes->start + nodes->size) << PAGE_SHIFT) {
1631 			++nodes;
1632 			pos = (nodes->start << PAGE_SHIFT);
1633 		}
1634 	}
1635 
1636 	return ret;
1637 }
1638 
1639 static struct ttm_bo_driver amdgpu_bo_driver = {
1640 	.ttm_tt_create = &amdgpu_ttm_tt_create,
1641 	.ttm_tt_populate = &amdgpu_ttm_tt_populate,
1642 	.ttm_tt_unpopulate = &amdgpu_ttm_tt_unpopulate,
1643 	.init_mem_type = &amdgpu_init_mem_type,
1644 	.eviction_valuable = amdgpu_ttm_bo_eviction_valuable,
1645 	.evict_flags = &amdgpu_evict_flags,
1646 	.move = &amdgpu_bo_move,
1647 	.verify_access = &amdgpu_verify_access,
1648 	.move_notify = &amdgpu_bo_move_notify,
1649 	.release_notify = &amdgpu_bo_release_notify,
1650 	.fault_reserve_notify = &amdgpu_bo_fault_reserve_notify,
1651 	.io_mem_reserve = &amdgpu_ttm_io_mem_reserve,
1652 	.io_mem_free = &amdgpu_ttm_io_mem_free,
1653 	.io_mem_pfn = amdgpu_ttm_io_mem_pfn,
1654 	.access_memory = &amdgpu_ttm_access_memory,
1655 	.del_from_lru_notify = &amdgpu_vm_del_from_lru_notify
1656 };
1657 
1658 /*
1659  * Firmware Reservation functions
1660  */
1661 /**
1662  * amdgpu_ttm_fw_reserve_vram_fini - free fw reserved vram
1663  *
1664  * @adev: amdgpu_device pointer
1665  *
1666  * free fw reserved vram if it has been reserved.
1667  */
1668 static void amdgpu_ttm_fw_reserve_vram_fini(struct amdgpu_device *adev)
1669 {
1670 	amdgpu_bo_free_kernel(&adev->fw_vram_usage.reserved_bo,
1671 		NULL, &adev->fw_vram_usage.va);
1672 }
1673 
1674 /**
1675  * amdgpu_ttm_fw_reserve_vram_init - create bo vram reservation from fw
1676  *
1677  * @adev: amdgpu_device pointer
1678  *
1679  * create bo vram reservation from fw.
1680  */
1681 static int amdgpu_ttm_fw_reserve_vram_init(struct amdgpu_device *adev)
1682 {
1683 	uint64_t vram_size = adev->gmc.visible_vram_size;
1684 
1685 	adev->fw_vram_usage.va = NULL;
1686 	adev->fw_vram_usage.reserved_bo = NULL;
1687 
1688 	if (adev->fw_vram_usage.size == 0 ||
1689 	    adev->fw_vram_usage.size > vram_size)
1690 		return 0;
1691 
1692 	return amdgpu_bo_create_kernel_at(adev,
1693 					  adev->fw_vram_usage.start_offset,
1694 					  adev->fw_vram_usage.size,
1695 					  AMDGPU_GEM_DOMAIN_VRAM,
1696 					  &adev->fw_vram_usage.reserved_bo,
1697 					  &adev->fw_vram_usage.va);
1698 }
1699 
1700 /*
1701  * Memoy training reservation functions
1702  */
1703 
1704 /**
1705  * amdgpu_ttm_training_reserve_vram_fini - free memory training reserved vram
1706  *
1707  * @adev: amdgpu_device pointer
1708  *
1709  * free memory training reserved vram if it has been reserved.
1710  */
1711 static int amdgpu_ttm_training_reserve_vram_fini(struct amdgpu_device *adev)
1712 {
1713 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1714 
1715 	ctx->init = PSP_MEM_TRAIN_NOT_SUPPORT;
1716 	amdgpu_bo_free_kernel(&ctx->c2p_bo, NULL, NULL);
1717 	ctx->c2p_bo = NULL;
1718 
1719 	return 0;
1720 }
1721 
1722 static u64 amdgpu_ttm_training_get_c2p_offset(u64 vram_size)
1723 {
1724        if ((vram_size & (SZ_1M - 1)) < (SZ_4K + 1) )
1725                vram_size -= SZ_1M;
1726 
1727        return ALIGN(vram_size, SZ_1M);
1728 }
1729 
1730 /**
1731  * amdgpu_ttm_training_reserve_vram_init - create bo vram reservation from memory training
1732  *
1733  * @adev: amdgpu_device pointer
1734  *
1735  * create bo vram reservation from memory training.
1736  */
1737 static int amdgpu_ttm_training_reserve_vram_init(struct amdgpu_device *adev)
1738 {
1739 	int ret;
1740 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1741 
1742 	memset(ctx, 0, sizeof(*ctx));
1743 	if (!adev->fw_vram_usage.mem_train_support) {
1744 		DRM_DEBUG("memory training does not support!\n");
1745 		return 0;
1746 	}
1747 
1748 	ctx->c2p_train_data_offset = amdgpu_ttm_training_get_c2p_offset(adev->gmc.mc_vram_size);
1749 	ctx->p2c_train_data_offset = (adev->gmc.mc_vram_size - GDDR6_MEM_TRAINING_OFFSET);
1750 	ctx->train_data_size = GDDR6_MEM_TRAINING_DATA_SIZE_IN_BYTES;
1751 
1752 	DRM_DEBUG("train_data_size:%llx,p2c_train_data_offset:%llx,c2p_train_data_offset:%llx.\n",
1753 		  ctx->train_data_size,
1754 		  ctx->p2c_train_data_offset,
1755 		  ctx->c2p_train_data_offset);
1756 
1757 	ret = amdgpu_bo_create_kernel_at(adev,
1758 					 ctx->c2p_train_data_offset,
1759 					 ctx->train_data_size,
1760 					 AMDGPU_GEM_DOMAIN_VRAM,
1761 					 &ctx->c2p_bo,
1762 					 NULL);
1763 	if (ret) {
1764 		DRM_ERROR("alloc c2p_bo failed(%d)!\n", ret);
1765 		amdgpu_ttm_training_reserve_vram_fini(adev);
1766 		return ret;
1767 	}
1768 
1769 	ctx->init = PSP_MEM_TRAIN_RESERVE_SUCCESS;
1770 	return 0;
1771 }
1772 
1773 /**
1774  * amdgpu_ttm_init - Init the memory management (ttm) as well as various
1775  * gtt/vram related fields.
1776  *
1777  * This initializes all of the memory space pools that the TTM layer
1778  * will need such as the GTT space (system memory mapped to the device),
1779  * VRAM (on-board memory), and on-chip memories (GDS, GWS, OA) which
1780  * can be mapped per VMID.
1781  */
1782 int amdgpu_ttm_init(struct amdgpu_device *adev)
1783 {
1784 	uint64_t gtt_size;
1785 	int r;
1786 	u64 vis_vram_limit;
1787 	void *stolen_vga_buf;
1788 
1789 	mutex_init(&adev->mman.gtt_window_lock);
1790 
1791 	/* No others user of address space so set it to 0 */
1792 	r = ttm_bo_device_init(&adev->mman.bdev,
1793 			       &amdgpu_bo_driver,
1794 			       adev->ddev->anon_inode->i_mapping,
1795 			       adev->ddev->vma_offset_manager,
1796 			       dma_addressing_limited(adev->dev));
1797 	if (r) {
1798 		DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
1799 		return r;
1800 	}
1801 	adev->mman.initialized = true;
1802 
1803 	/* We opt to avoid OOM on system pages allocations */
1804 	adev->mman.bdev.no_retry = true;
1805 
1806 	/* Initialize VRAM pool with all of VRAM divided into pages */
1807 	r = ttm_bo_init_mm(&adev->mman.bdev, TTM_PL_VRAM,
1808 				adev->gmc.real_vram_size >> PAGE_SHIFT);
1809 	if (r) {
1810 		DRM_ERROR("Failed initializing VRAM heap.\n");
1811 		return r;
1812 	}
1813 
1814 	/* Reduce size of CPU-visible VRAM if requested */
1815 	vis_vram_limit = (u64)amdgpu_vis_vram_limit * 1024 * 1024;
1816 	if (amdgpu_vis_vram_limit > 0 &&
1817 	    vis_vram_limit <= adev->gmc.visible_vram_size)
1818 		adev->gmc.visible_vram_size = vis_vram_limit;
1819 
1820 	/* Change the size here instead of the init above so only lpfn is affected */
1821 	amdgpu_ttm_set_buffer_funcs_status(adev, false);
1822 #ifdef CONFIG_64BIT
1823 	adev->mman.aper_base_kaddr = ioremap_wc(adev->gmc.aper_base,
1824 						adev->gmc.visible_vram_size);
1825 #endif
1826 
1827 	/*
1828 	 *The reserved vram for firmware must be pinned to the specified
1829 	 *place on the VRAM, so reserve it early.
1830 	 */
1831 	r = amdgpu_ttm_fw_reserve_vram_init(adev);
1832 	if (r) {
1833 		return r;
1834 	}
1835 
1836 	/*
1837 	 *The reserved vram for memory training must be pinned to the specified
1838 	 *place on the VRAM, so reserve it early.
1839 	 */
1840 	r = amdgpu_ttm_training_reserve_vram_init(adev);
1841 	if (r)
1842 		return r;
1843 
1844 	/* allocate memory as required for VGA
1845 	 * This is used for VGA emulation and pre-OS scanout buffers to
1846 	 * avoid display artifacts while transitioning between pre-OS
1847 	 * and driver.  */
1848 	r = amdgpu_bo_create_kernel(adev, adev->gmc.stolen_size, PAGE_SIZE,
1849 				    AMDGPU_GEM_DOMAIN_VRAM,
1850 				    &adev->stolen_vga_memory,
1851 				    NULL, &stolen_vga_buf);
1852 	if (r)
1853 		return r;
1854 
1855 	/*
1856 	 * reserve one TMR (64K) memory at the top of VRAM which holds
1857 	 * IP Discovery data and is protected by PSP.
1858 	 */
1859 	r = amdgpu_bo_create_kernel_at(adev,
1860 				       adev->gmc.real_vram_size - DISCOVERY_TMR_SIZE,
1861 				       DISCOVERY_TMR_SIZE,
1862 				       AMDGPU_GEM_DOMAIN_VRAM,
1863 				       &adev->discovery_memory,
1864 				       NULL);
1865 	if (r)
1866 		return r;
1867 
1868 	DRM_INFO("amdgpu: %uM of VRAM memory ready\n",
1869 		 (unsigned) (adev->gmc.real_vram_size / (1024 * 1024)));
1870 
1871 	/* Compute GTT size, either bsaed on 3/4th the size of RAM size
1872 	 * or whatever the user passed on module init */
1873 	if (amdgpu_gtt_size == -1) {
1874 		struct sysinfo si;
1875 
1876 		si_meminfo(&si);
1877 		gtt_size = min(max((AMDGPU_DEFAULT_GTT_SIZE_MB << 20),
1878 			       adev->gmc.mc_vram_size),
1879 			       ((uint64_t)si.totalram * si.mem_unit * 3/4));
1880 	}
1881 	else
1882 		gtt_size = (uint64_t)amdgpu_gtt_size << 20;
1883 
1884 	/* Initialize GTT memory pool */
1885 	r = ttm_bo_init_mm(&adev->mman.bdev, TTM_PL_TT, gtt_size >> PAGE_SHIFT);
1886 	if (r) {
1887 		DRM_ERROR("Failed initializing GTT heap.\n");
1888 		return r;
1889 	}
1890 	DRM_INFO("amdgpu: %uM of GTT memory ready.\n",
1891 		 (unsigned)(gtt_size / (1024 * 1024)));
1892 
1893 	/* Initialize various on-chip memory pools */
1894 	r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_GDS,
1895 			   adev->gds.gds_size);
1896 	if (r) {
1897 		DRM_ERROR("Failed initializing GDS heap.\n");
1898 		return r;
1899 	}
1900 
1901 	r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_GWS,
1902 			   adev->gds.gws_size);
1903 	if (r) {
1904 		DRM_ERROR("Failed initializing gws heap.\n");
1905 		return r;
1906 	}
1907 
1908 	r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_OA,
1909 			   adev->gds.oa_size);
1910 	if (r) {
1911 		DRM_ERROR("Failed initializing oa heap.\n");
1912 		return r;
1913 	}
1914 
1915 	return 0;
1916 }
1917 
1918 /**
1919  * amdgpu_ttm_late_init - Handle any late initialization for amdgpu_ttm
1920  */
1921 void amdgpu_ttm_late_init(struct amdgpu_device *adev)
1922 {
1923 	void *stolen_vga_buf;
1924 	/* return the VGA stolen memory (if any) back to VRAM */
1925 	amdgpu_bo_free_kernel(&adev->stolen_vga_memory, NULL, &stolen_vga_buf);
1926 }
1927 
1928 /**
1929  * amdgpu_ttm_fini - De-initialize the TTM memory pools
1930  */
1931 void amdgpu_ttm_fini(struct amdgpu_device *adev)
1932 {
1933 	if (!adev->mman.initialized)
1934 		return;
1935 
1936 	amdgpu_ttm_training_reserve_vram_fini(adev);
1937 	/* return the IP Discovery TMR memory back to VRAM */
1938 	amdgpu_bo_free_kernel(&adev->discovery_memory, NULL, NULL);
1939 	amdgpu_ttm_fw_reserve_vram_fini(adev);
1940 
1941 	if (adev->mman.aper_base_kaddr)
1942 		iounmap(adev->mman.aper_base_kaddr);
1943 	adev->mman.aper_base_kaddr = NULL;
1944 
1945 	ttm_bo_clean_mm(&adev->mman.bdev, TTM_PL_VRAM);
1946 	ttm_bo_clean_mm(&adev->mman.bdev, TTM_PL_TT);
1947 	ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_GDS);
1948 	ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_GWS);
1949 	ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_OA);
1950 	ttm_bo_device_release(&adev->mman.bdev);
1951 	adev->mman.initialized = false;
1952 	DRM_INFO("amdgpu: ttm finalized\n");
1953 }
1954 
1955 /**
1956  * amdgpu_ttm_set_buffer_funcs_status - enable/disable use of buffer functions
1957  *
1958  * @adev: amdgpu_device pointer
1959  * @enable: true when we can use buffer functions.
1960  *
1961  * Enable/disable use of buffer functions during suspend/resume. This should
1962  * only be called at bootup or when userspace isn't running.
1963  */
1964 void amdgpu_ttm_set_buffer_funcs_status(struct amdgpu_device *adev, bool enable)
1965 {
1966 	struct ttm_mem_type_manager *man = &adev->mman.bdev.man[TTM_PL_VRAM];
1967 	uint64_t size;
1968 	int r;
1969 
1970 	if (!adev->mman.initialized || adev->in_gpu_reset ||
1971 	    adev->mman.buffer_funcs_enabled == enable)
1972 		return;
1973 
1974 	if (enable) {
1975 		struct amdgpu_ring *ring;
1976 		struct drm_gpu_scheduler *sched;
1977 
1978 		ring = adev->mman.buffer_funcs_ring;
1979 		sched = &ring->sched;
1980 		r = drm_sched_entity_init(&adev->mman.entity,
1981 				          DRM_SCHED_PRIORITY_KERNEL, &sched,
1982 					  1, NULL);
1983 		if (r) {
1984 			DRM_ERROR("Failed setting up TTM BO move entity (%d)\n",
1985 				  r);
1986 			return;
1987 		}
1988 	} else {
1989 		drm_sched_entity_destroy(&adev->mman.entity);
1990 		dma_fence_put(man->move);
1991 		man->move = NULL;
1992 	}
1993 
1994 	/* this just adjusts TTM size idea, which sets lpfn to the correct value */
1995 	if (enable)
1996 		size = adev->gmc.real_vram_size;
1997 	else
1998 		size = adev->gmc.visible_vram_size;
1999 	man->size = size >> PAGE_SHIFT;
2000 	adev->mman.buffer_funcs_enabled = enable;
2001 }
2002 
2003 int amdgpu_mmap(struct file *filp, struct vm_area_struct *vma)
2004 {
2005 	struct drm_file *file_priv = filp->private_data;
2006 	struct amdgpu_device *adev = file_priv->minor->dev->dev_private;
2007 
2008 	if (adev == NULL)
2009 		return -EINVAL;
2010 
2011 	return ttm_bo_mmap(filp, vma, &adev->mman.bdev);
2012 }
2013 
2014 static int amdgpu_map_buffer(struct ttm_buffer_object *bo,
2015 			     struct ttm_mem_reg *mem, unsigned num_pages,
2016 			     uint64_t offset, unsigned window,
2017 			     struct amdgpu_ring *ring,
2018 			     uint64_t *addr)
2019 {
2020 	struct amdgpu_ttm_tt *gtt = (void *)bo->ttm;
2021 	struct amdgpu_device *adev = ring->adev;
2022 	struct ttm_tt *ttm = bo->ttm;
2023 	struct amdgpu_job *job;
2024 	unsigned num_dw, num_bytes;
2025 	dma_addr_t *dma_address;
2026 	struct dma_fence *fence;
2027 	uint64_t src_addr, dst_addr;
2028 	uint64_t flags;
2029 	int r;
2030 
2031 	BUG_ON(adev->mman.buffer_funcs->copy_max_bytes <
2032 	       AMDGPU_GTT_MAX_TRANSFER_SIZE * 8);
2033 
2034 	*addr = adev->gmc.gart_start;
2035 	*addr += (u64)window * AMDGPU_GTT_MAX_TRANSFER_SIZE *
2036 		AMDGPU_GPU_PAGE_SIZE;
2037 
2038 	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
2039 	num_bytes = num_pages * 8;
2040 
2041 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4 + num_bytes, &job);
2042 	if (r)
2043 		return r;
2044 
2045 	src_addr = num_dw * 4;
2046 	src_addr += job->ibs[0].gpu_addr;
2047 
2048 	dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
2049 	dst_addr += window * AMDGPU_GTT_MAX_TRANSFER_SIZE * 8;
2050 	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
2051 				dst_addr, num_bytes);
2052 
2053 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2054 	WARN_ON(job->ibs[0].length_dw > num_dw);
2055 
2056 	dma_address = &gtt->ttm.dma_address[offset >> PAGE_SHIFT];
2057 	flags = amdgpu_ttm_tt_pte_flags(adev, ttm, mem);
2058 	r = amdgpu_gart_map(adev, 0, num_pages, dma_address, flags,
2059 			    &job->ibs[0].ptr[num_dw]);
2060 	if (r)
2061 		goto error_free;
2062 
2063 	r = amdgpu_job_submit(job, &adev->mman.entity,
2064 			      AMDGPU_FENCE_OWNER_UNDEFINED, &fence);
2065 	if (r)
2066 		goto error_free;
2067 
2068 	dma_fence_put(fence);
2069 
2070 	return r;
2071 
2072 error_free:
2073 	amdgpu_job_free(job);
2074 	return r;
2075 }
2076 
2077 int amdgpu_copy_buffer(struct amdgpu_ring *ring, uint64_t src_offset,
2078 		       uint64_t dst_offset, uint32_t byte_count,
2079 		       struct dma_resv *resv,
2080 		       struct dma_fence **fence, bool direct_submit,
2081 		       bool vm_needs_flush)
2082 {
2083 	struct amdgpu_device *adev = ring->adev;
2084 	struct amdgpu_job *job;
2085 
2086 	uint32_t max_bytes;
2087 	unsigned num_loops, num_dw;
2088 	unsigned i;
2089 	int r;
2090 
2091 	if (direct_submit && !ring->sched.ready) {
2092 		DRM_ERROR("Trying to move memory with ring turned off.\n");
2093 		return -EINVAL;
2094 	}
2095 
2096 	max_bytes = adev->mman.buffer_funcs->copy_max_bytes;
2097 	num_loops = DIV_ROUND_UP(byte_count, max_bytes);
2098 	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->copy_num_dw, 8);
2099 
2100 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, &job);
2101 	if (r)
2102 		return r;
2103 
2104 	if (vm_needs_flush) {
2105 		job->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gart.bo);
2106 		job->vm_needs_flush = true;
2107 	}
2108 	if (resv) {
2109 		r = amdgpu_sync_resv(adev, &job->sync, resv,
2110 				     AMDGPU_SYNC_ALWAYS,
2111 				     AMDGPU_FENCE_OWNER_UNDEFINED);
2112 		if (r) {
2113 			DRM_ERROR("sync failed (%d).\n", r);
2114 			goto error_free;
2115 		}
2116 	}
2117 
2118 	for (i = 0; i < num_loops; i++) {
2119 		uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
2120 
2121 		amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
2122 					dst_offset, cur_size_in_bytes);
2123 
2124 		src_offset += cur_size_in_bytes;
2125 		dst_offset += cur_size_in_bytes;
2126 		byte_count -= cur_size_in_bytes;
2127 	}
2128 
2129 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2130 	WARN_ON(job->ibs[0].length_dw > num_dw);
2131 	if (direct_submit)
2132 		r = amdgpu_job_submit_direct(job, ring, fence);
2133 	else
2134 		r = amdgpu_job_submit(job, &adev->mman.entity,
2135 				      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
2136 	if (r)
2137 		goto error_free;
2138 
2139 	return r;
2140 
2141 error_free:
2142 	amdgpu_job_free(job);
2143 	DRM_ERROR("Error scheduling IBs (%d)\n", r);
2144 	return r;
2145 }
2146 
2147 int amdgpu_fill_buffer(struct amdgpu_bo *bo,
2148 		       uint32_t src_data,
2149 		       struct dma_resv *resv,
2150 		       struct dma_fence **fence)
2151 {
2152 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
2153 	uint32_t max_bytes = adev->mman.buffer_funcs->fill_max_bytes;
2154 	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
2155 
2156 	struct drm_mm_node *mm_node;
2157 	unsigned long num_pages;
2158 	unsigned int num_loops, num_dw;
2159 
2160 	struct amdgpu_job *job;
2161 	int r;
2162 
2163 	if (!adev->mman.buffer_funcs_enabled) {
2164 		DRM_ERROR("Trying to clear memory with ring turned off.\n");
2165 		return -EINVAL;
2166 	}
2167 
2168 	if (bo->tbo.mem.mem_type == TTM_PL_TT) {
2169 		r = amdgpu_ttm_alloc_gart(&bo->tbo);
2170 		if (r)
2171 			return r;
2172 	}
2173 
2174 	num_pages = bo->tbo.num_pages;
2175 	mm_node = bo->tbo.mem.mm_node;
2176 	num_loops = 0;
2177 	while (num_pages) {
2178 		uint64_t byte_count = mm_node->size << PAGE_SHIFT;
2179 
2180 		num_loops += DIV_ROUND_UP_ULL(byte_count, max_bytes);
2181 		num_pages -= mm_node->size;
2182 		++mm_node;
2183 	}
2184 	num_dw = num_loops * adev->mman.buffer_funcs->fill_num_dw;
2185 
2186 	/* for IB padding */
2187 	num_dw += 64;
2188 
2189 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, &job);
2190 	if (r)
2191 		return r;
2192 
2193 	if (resv) {
2194 		r = amdgpu_sync_resv(adev, &job->sync, resv,
2195 				     AMDGPU_SYNC_ALWAYS,
2196 				     AMDGPU_FENCE_OWNER_UNDEFINED);
2197 		if (r) {
2198 			DRM_ERROR("sync failed (%d).\n", r);
2199 			goto error_free;
2200 		}
2201 	}
2202 
2203 	num_pages = bo->tbo.num_pages;
2204 	mm_node = bo->tbo.mem.mm_node;
2205 
2206 	while (num_pages) {
2207 		uint64_t byte_count = mm_node->size << PAGE_SHIFT;
2208 		uint64_t dst_addr;
2209 
2210 		dst_addr = amdgpu_mm_node_addr(&bo->tbo, mm_node, &bo->tbo.mem);
2211 		while (byte_count) {
2212 			uint32_t cur_size_in_bytes = min_t(uint64_t, byte_count,
2213 							   max_bytes);
2214 
2215 			amdgpu_emit_fill_buffer(adev, &job->ibs[0], src_data,
2216 						dst_addr, cur_size_in_bytes);
2217 
2218 			dst_addr += cur_size_in_bytes;
2219 			byte_count -= cur_size_in_bytes;
2220 		}
2221 
2222 		num_pages -= mm_node->size;
2223 		++mm_node;
2224 	}
2225 
2226 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2227 	WARN_ON(job->ibs[0].length_dw > num_dw);
2228 	r = amdgpu_job_submit(job, &adev->mman.entity,
2229 			      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
2230 	if (r)
2231 		goto error_free;
2232 
2233 	return 0;
2234 
2235 error_free:
2236 	amdgpu_job_free(job);
2237 	return r;
2238 }
2239 
2240 #if defined(CONFIG_DEBUG_FS)
2241 
2242 static int amdgpu_mm_dump_table(struct seq_file *m, void *data)
2243 {
2244 	struct drm_info_node *node = (struct drm_info_node *)m->private;
2245 	unsigned ttm_pl = (uintptr_t)node->info_ent->data;
2246 	struct drm_device *dev = node->minor->dev;
2247 	struct amdgpu_device *adev = dev->dev_private;
2248 	struct ttm_mem_type_manager *man = &adev->mman.bdev.man[ttm_pl];
2249 	struct drm_printer p = drm_seq_file_printer(m);
2250 
2251 	man->func->debug(man, &p);
2252 	return 0;
2253 }
2254 
2255 static const struct drm_info_list amdgpu_ttm_debugfs_list[] = {
2256 	{"amdgpu_vram_mm", amdgpu_mm_dump_table, 0, (void *)TTM_PL_VRAM},
2257 	{"amdgpu_gtt_mm", amdgpu_mm_dump_table, 0, (void *)TTM_PL_TT},
2258 	{"amdgpu_gds_mm", amdgpu_mm_dump_table, 0, (void *)AMDGPU_PL_GDS},
2259 	{"amdgpu_gws_mm", amdgpu_mm_dump_table, 0, (void *)AMDGPU_PL_GWS},
2260 	{"amdgpu_oa_mm", amdgpu_mm_dump_table, 0, (void *)AMDGPU_PL_OA},
2261 	{"ttm_page_pool", ttm_page_alloc_debugfs, 0, NULL},
2262 #ifdef CONFIG_SWIOTLB
2263 	{"ttm_dma_page_pool", ttm_dma_page_alloc_debugfs, 0, NULL}
2264 #endif
2265 };
2266 
2267 /**
2268  * amdgpu_ttm_vram_read - Linear read access to VRAM
2269  *
2270  * Accesses VRAM via MMIO for debugging purposes.
2271  */
2272 static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
2273 				    size_t size, loff_t *pos)
2274 {
2275 	struct amdgpu_device *adev = file_inode(f)->i_private;
2276 	ssize_t result = 0;
2277 
2278 	if (size & 0x3 || *pos & 0x3)
2279 		return -EINVAL;
2280 
2281 	if (*pos >= adev->gmc.mc_vram_size)
2282 		return -ENXIO;
2283 
2284 	size = min(size, (size_t)(adev->gmc.mc_vram_size - *pos));
2285 	while (size) {
2286 		size_t bytes = min(size, AMDGPU_TTM_VRAM_MAX_DW_READ * 4);
2287 		uint32_t value[AMDGPU_TTM_VRAM_MAX_DW_READ];
2288 
2289 		amdgpu_device_vram_access(adev, *pos, value, bytes, false);
2290 		if (copy_to_user(buf, value, bytes))
2291 			return -EFAULT;
2292 
2293 		result += bytes;
2294 		buf += bytes;
2295 		*pos += bytes;
2296 		size -= bytes;
2297 	}
2298 
2299 	return result;
2300 }
2301 
2302 /**
2303  * amdgpu_ttm_vram_write - Linear write access to VRAM
2304  *
2305  * Accesses VRAM via MMIO for debugging purposes.
2306  */
2307 static ssize_t amdgpu_ttm_vram_write(struct file *f, const char __user *buf,
2308 				    size_t size, loff_t *pos)
2309 {
2310 	struct amdgpu_device *adev = file_inode(f)->i_private;
2311 	ssize_t result = 0;
2312 	int r;
2313 
2314 	if (size & 0x3 || *pos & 0x3)
2315 		return -EINVAL;
2316 
2317 	if (*pos >= adev->gmc.mc_vram_size)
2318 		return -ENXIO;
2319 
2320 	while (size) {
2321 		unsigned long flags;
2322 		uint32_t value;
2323 
2324 		if (*pos >= adev->gmc.mc_vram_size)
2325 			return result;
2326 
2327 		r = get_user(value, (uint32_t *)buf);
2328 		if (r)
2329 			return r;
2330 
2331 		spin_lock_irqsave(&adev->mmio_idx_lock, flags);
2332 		WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)*pos) | 0x80000000);
2333 		WREG32_NO_KIQ(mmMM_INDEX_HI, *pos >> 31);
2334 		WREG32_NO_KIQ(mmMM_DATA, value);
2335 		spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
2336 
2337 		result += 4;
2338 		buf += 4;
2339 		*pos += 4;
2340 		size -= 4;
2341 	}
2342 
2343 	return result;
2344 }
2345 
2346 static const struct file_operations amdgpu_ttm_vram_fops = {
2347 	.owner = THIS_MODULE,
2348 	.read = amdgpu_ttm_vram_read,
2349 	.write = amdgpu_ttm_vram_write,
2350 	.llseek = default_llseek,
2351 };
2352 
2353 #ifdef CONFIG_DRM_AMDGPU_GART_DEBUGFS
2354 
2355 /**
2356  * amdgpu_ttm_gtt_read - Linear read access to GTT memory
2357  */
2358 static ssize_t amdgpu_ttm_gtt_read(struct file *f, char __user *buf,
2359 				   size_t size, loff_t *pos)
2360 {
2361 	struct amdgpu_device *adev = file_inode(f)->i_private;
2362 	ssize_t result = 0;
2363 	int r;
2364 
2365 	while (size) {
2366 		loff_t p = *pos / PAGE_SIZE;
2367 		unsigned off = *pos & ~PAGE_MASK;
2368 		size_t cur_size = min_t(size_t, size, PAGE_SIZE - off);
2369 		struct page *page;
2370 		void *ptr;
2371 
2372 		if (p >= adev->gart.num_cpu_pages)
2373 			return result;
2374 
2375 		page = adev->gart.pages[p];
2376 		if (page) {
2377 			ptr = kmap(page);
2378 			ptr += off;
2379 
2380 			r = copy_to_user(buf, ptr, cur_size);
2381 			kunmap(adev->gart.pages[p]);
2382 		} else
2383 			r = clear_user(buf, cur_size);
2384 
2385 		if (r)
2386 			return -EFAULT;
2387 
2388 		result += cur_size;
2389 		buf += cur_size;
2390 		*pos += cur_size;
2391 		size -= cur_size;
2392 	}
2393 
2394 	return result;
2395 }
2396 
2397 static const struct file_operations amdgpu_ttm_gtt_fops = {
2398 	.owner = THIS_MODULE,
2399 	.read = amdgpu_ttm_gtt_read,
2400 	.llseek = default_llseek
2401 };
2402 
2403 #endif
2404 
2405 /**
2406  * amdgpu_iomem_read - Virtual read access to GPU mapped memory
2407  *
2408  * This function is used to read memory that has been mapped to the
2409  * GPU and the known addresses are not physical addresses but instead
2410  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2411  */
2412 static ssize_t amdgpu_iomem_read(struct file *f, char __user *buf,
2413 				 size_t size, loff_t *pos)
2414 {
2415 	struct amdgpu_device *adev = file_inode(f)->i_private;
2416 	struct iommu_domain *dom;
2417 	ssize_t result = 0;
2418 	int r;
2419 
2420 	/* retrieve the IOMMU domain if any for this device */
2421 	dom = iommu_get_domain_for_dev(adev->dev);
2422 
2423 	while (size) {
2424 		phys_addr_t addr = *pos & PAGE_MASK;
2425 		loff_t off = *pos & ~PAGE_MASK;
2426 		size_t bytes = PAGE_SIZE - off;
2427 		unsigned long pfn;
2428 		struct page *p;
2429 		void *ptr;
2430 
2431 		bytes = bytes < size ? bytes : size;
2432 
2433 		/* Translate the bus address to a physical address.  If
2434 		 * the domain is NULL it means there is no IOMMU active
2435 		 * and the address translation is the identity
2436 		 */
2437 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2438 
2439 		pfn = addr >> PAGE_SHIFT;
2440 		if (!pfn_valid(pfn))
2441 			return -EPERM;
2442 
2443 		p = pfn_to_page(pfn);
2444 		if (p->mapping != adev->mman.bdev.dev_mapping)
2445 			return -EPERM;
2446 
2447 		ptr = kmap(p);
2448 		r = copy_to_user(buf, ptr + off, bytes);
2449 		kunmap(p);
2450 		if (r)
2451 			return -EFAULT;
2452 
2453 		size -= bytes;
2454 		*pos += bytes;
2455 		result += bytes;
2456 	}
2457 
2458 	return result;
2459 }
2460 
2461 /**
2462  * amdgpu_iomem_write - Virtual write access to GPU mapped memory
2463  *
2464  * This function is used to write memory that has been mapped to the
2465  * GPU and the known addresses are not physical addresses but instead
2466  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2467  */
2468 static ssize_t amdgpu_iomem_write(struct file *f, const char __user *buf,
2469 				 size_t size, loff_t *pos)
2470 {
2471 	struct amdgpu_device *adev = file_inode(f)->i_private;
2472 	struct iommu_domain *dom;
2473 	ssize_t result = 0;
2474 	int r;
2475 
2476 	dom = iommu_get_domain_for_dev(adev->dev);
2477 
2478 	while (size) {
2479 		phys_addr_t addr = *pos & PAGE_MASK;
2480 		loff_t off = *pos & ~PAGE_MASK;
2481 		size_t bytes = PAGE_SIZE - off;
2482 		unsigned long pfn;
2483 		struct page *p;
2484 		void *ptr;
2485 
2486 		bytes = bytes < size ? bytes : size;
2487 
2488 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2489 
2490 		pfn = addr >> PAGE_SHIFT;
2491 		if (!pfn_valid(pfn))
2492 			return -EPERM;
2493 
2494 		p = pfn_to_page(pfn);
2495 		if (p->mapping != adev->mman.bdev.dev_mapping)
2496 			return -EPERM;
2497 
2498 		ptr = kmap(p);
2499 		r = copy_from_user(ptr + off, buf, bytes);
2500 		kunmap(p);
2501 		if (r)
2502 			return -EFAULT;
2503 
2504 		size -= bytes;
2505 		*pos += bytes;
2506 		result += bytes;
2507 	}
2508 
2509 	return result;
2510 }
2511 
2512 static const struct file_operations amdgpu_ttm_iomem_fops = {
2513 	.owner = THIS_MODULE,
2514 	.read = amdgpu_iomem_read,
2515 	.write = amdgpu_iomem_write,
2516 	.llseek = default_llseek
2517 };
2518 
2519 static const struct {
2520 	char *name;
2521 	const struct file_operations *fops;
2522 	int domain;
2523 } ttm_debugfs_entries[] = {
2524 	{ "amdgpu_vram", &amdgpu_ttm_vram_fops, TTM_PL_VRAM },
2525 #ifdef CONFIG_DRM_AMDGPU_GART_DEBUGFS
2526 	{ "amdgpu_gtt", &amdgpu_ttm_gtt_fops, TTM_PL_TT },
2527 #endif
2528 	{ "amdgpu_iomem", &amdgpu_ttm_iomem_fops, TTM_PL_SYSTEM },
2529 };
2530 
2531 #endif
2532 
2533 int amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
2534 {
2535 #if defined(CONFIG_DEBUG_FS)
2536 	unsigned count;
2537 
2538 	struct drm_minor *minor = adev->ddev->primary;
2539 	struct dentry *ent, *root = minor->debugfs_root;
2540 
2541 	for (count = 0; count < ARRAY_SIZE(ttm_debugfs_entries); count++) {
2542 		ent = debugfs_create_file(
2543 				ttm_debugfs_entries[count].name,
2544 				S_IFREG | S_IRUGO, root,
2545 				adev,
2546 				ttm_debugfs_entries[count].fops);
2547 		if (IS_ERR(ent))
2548 			return PTR_ERR(ent);
2549 		if (ttm_debugfs_entries[count].domain == TTM_PL_VRAM)
2550 			i_size_write(ent->d_inode, adev->gmc.mc_vram_size);
2551 		else if (ttm_debugfs_entries[count].domain == TTM_PL_TT)
2552 			i_size_write(ent->d_inode, adev->gmc.gart_size);
2553 		adev->mman.debugfs_entries[count] = ent;
2554 	}
2555 
2556 	count = ARRAY_SIZE(amdgpu_ttm_debugfs_list);
2557 
2558 #ifdef CONFIG_SWIOTLB
2559 	if (!(adev->need_swiotlb && swiotlb_nr_tbl()))
2560 		--count;
2561 #endif
2562 
2563 	return amdgpu_debugfs_add_files(adev, amdgpu_ttm_debugfs_list, count);
2564 #else
2565 	return 0;
2566 #endif
2567 }
2568