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