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 	.del_from_lru_notify = &amdgpu_vm_del_from_lru_notify
1502 };
1503 
1504 /*
1505  * Firmware Reservation functions
1506  */
1507 /**
1508  * amdgpu_ttm_fw_reserve_vram_fini - free fw reserved vram
1509  *
1510  * @adev: amdgpu_device pointer
1511  *
1512  * free fw reserved vram if it has been reserved.
1513  */
1514 static void amdgpu_ttm_fw_reserve_vram_fini(struct amdgpu_device *adev)
1515 {
1516 	amdgpu_bo_free_kernel(&adev->mman.fw_vram_usage_reserved_bo,
1517 		NULL, &adev->mman.fw_vram_usage_va);
1518 }
1519 
1520 /**
1521  * amdgpu_ttm_fw_reserve_vram_init - create bo vram reservation from fw
1522  *
1523  * @adev: amdgpu_device pointer
1524  *
1525  * create bo vram reservation from fw.
1526  */
1527 static int amdgpu_ttm_fw_reserve_vram_init(struct amdgpu_device *adev)
1528 {
1529 	uint64_t vram_size = adev->gmc.visible_vram_size;
1530 
1531 	adev->mman.fw_vram_usage_va = NULL;
1532 	adev->mman.fw_vram_usage_reserved_bo = NULL;
1533 
1534 	if (adev->mman.fw_vram_usage_size == 0 ||
1535 	    adev->mman.fw_vram_usage_size > vram_size)
1536 		return 0;
1537 
1538 	return amdgpu_bo_create_kernel_at(adev,
1539 					  adev->mman.fw_vram_usage_start_offset,
1540 					  adev->mman.fw_vram_usage_size,
1541 					  AMDGPU_GEM_DOMAIN_VRAM,
1542 					  &adev->mman.fw_vram_usage_reserved_bo,
1543 					  &adev->mman.fw_vram_usage_va);
1544 }
1545 
1546 /*
1547  * Memoy training reservation functions
1548  */
1549 
1550 /**
1551  * amdgpu_ttm_training_reserve_vram_fini - free memory training reserved vram
1552  *
1553  * @adev: amdgpu_device pointer
1554  *
1555  * free memory training reserved vram if it has been reserved.
1556  */
1557 static int amdgpu_ttm_training_reserve_vram_fini(struct amdgpu_device *adev)
1558 {
1559 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1560 
1561 	ctx->init = PSP_MEM_TRAIN_NOT_SUPPORT;
1562 	amdgpu_bo_free_kernel(&ctx->c2p_bo, NULL, NULL);
1563 	ctx->c2p_bo = NULL;
1564 
1565 	return 0;
1566 }
1567 
1568 static void amdgpu_ttm_training_data_block_init(struct amdgpu_device *adev)
1569 {
1570 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1571 
1572 	memset(ctx, 0, sizeof(*ctx));
1573 
1574 	ctx->c2p_train_data_offset =
1575 		ALIGN((adev->gmc.mc_vram_size - adev->mman.discovery_tmr_size - SZ_1M), SZ_1M);
1576 	ctx->p2c_train_data_offset =
1577 		(adev->gmc.mc_vram_size - GDDR6_MEM_TRAINING_OFFSET);
1578 	ctx->train_data_size =
1579 		GDDR6_MEM_TRAINING_DATA_SIZE_IN_BYTES;
1580 
1581 	DRM_DEBUG("train_data_size:%llx,p2c_train_data_offset:%llx,c2p_train_data_offset:%llx.\n",
1582 			ctx->train_data_size,
1583 			ctx->p2c_train_data_offset,
1584 			ctx->c2p_train_data_offset);
1585 }
1586 
1587 /*
1588  * reserve TMR memory at the top of VRAM which holds
1589  * IP Discovery data and is protected by PSP.
1590  */
1591 static int amdgpu_ttm_reserve_tmr(struct amdgpu_device *adev)
1592 {
1593 	int ret;
1594 	struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1595 	bool mem_train_support = false;
1596 
1597 	if (!amdgpu_sriov_vf(adev)) {
1598 		if (amdgpu_atomfirmware_mem_training_supported(adev))
1599 			mem_train_support = true;
1600 		else
1601 			DRM_DEBUG("memory training does not support!\n");
1602 	}
1603 
1604 	/*
1605 	 * Query reserved tmr size through atom firmwareinfo for Sienna_Cichlid and onwards for all
1606 	 * the use cases (IP discovery/G6 memory training/profiling/diagnostic data.etc)
1607 	 *
1608 	 * Otherwise, fallback to legacy approach to check and reserve tmr block for ip
1609 	 * discovery data and G6 memory training data respectively
1610 	 */
1611 	adev->mman.discovery_tmr_size =
1612 		amdgpu_atomfirmware_get_fw_reserved_fb_size(adev);
1613 	if (!adev->mman.discovery_tmr_size)
1614 		adev->mman.discovery_tmr_size = DISCOVERY_TMR_OFFSET;
1615 
1616 	if (mem_train_support) {
1617 		/* reserve vram for mem train according to TMR location */
1618 		amdgpu_ttm_training_data_block_init(adev);
1619 		ret = amdgpu_bo_create_kernel_at(adev,
1620 					 ctx->c2p_train_data_offset,
1621 					 ctx->train_data_size,
1622 					 AMDGPU_GEM_DOMAIN_VRAM,
1623 					 &ctx->c2p_bo,
1624 					 NULL);
1625 		if (ret) {
1626 			DRM_ERROR("alloc c2p_bo failed(%d)!\n", ret);
1627 			amdgpu_ttm_training_reserve_vram_fini(adev);
1628 			return ret;
1629 		}
1630 		ctx->init = PSP_MEM_TRAIN_RESERVE_SUCCESS;
1631 	}
1632 
1633 	ret = amdgpu_bo_create_kernel_at(adev,
1634 				adev->gmc.real_vram_size - adev->mman.discovery_tmr_size,
1635 				adev->mman.discovery_tmr_size,
1636 				AMDGPU_GEM_DOMAIN_VRAM,
1637 				&adev->mman.discovery_memory,
1638 				NULL);
1639 	if (ret) {
1640 		DRM_ERROR("alloc tmr failed(%d)!\n", ret);
1641 		amdgpu_bo_free_kernel(&adev->mman.discovery_memory, NULL, NULL);
1642 		return ret;
1643 	}
1644 
1645 	return 0;
1646 }
1647 
1648 /*
1649  * amdgpu_ttm_init - Init the memory management (ttm) as well as various
1650  * gtt/vram related fields.
1651  *
1652  * This initializes all of the memory space pools that the TTM layer
1653  * will need such as the GTT space (system memory mapped to the device),
1654  * VRAM (on-board memory), and on-chip memories (GDS, GWS, OA) which
1655  * can be mapped per VMID.
1656  */
1657 int amdgpu_ttm_init(struct amdgpu_device *adev)
1658 {
1659 	uint64_t gtt_size;
1660 	int r;
1661 	u64 vis_vram_limit;
1662 
1663 	mutex_init(&adev->mman.gtt_window_lock);
1664 
1665 	/* No others user of address space so set it to 0 */
1666 	r = ttm_device_init(&adev->mman.bdev, &amdgpu_bo_driver, adev->dev,
1667 			       adev_to_drm(adev)->anon_inode->i_mapping,
1668 			       adev_to_drm(adev)->vma_offset_manager,
1669 			       adev->need_swiotlb,
1670 			       dma_addressing_limited(adev->dev));
1671 	if (r) {
1672 		DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
1673 		return r;
1674 	}
1675 	adev->mman.initialized = true;
1676 
1677 	/* Initialize VRAM pool with all of VRAM divided into pages */
1678 	r = amdgpu_vram_mgr_init(adev);
1679 	if (r) {
1680 		DRM_ERROR("Failed initializing VRAM heap.\n");
1681 		return r;
1682 	}
1683 
1684 	/* Reduce size of CPU-visible VRAM if requested */
1685 	vis_vram_limit = (u64)amdgpu_vis_vram_limit * 1024 * 1024;
1686 	if (amdgpu_vis_vram_limit > 0 &&
1687 	    vis_vram_limit <= adev->gmc.visible_vram_size)
1688 		adev->gmc.visible_vram_size = vis_vram_limit;
1689 
1690 	/* Change the size here instead of the init above so only lpfn is affected */
1691 	amdgpu_ttm_set_buffer_funcs_status(adev, false);
1692 #ifdef CONFIG_64BIT
1693 #ifdef CONFIG_X86
1694 	if (adev->gmc.xgmi.connected_to_cpu)
1695 		adev->mman.aper_base_kaddr = ioremap_cache(adev->gmc.aper_base,
1696 				adev->gmc.visible_vram_size);
1697 
1698 	else
1699 #endif
1700 		adev->mman.aper_base_kaddr = ioremap_wc(adev->gmc.aper_base,
1701 				adev->gmc.visible_vram_size);
1702 #endif
1703 
1704 	/*
1705 	 *The reserved vram for firmware must be pinned to the specified
1706 	 *place on the VRAM, so reserve it early.
1707 	 */
1708 	r = amdgpu_ttm_fw_reserve_vram_init(adev);
1709 	if (r) {
1710 		return r;
1711 	}
1712 
1713 	/*
1714 	 * only NAVI10 and onwards ASIC support for IP discovery.
1715 	 * If IP discovery enabled, a block of memory should be
1716 	 * reserved for IP discovey.
1717 	 */
1718 	if (adev->mman.discovery_bin) {
1719 		r = amdgpu_ttm_reserve_tmr(adev);
1720 		if (r)
1721 			return r;
1722 	}
1723 
1724 	/* allocate memory as required for VGA
1725 	 * This is used for VGA emulation and pre-OS scanout buffers to
1726 	 * avoid display artifacts while transitioning between pre-OS
1727 	 * and driver.  */
1728 	r = amdgpu_bo_create_kernel_at(adev, 0, adev->mman.stolen_vga_size,
1729 				       AMDGPU_GEM_DOMAIN_VRAM,
1730 				       &adev->mman.stolen_vga_memory,
1731 				       NULL);
1732 	if (r)
1733 		return r;
1734 	r = amdgpu_bo_create_kernel_at(adev, adev->mman.stolen_vga_size,
1735 				       adev->mman.stolen_extended_size,
1736 				       AMDGPU_GEM_DOMAIN_VRAM,
1737 				       &adev->mman.stolen_extended_memory,
1738 				       NULL);
1739 	if (r)
1740 		return r;
1741 	r = amdgpu_bo_create_kernel_at(adev, adev->mman.stolen_reserved_offset,
1742 				       adev->mman.stolen_reserved_size,
1743 				       AMDGPU_GEM_DOMAIN_VRAM,
1744 				       &adev->mman.stolen_reserved_memory,
1745 				       NULL);
1746 	if (r)
1747 		return r;
1748 
1749 	DRM_INFO("amdgpu: %uM of VRAM memory ready\n",
1750 		 (unsigned) (adev->gmc.real_vram_size / (1024 * 1024)));
1751 
1752 	/* Compute GTT size, either bsaed on 3/4th the size of RAM size
1753 	 * or whatever the user passed on module init */
1754 	if (amdgpu_gtt_size == -1) {
1755 		struct sysinfo si;
1756 
1757 		si_meminfo(&si);
1758 		gtt_size = min(max((AMDGPU_DEFAULT_GTT_SIZE_MB << 20),
1759 			       adev->gmc.mc_vram_size),
1760 			       ((uint64_t)si.totalram * si.mem_unit * 3/4));
1761 	}
1762 	else
1763 		gtt_size = (uint64_t)amdgpu_gtt_size << 20;
1764 
1765 	/* Initialize GTT memory pool */
1766 	r = amdgpu_gtt_mgr_init(adev, gtt_size);
1767 	if (r) {
1768 		DRM_ERROR("Failed initializing GTT heap.\n");
1769 		return r;
1770 	}
1771 	DRM_INFO("amdgpu: %uM of GTT memory ready.\n",
1772 		 (unsigned)(gtt_size / (1024 * 1024)));
1773 
1774 	/* Initialize preemptible memory pool */
1775 	r = amdgpu_preempt_mgr_init(adev);
1776 	if (r) {
1777 		DRM_ERROR("Failed initializing PREEMPT heap.\n");
1778 		return r;
1779 	}
1780 
1781 	/* Initialize various on-chip memory pools */
1782 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GDS, adev->gds.gds_size);
1783 	if (r) {
1784 		DRM_ERROR("Failed initializing GDS heap.\n");
1785 		return r;
1786 	}
1787 
1788 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GWS, adev->gds.gws_size);
1789 	if (r) {
1790 		DRM_ERROR("Failed initializing gws heap.\n");
1791 		return r;
1792 	}
1793 
1794 	r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_OA, adev->gds.oa_size);
1795 	if (r) {
1796 		DRM_ERROR("Failed initializing oa heap.\n");
1797 		return r;
1798 	}
1799 
1800 	return 0;
1801 }
1802 
1803 /*
1804  * amdgpu_ttm_fini - De-initialize the TTM memory pools
1805  */
1806 void amdgpu_ttm_fini(struct amdgpu_device *adev)
1807 {
1808 	int idx;
1809 	if (!adev->mman.initialized)
1810 		return;
1811 
1812 	amdgpu_ttm_training_reserve_vram_fini(adev);
1813 	/* return the stolen vga memory back to VRAM */
1814 	amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
1815 	amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
1816 	/* return the IP Discovery TMR memory back to VRAM */
1817 	amdgpu_bo_free_kernel(&adev->mman.discovery_memory, NULL, NULL);
1818 	if (adev->mman.stolen_reserved_size)
1819 		amdgpu_bo_free_kernel(&adev->mman.stolen_reserved_memory,
1820 				      NULL, NULL);
1821 	amdgpu_ttm_fw_reserve_vram_fini(adev);
1822 
1823 	if (drm_dev_enter(adev_to_drm(adev), &idx)) {
1824 
1825 		if (adev->mman.aper_base_kaddr)
1826 			iounmap(adev->mman.aper_base_kaddr);
1827 		adev->mman.aper_base_kaddr = NULL;
1828 
1829 		drm_dev_exit(idx);
1830 	}
1831 
1832 	amdgpu_vram_mgr_fini(adev);
1833 	amdgpu_gtt_mgr_fini(adev);
1834 	amdgpu_preempt_mgr_fini(adev);
1835 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GDS);
1836 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GWS);
1837 	ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_OA);
1838 	ttm_device_fini(&adev->mman.bdev);
1839 	adev->mman.initialized = false;
1840 	DRM_INFO("amdgpu: ttm finalized\n");
1841 }
1842 
1843 /**
1844  * amdgpu_ttm_set_buffer_funcs_status - enable/disable use of buffer functions
1845  *
1846  * @adev: amdgpu_device pointer
1847  * @enable: true when we can use buffer functions.
1848  *
1849  * Enable/disable use of buffer functions during suspend/resume. This should
1850  * only be called at bootup or when userspace isn't running.
1851  */
1852 void amdgpu_ttm_set_buffer_funcs_status(struct amdgpu_device *adev, bool enable)
1853 {
1854 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM);
1855 	uint64_t size;
1856 	int r;
1857 
1858 	if (!adev->mman.initialized || amdgpu_in_reset(adev) ||
1859 	    adev->mman.buffer_funcs_enabled == enable)
1860 		return;
1861 
1862 	if (enable) {
1863 		struct amdgpu_ring *ring;
1864 		struct drm_gpu_scheduler *sched;
1865 
1866 		ring = adev->mman.buffer_funcs_ring;
1867 		sched = &ring->sched;
1868 		r = drm_sched_entity_init(&adev->mman.entity,
1869 					  DRM_SCHED_PRIORITY_KERNEL, &sched,
1870 					  1, NULL);
1871 		if (r) {
1872 			DRM_ERROR("Failed setting up TTM BO move entity (%d)\n",
1873 				  r);
1874 			return;
1875 		}
1876 	} else {
1877 		drm_sched_entity_destroy(&adev->mman.entity);
1878 		dma_fence_put(man->move);
1879 		man->move = NULL;
1880 	}
1881 
1882 	/* this just adjusts TTM size idea, which sets lpfn to the correct value */
1883 	if (enable)
1884 		size = adev->gmc.real_vram_size;
1885 	else
1886 		size = adev->gmc.visible_vram_size;
1887 	man->size = size >> PAGE_SHIFT;
1888 	adev->mman.buffer_funcs_enabled = enable;
1889 }
1890 
1891 int amdgpu_copy_buffer(struct amdgpu_ring *ring, uint64_t src_offset,
1892 		       uint64_t dst_offset, uint32_t byte_count,
1893 		       struct dma_resv *resv,
1894 		       struct dma_fence **fence, bool direct_submit,
1895 		       bool vm_needs_flush, bool tmz)
1896 {
1897 	enum amdgpu_ib_pool_type pool = direct_submit ? AMDGPU_IB_POOL_DIRECT :
1898 		AMDGPU_IB_POOL_DELAYED;
1899 	struct amdgpu_device *adev = ring->adev;
1900 	struct amdgpu_job *job;
1901 
1902 	uint32_t max_bytes;
1903 	unsigned num_loops, num_dw;
1904 	unsigned i;
1905 	int r;
1906 
1907 	if (!direct_submit && !ring->sched.ready) {
1908 		DRM_ERROR("Trying to move memory with ring turned off.\n");
1909 		return -EINVAL;
1910 	}
1911 
1912 	max_bytes = adev->mman.buffer_funcs->copy_max_bytes;
1913 	num_loops = DIV_ROUND_UP(byte_count, max_bytes);
1914 	num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->copy_num_dw, 8);
1915 
1916 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, pool, &job);
1917 	if (r)
1918 		return r;
1919 
1920 	if (vm_needs_flush) {
1921 		job->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gmc.pdb0_bo ?
1922 					adev->gmc.pdb0_bo : adev->gart.bo);
1923 		job->vm_needs_flush = true;
1924 	}
1925 	if (resv) {
1926 		r = amdgpu_sync_resv(adev, &job->sync, resv,
1927 				     AMDGPU_SYNC_ALWAYS,
1928 				     AMDGPU_FENCE_OWNER_UNDEFINED);
1929 		if (r) {
1930 			DRM_ERROR("sync failed (%d).\n", r);
1931 			goto error_free;
1932 		}
1933 	}
1934 
1935 	for (i = 0; i < num_loops; i++) {
1936 		uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
1937 
1938 		amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
1939 					dst_offset, cur_size_in_bytes, tmz);
1940 
1941 		src_offset += cur_size_in_bytes;
1942 		dst_offset += cur_size_in_bytes;
1943 		byte_count -= cur_size_in_bytes;
1944 	}
1945 
1946 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
1947 	WARN_ON(job->ibs[0].length_dw > num_dw);
1948 	if (direct_submit)
1949 		r = amdgpu_job_submit_direct(job, ring, fence);
1950 	else
1951 		r = amdgpu_job_submit(job, &adev->mman.entity,
1952 				      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
1953 	if (r)
1954 		goto error_free;
1955 
1956 	return r;
1957 
1958 error_free:
1959 	amdgpu_job_free(job);
1960 	DRM_ERROR("Error scheduling IBs (%d)\n", r);
1961 	return r;
1962 }
1963 
1964 int amdgpu_fill_buffer(struct amdgpu_bo *bo,
1965 		       uint32_t src_data,
1966 		       struct dma_resv *resv,
1967 		       struct dma_fence **fence)
1968 {
1969 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1970 	uint32_t max_bytes = adev->mman.buffer_funcs->fill_max_bytes;
1971 	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
1972 
1973 	struct amdgpu_res_cursor cursor;
1974 	unsigned int num_loops, num_dw;
1975 	uint64_t num_bytes;
1976 
1977 	struct amdgpu_job *job;
1978 	int r;
1979 
1980 	if (!adev->mman.buffer_funcs_enabled) {
1981 		DRM_ERROR("Trying to clear memory with ring turned off.\n");
1982 		return -EINVAL;
1983 	}
1984 
1985 	if (bo->tbo.resource->mem_type == AMDGPU_PL_PREEMPT) {
1986 		DRM_ERROR("Trying to clear preemptible memory.\n");
1987 		return -EINVAL;
1988 	}
1989 
1990 	if (bo->tbo.resource->mem_type == TTM_PL_TT) {
1991 		r = amdgpu_ttm_alloc_gart(&bo->tbo);
1992 		if (r)
1993 			return r;
1994 	}
1995 
1996 	num_bytes = bo->tbo.resource->num_pages << PAGE_SHIFT;
1997 	num_loops = 0;
1998 
1999 	amdgpu_res_first(bo->tbo.resource, 0, num_bytes, &cursor);
2000 	while (cursor.remaining) {
2001 		num_loops += DIV_ROUND_UP_ULL(cursor.size, max_bytes);
2002 		amdgpu_res_next(&cursor, cursor.size);
2003 	}
2004 	num_dw = num_loops * adev->mman.buffer_funcs->fill_num_dw;
2005 
2006 	/* for IB padding */
2007 	num_dw += 64;
2008 
2009 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, AMDGPU_IB_POOL_DELAYED,
2010 				     &job);
2011 	if (r)
2012 		return r;
2013 
2014 	if (resv) {
2015 		r = amdgpu_sync_resv(adev, &job->sync, resv,
2016 				     AMDGPU_SYNC_ALWAYS,
2017 				     AMDGPU_FENCE_OWNER_UNDEFINED);
2018 		if (r) {
2019 			DRM_ERROR("sync failed (%d).\n", r);
2020 			goto error_free;
2021 		}
2022 	}
2023 
2024 	amdgpu_res_first(bo->tbo.resource, 0, num_bytes, &cursor);
2025 	while (cursor.remaining) {
2026 		uint32_t cur_size = min_t(uint64_t, cursor.size, max_bytes);
2027 		uint64_t dst_addr = cursor.start;
2028 
2029 		dst_addr += amdgpu_ttm_domain_start(adev,
2030 						    bo->tbo.resource->mem_type);
2031 		amdgpu_emit_fill_buffer(adev, &job->ibs[0], src_data, dst_addr,
2032 					cur_size);
2033 
2034 		amdgpu_res_next(&cursor, cur_size);
2035 	}
2036 
2037 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2038 	WARN_ON(job->ibs[0].length_dw > num_dw);
2039 	r = amdgpu_job_submit(job, &adev->mman.entity,
2040 			      AMDGPU_FENCE_OWNER_UNDEFINED, fence);
2041 	if (r)
2042 		goto error_free;
2043 
2044 	return 0;
2045 
2046 error_free:
2047 	amdgpu_job_free(job);
2048 	return r;
2049 }
2050 
2051 /**
2052  * amdgpu_ttm_evict_resources - evict memory buffers
2053  * @adev: amdgpu device object
2054  * @mem_type: evicted BO's memory type
2055  *
2056  * Evicts all @mem_type buffers on the lru list of the memory type.
2057  *
2058  * Returns:
2059  * 0 for success or a negative error code on failure.
2060  */
2061 int amdgpu_ttm_evict_resources(struct amdgpu_device *adev, int mem_type)
2062 {
2063 	struct ttm_resource_manager *man;
2064 
2065 	switch (mem_type) {
2066 	case TTM_PL_VRAM:
2067 	case TTM_PL_TT:
2068 	case AMDGPU_PL_GWS:
2069 	case AMDGPU_PL_GDS:
2070 	case AMDGPU_PL_OA:
2071 		man = ttm_manager_type(&adev->mman.bdev, mem_type);
2072 		break;
2073 	default:
2074 		DRM_ERROR("Trying to evict invalid memory type\n");
2075 		return -EINVAL;
2076 	}
2077 
2078 	return ttm_resource_manager_evict_all(&adev->mman.bdev, man);
2079 }
2080 
2081 #if defined(CONFIG_DEBUG_FS)
2082 
2083 static int amdgpu_mm_vram_table_show(struct seq_file *m, void *unused)
2084 {
2085 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2086 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2087 							    TTM_PL_VRAM);
2088 	struct drm_printer p = drm_seq_file_printer(m);
2089 
2090 	man->func->debug(man, &p);
2091 	return 0;
2092 }
2093 
2094 static int amdgpu_ttm_page_pool_show(struct seq_file *m, void *unused)
2095 {
2096 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2097 
2098 	return ttm_pool_debugfs(&adev->mman.bdev.pool, m);
2099 }
2100 
2101 static int amdgpu_mm_tt_table_show(struct seq_file *m, void *unused)
2102 {
2103 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2104 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2105 							    TTM_PL_TT);
2106 	struct drm_printer p = drm_seq_file_printer(m);
2107 
2108 	man->func->debug(man, &p);
2109 	return 0;
2110 }
2111 
2112 static int amdgpu_mm_gds_table_show(struct seq_file *m, void *unused)
2113 {
2114 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2115 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2116 							    AMDGPU_PL_GDS);
2117 	struct drm_printer p = drm_seq_file_printer(m);
2118 
2119 	man->func->debug(man, &p);
2120 	return 0;
2121 }
2122 
2123 static int amdgpu_mm_gws_table_show(struct seq_file *m, void *unused)
2124 {
2125 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2126 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2127 							    AMDGPU_PL_GWS);
2128 	struct drm_printer p = drm_seq_file_printer(m);
2129 
2130 	man->func->debug(man, &p);
2131 	return 0;
2132 }
2133 
2134 static int amdgpu_mm_oa_table_show(struct seq_file *m, void *unused)
2135 {
2136 	struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2137 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2138 							    AMDGPU_PL_OA);
2139 	struct drm_printer p = drm_seq_file_printer(m);
2140 
2141 	man->func->debug(man, &p);
2142 	return 0;
2143 }
2144 
2145 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_vram_table);
2146 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_tt_table);
2147 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_gds_table);
2148 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_gws_table);
2149 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_oa_table);
2150 DEFINE_SHOW_ATTRIBUTE(amdgpu_ttm_page_pool);
2151 
2152 /*
2153  * amdgpu_ttm_vram_read - Linear read access to VRAM
2154  *
2155  * Accesses VRAM via MMIO for debugging purposes.
2156  */
2157 static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
2158 				    size_t size, loff_t *pos)
2159 {
2160 	struct amdgpu_device *adev = file_inode(f)->i_private;
2161 	ssize_t result = 0;
2162 
2163 	if (size & 0x3 || *pos & 0x3)
2164 		return -EINVAL;
2165 
2166 	if (*pos >= adev->gmc.mc_vram_size)
2167 		return -ENXIO;
2168 
2169 	size = min(size, (size_t)(adev->gmc.mc_vram_size - *pos));
2170 	while (size) {
2171 		size_t bytes = min(size, AMDGPU_TTM_VRAM_MAX_DW_READ * 4);
2172 		uint32_t value[AMDGPU_TTM_VRAM_MAX_DW_READ];
2173 
2174 		amdgpu_device_vram_access(adev, *pos, value, bytes, false);
2175 		if (copy_to_user(buf, value, bytes))
2176 			return -EFAULT;
2177 
2178 		result += bytes;
2179 		buf += bytes;
2180 		*pos += bytes;
2181 		size -= bytes;
2182 	}
2183 
2184 	return result;
2185 }
2186 
2187 /*
2188  * amdgpu_ttm_vram_write - Linear write access to VRAM
2189  *
2190  * Accesses VRAM via MMIO for debugging purposes.
2191  */
2192 static ssize_t amdgpu_ttm_vram_write(struct file *f, const char __user *buf,
2193 				    size_t size, loff_t *pos)
2194 {
2195 	struct amdgpu_device *adev = file_inode(f)->i_private;
2196 	ssize_t result = 0;
2197 	int r;
2198 
2199 	if (size & 0x3 || *pos & 0x3)
2200 		return -EINVAL;
2201 
2202 	if (*pos >= adev->gmc.mc_vram_size)
2203 		return -ENXIO;
2204 
2205 	while (size) {
2206 		uint32_t value;
2207 
2208 		if (*pos >= adev->gmc.mc_vram_size)
2209 			return result;
2210 
2211 		r = get_user(value, (uint32_t *)buf);
2212 		if (r)
2213 			return r;
2214 
2215 		amdgpu_device_mm_access(adev, *pos, &value, 4, true);
2216 
2217 		result += 4;
2218 		buf += 4;
2219 		*pos += 4;
2220 		size -= 4;
2221 	}
2222 
2223 	return result;
2224 }
2225 
2226 static const struct file_operations amdgpu_ttm_vram_fops = {
2227 	.owner = THIS_MODULE,
2228 	.read = amdgpu_ttm_vram_read,
2229 	.write = amdgpu_ttm_vram_write,
2230 	.llseek = default_llseek,
2231 };
2232 
2233 /*
2234  * amdgpu_iomem_read - Virtual read access to GPU mapped memory
2235  *
2236  * This function is used to read memory that has been mapped to the
2237  * GPU and the known addresses are not physical addresses but instead
2238  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2239  */
2240 static ssize_t amdgpu_iomem_read(struct file *f, char __user *buf,
2241 				 size_t size, loff_t *pos)
2242 {
2243 	struct amdgpu_device *adev = file_inode(f)->i_private;
2244 	struct iommu_domain *dom;
2245 	ssize_t result = 0;
2246 	int r;
2247 
2248 	/* retrieve the IOMMU domain if any for this device */
2249 	dom = iommu_get_domain_for_dev(adev->dev);
2250 
2251 	while (size) {
2252 		phys_addr_t addr = *pos & PAGE_MASK;
2253 		loff_t off = *pos & ~PAGE_MASK;
2254 		size_t bytes = PAGE_SIZE - off;
2255 		unsigned long pfn;
2256 		struct page *p;
2257 		void *ptr;
2258 
2259 		bytes = bytes < size ? bytes : size;
2260 
2261 		/* Translate the bus address to a physical address.  If
2262 		 * the domain is NULL it means there is no IOMMU active
2263 		 * and the address translation is the identity
2264 		 */
2265 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2266 
2267 		pfn = addr >> PAGE_SHIFT;
2268 		if (!pfn_valid(pfn))
2269 			return -EPERM;
2270 
2271 		p = pfn_to_page(pfn);
2272 		if (p->mapping != adev->mman.bdev.dev_mapping)
2273 			return -EPERM;
2274 
2275 		ptr = kmap(p);
2276 		r = copy_to_user(buf, ptr + off, bytes);
2277 		kunmap(p);
2278 		if (r)
2279 			return -EFAULT;
2280 
2281 		size -= bytes;
2282 		*pos += bytes;
2283 		result += bytes;
2284 	}
2285 
2286 	return result;
2287 }
2288 
2289 /*
2290  * amdgpu_iomem_write - Virtual write access to GPU mapped memory
2291  *
2292  * This function is used to write memory that has been mapped to the
2293  * GPU and the known addresses are not physical addresses but instead
2294  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2295  */
2296 static ssize_t amdgpu_iomem_write(struct file *f, const char __user *buf,
2297 				 size_t size, loff_t *pos)
2298 {
2299 	struct amdgpu_device *adev = file_inode(f)->i_private;
2300 	struct iommu_domain *dom;
2301 	ssize_t result = 0;
2302 	int r;
2303 
2304 	dom = iommu_get_domain_for_dev(adev->dev);
2305 
2306 	while (size) {
2307 		phys_addr_t addr = *pos & PAGE_MASK;
2308 		loff_t off = *pos & ~PAGE_MASK;
2309 		size_t bytes = PAGE_SIZE - off;
2310 		unsigned long pfn;
2311 		struct page *p;
2312 		void *ptr;
2313 
2314 		bytes = bytes < size ? bytes : size;
2315 
2316 		addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2317 
2318 		pfn = addr >> PAGE_SHIFT;
2319 		if (!pfn_valid(pfn))
2320 			return -EPERM;
2321 
2322 		p = pfn_to_page(pfn);
2323 		if (p->mapping != adev->mman.bdev.dev_mapping)
2324 			return -EPERM;
2325 
2326 		ptr = kmap(p);
2327 		r = copy_from_user(ptr + off, buf, bytes);
2328 		kunmap(p);
2329 		if (r)
2330 			return -EFAULT;
2331 
2332 		size -= bytes;
2333 		*pos += bytes;
2334 		result += bytes;
2335 	}
2336 
2337 	return result;
2338 }
2339 
2340 static const struct file_operations amdgpu_ttm_iomem_fops = {
2341 	.owner = THIS_MODULE,
2342 	.read = amdgpu_iomem_read,
2343 	.write = amdgpu_iomem_write,
2344 	.llseek = default_llseek
2345 };
2346 
2347 #endif
2348 
2349 void amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
2350 {
2351 #if defined(CONFIG_DEBUG_FS)
2352 	struct drm_minor *minor = adev_to_drm(adev)->primary;
2353 	struct dentry *root = minor->debugfs_root;
2354 
2355 	debugfs_create_file_size("amdgpu_vram", 0444, root, adev,
2356 				 &amdgpu_ttm_vram_fops, adev->gmc.mc_vram_size);
2357 	debugfs_create_file("amdgpu_iomem", 0444, root, adev,
2358 			    &amdgpu_ttm_iomem_fops);
2359 	debugfs_create_file("amdgpu_vram_mm", 0444, root, adev,
2360 			    &amdgpu_mm_vram_table_fops);
2361 	debugfs_create_file("amdgpu_gtt_mm", 0444, root, adev,
2362 			    &amdgpu_mm_tt_table_fops);
2363 	debugfs_create_file("amdgpu_gds_mm", 0444, root, adev,
2364 			    &amdgpu_mm_gds_table_fops);
2365 	debugfs_create_file("amdgpu_gws_mm", 0444, root, adev,
2366 			    &amdgpu_mm_gws_table_fops);
2367 	debugfs_create_file("amdgpu_oa_mm", 0444, root, adev,
2368 			    &amdgpu_mm_oa_table_fops);
2369 	debugfs_create_file("ttm_page_pool", 0444, root, adev,
2370 			    &amdgpu_ttm_page_pool_fops);
2371 #endif
2372 }
2373