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