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/swiotlb.h>
42 #include <linux/dma-buf.h>
43 #include <linux/sizes.h>
44 #include <linux/module.h>
45 
46 #include <drm/ttm/ttm_bo_api.h>
47 #include <drm/ttm/ttm_bo_driver.h>
48 #include <drm/ttm/ttm_placement.h>
49 #include <drm/ttm/ttm_range_manager.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_atomfirmware.h"
60 #include "amdgpu_res_cursor.h"
61 #include "bif/bif_4_1_d.h"
62 
63 MODULE_IMPORT_NS(DMA_BUF);
64 
65 #define AMDGPU_TTM_VRAM_MAX_DW_READ	(size_t)128
66 
67 static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
68 				   struct ttm_tt *ttm,
69 				   struct ttm_resource *bo_mem);
70 static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
71 				      struct ttm_tt *ttm);
72 
73 static int amdgpu_ttm_init_on_chip(struct amdgpu_device *adev,
74 				    unsigned int type,
75 				    uint64_t size_in_page)
76 {
77 	return ttm_range_man_init(&adev->mman.bdev, type,
78 				  false, size_in_page);
79 }
80 
81 /**
82  * amdgpu_evict_flags - Compute placement flags
83  *
84  * @bo: The buffer object to evict
85  * @placement: Possible destination(s) for evicted BO
86  *
87  * Fill in placement data when ttm_bo_evict() is called
88  */
89 static void amdgpu_evict_flags(struct ttm_buffer_object *bo,
90 				struct ttm_placement *placement)
91 {
92 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
93 	struct amdgpu_bo *abo;
94 	static const struct ttm_place placements = {
95 		.fpfn = 0,
96 		.lpfn = 0,
97 		.mem_type = TTM_PL_SYSTEM,
98 		.flags = 0
99 	};
100 
101 	/* Don't handle scatter gather BOs */
102 	if (bo->type == ttm_bo_type_sg) {
103 		placement->num_placement = 0;
104 		placement->num_busy_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->busy_placement = &placements;
112 		placement->num_placement = 1;
113 		placement->num_busy_placement = 1;
114 		return;
115 	}
116 
117 	abo = ttm_to_amdgpu_bo(bo);
118 	if (abo->flags & AMDGPU_AMDKFD_CREATE_SVM_BO) {
119 		struct dma_fence *fence;
120 		struct dma_resv *resv = &bo->base._resv;
121 
122 		rcu_read_lock();
123 		fence = rcu_dereference(resv->fence_excl);
124 		if (fence && !fence->ops->signaled)
125 			dma_fence_enable_sw_signaling(fence);
126 
127 		placement->num_placement = 0;
128 		placement->num_busy_placement = 0;
129 		rcu_read_unlock();
130 		return;
131 	}
132 
133 	switch (bo->resource->mem_type) {
134 	case AMDGPU_PL_GDS:
135 	case AMDGPU_PL_GWS:
136 	case AMDGPU_PL_OA:
137 		placement->num_placement = 0;
138 		placement->num_busy_placement = 0;
139 		return;
140 
141 	case TTM_PL_VRAM:
142 		if (!adev->mman.buffer_funcs_enabled) {
143 			/* Move to system memory */
144 			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
145 		} else if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
146 			   !(abo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) &&
147 			   amdgpu_bo_in_cpu_visible_vram(abo)) {
148 
149 			/* Try evicting to the CPU inaccessible part of VRAM
150 			 * first, but only set GTT as busy placement, so this
151 			 * BO will be evicted to GTT rather than causing other
152 			 * BOs to be evicted from VRAM
153 			 */
154 			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
155 							AMDGPU_GEM_DOMAIN_GTT |
156 							AMDGPU_GEM_DOMAIN_CPU);
157 			abo->placements[0].fpfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
158 			abo->placements[0].lpfn = 0;
159 			abo->placement.busy_placement = &abo->placements[1];
160 			abo->placement.num_busy_placement = 1;
161 		} else {
162 			/* Move to GTT memory */
163 			amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_GTT |
164 							AMDGPU_GEM_DOMAIN_CPU);
165 		}
166 		break;
167 	case TTM_PL_TT:
168 	case AMDGPU_PL_PREEMPT:
169 	default:
170 		amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
171 		break;
172 	}
173 	*placement = abo->placement;
174 }
175 
176 /**
177  * amdgpu_ttm_map_buffer - Map memory into the GART windows
178  * @bo: buffer object to map
179  * @mem: memory object to map
180  * @mm_cur: range to map
181  * @num_pages: number of pages to map
182  * @window: which GART window to use
183  * @ring: DMA ring to use for the copy
184  * @tmz: if we should setup a TMZ enabled mapping
185  * @addr: resulting address inside the MC address space
186  *
187  * Setup one of the GART windows to access a specific piece of memory or return
188  * the physical address for local memory.
189  */
190 static int amdgpu_ttm_map_buffer(struct ttm_buffer_object *bo,
191 				 struct ttm_resource *mem,
192 				 struct amdgpu_res_cursor *mm_cur,
193 				 unsigned num_pages, unsigned window,
194 				 struct amdgpu_ring *ring, bool tmz,
195 				 uint64_t *addr)
196 {
197 	struct amdgpu_device *adev = ring->adev;
198 	struct amdgpu_job *job;
199 	unsigned num_dw, num_bytes;
200 	struct dma_fence *fence;
201 	uint64_t src_addr, dst_addr;
202 	void *cpu_addr;
203 	uint64_t flags;
204 	unsigned int i;
205 	int r;
206 
207 	BUG_ON(adev->mman.buffer_funcs->copy_max_bytes <
208 	       AMDGPU_GTT_MAX_TRANSFER_SIZE * 8);
209 	BUG_ON(mem->mem_type == AMDGPU_PL_PREEMPT);
210 
211 	/* Map only what can't be accessed directly */
212 	if (!tmz && mem->start != AMDGPU_BO_INVALID_OFFSET) {
213 		*addr = amdgpu_ttm_domain_start(adev, mem->mem_type) +
214 			mm_cur->start;
215 		return 0;
216 	}
217 
218 	*addr = adev->gmc.gart_start;
219 	*addr += (u64)window * AMDGPU_GTT_MAX_TRANSFER_SIZE *
220 		AMDGPU_GPU_PAGE_SIZE;
221 	*addr += mm_cur->start & ~PAGE_MASK;
222 
223 	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
224 	num_bytes = num_pages * 8 * AMDGPU_GPU_PAGES_IN_CPU_PAGE;
225 
226 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4 + num_bytes,
227 				     AMDGPU_IB_POOL_DELAYED, &job);
228 	if (r)
229 		return r;
230 
231 	src_addr = num_dw * 4;
232 	src_addr += job->ibs[0].gpu_addr;
233 
234 	dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
235 	dst_addr += window * AMDGPU_GTT_MAX_TRANSFER_SIZE * 8;
236 	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
237 				dst_addr, num_bytes, false);
238 
239 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
240 	WARN_ON(job->ibs[0].length_dw > num_dw);
241 
242 	flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, mem);
243 	if (tmz)
244 		flags |= AMDGPU_PTE_TMZ;
245 
246 	cpu_addr = &job->ibs[0].ptr[num_dw];
247 
248 	if (mem->mem_type == TTM_PL_TT) {
249 		dma_addr_t *dma_addr;
250 
251 		dma_addr = &bo->ttm->dma_address[mm_cur->start >> PAGE_SHIFT];
252 		r = amdgpu_gart_map(adev, 0, num_pages, dma_addr, flags,
253 				    cpu_addr);
254 		if (r)
255 			goto error_free;
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 			r = amdgpu_gart_map(adev, i << PAGE_SHIFT, 1,
264 					    &dma_address, flags, cpu_addr);
265 			if (r)
266 				goto error_free;
267 
268 			dma_address += PAGE_SIZE;
269 		}
270 	}
271 
272 	r = amdgpu_job_submit(job, &adev->mman.entity,
273 			      AMDGPU_FENCE_OWNER_UNDEFINED, &fence);
274 	if (r)
275 		goto error_free;
276 
277 	dma_fence_put(fence);
278 
279 	return r;
280 
281 error_free:
282 	amdgpu_job_free(job);
283 	return r;
284 }
285 
286 /**
287  * amdgpu_ttm_copy_mem_to_mem - Helper function for copy
288  * @adev: amdgpu device
289  * @src: buffer/address where to read from
290  * @dst: buffer/address where to write to
291  * @size: number of bytes to copy
292  * @tmz: if a secure copy should be used
293  * @resv: resv object to sync to
294  * @f: Returns the last fence if multiple jobs are submitted.
295  *
296  * The function copies @size bytes from {src->mem + src->offset} to
297  * {dst->mem + dst->offset}. src->bo and dst->bo could be same BO for a
298  * move and different for a BO to BO copy.
299  *
300  */
301 int amdgpu_ttm_copy_mem_to_mem(struct amdgpu_device *adev,
302 			       const struct amdgpu_copy_mem *src,
303 			       const struct amdgpu_copy_mem *dst,
304 			       uint64_t size, bool tmz,
305 			       struct dma_resv *resv,
306 			       struct dma_fence **f)
307 {
308 	const uint32_t GTT_MAX_BYTES = (AMDGPU_GTT_MAX_TRANSFER_SIZE *
309 					AMDGPU_GPU_PAGE_SIZE);
310 
311 	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
312 	struct amdgpu_res_cursor src_mm, dst_mm;
313 	struct dma_fence *fence = NULL;
314 	int r = 0;
315 
316 	if (!adev->mman.buffer_funcs_enabled) {
317 		DRM_ERROR("Trying to move memory with ring turned off.\n");
318 		return -EINVAL;
319 	}
320 
321 	amdgpu_res_first(src->mem, src->offset, size, &src_mm);
322 	amdgpu_res_first(dst->mem, dst->offset, size, &dst_mm);
323 
324 	mutex_lock(&adev->mman.gtt_window_lock);
325 	while (src_mm.remaining) {
326 		uint32_t src_page_offset = src_mm.start & ~PAGE_MASK;
327 		uint32_t dst_page_offset = dst_mm.start & ~PAGE_MASK;
328 		struct dma_fence *next;
329 		uint32_t cur_size;
330 		uint64_t from, to;
331 
332 		/* Copy size cannot exceed GTT_MAX_BYTES. So if src or dst
333 		 * begins at an offset, then adjust the size accordingly
334 		 */
335 		cur_size = max(src_page_offset, dst_page_offset);
336 		cur_size = min(min3(src_mm.size, dst_mm.size, size),
337 			       (uint64_t)(GTT_MAX_BYTES - cur_size));
338 
339 		/* Map src to window 0 and dst to window 1. */
340 		r = amdgpu_ttm_map_buffer(src->bo, src->mem, &src_mm,
341 					  PFN_UP(cur_size + src_page_offset),
342 					  0, ring, tmz, &from);
343 		if (r)
344 			goto error;
345 
346 		r = amdgpu_ttm_map_buffer(dst->bo, dst->mem, &dst_mm,
347 					  PFN_UP(cur_size + dst_page_offset),
348 					  1, ring, tmz, &to);
349 		if (r)
350 			goto error;
351 
352 		r = amdgpu_copy_buffer(ring, from, to, cur_size,
353 				       resv, &next, false, true, tmz);
354 		if (r)
355 			goto error;
356 
357 		dma_fence_put(fence);
358 		fence = next;
359 
360 		amdgpu_res_next(&src_mm, cur_size);
361 		amdgpu_res_next(&dst_mm, cur_size);
362 	}
363 error:
364 	mutex_unlock(&adev->mman.gtt_window_lock);
365 	if (f)
366 		*f = dma_fence_get(fence);
367 	dma_fence_put(fence);
368 	return r;
369 }
370 
371 /*
372  * amdgpu_move_blit - Copy an entire buffer to another buffer
373  *
374  * This is a helper called by amdgpu_bo_move() and amdgpu_move_vram_ram() to
375  * help move buffers to and from VRAM.
376  */
377 static int amdgpu_move_blit(struct ttm_buffer_object *bo,
378 			    bool evict,
379 			    struct ttm_resource *new_mem,
380 			    struct ttm_resource *old_mem)
381 {
382 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
383 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
384 	struct amdgpu_copy_mem src, dst;
385 	struct dma_fence *fence = NULL;
386 	int r;
387 
388 	src.bo = bo;
389 	dst.bo = bo;
390 	src.mem = old_mem;
391 	dst.mem = new_mem;
392 	src.offset = 0;
393 	dst.offset = 0;
394 
395 	r = amdgpu_ttm_copy_mem_to_mem(adev, &src, &dst,
396 				       new_mem->num_pages << PAGE_SHIFT,
397 				       amdgpu_bo_encrypted(abo),
398 				       bo->base.resv, &fence);
399 	if (r)
400 		goto error;
401 
402 	/* clear the space being freed */
403 	if (old_mem->mem_type == TTM_PL_VRAM &&
404 	    (abo->flags & AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE)) {
405 		struct dma_fence *wipe_fence = NULL;
406 
407 		r = amdgpu_fill_buffer(ttm_to_amdgpu_bo(bo), AMDGPU_POISON,
408 				       NULL, &wipe_fence);
409 		if (r) {
410 			goto error;
411 		} else if (wipe_fence) {
412 			dma_fence_put(fence);
413 			fence = wipe_fence;
414 		}
415 	}
416 
417 	/* Always block for VM page tables before committing the new location */
418 	if (bo->type == ttm_bo_type_kernel)
419 		r = ttm_bo_move_accel_cleanup(bo, fence, true, false, new_mem);
420 	else
421 		r = ttm_bo_move_accel_cleanup(bo, fence, evict, true, new_mem);
422 	dma_fence_put(fence);
423 	return r;
424 
425 error:
426 	if (fence)
427 		dma_fence_wait(fence, false);
428 	dma_fence_put(fence);
429 	return r;
430 }
431 
432 /*
433  * amdgpu_mem_visible - Check that memory can be accessed by ttm_bo_move_memcpy
434  *
435  * Called by amdgpu_bo_move()
436  */
437 static bool amdgpu_mem_visible(struct amdgpu_device *adev,
438 			       struct ttm_resource *mem)
439 {
440 	uint64_t mem_size = (u64)mem->num_pages << PAGE_SHIFT;
441 	struct amdgpu_res_cursor cursor;
442 
443 	if (mem->mem_type == TTM_PL_SYSTEM ||
444 	    mem->mem_type == TTM_PL_TT)
445 		return true;
446 	if (mem->mem_type != TTM_PL_VRAM)
447 		return false;
448 
449 	amdgpu_res_first(mem, 0, mem_size, &cursor);
450 
451 	/* ttm_resource_ioremap only supports contiguous memory */
452 	if (cursor.size != mem_size)
453 		return false;
454 
455 	return cursor.start + cursor.size <= adev->gmc.visible_vram_size;
456 }
457 
458 /*
459  * amdgpu_bo_move - Move a buffer object to a new memory location
460  *
461  * Called by ttm_bo_handle_move_mem()
462  */
463 static int amdgpu_bo_move(struct ttm_buffer_object *bo, bool evict,
464 			  struct ttm_operation_ctx *ctx,
465 			  struct ttm_resource *new_mem,
466 			  struct ttm_place *hop)
467 {
468 	struct amdgpu_device *adev;
469 	struct amdgpu_bo *abo;
470 	struct ttm_resource *old_mem = bo->resource;
471 	int r;
472 
473 	if (new_mem->mem_type == TTM_PL_TT ||
474 	    new_mem->mem_type == AMDGPU_PL_PREEMPT) {
475 		r = amdgpu_ttm_backend_bind(bo->bdev, bo->ttm, new_mem);
476 		if (r)
477 			return r;
478 	}
479 
480 	/* Can't move a pinned BO */
481 	abo = ttm_to_amdgpu_bo(bo);
482 	if (WARN_ON_ONCE(abo->tbo.pin_count > 0))
483 		return -EINVAL;
484 
485 	adev = amdgpu_ttm_adev(bo->bdev);
486 
487 	if (old_mem->mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
488 		ttm_bo_move_null(bo, new_mem);
489 		goto out;
490 	}
491 	if (old_mem->mem_type == TTM_PL_SYSTEM &&
492 	    (new_mem->mem_type == TTM_PL_TT ||
493 	     new_mem->mem_type == AMDGPU_PL_PREEMPT)) {
494 		ttm_bo_move_null(bo, new_mem);
495 		goto out;
496 	}
497 	if ((old_mem->mem_type == TTM_PL_TT ||
498 	     old_mem->mem_type == AMDGPU_PL_PREEMPT) &&
499 	    new_mem->mem_type == TTM_PL_SYSTEM) {
500 		r = ttm_bo_wait_ctx(bo, ctx);
501 		if (r)
502 			return r;
503 
504 		amdgpu_ttm_backend_unbind(bo->bdev, bo->ttm);
505 		ttm_resource_free(bo, &bo->resource);
506 		ttm_bo_assign_mem(bo, new_mem);
507 		goto out;
508 	}
509 
510 	if (old_mem->mem_type == AMDGPU_PL_GDS ||
511 	    old_mem->mem_type == AMDGPU_PL_GWS ||
512 	    old_mem->mem_type == AMDGPU_PL_OA ||
513 	    new_mem->mem_type == AMDGPU_PL_GDS ||
514 	    new_mem->mem_type == AMDGPU_PL_GWS ||
515 	    new_mem->mem_type == AMDGPU_PL_OA) {
516 		/* Nothing to save here */
517 		ttm_bo_move_null(bo, new_mem);
518 		goto out;
519 	}
520 
521 	if (bo->type == ttm_bo_type_device &&
522 	    new_mem->mem_type == TTM_PL_VRAM &&
523 	    old_mem->mem_type != TTM_PL_VRAM) {
524 		/* amdgpu_bo_fault_reserve_notify will re-set this if the CPU
525 		 * accesses the BO after it's moved.
526 		 */
527 		abo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
528 	}
529 
530 	if (adev->mman.buffer_funcs_enabled) {
531 		if (((old_mem->mem_type == TTM_PL_SYSTEM &&
532 		      new_mem->mem_type == TTM_PL_VRAM) ||
533 		     (old_mem->mem_type == TTM_PL_VRAM &&
534 		      new_mem->mem_type == TTM_PL_SYSTEM))) {
535 			hop->fpfn = 0;
536 			hop->lpfn = 0;
537 			hop->mem_type = TTM_PL_TT;
538 			hop->flags = TTM_PL_FLAG_TEMPORARY;
539 			return -EMULTIHOP;
540 		}
541 
542 		r = amdgpu_move_blit(bo, evict, new_mem, old_mem);
543 	} else {
544 		r = -ENODEV;
545 	}
546 
547 	if (r) {
548 		/* Check that all memory is CPU accessible */
549 		if (!amdgpu_mem_visible(adev, old_mem) ||
550 		    !amdgpu_mem_visible(adev, new_mem)) {
551 			pr_err("Move buffer fallback to memcpy unavailable\n");
552 			return r;
553 		}
554 
555 		r = ttm_bo_move_memcpy(bo, ctx, new_mem);
556 		if (r)
557 			return r;
558 	}
559 
560 out:
561 	/* update statistics */
562 	atomic64_add(bo->base.size, &adev->num_bytes_moved);
563 	amdgpu_bo_move_notify(bo, evict, new_mem);
564 	return 0;
565 }
566 
567 /*
568  * amdgpu_ttm_io_mem_reserve - Reserve a block of memory during a fault
569  *
570  * Called by ttm_mem_io_reserve() ultimately via ttm_bo_vm_fault()
571  */
572 static int amdgpu_ttm_io_mem_reserve(struct ttm_device *bdev,
573 				     struct ttm_resource *mem)
574 {
575 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
576 	size_t bus_size = (size_t)mem->num_pages << PAGE_SHIFT;
577 
578 	switch (mem->mem_type) {
579 	case TTM_PL_SYSTEM:
580 		/* system memory */
581 		return 0;
582 	case TTM_PL_TT:
583 	case AMDGPU_PL_PREEMPT:
584 		break;
585 	case TTM_PL_VRAM:
586 		mem->bus.offset = mem->start << PAGE_SHIFT;
587 		/* check if it's visible */
588 		if ((mem->bus.offset + bus_size) > adev->gmc.visible_vram_size)
589 			return -EINVAL;
590 
591 		if (adev->mman.aper_base_kaddr &&
592 		    mem->placement & TTM_PL_FLAG_CONTIGUOUS)
593 			mem->bus.addr = (u8 *)adev->mman.aper_base_kaddr +
594 					mem->bus.offset;
595 
596 		mem->bus.offset += adev->gmc.aper_base;
597 		mem->bus.is_iomem = true;
598 		break;
599 	default:
600 		return -EINVAL;
601 	}
602 	return 0;
603 }
604 
605 static unsigned long amdgpu_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
606 					   unsigned long page_offset)
607 {
608 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
609 	struct amdgpu_res_cursor cursor;
610 
611 	amdgpu_res_first(bo->resource, (u64)page_offset << PAGE_SHIFT, 0,
612 			 &cursor);
613 	return (adev->gmc.aper_base + cursor.start) >> PAGE_SHIFT;
614 }
615 
616 /**
617  * amdgpu_ttm_domain_start - Returns GPU start address
618  * @adev: amdgpu device object
619  * @type: type of the memory
620  *
621  * Returns:
622  * GPU start address of a memory domain
623  */
624 
625 uint64_t amdgpu_ttm_domain_start(struct amdgpu_device *adev, uint32_t type)
626 {
627 	switch (type) {
628 	case TTM_PL_TT:
629 		return adev->gmc.gart_start;
630 	case TTM_PL_VRAM:
631 		return adev->gmc.vram_start;
632 	}
633 
634 	return 0;
635 }
636 
637 /*
638  * TTM backend functions.
639  */
640 struct amdgpu_ttm_tt {
641 	struct ttm_tt	ttm;
642 	struct drm_gem_object	*gobj;
643 	u64			offset;
644 	uint64_t		userptr;
645 	struct task_struct	*usertask;
646 	uint32_t		userflags;
647 	bool			bound;
648 #if IS_ENABLED(CONFIG_DRM_AMDGPU_USERPTR)
649 	struct hmm_range	*range;
650 #endif
651 };
652 
653 #ifdef CONFIG_DRM_AMDGPU_USERPTR
654 /*
655  * amdgpu_ttm_tt_get_user_pages - get device accessible pages that back user
656  * memory and start HMM tracking CPU page table update
657  *
658  * Calling function must call amdgpu_ttm_tt_userptr_range_done() once and only
659  * once afterwards to stop HMM tracking
660  */
661 int amdgpu_ttm_tt_get_user_pages(struct amdgpu_bo *bo, struct page **pages)
662 {
663 	struct ttm_tt *ttm = bo->tbo.ttm;
664 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
665 	unsigned long start = gtt->userptr;
666 	struct vm_area_struct *vma;
667 	struct mm_struct *mm;
668 	bool readonly;
669 	int r = 0;
670 
671 	mm = bo->notifier.mm;
672 	if (unlikely(!mm)) {
673 		DRM_DEBUG_DRIVER("BO is not registered?\n");
674 		return -EFAULT;
675 	}
676 
677 	/* Another get_user_pages is running at the same time?? */
678 	if (WARN_ON(gtt->range))
679 		return -EFAULT;
680 
681 	if (!mmget_not_zero(mm)) /* Happens during process shutdown */
682 		return -ESRCH;
683 
684 	mmap_read_lock(mm);
685 	vma = vma_lookup(mm, start);
686 	if (unlikely(!vma)) {
687 		r = -EFAULT;
688 		goto out_unlock;
689 	}
690 	if (unlikely((gtt->userflags & AMDGPU_GEM_USERPTR_ANONONLY) &&
691 		vma->vm_file)) {
692 		r = -EPERM;
693 		goto out_unlock;
694 	}
695 
696 	readonly = amdgpu_ttm_tt_is_readonly(ttm);
697 	r = amdgpu_hmm_range_get_pages(&bo->notifier, mm, pages, start,
698 				       ttm->num_pages, &gtt->range, readonly,
699 				       true, NULL);
700 out_unlock:
701 	mmap_read_unlock(mm);
702 	if (r)
703 		pr_debug("failed %d to get user pages 0x%lx\n", r, start);
704 
705 	mmput(mm);
706 
707 	return r;
708 }
709 
710 /*
711  * amdgpu_ttm_tt_userptr_range_done - stop HMM track the CPU page table change
712  * Check if the pages backing this ttm range have been invalidated
713  *
714  * Returns: true if pages are still valid
715  */
716 bool amdgpu_ttm_tt_get_user_pages_done(struct ttm_tt *ttm)
717 {
718 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
719 	bool r = false;
720 
721 	if (!gtt || !gtt->userptr)
722 		return false;
723 
724 	DRM_DEBUG_DRIVER("user_pages_done 0x%llx pages 0x%x\n",
725 		gtt->userptr, ttm->num_pages);
726 
727 	WARN_ONCE(!gtt->range || !gtt->range->hmm_pfns,
728 		"No user pages to check\n");
729 
730 	if (gtt->range) {
731 		/*
732 		 * FIXME: Must always hold notifier_lock for this, and must
733 		 * not ignore the return code.
734 		 */
735 		r = amdgpu_hmm_range_get_pages_done(gtt->range);
736 		gtt->range = NULL;
737 	}
738 
739 	return !r;
740 }
741 #endif
742 
743 /*
744  * amdgpu_ttm_tt_set_user_pages - Copy pages in, putting old pages as necessary.
745  *
746  * Called by amdgpu_cs_list_validate(). This creates the page list
747  * that backs user memory and will ultimately be mapped into the device
748  * address space.
749  */
750 void amdgpu_ttm_tt_set_user_pages(struct ttm_tt *ttm, struct page **pages)
751 {
752 	unsigned long i;
753 
754 	for (i = 0; i < ttm->num_pages; ++i)
755 		ttm->pages[i] = pages ? pages[i] : NULL;
756 }
757 
758 /*
759  * amdgpu_ttm_tt_pin_userptr - prepare the sg table with the user pages
760  *
761  * Called by amdgpu_ttm_backend_bind()
762  **/
763 static int amdgpu_ttm_tt_pin_userptr(struct ttm_device *bdev,
764 				     struct ttm_tt *ttm)
765 {
766 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
767 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
768 	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
769 	enum dma_data_direction direction = write ?
770 		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
771 	int r;
772 
773 	/* Allocate an SG array and squash pages into it */
774 	r = sg_alloc_table_from_pages(ttm->sg, ttm->pages, ttm->num_pages, 0,
775 				      (u64)ttm->num_pages << PAGE_SHIFT,
776 				      GFP_KERNEL);
777 	if (r)
778 		goto release_sg;
779 
780 	/* Map SG to device */
781 	r = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
782 	if (r)
783 		goto release_sg;
784 
785 	/* convert SG to linear array of pages and dma addresses */
786 	drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
787 				       ttm->num_pages);
788 
789 	return 0;
790 
791 release_sg:
792 	kfree(ttm->sg);
793 	ttm->sg = NULL;
794 	return r;
795 }
796 
797 /*
798  * amdgpu_ttm_tt_unpin_userptr - Unpin and unmap userptr pages
799  */
800 static void amdgpu_ttm_tt_unpin_userptr(struct ttm_device *bdev,
801 					struct ttm_tt *ttm)
802 {
803 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
804 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
805 	int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
806 	enum dma_data_direction direction = write ?
807 		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
808 
809 	/* double check that we don't free the table twice */
810 	if (!ttm->sg || !ttm->sg->sgl)
811 		return;
812 
813 	/* unmap the pages mapped to the device */
814 	dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
815 	sg_free_table(ttm->sg);
816 
817 #if IS_ENABLED(CONFIG_DRM_AMDGPU_USERPTR)
818 	if (gtt->range) {
819 		unsigned long i;
820 
821 		for (i = 0; i < ttm->num_pages; i++) {
822 			if (ttm->pages[i] !=
823 			    hmm_pfn_to_page(gtt->range->hmm_pfns[i]))
824 				break;
825 		}
826 
827 		WARN((i == ttm->num_pages), "Missing get_user_page_done\n");
828 	}
829 #endif
830 }
831 
832 static int amdgpu_ttm_gart_bind(struct amdgpu_device *adev,
833 				struct ttm_buffer_object *tbo,
834 				uint64_t flags)
835 {
836 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(tbo);
837 	struct ttm_tt *ttm = tbo->ttm;
838 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
839 	int r;
840 
841 	if (amdgpu_bo_encrypted(abo))
842 		flags |= AMDGPU_PTE_TMZ;
843 
844 	if (abo->flags & AMDGPU_GEM_CREATE_CP_MQD_GFX9) {
845 		uint64_t page_idx = 1;
846 
847 		r = amdgpu_gart_bind(adev, gtt->offset, page_idx,
848 				gtt->ttm.dma_address, flags);
849 		if (r)
850 			goto gart_bind_fail;
851 
852 		/* The memory type of the first page defaults to UC. Now
853 		 * modify the memory type to NC from the second page of
854 		 * the BO onward.
855 		 */
856 		flags &= ~AMDGPU_PTE_MTYPE_VG10_MASK;
857 		flags |= AMDGPU_PTE_MTYPE_VG10(AMDGPU_MTYPE_NC);
858 
859 		r = amdgpu_gart_bind(adev,
860 				gtt->offset + (page_idx << PAGE_SHIFT),
861 				ttm->num_pages - page_idx,
862 				&(gtt->ttm.dma_address[page_idx]), flags);
863 	} else {
864 		r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
865 				     gtt->ttm.dma_address, flags);
866 	}
867 
868 gart_bind_fail:
869 	if (r)
870 		DRM_ERROR("failed to bind %u pages at 0x%08llX\n",
871 			  ttm->num_pages, gtt->offset);
872 
873 	return r;
874 }
875 
876 /*
877  * amdgpu_ttm_backend_bind - Bind GTT memory
878  *
879  * Called by ttm_tt_bind() on behalf of ttm_bo_handle_move_mem().
880  * This handles binding GTT memory to the device address space.
881  */
882 static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
883 				   struct ttm_tt *ttm,
884 				   struct ttm_resource *bo_mem)
885 {
886 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
887 	struct amdgpu_ttm_tt *gtt = (void*)ttm;
888 	uint64_t flags;
889 	int r = 0;
890 
891 	if (!bo_mem)
892 		return -EINVAL;
893 
894 	if (gtt->bound)
895 		return 0;
896 
897 	if (gtt->userptr) {
898 		r = amdgpu_ttm_tt_pin_userptr(bdev, ttm);
899 		if (r) {
900 			DRM_ERROR("failed to pin userptr\n");
901 			return r;
902 		}
903 	} else if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL) {
904 		if (!ttm->sg) {
905 			struct dma_buf_attachment *attach;
906 			struct sg_table *sgt;
907 
908 			attach = gtt->gobj->import_attach;
909 			sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
910 			if (IS_ERR(sgt))
911 				return PTR_ERR(sgt);
912 
913 			ttm->sg = sgt;
914 		}
915 
916 		drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
917 					       ttm->num_pages);
918 	}
919 
920 	if (!ttm->num_pages) {
921 		WARN(1, "nothing to bind %u pages for mreg %p back %p!\n",
922 		     ttm->num_pages, bo_mem, ttm);
923 	}
924 
925 	if (bo_mem->mem_type == AMDGPU_PL_GDS ||
926 	    bo_mem->mem_type == AMDGPU_PL_GWS ||
927 	    bo_mem->mem_type == AMDGPU_PL_OA)
928 		return -EINVAL;
929 
930 	if (bo_mem->mem_type != TTM_PL_TT ||
931 	    !amdgpu_gtt_mgr_has_gart_addr(bo_mem)) {
932 		gtt->offset = AMDGPU_BO_INVALID_OFFSET;
933 		return 0;
934 	}
935 
936 	/* compute PTE flags relevant to this BO memory */
937 	flags = amdgpu_ttm_tt_pte_flags(adev, ttm, bo_mem);
938 
939 	/* bind pages into GART page tables */
940 	gtt->offset = (u64)bo_mem->start << PAGE_SHIFT;
941 	r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
942 		gtt->ttm.dma_address, flags);
943 
944 	if (r)
945 		DRM_ERROR("failed to bind %u pages at 0x%08llX\n",
946 			  ttm->num_pages, gtt->offset);
947 	gtt->bound = true;
948 	return r;
949 }
950 
951 /*
952  * amdgpu_ttm_alloc_gart - Make sure buffer object is accessible either
953  * through AGP or GART aperture.
954  *
955  * If bo is accessible through AGP aperture, then use AGP aperture
956  * to access bo; otherwise allocate logical space in GART aperture
957  * and map bo to GART aperture.
958  */
959 int amdgpu_ttm_alloc_gart(struct ttm_buffer_object *bo)
960 {
961 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
962 	struct ttm_operation_ctx ctx = { false, false };
963 	struct amdgpu_ttm_tt *gtt = (void *)bo->ttm;
964 	struct ttm_placement placement;
965 	struct ttm_place placements;
966 	struct ttm_resource *tmp;
967 	uint64_t addr, flags;
968 	int r;
969 
970 	if (bo->resource->start != AMDGPU_BO_INVALID_OFFSET)
971 		return 0;
972 
973 	addr = amdgpu_gmc_agp_addr(bo);
974 	if (addr != AMDGPU_BO_INVALID_OFFSET) {
975 		bo->resource->start = addr >> PAGE_SHIFT;
976 		return 0;
977 	}
978 
979 	/* allocate GART space */
980 	placement.num_placement = 1;
981 	placement.placement = &placements;
982 	placement.num_busy_placement = 1;
983 	placement.busy_placement = &placements;
984 	placements.fpfn = 0;
985 	placements.lpfn = adev->gmc.gart_size >> PAGE_SHIFT;
986 	placements.mem_type = TTM_PL_TT;
987 	placements.flags = bo->resource->placement;
988 
989 	r = ttm_bo_mem_space(bo, &placement, &tmp, &ctx);
990 	if (unlikely(r))
991 		return r;
992 
993 	/* compute PTE flags for this buffer object */
994 	flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, tmp);
995 
996 	/* Bind pages */
997 	gtt->offset = (u64)tmp->start << PAGE_SHIFT;
998 	r = amdgpu_ttm_gart_bind(adev, bo, flags);
999 	if (unlikely(r)) {
1000 		ttm_resource_free(bo, &tmp);
1001 		return r;
1002 	}
1003 
1004 	amdgpu_gart_invalidate_tlb(adev);
1005 	ttm_resource_free(bo, &bo->resource);
1006 	ttm_bo_assign_mem(bo, tmp);
1007 
1008 	return 0;
1009 }
1010 
1011 /*
1012  * amdgpu_ttm_recover_gart - Rebind GTT pages
1013  *
1014  * Called by amdgpu_gtt_mgr_recover() from amdgpu_device_reset() to
1015  * rebind GTT pages during a GPU reset.
1016  */
1017 int amdgpu_ttm_recover_gart(struct ttm_buffer_object *tbo)
1018 {
1019 	struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
1020 	uint64_t flags;
1021 	int r;
1022 
1023 	if (!tbo->ttm)
1024 		return 0;
1025 
1026 	flags = amdgpu_ttm_tt_pte_flags(adev, tbo->ttm, tbo->resource);
1027 	r = amdgpu_ttm_gart_bind(adev, tbo, flags);
1028 
1029 	return r;
1030 }
1031 
1032 /*
1033  * amdgpu_ttm_backend_unbind - Unbind GTT mapped pages
1034  *
1035  * Called by ttm_tt_unbind() on behalf of ttm_bo_move_ttm() and
1036  * ttm_tt_destroy().
1037  */
1038 static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
1039 				      struct ttm_tt *ttm)
1040 {
1041 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1042 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1043 	int r;
1044 
1045 	/* if the pages have userptr pinning then clear that first */
1046 	if (gtt->userptr) {
1047 		amdgpu_ttm_tt_unpin_userptr(bdev, ttm);
1048 	} else if (ttm->sg && gtt->gobj->import_attach) {
1049 		struct dma_buf_attachment *attach;
1050 
1051 		attach = gtt->gobj->import_attach;
1052 		dma_buf_unmap_attachment(attach, ttm->sg, DMA_BIDIRECTIONAL);
1053 		ttm->sg = NULL;
1054 	}
1055 
1056 	if (!gtt->bound)
1057 		return;
1058 
1059 	if (gtt->offset == AMDGPU_BO_INVALID_OFFSET)
1060 		return;
1061 
1062 	/* unbind shouldn't be done for GDS/GWS/OA in ttm_bo_clean_mm */
1063 	r = amdgpu_gart_unbind(adev, gtt->offset, ttm->num_pages);
1064 	if (r)
1065 		DRM_ERROR("failed to unbind %u pages at 0x%08llX\n",
1066 			  gtt->ttm.num_pages, gtt->offset);
1067 	gtt->bound = false;
1068 }
1069 
1070 static void amdgpu_ttm_backend_destroy(struct ttm_device *bdev,
1071 				       struct ttm_tt *ttm)
1072 {
1073 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1074 
1075 	if (gtt->usertask)
1076 		put_task_struct(gtt->usertask);
1077 
1078 	ttm_tt_fini(&gtt->ttm);
1079 	kfree(gtt);
1080 }
1081 
1082 /**
1083  * amdgpu_ttm_tt_create - Create a ttm_tt object for a given BO
1084  *
1085  * @bo: The buffer object to create a GTT ttm_tt object around
1086  * @page_flags: Page flags to be added to the ttm_tt object
1087  *
1088  * Called by ttm_tt_create().
1089  */
1090 static struct ttm_tt *amdgpu_ttm_tt_create(struct ttm_buffer_object *bo,
1091 					   uint32_t page_flags)
1092 {
1093 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1094 	struct amdgpu_ttm_tt *gtt;
1095 	enum ttm_caching caching;
1096 
1097 	gtt = kzalloc(sizeof(struct amdgpu_ttm_tt), GFP_KERNEL);
1098 	if (gtt == NULL) {
1099 		return NULL;
1100 	}
1101 	gtt->gobj = &bo->base;
1102 
1103 	if (abo->flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
1104 		caching = ttm_write_combined;
1105 	else
1106 		caching = ttm_cached;
1107 
1108 	/* allocate space for the uninitialized page entries */
1109 	if (ttm_sg_tt_init(&gtt->ttm, bo, page_flags, caching)) {
1110 		kfree(gtt);
1111 		return NULL;
1112 	}
1113 	return &gtt->ttm;
1114 }
1115 
1116 /*
1117  * amdgpu_ttm_tt_populate - Map GTT pages visible to the device
1118  *
1119  * Map the pages of a ttm_tt object to an address space visible
1120  * to the underlying device.
1121  */
1122 static int amdgpu_ttm_tt_populate(struct ttm_device *bdev,
1123 				  struct ttm_tt *ttm,
1124 				  struct ttm_operation_ctx *ctx)
1125 {
1126 	struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1127 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1128 	pgoff_t i;
1129 	int ret;
1130 
1131 	/* user pages are bound by amdgpu_ttm_tt_pin_userptr() */
1132 	if (gtt->userptr) {
1133 		ttm->sg = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
1134 		if (!ttm->sg)
1135 			return -ENOMEM;
1136 		return 0;
1137 	}
1138 
1139 	if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
1140 		return 0;
1141 
1142 	ret = ttm_pool_alloc(&adev->mman.bdev.pool, ttm, ctx);
1143 	if (ret)
1144 		return ret;
1145 
1146 	for (i = 0; i < ttm->num_pages; ++i)
1147 		ttm->pages[i]->mapping = bdev->dev_mapping;
1148 
1149 	return 0;
1150 }
1151 
1152 /*
1153  * amdgpu_ttm_tt_unpopulate - unmap GTT pages and unpopulate page arrays
1154  *
1155  * Unmaps pages of a ttm_tt object from the device address space and
1156  * unpopulates the page array backing it.
1157  */
1158 static void amdgpu_ttm_tt_unpopulate(struct ttm_device *bdev,
1159 				     struct ttm_tt *ttm)
1160 {
1161 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1162 	struct amdgpu_device *adev;
1163 	pgoff_t i;
1164 
1165 	amdgpu_ttm_backend_unbind(bdev, ttm);
1166 
1167 	if (gtt->userptr) {
1168 		amdgpu_ttm_tt_set_user_pages(ttm, NULL);
1169 		kfree(ttm->sg);
1170 		ttm->sg = NULL;
1171 		return;
1172 	}
1173 
1174 	if (ttm->page_flags & TTM_TT_FLAG_EXTERNAL)
1175 		return;
1176 
1177 	for (i = 0; i < ttm->num_pages; ++i)
1178 		ttm->pages[i]->mapping = NULL;
1179 
1180 	adev = amdgpu_ttm_adev(bdev);
1181 	return ttm_pool_free(&adev->mman.bdev.pool, ttm);
1182 }
1183 
1184 /**
1185  * amdgpu_ttm_tt_set_userptr - Initialize userptr GTT ttm_tt for the current
1186  * task
1187  *
1188  * @bo: The ttm_buffer_object to bind this userptr to
1189  * @addr:  The address in the current tasks VM space to use
1190  * @flags: Requirements of userptr object.
1191  *
1192  * Called by amdgpu_gem_userptr_ioctl() to bind userptr pages
1193  * to current task
1194  */
1195 int amdgpu_ttm_tt_set_userptr(struct ttm_buffer_object *bo,
1196 			      uint64_t addr, uint32_t flags)
1197 {
1198 	struct amdgpu_ttm_tt *gtt;
1199 
1200 	if (!bo->ttm) {
1201 		/* TODO: We want a separate TTM object type for userptrs */
1202 		bo->ttm = amdgpu_ttm_tt_create(bo, 0);
1203 		if (bo->ttm == NULL)
1204 			return -ENOMEM;
1205 	}
1206 
1207 	/* Set TTM_TT_FLAG_EXTERNAL before populate but after create. */
1208 	bo->ttm->page_flags |= TTM_TT_FLAG_EXTERNAL;
1209 
1210 	gtt = (void *)bo->ttm;
1211 	gtt->userptr = addr;
1212 	gtt->userflags = flags;
1213 
1214 	if (gtt->usertask)
1215 		put_task_struct(gtt->usertask);
1216 	gtt->usertask = current->group_leader;
1217 	get_task_struct(gtt->usertask);
1218 
1219 	return 0;
1220 }
1221 
1222 /*
1223  * amdgpu_ttm_tt_get_usermm - Return memory manager for ttm_tt object
1224  */
1225 struct mm_struct *amdgpu_ttm_tt_get_usermm(struct ttm_tt *ttm)
1226 {
1227 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1228 
1229 	if (gtt == NULL)
1230 		return NULL;
1231 
1232 	if (gtt->usertask == NULL)
1233 		return NULL;
1234 
1235 	return gtt->usertask->mm;
1236 }
1237 
1238 /*
1239  * amdgpu_ttm_tt_affect_userptr - Determine if a ttm_tt object lays inside an
1240  * address range for the current task.
1241  *
1242  */
1243 bool amdgpu_ttm_tt_affect_userptr(struct ttm_tt *ttm, unsigned long start,
1244 				  unsigned long end, unsigned long *userptr)
1245 {
1246 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1247 	unsigned long size;
1248 
1249 	if (gtt == NULL || !gtt->userptr)
1250 		return false;
1251 
1252 	/* Return false if no part of the ttm_tt object lies within
1253 	 * the range
1254 	 */
1255 	size = (unsigned long)gtt->ttm.num_pages * PAGE_SIZE;
1256 	if (gtt->userptr > end || gtt->userptr + size <= start)
1257 		return false;
1258 
1259 	if (userptr)
1260 		*userptr = gtt->userptr;
1261 	return true;
1262 }
1263 
1264 /*
1265  * amdgpu_ttm_tt_is_userptr - Have the pages backing by userptr?
1266  */
1267 bool amdgpu_ttm_tt_is_userptr(struct ttm_tt *ttm)
1268 {
1269 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1270 
1271 	if (gtt == NULL || !gtt->userptr)
1272 		return false;
1273 
1274 	return true;
1275 }
1276 
1277 /*
1278  * amdgpu_ttm_tt_is_readonly - Is the ttm_tt object read only?
1279  */
1280 bool amdgpu_ttm_tt_is_readonly(struct ttm_tt *ttm)
1281 {
1282 	struct amdgpu_ttm_tt *gtt = (void *)ttm;
1283 
1284 	if (gtt == NULL)
1285 		return false;
1286 
1287 	return !!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1288 }
1289 
1290 /**
1291  * amdgpu_ttm_tt_pde_flags - Compute PDE flags for ttm_tt object
1292  *
1293  * @ttm: The ttm_tt object to compute the flags for
1294  * @mem: The memory registry backing this ttm_tt object
1295  *
1296  * Figure out the flags to use for a VM PDE (Page Directory Entry).
1297  */
1298 uint64_t amdgpu_ttm_tt_pde_flags(struct ttm_tt *ttm, struct ttm_resource *mem)
1299 {
1300 	uint64_t flags = 0;
1301 
1302 	if (mem && mem->mem_type != TTM_PL_SYSTEM)
1303 		flags |= AMDGPU_PTE_VALID;
1304 
1305 	if (mem && (mem->mem_type == TTM_PL_TT ||
1306 		    mem->mem_type == AMDGPU_PL_PREEMPT)) {
1307 		flags |= AMDGPU_PTE_SYSTEM;
1308 
1309 		if (ttm->caching == ttm_cached)
1310 			flags |= AMDGPU_PTE_SNOOPED;
1311 	}
1312 
1313 	if (mem && mem->mem_type == TTM_PL_VRAM &&
1314 			mem->bus.caching == ttm_cached)
1315 		flags |= AMDGPU_PTE_SNOOPED;
1316 
1317 	return flags;
1318 }
1319 
1320 /**
1321  * amdgpu_ttm_tt_pte_flags - Compute PTE flags for ttm_tt object
1322  *
1323  * @adev: amdgpu_device pointer
1324  * @ttm: The ttm_tt object to compute the flags for
1325  * @mem: The memory registry backing this ttm_tt object
1326  *
1327  * Figure out the flags to use for a VM PTE (Page Table Entry).
1328  */
1329 uint64_t amdgpu_ttm_tt_pte_flags(struct amdgpu_device *adev, struct ttm_tt *ttm,
1330 				 struct ttm_resource *mem)
1331 {
1332 	uint64_t flags = amdgpu_ttm_tt_pde_flags(ttm, mem);
1333 
1334 	flags |= adev->gart.gart_pte_flags;
1335 	flags |= AMDGPU_PTE_READABLE;
1336 
1337 	if (!amdgpu_ttm_tt_is_readonly(ttm))
1338 		flags |= AMDGPU_PTE_WRITEABLE;
1339 
1340 	return flags;
1341 }
1342 
1343 /*
1344  * amdgpu_ttm_bo_eviction_valuable - Check to see if we can evict a buffer
1345  * object.
1346  *
1347  * Return true if eviction is sensible. Called by ttm_mem_evict_first() on
1348  * behalf of ttm_bo_mem_force_space() which tries to evict buffer objects until
1349  * it can find space for a new object and by ttm_bo_force_list_clean() which is
1350  * used to clean out a memory space.
1351  */
1352 static bool amdgpu_ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
1353 					    const struct ttm_place *place)
1354 {
1355 	unsigned long num_pages = bo->resource->num_pages;
1356 	struct amdgpu_res_cursor cursor;
1357 	struct dma_resv_list *flist;
1358 	struct dma_fence *f;
1359 	int i;
1360 
1361 	/* Swapout? */
1362 	if (bo->resource->mem_type == TTM_PL_SYSTEM)
1363 		return true;
1364 
1365 	if (bo->type == ttm_bo_type_kernel &&
1366 	    !amdgpu_vm_evictable(ttm_to_amdgpu_bo(bo)))
1367 		return false;
1368 
1369 	/* If bo is a KFD BO, check if the bo belongs to the current process.
1370 	 * If true, then return false as any KFD process needs all its BOs to
1371 	 * be resident to run successfully
1372 	 */
1373 	flist = dma_resv_shared_list(bo->base.resv);
1374 	if (flist) {
1375 		for (i = 0; i < flist->shared_count; ++i) {
1376 			f = rcu_dereference_protected(flist->shared[i],
1377 				dma_resv_held(bo->base.resv));
1378 			if (amdkfd_fence_check_mm(f, current->mm))
1379 				return false;
1380 		}
1381 	}
1382 
1383 	switch (bo->resource->mem_type) {
1384 	case AMDGPU_PL_PREEMPT:
1385 		/* Preemptible BOs don't own system resources managed by the
1386 		 * driver (pages, VRAM, GART space). They point to resources
1387 		 * owned by someone else (e.g. pageable memory in user mode
1388 		 * or a DMABuf). They are used in a preemptible context so we
1389 		 * can guarantee no deadlocks and good QoS in case of MMU
1390 		 * notifiers or DMABuf move notifiers from the resource owner.
1391 		 */
1392 		return false;
1393 	case TTM_PL_TT:
1394 		if (amdgpu_bo_is_amdgpu_bo(bo) &&
1395 		    amdgpu_bo_encrypted(ttm_to_amdgpu_bo(bo)))
1396 			return false;
1397 		return true;
1398 
1399 	case TTM_PL_VRAM:
1400 		/* Check each drm MM node individually */
1401 		amdgpu_res_first(bo->resource, 0, (u64)num_pages << PAGE_SHIFT,
1402 				 &cursor);
1403 		while (cursor.remaining) {
1404 			if (place->fpfn < PFN_DOWN(cursor.start + cursor.size)
1405 			    && !(place->lpfn &&
1406 				 place->lpfn <= PFN_DOWN(cursor.start)))
1407 				return true;
1408 
1409 			amdgpu_res_next(&cursor, cursor.size);
1410 		}
1411 		return false;
1412 
1413 	default:
1414 		break;
1415 	}
1416 
1417 	return ttm_bo_eviction_valuable(bo, place);
1418 }
1419 
1420 static void amdgpu_ttm_vram_mm_access(struct amdgpu_device *adev, loff_t pos,
1421 				      void *buf, size_t size, bool write)
1422 {
1423 	while (size) {
1424 		uint64_t aligned_pos = ALIGN_DOWN(pos, 4);
1425 		uint64_t bytes = 4 - (pos & 0x3);
1426 		uint32_t shift = (pos & 0x3) * 8;
1427 		uint32_t mask = 0xffffffff << shift;
1428 		uint32_t value = 0;
1429 
1430 		if (size < bytes) {
1431 			mask &= 0xffffffff >> (bytes - size) * 8;
1432 			bytes = size;
1433 		}
1434 
1435 		if (mask != 0xffffffff) {
1436 			amdgpu_device_mm_access(adev, aligned_pos, &value, 4, false);
1437 			if (write) {
1438 				value &= ~mask;
1439 				value |= (*(uint32_t *)buf << shift) & mask;
1440 				amdgpu_device_mm_access(adev, aligned_pos, &value, 4, true);
1441 			} else {
1442 				value = (value & mask) >> shift;
1443 				memcpy(buf, &value, bytes);
1444 			}
1445 		} else {
1446 			amdgpu_device_mm_access(adev, aligned_pos, buf, 4, write);
1447 		}
1448 
1449 		pos += bytes;
1450 		buf += bytes;
1451 		size -= bytes;
1452 	}
1453 }
1454 
1455 /**
1456  * amdgpu_ttm_access_memory - Read or Write memory that backs a buffer object.
1457  *
1458  * @bo:  The buffer object to read/write
1459  * @offset:  Offset into buffer object
1460  * @buf:  Secondary buffer to write/read from
1461  * @len: Length in bytes of access
1462  * @write:  true if writing
1463  *
1464  * This is used to access VRAM that backs a buffer object via MMIO
1465  * access for debugging purposes.
1466  */
1467 static int amdgpu_ttm_access_memory(struct ttm_buffer_object *bo,
1468 				    unsigned long offset, void *buf, int len,
1469 				    int write)
1470 {
1471 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1472 	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1473 	struct amdgpu_res_cursor cursor;
1474 	int ret = 0;
1475 
1476 	if (bo->resource->mem_type != TTM_PL_VRAM)
1477 		return -EIO;
1478 
1479 	amdgpu_res_first(bo->resource, offset, len, &cursor);
1480 	while (cursor.remaining) {
1481 		size_t count, size = cursor.size;
1482 		loff_t pos = cursor.start;
1483 
1484 		count = amdgpu_device_aper_access(adev, pos, buf, size, write);
1485 		size -= count;
1486 		if (size) {
1487 			/* using MM to access rest vram and handle un-aligned address */
1488 			pos += count;
1489 			buf += count;
1490 			amdgpu_ttm_vram_mm_access(adev, pos, buf, size, write);
1491 		}
1492 
1493 		ret += cursor.size;
1494 		buf += cursor.size;
1495 		amdgpu_res_next(&cursor, cursor.size);
1496 	}
1497 
1498 	return ret;
1499 }
1500 
1501 static void
1502 amdgpu_bo_delete_mem_notify(struct ttm_buffer_object *bo)
1503 {
1504 	amdgpu_bo_move_notify(bo, false, NULL);
1505 }
1506 
1507 static struct ttm_device_funcs amdgpu_bo_driver = {
1508 	.ttm_tt_create = &amdgpu_ttm_tt_create,
1509 	.ttm_tt_populate = &amdgpu_ttm_tt_populate,
1510 	.ttm_tt_unpopulate = &amdgpu_ttm_tt_unpopulate,
1511 	.ttm_tt_destroy = &amdgpu_ttm_backend_destroy,
1512 	.eviction_valuable = amdgpu_ttm_bo_eviction_valuable,
1513 	.evict_flags = &amdgpu_evict_flags,
1514 	.move = &amdgpu_bo_move,
1515 	.delete_mem_notify = &amdgpu_bo_delete_mem_notify,
1516 	.release_notify = &amdgpu_bo_release_notify,
1517 	.io_mem_reserve = &amdgpu_ttm_io_mem_reserve,
1518 	.io_mem_pfn = amdgpu_ttm_io_mem_pfn,
1519 	.access_memory = &amdgpu_ttm_access_memory,
1520 	.del_from_lru_notify = &amdgpu_vm_del_from_lru_notify
1521 };
1522 
1523 /*
1524  * Firmware Reservation functions
1525  */
1526 /**
1527  * amdgpu_ttm_fw_reserve_vram_fini - free fw reserved vram
1528  *
1529  * @adev: amdgpu_device pointer
1530  *
1531  * free fw reserved vram if it has been reserved.
1532  */
1533 static void amdgpu_ttm_fw_reserve_vram_fini(struct amdgpu_device *adev)
1534 {
1535 	amdgpu_bo_free_kernel(&adev->mman.fw_vram_usage_reserved_bo,
1536 		NULL, &adev->mman.fw_vram_usage_va);
1537 }
1538 
1539 /**
1540  * amdgpu_ttm_fw_reserve_vram_init - create bo vram reservation from fw
1541  *
1542  * @adev: amdgpu_device pointer
1543  *
1544  * create bo vram reservation from fw.
1545  */
1546 static int amdgpu_ttm_fw_reserve_vram_init(struct amdgpu_device *adev)
1547 {
1548 	uint64_t vram_size = adev->gmc.visible_vram_size;
1549 
1550 	adev->mman.fw_vram_usage_va = NULL;
1551 	adev->mman.fw_vram_usage_reserved_bo = NULL;
1552 
1553 	if (adev->mman.fw_vram_usage_size == 0 ||
1554 	    adev->mman.fw_vram_usage_size > vram_size)
1555 		return 0;
1556 
1557 	return amdgpu_bo_create_kernel_at(adev,
1558 					  adev->mman.fw_vram_usage_start_offset,
1559 					  adev->mman.fw_vram_usage_size,
1560 					  AMDGPU_GEM_DOMAIN_VRAM,
1561 					  &adev->mman.fw_vram_usage_reserved_bo,
1562 					  &adev->mman.fw_vram_usage_va);
1563 }
1564 
1565 /*
1566  * Memoy training reservation functions
1567  */
1568 
1569 /**
1570  * amdgpu_ttm_training_reserve_vram_fini - free memory training reserved vram
1571  *
1572  * @adev: amdgpu_device pointer
1573  *
1574  * free memory training reserved vram if it has been reserved.
1575  */
1576 static int amdgpu_ttm_training_reserve_vram_fini(struct amdgpu_device *adev)
1577 {
1578 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1579 
1580 	ctx->init = PSP_MEM_TRAIN_NOT_SUPPORT;
1581 	amdgpu_bo_free_kernel(&ctx->c2p_bo, NULL, NULL);
1582 	ctx->c2p_bo = NULL;
1583 
1584 	return 0;
1585 }
1586 
1587 static void amdgpu_ttm_training_data_block_init(struct amdgpu_device *adev)
1588 {
1589 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1590 
1591 	memset(ctx, 0, sizeof(*ctx));
1592 
1593 	ctx->c2p_train_data_offset =
1594 		ALIGN((adev->gmc.mc_vram_size - adev->mman.discovery_tmr_size - SZ_1M), SZ_1M);
1595 	ctx->p2c_train_data_offset =
1596 		(adev->gmc.mc_vram_size - GDDR6_MEM_TRAINING_OFFSET);
1597 	ctx->train_data_size =
1598 		GDDR6_MEM_TRAINING_DATA_SIZE_IN_BYTES;
1599 
1600 	DRM_DEBUG("train_data_size:%llx,p2c_train_data_offset:%llx,c2p_train_data_offset:%llx.\n",
1601 			ctx->train_data_size,
1602 			ctx->p2c_train_data_offset,
1603 			ctx->c2p_train_data_offset);
1604 }
1605 
1606 /*
1607  * reserve TMR memory at the top of VRAM which holds
1608  * IP Discovery data and is protected by PSP.
1609  */
1610 static int amdgpu_ttm_reserve_tmr(struct amdgpu_device *adev)
1611 {
1612 	int ret;
1613 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1614 	bool mem_train_support = false;
1615 
1616 	if (!amdgpu_sriov_vf(adev)) {
1617 		if (amdgpu_atomfirmware_mem_training_supported(adev))
1618 			mem_train_support = true;
1619 		else
1620 			DRM_DEBUG("memory training does not support!\n");
1621 	}
1622 
1623 	/*
1624 	 * Query reserved tmr size through atom firmwareinfo for Sienna_Cichlid and onwards for all
1625 	 * the use cases (IP discovery/G6 memory training/profiling/diagnostic data.etc)
1626 	 *
1627 	 * Otherwise, fallback to legacy approach to check and reserve tmr block for ip
1628 	 * discovery data and G6 memory training data respectively
1629 	 */
1630 	adev->mman.discovery_tmr_size =
1631 		amdgpu_atomfirmware_get_fw_reserved_fb_size(adev);
1632 	if (!adev->mman.discovery_tmr_size)
1633 		adev->mman.discovery_tmr_size = DISCOVERY_TMR_OFFSET;
1634 
1635 	if (mem_train_support) {
1636 		/* reserve vram for mem train according to TMR location */
1637 		amdgpu_ttm_training_data_block_init(adev);
1638 		ret = amdgpu_bo_create_kernel_at(adev,
1639 					 ctx->c2p_train_data_offset,
1640 					 ctx->train_data_size,
1641 					 AMDGPU_GEM_DOMAIN_VRAM,
1642 					 &ctx->c2p_bo,
1643 					 NULL);
1644 		if (ret) {
1645 			DRM_ERROR("alloc c2p_bo failed(%d)!\n", ret);
1646 			amdgpu_ttm_training_reserve_vram_fini(adev);
1647 			return ret;
1648 		}
1649 		ctx->init = PSP_MEM_TRAIN_RESERVE_SUCCESS;
1650 	}
1651 
1652 	ret = amdgpu_bo_create_kernel_at(adev,
1653 				adev->gmc.real_vram_size - adev->mman.discovery_tmr_size,
1654 				adev->mman.discovery_tmr_size,
1655 				AMDGPU_GEM_DOMAIN_VRAM,
1656 				&adev->mman.discovery_memory,
1657 				NULL);
1658 	if (ret) {
1659 		DRM_ERROR("alloc tmr failed(%d)!\n", ret);
1660 		amdgpu_bo_free_kernel(&adev->mman.discovery_memory, NULL, NULL);
1661 		return ret;
1662 	}
1663 
1664 	return 0;
1665 }
1666 
1667 /*
1668  * amdgpu_ttm_init - Init the memory management (ttm) as well as various
1669  * gtt/vram related fields.
1670  *
1671  * This initializes all of the memory space pools that the TTM layer
1672  * will need such as the GTT space (system memory mapped to the device),
1673  * VRAM (on-board memory), and on-chip memories (GDS, GWS, OA) which
1674  * can be mapped per VMID.
1675  */
1676 int amdgpu_ttm_init(struct amdgpu_device *adev)
1677 {
1678 	uint64_t gtt_size;
1679 	int r;
1680 	u64 vis_vram_limit;
1681 
1682 	mutex_init(&adev->mman.gtt_window_lock);
1683 
1684 	/* No others user of address space so set it to 0 */
1685 	r = ttm_device_init(&adev->mman.bdev, &amdgpu_bo_driver, adev->dev,
1686 			       adev_to_drm(adev)->anon_inode->i_mapping,
1687 			       adev_to_drm(adev)->vma_offset_manager,
1688 			       adev->need_swiotlb,
1689 			       dma_addressing_limited(adev->dev));
1690 	if (r) {
1691 		DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
1692 		return r;
1693 	}
1694 	adev->mman.initialized = true;
1695 
1696 	/* Initialize VRAM pool with all of VRAM divided into pages */
1697 	r = amdgpu_vram_mgr_init(adev);
1698 	if (r) {
1699 		DRM_ERROR("Failed initializing VRAM heap.\n");
1700 		return r;
1701 	}
1702 
1703 	/* Reduce size of CPU-visible VRAM if requested */
1704 	vis_vram_limit = (u64)amdgpu_vis_vram_limit * 1024 * 1024;
1705 	if (amdgpu_vis_vram_limit > 0 &&
1706 	    vis_vram_limit <= adev->gmc.visible_vram_size)
1707 		adev->gmc.visible_vram_size = vis_vram_limit;
1708 
1709 	/* Change the size here instead of the init above so only lpfn is affected */
1710 	amdgpu_ttm_set_buffer_funcs_status(adev, false);
1711 #ifdef CONFIG_64BIT
1712 #ifdef CONFIG_X86
1713 	if (adev->gmc.xgmi.connected_to_cpu)
1714 		adev->mman.aper_base_kaddr = ioremap_cache(adev->gmc.aper_base,
1715 				adev->gmc.visible_vram_size);
1716 
1717 	else
1718 #endif
1719 		adev->mman.aper_base_kaddr = ioremap_wc(adev->gmc.aper_base,
1720 				adev->gmc.visible_vram_size);
1721 #endif
1722 
1723 	/*
1724 	 *The reserved vram for firmware must be pinned to the specified
1725 	 *place on the VRAM, so reserve it early.
1726 	 */
1727 	r = amdgpu_ttm_fw_reserve_vram_init(adev);
1728 	if (r) {
1729 		return r;
1730 	}
1731 
1732 	/*
1733 	 * only NAVI10 and onwards ASIC support for IP discovery.
1734 	 * If IP discovery enabled, a block of memory should be
1735 	 * reserved for IP discovey.
1736 	 */
1737 	if (adev->mman.discovery_bin) {
1738 		r = amdgpu_ttm_reserve_tmr(adev);
1739 		if (r)
1740 			return r;
1741 	}
1742 
1743 	/* allocate memory as required for VGA
1744 	 * This is used for VGA emulation and pre-OS scanout buffers to
1745 	 * avoid display artifacts while transitioning between pre-OS
1746 	 * and driver.  */
1747 	r = amdgpu_bo_create_kernel_at(adev, 0, adev->mman.stolen_vga_size,
1748 				       AMDGPU_GEM_DOMAIN_VRAM,
1749 				       &adev->mman.stolen_vga_memory,
1750 				       NULL);
1751 	if (r)
1752 		return r;
1753 	r = amdgpu_bo_create_kernel_at(adev, adev->mman.stolen_vga_size,
1754 				       adev->mman.stolen_extended_size,
1755 				       AMDGPU_GEM_DOMAIN_VRAM,
1756 				       &adev->mman.stolen_extended_memory,
1757 				       NULL);
1758 	if (r)
1759 		return r;
1760 	r = amdgpu_bo_create_kernel_at(adev, adev->mman.stolen_reserved_offset,
1761 				       adev->mman.stolen_reserved_size,
1762 				       AMDGPU_GEM_DOMAIN_VRAM,
1763 				       &adev->mman.stolen_reserved_memory,
1764 				       NULL);
1765 	if (r)
1766 		return r;
1767 
1768 	DRM_INFO("amdgpu: %uM of VRAM memory ready\n",
1769 		 (unsigned) (adev->gmc.real_vram_size / (1024 * 1024)));
1770 
1771 	/* Compute GTT size, either bsaed on 3/4th the size of RAM size
1772 	 * or whatever the user passed on module init */
1773 	if (amdgpu_gtt_size == -1) {
1774 		struct sysinfo si;
1775 
1776 		si_meminfo(&si);
1777 		gtt_size = min(max((AMDGPU_DEFAULT_GTT_SIZE_MB << 20),
1778 			       adev->gmc.mc_vram_size),
1779 			       ((uint64_t)si.totalram * si.mem_unit * 3/4));
1780 	}
1781 	else
1782 		gtt_size = (uint64_t)amdgpu_gtt_size << 20;
1783 
1784 	/* Initialize GTT memory pool */
1785 	r = amdgpu_gtt_mgr_init(adev, gtt_size);
1786 	if (r) {
1787 		DRM_ERROR("Failed initializing GTT heap.\n");
1788 		return r;
1789 	}
1790 	DRM_INFO("amdgpu: %uM of GTT memory ready.\n",
1791 		 (unsigned)(gtt_size / (1024 * 1024)));
1792 
1793 	/* Initialize preemptible memory pool */
1794 	r = amdgpu_preempt_mgr_init(adev);
1795 	if (r) {
1796 		DRM_ERROR("Failed initializing PREEMPT heap.\n");
1797 		return r;
1798 	}
1799 
1800 	/* Initialize various on-chip memory pools */
1801 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GDS, adev->gds.gds_size);
1802 	if (r) {
1803 		DRM_ERROR("Failed initializing GDS heap.\n");
1804 		return r;
1805 	}
1806 
1807 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GWS, adev->gds.gws_size);
1808 	if (r) {
1809 		DRM_ERROR("Failed initializing gws heap.\n");
1810 		return r;
1811 	}
1812 
1813 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_OA, adev->gds.oa_size);
1814 	if (r) {
1815 		DRM_ERROR("Failed initializing oa heap.\n");
1816 		return r;
1817 	}
1818 
1819 	return 0;
1820 }
1821 
1822 /*
1823  * amdgpu_ttm_fini - De-initialize the TTM memory pools
1824  */
1825 void amdgpu_ttm_fini(struct amdgpu_device *adev)
1826 {
1827 	if (!adev->mman.initialized)
1828 		return;
1829 
1830 	amdgpu_ttm_training_reserve_vram_fini(adev);
1831 	/* return the stolen vga memory back to VRAM */
1832 	amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
1833 	amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
1834 	/* return the IP Discovery TMR memory back to VRAM */
1835 	amdgpu_bo_free_kernel(&adev->mman.discovery_memory, NULL, NULL);
1836 	if (adev->mman.stolen_reserved_size)
1837 		amdgpu_bo_free_kernel(&adev->mman.stolen_reserved_memory,
1838 				      NULL, NULL);
1839 	amdgpu_ttm_fw_reserve_vram_fini(adev);
1840 
1841 	amdgpu_vram_mgr_fini(adev);
1842 	amdgpu_gtt_mgr_fini(adev);
1843 	amdgpu_preempt_mgr_fini(adev);
1844 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GDS);
1845 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GWS);
1846 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_OA);
1847 	ttm_device_fini(&adev->mman.bdev);
1848 	adev->mman.initialized = false;
1849 	DRM_INFO("amdgpu: ttm finalized\n");
1850 }
1851 
1852 /**
1853  * amdgpu_ttm_set_buffer_funcs_status - enable/disable use of buffer functions
1854  *
1855  * @adev: amdgpu_device pointer
1856  * @enable: true when we can use buffer functions.
1857  *
1858  * Enable/disable use of buffer functions during suspend/resume. This should
1859  * only be called at bootup or when userspace isn't running.
1860  */
1861 void amdgpu_ttm_set_buffer_funcs_status(struct amdgpu_device *adev, bool enable)
1862 {
1863 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM);
1864 	uint64_t size;
1865 	int r;
1866 
1867 	if (!adev->mman.initialized || amdgpu_in_reset(adev) ||
1868 	    adev->mman.buffer_funcs_enabled == enable)
1869 		return;
1870 
1871 	if (enable) {
1872 		struct amdgpu_ring *ring;
1873 		struct drm_gpu_scheduler *sched;
1874 
1875 		ring = adev->mman.buffer_funcs_ring;
1876 		sched = &ring->sched;
1877 		r = drm_sched_entity_init(&adev->mman.entity,
1878 					  DRM_SCHED_PRIORITY_KERNEL, &sched,
1879 					  1, NULL);
1880 		if (r) {
1881 			DRM_ERROR("Failed setting up TTM BO move entity (%d)\n",
1882 				  r);
1883 			return;
1884 		}
1885 	} else {
1886 		drm_sched_entity_destroy(&adev->mman.entity);
1887 		dma_fence_put(man->move);
1888 		man->move = NULL;
1889 	}
1890 
1891 	/* this just adjusts TTM size idea, which sets lpfn to the correct value */
1892 	if (enable)
1893 		size = adev->gmc.real_vram_size;
1894 	else
1895 		size = adev->gmc.visible_vram_size;
1896 	man->size = size >> PAGE_SHIFT;
1897 	adev->mman.buffer_funcs_enabled = enable;
1898 }
1899 
1900 int amdgpu_copy_buffer(struct amdgpu_ring *ring, uint64_t src_offset,
1901 		       uint64_t dst_offset, uint32_t byte_count,
1902 		       struct dma_resv *resv,
1903 		       struct dma_fence **fence, bool direct_submit,
1904 		       bool vm_needs_flush, bool tmz)
1905 {
1906 	enum amdgpu_ib_pool_type pool = direct_submit ? AMDGPU_IB_POOL_DIRECT :
1907 		AMDGPU_IB_POOL_DELAYED;
1908 	struct amdgpu_device *adev = ring->adev;
1909 	struct amdgpu_job *job;
1910 
1911 	uint32_t max_bytes;
1912 	unsigned num_loops, num_dw;
1913 	unsigned i;
1914 	int r;
1915 
1916 	if (direct_submit && !ring->sched.ready) {
1917 		DRM_ERROR("Trying to move memory with ring turned off.\n");
1918 		return -EINVAL;
1919 	}
1920 
1921 	max_bytes = adev->mman.buffer_funcs->copy_max_bytes;
1922 	num_loops = DIV_ROUND_UP(byte_count, max_bytes);
1923 	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->copy_num_dw, 8);
1924 
1925 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, pool, &job);
1926 	if (r)
1927 		return r;
1928 
1929 	if (vm_needs_flush) {
1930 		job->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gmc.pdb0_bo ?
1931 					adev->gmc.pdb0_bo : adev->gart.bo);
1932 		job->vm_needs_flush = true;
1933 	}
1934 	if (resv) {
1935 		r = amdgpu_sync_resv(adev, &job->sync, resv,
1936 				     AMDGPU_SYNC_ALWAYS,
1937 				     AMDGPU_FENCE_OWNER_UNDEFINED);
1938 		if (r) {
1939 			DRM_ERROR("sync failed (%d).\n", r);
1940 			goto error_free;
1941 		}
1942 	}
1943 
1944 	for (i = 0; i < num_loops; i++) {
1945 		uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
1946 
1947 		amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
1948 					dst_offset, cur_size_in_bytes, tmz);
1949 
1950 		src_offset += cur_size_in_bytes;
1951 		dst_offset += cur_size_in_bytes;
1952 		byte_count -= cur_size_in_bytes;
1953 	}
1954 
1955 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
1956 	WARN_ON(job->ibs[0].length_dw > num_dw);
1957 	if (direct_submit)
1958 		r = amdgpu_job_submit_direct(job, ring, fence);
1959 	else
1960 		r = amdgpu_job_submit(job, &adev->mman.entity,
1961 				      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
1962 	if (r)
1963 		goto error_free;
1964 
1965 	return r;
1966 
1967 error_free:
1968 	amdgpu_job_free(job);
1969 	DRM_ERROR("Error scheduling IBs (%d)\n", r);
1970 	return r;
1971 }
1972 
1973 int amdgpu_fill_buffer(struct amdgpu_bo *bo,
1974 		       uint32_t src_data,
1975 		       struct dma_resv *resv,
1976 		       struct dma_fence **fence)
1977 {
1978 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1979 	uint32_t max_bytes = adev->mman.buffer_funcs->fill_max_bytes;
1980 	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
1981 
1982 	struct amdgpu_res_cursor cursor;
1983 	unsigned int num_loops, num_dw;
1984 	uint64_t num_bytes;
1985 
1986 	struct amdgpu_job *job;
1987 	int r;
1988 
1989 	if (!adev->mman.buffer_funcs_enabled) {
1990 		DRM_ERROR("Trying to clear memory with ring turned off.\n");
1991 		return -EINVAL;
1992 	}
1993 
1994 	if (bo->tbo.resource->mem_type == AMDGPU_PL_PREEMPT) {
1995 		DRM_ERROR("Trying to clear preemptible memory.\n");
1996 		return -EINVAL;
1997 	}
1998 
1999 	if (bo->tbo.resource->mem_type == TTM_PL_TT) {
2000 		r = amdgpu_ttm_alloc_gart(&bo->tbo);
2001 		if (r)
2002 			return r;
2003 	}
2004 
2005 	num_bytes = bo->tbo.resource->num_pages << PAGE_SHIFT;
2006 	num_loops = 0;
2007 
2008 	amdgpu_res_first(bo->tbo.resource, 0, num_bytes, &cursor);
2009 	while (cursor.remaining) {
2010 		num_loops += DIV_ROUND_UP_ULL(cursor.size, max_bytes);
2011 		amdgpu_res_next(&cursor, cursor.size);
2012 	}
2013 	num_dw = num_loops * adev->mman.buffer_funcs->fill_num_dw;
2014 
2015 	/* for IB padding */
2016 	num_dw += 64;
2017 
2018 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, AMDGPU_IB_POOL_DELAYED,
2019 				     &job);
2020 	if (r)
2021 		return r;
2022 
2023 	if (resv) {
2024 		r = amdgpu_sync_resv(adev, &job->sync, resv,
2025 				     AMDGPU_SYNC_ALWAYS,
2026 				     AMDGPU_FENCE_OWNER_UNDEFINED);
2027 		if (r) {
2028 			DRM_ERROR("sync failed (%d).\n", r);
2029 			goto error_free;
2030 		}
2031 	}
2032 
2033 	amdgpu_res_first(bo->tbo.resource, 0, num_bytes, &cursor);
2034 	while (cursor.remaining) {
2035 		uint32_t cur_size = min_t(uint64_t, cursor.size, max_bytes);
2036 		uint64_t dst_addr = cursor.start;
2037 
2038 		dst_addr += amdgpu_ttm_domain_start(adev,
2039 						    bo->tbo.resource->mem_type);
2040 		amdgpu_emit_fill_buffer(adev, &job->ibs[0], src_data, dst_addr,
2041 					cur_size);
2042 
2043 		amdgpu_res_next(&cursor, cur_size);
2044 	}
2045 
2046 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2047 	WARN_ON(job->ibs[0].length_dw > num_dw);
2048 	r = amdgpu_job_submit(job, &adev->mman.entity,
2049 			      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
2050 	if (r)
2051 		goto error_free;
2052 
2053 	return 0;
2054 
2055 error_free:
2056 	amdgpu_job_free(job);
2057 	return r;
2058 }
2059 
2060 /**
2061  * amdgpu_ttm_evict_resources - evict memory buffers
2062  * @adev: amdgpu device object
2063  * @mem_type: evicted BO's memory type
2064  *
2065  * Evicts all @mem_type buffers on the lru list of the memory type.
2066  *
2067  * Returns:
2068  * 0 for success or a negative error code on failure.
2069  */
2070 int amdgpu_ttm_evict_resources(struct amdgpu_device *adev, int mem_type)
2071 {
2072 	struct ttm_resource_manager *man;
2073 
2074 	switch (mem_type) {
2075 	case TTM_PL_VRAM:
2076 	case TTM_PL_TT:
2077 	case AMDGPU_PL_GWS:
2078 	case AMDGPU_PL_GDS:
2079 	case AMDGPU_PL_OA:
2080 		man = ttm_manager_type(&adev->mman.bdev, mem_type);
2081 		break;
2082 	default:
2083 		DRM_ERROR("Trying to evict invalid memory type\n");
2084 		return -EINVAL;
2085 	}
2086 
2087 	return ttm_resource_manager_evict_all(&adev->mman.bdev, man);
2088 }
2089 
2090 #if defined(CONFIG_DEBUG_FS)
2091 
2092 static int amdgpu_mm_vram_table_show(struct seq_file *m, void *unused)
2093 {
2094 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2095 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2096 							    TTM_PL_VRAM);
2097 	struct drm_printer p = drm_seq_file_printer(m);
2098 
2099 	man->func->debug(man, &p);
2100 	return 0;
2101 }
2102 
2103 static int amdgpu_ttm_page_pool_show(struct seq_file *m, void *unused)
2104 {
2105 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2106 
2107 	return ttm_pool_debugfs(&adev->mman.bdev.pool, m);
2108 }
2109 
2110 static int amdgpu_mm_tt_table_show(struct seq_file *m, void *unused)
2111 {
2112 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2113 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2114 							    TTM_PL_TT);
2115 	struct drm_printer p = drm_seq_file_printer(m);
2116 
2117 	man->func->debug(man, &p);
2118 	return 0;
2119 }
2120 
2121 static int amdgpu_mm_gds_table_show(struct seq_file *m, void *unused)
2122 {
2123 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2124 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2125 							    AMDGPU_PL_GDS);
2126 	struct drm_printer p = drm_seq_file_printer(m);
2127 
2128 	man->func->debug(man, &p);
2129 	return 0;
2130 }
2131 
2132 static int amdgpu_mm_gws_table_show(struct seq_file *m, void *unused)
2133 {
2134 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2135 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2136 							    AMDGPU_PL_GWS);
2137 	struct drm_printer p = drm_seq_file_printer(m);
2138 
2139 	man->func->debug(man, &p);
2140 	return 0;
2141 }
2142 
2143 static int amdgpu_mm_oa_table_show(struct seq_file *m, void *unused)
2144 {
2145 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2146 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2147 							    AMDGPU_PL_OA);
2148 	struct drm_printer p = drm_seq_file_printer(m);
2149 
2150 	man->func->debug(man, &p);
2151 	return 0;
2152 }
2153 
2154 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_vram_table);
2155 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_tt_table);
2156 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_gds_table);
2157 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_gws_table);
2158 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_oa_table);
2159 DEFINE_SHOW_ATTRIBUTE(amdgpu_ttm_page_pool);
2160 
2161 /*
2162  * amdgpu_ttm_vram_read - Linear read access to VRAM
2163  *
2164  * Accesses VRAM via MMIO for debugging purposes.
2165  */
2166 static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
2167 				    size_t size, loff_t *pos)
2168 {
2169 	struct amdgpu_device *adev = file_inode(f)->i_private;
2170 	ssize_t result = 0;
2171 
2172 	if (size & 0x3 || *pos & 0x3)
2173 		return -EINVAL;
2174 
2175 	if (*pos >= adev->gmc.mc_vram_size)
2176 		return -ENXIO;
2177 
2178 	size = min(size, (size_t)(adev->gmc.mc_vram_size - *pos));
2179 	while (size) {
2180 		size_t bytes = min(size, AMDGPU_TTM_VRAM_MAX_DW_READ * 4);
2181 		uint32_t value[AMDGPU_TTM_VRAM_MAX_DW_READ];
2182 
2183 		amdgpu_device_vram_access(adev, *pos, value, bytes, false);
2184 		if (copy_to_user(buf, value, bytes))
2185 			return -EFAULT;
2186 
2187 		result += bytes;
2188 		buf += bytes;
2189 		*pos += bytes;
2190 		size -= bytes;
2191 	}
2192 
2193 	return result;
2194 }
2195 
2196 /*
2197  * amdgpu_ttm_vram_write - Linear write access to VRAM
2198  *
2199  * Accesses VRAM via MMIO for debugging purposes.
2200  */
2201 static ssize_t amdgpu_ttm_vram_write(struct file *f, const char __user *buf,
2202 				    size_t size, loff_t *pos)
2203 {
2204 	struct amdgpu_device *adev = file_inode(f)->i_private;
2205 	ssize_t result = 0;
2206 	int r;
2207 
2208 	if (size & 0x3 || *pos & 0x3)
2209 		return -EINVAL;
2210 
2211 	if (*pos >= adev->gmc.mc_vram_size)
2212 		return -ENXIO;
2213 
2214 	while (size) {
2215 		uint32_t value;
2216 
2217 		if (*pos >= adev->gmc.mc_vram_size)
2218 			return result;
2219 
2220 		r = get_user(value, (uint32_t *)buf);
2221 		if (r)
2222 			return r;
2223 
2224 		amdgpu_device_mm_access(adev, *pos, &value, 4, true);
2225 
2226 		result += 4;
2227 		buf += 4;
2228 		*pos += 4;
2229 		size -= 4;
2230 	}
2231 
2232 	return result;
2233 }
2234 
2235 static const struct file_operations amdgpu_ttm_vram_fops = {
2236 	.owner = THIS_MODULE,
2237 	.read = amdgpu_ttm_vram_read,
2238 	.write = amdgpu_ttm_vram_write,
2239 	.llseek = default_llseek,
2240 };
2241 
2242 /*
2243  * amdgpu_iomem_read - Virtual read access to GPU mapped memory
2244  *
2245  * This function is used to read memory that has been mapped to the
2246  * GPU and the known addresses are not physical addresses but instead
2247  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2248  */
2249 static ssize_t amdgpu_iomem_read(struct file *f, char __user *buf,
2250 				 size_t size, loff_t *pos)
2251 {
2252 	struct amdgpu_device *adev = file_inode(f)->i_private;
2253 	struct iommu_domain *dom;
2254 	ssize_t result = 0;
2255 	int r;
2256 
2257 	/* retrieve the IOMMU domain if any for this device */
2258 	dom = iommu_get_domain_for_dev(adev->dev);
2259 
2260 	while (size) {
2261 		phys_addr_t addr = *pos & PAGE_MASK;
2262 		loff_t off = *pos & ~PAGE_MASK;
2263 		size_t bytes = PAGE_SIZE - off;
2264 		unsigned long pfn;
2265 		struct page *p;
2266 		void *ptr;
2267 
2268 		bytes = bytes < size ? bytes : size;
2269 
2270 		/* Translate the bus address to a physical address.  If
2271 		 * the domain is NULL it means there is no IOMMU active
2272 		 * and the address translation is the identity
2273 		 */
2274 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2275 
2276 		pfn = addr >> PAGE_SHIFT;
2277 		if (!pfn_valid(pfn))
2278 			return -EPERM;
2279 
2280 		p = pfn_to_page(pfn);
2281 		if (p->mapping != adev->mman.bdev.dev_mapping)
2282 			return -EPERM;
2283 
2284 		ptr = kmap(p);
2285 		r = copy_to_user(buf, ptr + off, bytes);
2286 		kunmap(p);
2287 		if (r)
2288 			return -EFAULT;
2289 
2290 		size -= bytes;
2291 		*pos += bytes;
2292 		result += bytes;
2293 	}
2294 
2295 	return result;
2296 }
2297 
2298 /*
2299  * amdgpu_iomem_write - Virtual write access to GPU mapped memory
2300  *
2301  * This function is used to write memory that has been mapped to the
2302  * GPU and the known addresses are not physical addresses but instead
2303  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2304  */
2305 static ssize_t amdgpu_iomem_write(struct file *f, const char __user *buf,
2306 				 size_t size, loff_t *pos)
2307 {
2308 	struct amdgpu_device *adev = file_inode(f)->i_private;
2309 	struct iommu_domain *dom;
2310 	ssize_t result = 0;
2311 	int r;
2312 
2313 	dom = iommu_get_domain_for_dev(adev->dev);
2314 
2315 	while (size) {
2316 		phys_addr_t addr = *pos & PAGE_MASK;
2317 		loff_t off = *pos & ~PAGE_MASK;
2318 		size_t bytes = PAGE_SIZE - off;
2319 		unsigned long pfn;
2320 		struct page *p;
2321 		void *ptr;
2322 
2323 		bytes = bytes < size ? bytes : size;
2324 
2325 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2326 
2327 		pfn = addr >> PAGE_SHIFT;
2328 		if (!pfn_valid(pfn))
2329 			return -EPERM;
2330 
2331 		p = pfn_to_page(pfn);
2332 		if (p->mapping != adev->mman.bdev.dev_mapping)
2333 			return -EPERM;
2334 
2335 		ptr = kmap(p);
2336 		r = copy_from_user(ptr + off, buf, bytes);
2337 		kunmap(p);
2338 		if (r)
2339 			return -EFAULT;
2340 
2341 		size -= bytes;
2342 		*pos += bytes;
2343 		result += bytes;
2344 	}
2345 
2346 	return result;
2347 }
2348 
2349 static const struct file_operations amdgpu_ttm_iomem_fops = {
2350 	.owner = THIS_MODULE,
2351 	.read = amdgpu_iomem_read,
2352 	.write = amdgpu_iomem_write,
2353 	.llseek = default_llseek
2354 };
2355 
2356 #endif
2357 
2358 void amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
2359 {
2360 #if defined(CONFIG_DEBUG_FS)
2361 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2362 	struct dentry *root = minor->debugfs_root;
2363 
2364 	debugfs_create_file_size("amdgpu_vram", 0444, root, adev,
2365 				 &amdgpu_ttm_vram_fops, adev->gmc.mc_vram_size);
2366 	debugfs_create_file("amdgpu_iomem", 0444, root, adev,
2367 			    &amdgpu_ttm_iomem_fops);
2368 	debugfs_create_file("amdgpu_vram_mm", 0444, root, adev,
2369 			    &amdgpu_mm_vram_table_fops);
2370 	debugfs_create_file("amdgpu_gtt_mm", 0444, root, adev,
2371 			    &amdgpu_mm_tt_table_fops);
2372 	debugfs_create_file("amdgpu_gds_mm", 0444, root, adev,
2373 			    &amdgpu_mm_gds_table_fops);
2374 	debugfs_create_file("amdgpu_gws_mm", 0444, root, adev,
2375 			    &amdgpu_mm_gws_table_fops);
2376 	debugfs_create_file("amdgpu_oa_mm", 0444, root, adev,
2377 			    &amdgpu_mm_oa_table_fops);
2378 	debugfs_create_file("ttm_page_pool", 0444, root, adev,
2379 			    &amdgpu_ttm_page_pool_fops);
2380 #endif
2381 }
2382