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