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