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