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