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