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