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