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