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