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