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