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