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