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 #include <linux/list.h>
33 #include <linux/slab.h>
34 #include <linux/dma-buf.h>
35 
36 #include <drm/drm_drv.h>
37 #include <drm/amdgpu_drm.h>
38 #include <drm/drm_cache.h>
39 #include "amdgpu.h"
40 #include "amdgpu_trace.h"
41 #include "amdgpu_amdkfd.h"
42 #include "amdgpu_vram_mgr.h"
43 
44 /**
45  * DOC: amdgpu_object
46  *
47  * This defines the interfaces to operate on an &amdgpu_bo buffer object which
48  * represents memory used by driver (VRAM, system memory, etc.). The driver
49  * provides DRM/GEM APIs to userspace. DRM/GEM APIs then use these interfaces
50  * to create/destroy/set buffer object which are then managed by the kernel TTM
51  * memory manager.
52  * The interfaces are also used internally by kernel clients, including gfx,
53  * uvd, etc. for kernel managed allocations used by the GPU.
54  *
55  */
56 
amdgpu_bo_destroy(struct ttm_buffer_object * tbo)57 static void amdgpu_bo_destroy(struct ttm_buffer_object *tbo)
58 {
59 	struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
60 	struct amdgpu_bo *bo = ttm_to_amdgpu_bo(tbo);
61 
62 	amdgpu_bo_kunmap(bo);
63 
64 	if (bo->tbo.base.import_attach)
65 		drm_prime_gem_destroy(&bo->tbo.base, bo->tbo.sg);
66 	drm_gem_object_release(&bo->tbo.base);
67 	amdgpu_bo_unref(&bo->parent);
68 	kvfree(bo);
69 }
70 
amdgpu_bo_user_destroy(struct ttm_buffer_object * tbo)71 static void amdgpu_bo_user_destroy(struct ttm_buffer_object *tbo)
72 {
73 	struct amdgpu_bo *bo = ttm_to_amdgpu_bo(tbo);
74 	struct amdgpu_bo_user *ubo;
75 
76 	ubo = to_amdgpu_bo_user(bo);
77 	kfree(ubo->metadata);
78 	amdgpu_bo_destroy(tbo);
79 }
80 
81 /**
82  * amdgpu_bo_is_amdgpu_bo - check if the buffer object is an &amdgpu_bo
83  * @bo: buffer object to be checked
84  *
85  * Uses destroy function associated with the object to determine if this is
86  * an &amdgpu_bo.
87  *
88  * Returns:
89  * true if the object belongs to &amdgpu_bo, false if not.
90  */
amdgpu_bo_is_amdgpu_bo(struct ttm_buffer_object * bo)91 bool amdgpu_bo_is_amdgpu_bo(struct ttm_buffer_object *bo)
92 {
93 	if (bo->destroy == &amdgpu_bo_destroy ||
94 	    bo->destroy == &amdgpu_bo_user_destroy)
95 		return true;
96 
97 	return false;
98 }
99 
100 /**
101  * amdgpu_bo_placement_from_domain - set buffer's placement
102  * @abo: &amdgpu_bo buffer object whose placement is to be set
103  * @domain: requested domain
104  *
105  * Sets buffer's placement according to requested domain and the buffer's
106  * flags.
107  */
amdgpu_bo_placement_from_domain(struct amdgpu_bo * abo,u32 domain)108 void amdgpu_bo_placement_from_domain(struct amdgpu_bo *abo, u32 domain)
109 {
110 	struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
111 	struct ttm_placement *placement = &abo->placement;
112 	struct ttm_place *places = abo->placements;
113 	u64 flags = abo->flags;
114 	u32 c = 0;
115 
116 	if (domain & AMDGPU_GEM_DOMAIN_VRAM) {
117 		unsigned int visible_pfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
118 		int8_t mem_id = KFD_XCP_MEM_ID(adev, abo->xcp_id);
119 
120 		if (adev->gmc.mem_partitions && mem_id >= 0) {
121 			places[c].fpfn = adev->gmc.mem_partitions[mem_id].range.fpfn;
122 			/*
123 			 * memory partition range lpfn is inclusive start + size - 1
124 			 * TTM place lpfn is exclusive start + size
125 			 */
126 			places[c].lpfn = adev->gmc.mem_partitions[mem_id].range.lpfn + 1;
127 		} else {
128 			places[c].fpfn = 0;
129 			places[c].lpfn = 0;
130 		}
131 		places[c].mem_type = TTM_PL_VRAM;
132 		places[c].flags = 0;
133 
134 		if (flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED)
135 			places[c].lpfn = min_not_zero(places[c].lpfn, visible_pfn);
136 		else
137 			places[c].flags |= TTM_PL_FLAG_TOPDOWN;
138 
139 		if (abo->tbo.type == ttm_bo_type_kernel &&
140 		    flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS)
141 			places[c].flags |= TTM_PL_FLAG_CONTIGUOUS;
142 
143 		c++;
144 	}
145 
146 	if (domain & AMDGPU_GEM_DOMAIN_DOORBELL) {
147 		places[c].fpfn = 0;
148 		places[c].lpfn = 0;
149 		places[c].mem_type = AMDGPU_PL_DOORBELL;
150 		places[c].flags = 0;
151 		c++;
152 	}
153 
154 	if (domain & AMDGPU_GEM_DOMAIN_GTT) {
155 		places[c].fpfn = 0;
156 		places[c].lpfn = 0;
157 		places[c].mem_type =
158 			abo->flags & AMDGPU_GEM_CREATE_PREEMPTIBLE ?
159 			AMDGPU_PL_PREEMPT : TTM_PL_TT;
160 		places[c].flags = 0;
161 		/*
162 		 * When GTT is just an alternative to VRAM make sure that we
163 		 * only use it as fallback and still try to fill up VRAM first.
164 		 */
165 		if (domain & abo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM &&
166 		    !(adev->flags & AMD_IS_APU))
167 			places[c].flags |= TTM_PL_FLAG_FALLBACK;
168 		c++;
169 	}
170 
171 	if (domain & AMDGPU_GEM_DOMAIN_CPU) {
172 		places[c].fpfn = 0;
173 		places[c].lpfn = 0;
174 		places[c].mem_type = TTM_PL_SYSTEM;
175 		places[c].flags = 0;
176 		c++;
177 	}
178 
179 	if (domain & AMDGPU_GEM_DOMAIN_GDS) {
180 		places[c].fpfn = 0;
181 		places[c].lpfn = 0;
182 		places[c].mem_type = AMDGPU_PL_GDS;
183 		places[c].flags = 0;
184 		c++;
185 	}
186 
187 	if (domain & AMDGPU_GEM_DOMAIN_GWS) {
188 		places[c].fpfn = 0;
189 		places[c].lpfn = 0;
190 		places[c].mem_type = AMDGPU_PL_GWS;
191 		places[c].flags = 0;
192 		c++;
193 	}
194 
195 	if (domain & AMDGPU_GEM_DOMAIN_OA) {
196 		places[c].fpfn = 0;
197 		places[c].lpfn = 0;
198 		places[c].mem_type = AMDGPU_PL_OA;
199 		places[c].flags = 0;
200 		c++;
201 	}
202 
203 	if (!c) {
204 		places[c].fpfn = 0;
205 		places[c].lpfn = 0;
206 		places[c].mem_type = TTM_PL_SYSTEM;
207 		places[c].flags = 0;
208 		c++;
209 	}
210 
211 	BUG_ON(c > AMDGPU_BO_MAX_PLACEMENTS);
212 
213 	placement->num_placement = c;
214 	placement->placement = places;
215 }
216 
217 /**
218  * amdgpu_bo_create_reserved - create reserved BO for kernel use
219  *
220  * @adev: amdgpu device object
221  * @size: size for the new BO
222  * @align: alignment for the new BO
223  * @domain: where to place it
224  * @bo_ptr: used to initialize BOs in structures
225  * @gpu_addr: GPU addr of the pinned BO
226  * @cpu_addr: optional CPU address mapping
227  *
228  * Allocates and pins a BO for kernel internal use, and returns it still
229  * reserved.
230  *
231  * Note: For bo_ptr new BO is only created if bo_ptr points to NULL.
232  *
233  * Returns:
234  * 0 on success, negative error code otherwise.
235  */
amdgpu_bo_create_reserved(struct amdgpu_device * adev,unsigned long size,int align,u32 domain,struct amdgpu_bo ** bo_ptr,u64 * gpu_addr,void ** cpu_addr)236 int amdgpu_bo_create_reserved(struct amdgpu_device *adev,
237 			      unsigned long size, int align,
238 			      u32 domain, struct amdgpu_bo **bo_ptr,
239 			      u64 *gpu_addr, void **cpu_addr)
240 {
241 	struct amdgpu_bo_param bp;
242 	bool free = false;
243 	int r;
244 
245 	if (!size) {
246 		amdgpu_bo_unref(bo_ptr);
247 		return 0;
248 	}
249 
250 	memset(&bp, 0, sizeof(bp));
251 	bp.size = size;
252 	bp.byte_align = align;
253 	bp.domain = domain;
254 	bp.flags = cpu_addr ? AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED
255 		: AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
256 	bp.flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
257 	bp.type = ttm_bo_type_kernel;
258 	bp.resv = NULL;
259 	bp.bo_ptr_size = sizeof(struct amdgpu_bo);
260 
261 	if (!*bo_ptr) {
262 		r = amdgpu_bo_create(adev, &bp, bo_ptr);
263 		if (r) {
264 			dev_err(adev->dev, "(%d) failed to allocate kernel bo\n",
265 				r);
266 			return r;
267 		}
268 		free = true;
269 	}
270 
271 	r = amdgpu_bo_reserve(*bo_ptr, false);
272 	if (r) {
273 		dev_err(adev->dev, "(%d) failed to reserve kernel bo\n", r);
274 		goto error_free;
275 	}
276 
277 	r = amdgpu_bo_pin(*bo_ptr, domain);
278 	if (r) {
279 		dev_err(adev->dev, "(%d) kernel bo pin failed\n", r);
280 		goto error_unreserve;
281 	}
282 
283 	r = amdgpu_ttm_alloc_gart(&(*bo_ptr)->tbo);
284 	if (r) {
285 		dev_err(adev->dev, "%p bind failed\n", *bo_ptr);
286 		goto error_unpin;
287 	}
288 
289 	if (gpu_addr)
290 		*gpu_addr = amdgpu_bo_gpu_offset(*bo_ptr);
291 
292 	if (cpu_addr) {
293 		r = amdgpu_bo_kmap(*bo_ptr, cpu_addr);
294 		if (r) {
295 			dev_err(adev->dev, "(%d) kernel bo map failed\n", r);
296 			goto error_unpin;
297 		}
298 	}
299 
300 	return 0;
301 
302 error_unpin:
303 	amdgpu_bo_unpin(*bo_ptr);
304 error_unreserve:
305 	amdgpu_bo_unreserve(*bo_ptr);
306 
307 error_free:
308 	if (free)
309 		amdgpu_bo_unref(bo_ptr);
310 
311 	return r;
312 }
313 
314 /**
315  * amdgpu_bo_create_kernel - create BO for kernel use
316  *
317  * @adev: amdgpu device object
318  * @size: size for the new BO
319  * @align: alignment for the new BO
320  * @domain: where to place it
321  * @bo_ptr:  used to initialize BOs in structures
322  * @gpu_addr: GPU addr of the pinned BO
323  * @cpu_addr: optional CPU address mapping
324  *
325  * Allocates and pins a BO for kernel internal use.
326  *
327  * Note: For bo_ptr new BO is only created if bo_ptr points to NULL.
328  *
329  * Returns:
330  * 0 on success, negative error code otherwise.
331  */
amdgpu_bo_create_kernel(struct amdgpu_device * adev,unsigned long size,int align,u32 domain,struct amdgpu_bo ** bo_ptr,u64 * gpu_addr,void ** cpu_addr)332 int amdgpu_bo_create_kernel(struct amdgpu_device *adev,
333 			    unsigned long size, int align,
334 			    u32 domain, struct amdgpu_bo **bo_ptr,
335 			    u64 *gpu_addr, void **cpu_addr)
336 {
337 	int r;
338 
339 	r = amdgpu_bo_create_reserved(adev, size, align, domain, bo_ptr,
340 				      gpu_addr, cpu_addr);
341 
342 	if (r)
343 		return r;
344 
345 	if (*bo_ptr)
346 		amdgpu_bo_unreserve(*bo_ptr);
347 
348 	return 0;
349 }
350 
351 /**
352  * amdgpu_bo_create_kernel_at - create BO for kernel use at specific location
353  *
354  * @adev: amdgpu device object
355  * @offset: offset of the BO
356  * @size: size of the BO
357  * @bo_ptr:  used to initialize BOs in structures
358  * @cpu_addr: optional CPU address mapping
359  *
360  * Creates a kernel BO at a specific offset in VRAM.
361  *
362  * Returns:
363  * 0 on success, negative error code otherwise.
364  */
amdgpu_bo_create_kernel_at(struct amdgpu_device * adev,uint64_t offset,uint64_t size,struct amdgpu_bo ** bo_ptr,void ** cpu_addr)365 int amdgpu_bo_create_kernel_at(struct amdgpu_device *adev,
366 			       uint64_t offset, uint64_t size,
367 			       struct amdgpu_bo **bo_ptr, void **cpu_addr)
368 {
369 	struct ttm_operation_ctx ctx = { false, false };
370 	unsigned int i;
371 	int r;
372 
373 	offset &= LINUX_PAGE_MASK;
374 	size = ALIGN(size, PAGE_SIZE);
375 
376 	r = amdgpu_bo_create_reserved(adev, size, PAGE_SIZE,
377 				      AMDGPU_GEM_DOMAIN_VRAM, bo_ptr, NULL,
378 				      cpu_addr);
379 	if (r)
380 		return r;
381 
382 	if ((*bo_ptr) == NULL)
383 		return 0;
384 
385 	/*
386 	 * Remove the original mem node and create a new one at the request
387 	 * position.
388 	 */
389 	if (cpu_addr)
390 		amdgpu_bo_kunmap(*bo_ptr);
391 
392 	ttm_resource_free(&(*bo_ptr)->tbo, &(*bo_ptr)->tbo.resource);
393 
394 	for (i = 0; i < (*bo_ptr)->placement.num_placement; ++i) {
395 		(*bo_ptr)->placements[i].fpfn = offset >> PAGE_SHIFT;
396 		(*bo_ptr)->placements[i].lpfn = (offset + size) >> PAGE_SHIFT;
397 	}
398 	r = ttm_bo_mem_space(&(*bo_ptr)->tbo, &(*bo_ptr)->placement,
399 			     &(*bo_ptr)->tbo.resource, &ctx);
400 	if (r)
401 		goto error;
402 
403 	if (cpu_addr) {
404 		r = amdgpu_bo_kmap(*bo_ptr, cpu_addr);
405 		if (r)
406 			goto error;
407 	}
408 
409 	amdgpu_bo_unreserve(*bo_ptr);
410 	return 0;
411 
412 error:
413 	amdgpu_bo_unreserve(*bo_ptr);
414 	amdgpu_bo_unref(bo_ptr);
415 	return r;
416 }
417 
418 /**
419  * amdgpu_bo_free_kernel - free BO for kernel use
420  *
421  * @bo: amdgpu BO to free
422  * @gpu_addr: pointer to where the BO's GPU memory space address was stored
423  * @cpu_addr: pointer to where the BO's CPU memory space address was stored
424  *
425  * unmaps and unpin a BO for kernel internal use.
426  */
amdgpu_bo_free_kernel(struct amdgpu_bo ** bo,u64 * gpu_addr,void ** cpu_addr)427 void amdgpu_bo_free_kernel(struct amdgpu_bo **bo, u64 *gpu_addr,
428 			   void **cpu_addr)
429 {
430 	if (*bo == NULL)
431 		return;
432 
433 	WARN_ON(amdgpu_ttm_adev((*bo)->tbo.bdev)->in_suspend);
434 
435 	if (likely(amdgpu_bo_reserve(*bo, true) == 0)) {
436 		if (cpu_addr)
437 			amdgpu_bo_kunmap(*bo);
438 
439 		amdgpu_bo_unpin(*bo);
440 		amdgpu_bo_unreserve(*bo);
441 	}
442 	amdgpu_bo_unref(bo);
443 
444 	if (gpu_addr)
445 		*gpu_addr = 0;
446 
447 	if (cpu_addr)
448 		*cpu_addr = NULL;
449 }
450 
451 /* Validate bo size is bit bigger than the request domain */
amdgpu_bo_validate_size(struct amdgpu_device * adev,unsigned long size,u32 domain)452 static bool amdgpu_bo_validate_size(struct amdgpu_device *adev,
453 					  unsigned long size, u32 domain)
454 {
455 	struct ttm_resource_manager *man = NULL;
456 
457 	/*
458 	 * If GTT is part of requested domains the check must succeed to
459 	 * allow fall back to GTT.
460 	 */
461 	if (domain & AMDGPU_GEM_DOMAIN_GTT)
462 		man = ttm_manager_type(&adev->mman.bdev, TTM_PL_TT);
463 	else if (domain & AMDGPU_GEM_DOMAIN_VRAM)
464 		man = ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM);
465 	else
466 		return true;
467 
468 	if (!man) {
469 		if (domain & AMDGPU_GEM_DOMAIN_GTT)
470 			WARN_ON_ONCE("GTT domain requested but GTT mem manager uninitialized");
471 		return false;
472 	}
473 
474 	/* TODO add more domains checks, such as AMDGPU_GEM_DOMAIN_CPU, _DOMAIN_DOORBELL */
475 	if (size < man->size)
476 		return true;
477 
478 	DRM_DEBUG("BO size %lu > total memory in domain: %llu\n", size, man->size);
479 	return false;
480 }
481 
amdgpu_bo_support_uswc(u64 bo_flags)482 bool amdgpu_bo_support_uswc(u64 bo_flags)
483 {
484 
485 #ifdef CONFIG_X86_32
486 	/* XXX: Write-combined CPU mappings of GTT seem broken on 32-bit
487 	 * See https://bugs.freedesktop.org/show_bug.cgi?id=84627
488 	 */
489 	return false;
490 #elif defined(CONFIG_X86) && !defined(CONFIG_X86_PAT)
491 	/* Don't try to enable write-combining when it can't work, or things
492 	 * may be slow
493 	 * See https://bugs.freedesktop.org/show_bug.cgi?id=88758
494 	 */
495 
496 #ifndef CONFIG_COMPILE_TEST
497 #warning Please enable CONFIG_MTRR and CONFIG_X86_PAT for better performance \
498 	 thanks to write-combining
499 #endif
500 
501 	if (bo_flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
502 		DRM_INFO_ONCE("Please enable CONFIG_MTRR and CONFIG_X86_PAT for "
503 			      "better performance thanks to write-combining\n");
504 	return false;
505 #else
506 	/* For architectures that don't support WC memory,
507 	 * mask out the WC flag from the BO
508 	 */
509 	if (!drm_arch_can_wc_memory())
510 		return false;
511 
512 	return true;
513 #endif
514 }
515 
516 /**
517  * amdgpu_bo_create - create an &amdgpu_bo buffer object
518  * @adev: amdgpu device object
519  * @bp: parameters to be used for the buffer object
520  * @bo_ptr: pointer to the buffer object pointer
521  *
522  * Creates an &amdgpu_bo buffer object.
523  *
524  * Returns:
525  * 0 for success or a negative error code on failure.
526  */
amdgpu_bo_create(struct amdgpu_device * adev,struct amdgpu_bo_param * bp,struct amdgpu_bo ** bo_ptr)527 int amdgpu_bo_create(struct amdgpu_device *adev,
528 			       struct amdgpu_bo_param *bp,
529 			       struct amdgpu_bo **bo_ptr)
530 {
531 	struct ttm_operation_ctx ctx = {
532 		.interruptible = (bp->type != ttm_bo_type_kernel),
533 		.no_wait_gpu = bp->no_wait_gpu,
534 		/* We opt to avoid OOM on system pages allocations */
535 		.gfp_retry_mayfail = true,
536 		.allow_res_evict = bp->type != ttm_bo_type_kernel,
537 		.resv = bp->resv
538 	};
539 	struct amdgpu_bo *bo;
540 	unsigned long page_align, size = bp->size;
541 	int r;
542 
543 	/* Note that GDS/GWS/OA allocates 1 page per byte/resource. */
544 	if (bp->domain & (AMDGPU_GEM_DOMAIN_GWS | AMDGPU_GEM_DOMAIN_OA)) {
545 		/* GWS and OA don't need any alignment. */
546 		page_align = bp->byte_align;
547 		size <<= PAGE_SHIFT;
548 
549 	} else if (bp->domain & AMDGPU_GEM_DOMAIN_GDS) {
550 		/* Both size and alignment must be a multiple of 4. */
551 		page_align = ALIGN(bp->byte_align, 4);
552 		size = ALIGN(size, 4) << PAGE_SHIFT;
553 	} else {
554 		/* Memory should be aligned at least to a page size. */
555 		page_align = ALIGN(bp->byte_align, PAGE_SIZE) >> PAGE_SHIFT;
556 		size = ALIGN(size, PAGE_SIZE);
557 	}
558 
559 	if (!amdgpu_bo_validate_size(adev, size, bp->domain))
560 		return -ENOMEM;
561 
562 	BUG_ON(bp->bo_ptr_size < sizeof(struct amdgpu_bo));
563 
564 	*bo_ptr = NULL;
565 	bo = kvzalloc(bp->bo_ptr_size, GFP_KERNEL);
566 	if (bo == NULL)
567 		return -ENOMEM;
568 	drm_gem_private_object_init(adev_to_drm(adev), &bo->tbo.base, size);
569 	bo->tbo.base.funcs = &amdgpu_gem_object_funcs;
570 	bo->adev = adev;
571 	bo->vm_bo = NULL;
572 	bo->preferred_domains = bp->preferred_domain ? bp->preferred_domain :
573 		bp->domain;
574 	bo->allowed_domains = bo->preferred_domains;
575 	if (bp->type != ttm_bo_type_kernel &&
576 	    !(bp->flags & AMDGPU_GEM_CREATE_DISCARDABLE) &&
577 	    bo->allowed_domains == AMDGPU_GEM_DOMAIN_VRAM)
578 		bo->allowed_domains |= AMDGPU_GEM_DOMAIN_GTT;
579 
580 	bo->flags = bp->flags;
581 
582 	if (adev->gmc.mem_partitions)
583 		/* For GPUs with spatial partitioning, bo->xcp_id=-1 means any partition */
584 		bo->xcp_id = bp->xcp_id_plus1 - 1;
585 	else
586 		/* For GPUs without spatial partitioning */
587 		bo->xcp_id = 0;
588 
589 	if (!amdgpu_bo_support_uswc(bo->flags))
590 		bo->flags &= ~AMDGPU_GEM_CREATE_CPU_GTT_USWC;
591 
592 	bo->tbo.bdev = &adev->mman.bdev;
593 	if (bp->domain & (AMDGPU_GEM_DOMAIN_GWS | AMDGPU_GEM_DOMAIN_OA |
594 			  AMDGPU_GEM_DOMAIN_GDS))
595 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
596 	else
597 		amdgpu_bo_placement_from_domain(bo, bp->domain);
598 	if (bp->type == ttm_bo_type_kernel)
599 		bo->tbo.priority = 2;
600 	else if (!(bp->flags & AMDGPU_GEM_CREATE_DISCARDABLE))
601 		bo->tbo.priority = 1;
602 
603 	if (!bp->destroy)
604 		bp->destroy = &amdgpu_bo_destroy;
605 
606 	r = ttm_bo_init_reserved(&adev->mman.bdev, &bo->tbo, bp->type,
607 				 &bo->placement, page_align, &ctx,  NULL,
608 				 bp->resv, bp->destroy);
609 	if (unlikely(r != 0))
610 		return r;
611 
612 	if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
613 	    amdgpu_res_cpu_visible(adev, bo->tbo.resource))
614 		amdgpu_cs_report_moved_bytes(adev, ctx.bytes_moved,
615 					     ctx.bytes_moved);
616 	else
617 		amdgpu_cs_report_moved_bytes(adev, ctx.bytes_moved, 0);
618 
619 	if (bp->flags & AMDGPU_GEM_CREATE_VRAM_CLEARED &&
620 	    bo->tbo.resource->mem_type == TTM_PL_VRAM) {
621 		struct dma_fence *fence;
622 
623 		r = amdgpu_ttm_clear_buffer(bo, bo->tbo.base.resv, &fence);
624 		if (unlikely(r))
625 			goto fail_unreserve;
626 
627 		dma_resv_add_fence(bo->tbo.base.resv, fence,
628 				   DMA_RESV_USAGE_KERNEL);
629 		dma_fence_put(fence);
630 	}
631 	if (!bp->resv)
632 		amdgpu_bo_unreserve(bo);
633 	*bo_ptr = bo;
634 
635 	trace_amdgpu_bo_create(bo);
636 
637 	/* Treat CPU_ACCESS_REQUIRED only as a hint if given by UMD */
638 	if (bp->type == ttm_bo_type_device)
639 		bo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
640 
641 	return 0;
642 
643 fail_unreserve:
644 	if (!bp->resv)
645 		dma_resv_unlock(bo->tbo.base.resv);
646 	amdgpu_bo_unref(&bo);
647 	return r;
648 }
649 
650 /**
651  * amdgpu_bo_create_user - create an &amdgpu_bo_user buffer object
652  * @adev: amdgpu device object
653  * @bp: parameters to be used for the buffer object
654  * @ubo_ptr: pointer to the buffer object pointer
655  *
656  * Create a BO to be used by user application;
657  *
658  * Returns:
659  * 0 for success or a negative error code on failure.
660  */
661 
amdgpu_bo_create_user(struct amdgpu_device * adev,struct amdgpu_bo_param * bp,struct amdgpu_bo_user ** ubo_ptr)662 int amdgpu_bo_create_user(struct amdgpu_device *adev,
663 			  struct amdgpu_bo_param *bp,
664 			  struct amdgpu_bo_user **ubo_ptr)
665 {
666 	struct amdgpu_bo *bo_ptr;
667 	int r;
668 
669 	bp->bo_ptr_size = sizeof(struct amdgpu_bo_user);
670 	bp->destroy = &amdgpu_bo_user_destroy;
671 	r = amdgpu_bo_create(adev, bp, &bo_ptr);
672 	if (r)
673 		return r;
674 
675 	*ubo_ptr = to_amdgpu_bo_user(bo_ptr);
676 	return r;
677 }
678 
679 /**
680  * amdgpu_bo_create_vm - create an &amdgpu_bo_vm buffer object
681  * @adev: amdgpu device object
682  * @bp: parameters to be used for the buffer object
683  * @vmbo_ptr: pointer to the buffer object pointer
684  *
685  * Create a BO to be for GPUVM.
686  *
687  * Returns:
688  * 0 for success or a negative error code on failure.
689  */
690 
amdgpu_bo_create_vm(struct amdgpu_device * adev,struct amdgpu_bo_param * bp,struct amdgpu_bo_vm ** vmbo_ptr)691 int amdgpu_bo_create_vm(struct amdgpu_device *adev,
692 			struct amdgpu_bo_param *bp,
693 			struct amdgpu_bo_vm **vmbo_ptr)
694 {
695 	struct amdgpu_bo *bo_ptr;
696 	int r;
697 
698 	/* bo_ptr_size will be determined by the caller and it depends on
699 	 * num of amdgpu_vm_pt entries.
700 	 */
701 	BUG_ON(bp->bo_ptr_size < sizeof(struct amdgpu_bo_vm));
702 	r = amdgpu_bo_create(adev, bp, &bo_ptr);
703 	if (r)
704 		return r;
705 
706 	*vmbo_ptr = to_amdgpu_bo_vm(bo_ptr);
707 	return r;
708 }
709 
710 /**
711  * amdgpu_bo_kmap - map an &amdgpu_bo buffer object
712  * @bo: &amdgpu_bo buffer object to be mapped
713  * @ptr: kernel virtual address to be returned
714  *
715  * Calls ttm_bo_kmap() to set up the kernel virtual mapping; calls
716  * amdgpu_bo_kptr() to get the kernel virtual address.
717  *
718  * Returns:
719  * 0 for success or a negative error code on failure.
720  */
amdgpu_bo_kmap(struct amdgpu_bo * bo,void ** ptr)721 int amdgpu_bo_kmap(struct amdgpu_bo *bo, void **ptr)
722 {
723 	void *kptr;
724 	long r;
725 
726 	if (bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS)
727 		return -EPERM;
728 
729 	r = dma_resv_wait_timeout(bo->tbo.base.resv, DMA_RESV_USAGE_KERNEL,
730 				  false, MAX_SCHEDULE_TIMEOUT);
731 	if (r < 0)
732 		return r;
733 
734 	kptr = amdgpu_bo_kptr(bo);
735 	if (kptr) {
736 		if (ptr)
737 			*ptr = kptr;
738 		return 0;
739 	}
740 
741 	r = ttm_bo_kmap(&bo->tbo, 0, PFN_UP(bo->tbo.base.size), &bo->kmap);
742 	if (r)
743 		return r;
744 
745 	if (ptr)
746 		*ptr = amdgpu_bo_kptr(bo);
747 
748 	return 0;
749 }
750 
751 /**
752  * amdgpu_bo_kptr - returns a kernel virtual address of the buffer object
753  * @bo: &amdgpu_bo buffer object
754  *
755  * Calls ttm_kmap_obj_virtual() to get the kernel virtual address
756  *
757  * Returns:
758  * the virtual address of a buffer object area.
759  */
amdgpu_bo_kptr(struct amdgpu_bo * bo)760 void *amdgpu_bo_kptr(struct amdgpu_bo *bo)
761 {
762 	bool is_iomem;
763 
764 	return ttm_kmap_obj_virtual(&bo->kmap, &is_iomem);
765 }
766 
767 /**
768  * amdgpu_bo_kunmap - unmap an &amdgpu_bo buffer object
769  * @bo: &amdgpu_bo buffer object to be unmapped
770  *
771  * Unmaps a kernel map set up by amdgpu_bo_kmap().
772  */
amdgpu_bo_kunmap(struct amdgpu_bo * bo)773 void amdgpu_bo_kunmap(struct amdgpu_bo *bo)
774 {
775 	if (bo->kmap.bo)
776 		ttm_bo_kunmap(&bo->kmap);
777 }
778 
779 /**
780  * amdgpu_bo_ref - reference an &amdgpu_bo buffer object
781  * @bo: &amdgpu_bo buffer object
782  *
783  * References the contained &ttm_buffer_object.
784  *
785  * Returns:
786  * a refcounted pointer to the &amdgpu_bo buffer object.
787  */
amdgpu_bo_ref(struct amdgpu_bo * bo)788 struct amdgpu_bo *amdgpu_bo_ref(struct amdgpu_bo *bo)
789 {
790 	if (bo == NULL)
791 		return NULL;
792 
793 	drm_gem_object_get(&bo->tbo.base);
794 	return bo;
795 }
796 
797 /**
798  * amdgpu_bo_unref - unreference an &amdgpu_bo buffer object
799  * @bo: &amdgpu_bo buffer object
800  *
801  * Unreferences the contained &ttm_buffer_object and clear the pointer
802  */
amdgpu_bo_unref(struct amdgpu_bo ** bo)803 void amdgpu_bo_unref(struct amdgpu_bo **bo)
804 {
805 	if ((*bo) == NULL)
806 		return;
807 
808 	drm_gem_object_put(&(*bo)->tbo.base);
809 	*bo = NULL;
810 }
811 
812 /**
813  * amdgpu_bo_pin - pin an &amdgpu_bo buffer object
814  * @bo: &amdgpu_bo buffer object to be pinned
815  * @domain: domain to be pinned to
816  *
817  * Pins the buffer object according to requested domain. If the memory is
818  * unbound gart memory, binds the pages into gart table. Adjusts pin_count and
819  * pin_size accordingly.
820  *
821  * Pinning means to lock pages in memory along with keeping them at a fixed
822  * offset. It is required when a buffer can not be moved, for example, when
823  * a display buffer is being scanned out.
824  *
825  * Returns:
826  * 0 for success or a negative error code on failure.
827  */
amdgpu_bo_pin(struct amdgpu_bo * bo,u32 domain)828 int amdgpu_bo_pin(struct amdgpu_bo *bo, u32 domain)
829 {
830 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
831 	struct ttm_operation_ctx ctx = { false, false };
832 	int r, i;
833 
834 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm))
835 		return -EPERM;
836 
837 	/* Check domain to be pinned to against preferred domains */
838 	if (bo->preferred_domains & domain)
839 		domain = bo->preferred_domains & domain;
840 
841 	/* A shared bo cannot be migrated to VRAM */
842 	if (bo->tbo.base.import_attach) {
843 		if (domain & AMDGPU_GEM_DOMAIN_GTT)
844 			domain = AMDGPU_GEM_DOMAIN_GTT;
845 		else
846 			return -EINVAL;
847 	}
848 
849 	if (bo->tbo.pin_count) {
850 		uint32_t mem_type = bo->tbo.resource->mem_type;
851 		uint32_t mem_flags = bo->tbo.resource->placement;
852 
853 		if (!(domain & amdgpu_mem_type_to_domain(mem_type)))
854 			return -EINVAL;
855 
856 		if ((mem_type == TTM_PL_VRAM) &&
857 		    (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS) &&
858 		    !(mem_flags & TTM_PL_FLAG_CONTIGUOUS))
859 			return -EINVAL;
860 
861 		ttm_bo_pin(&bo->tbo);
862 		return 0;
863 	}
864 
865 	/* This assumes only APU display buffers are pinned with (VRAM|GTT).
866 	 * See function amdgpu_display_supported_domains()
867 	 */
868 	domain = amdgpu_bo_get_preferred_domain(adev, domain);
869 
870 #ifdef notyet
871 	if (bo->tbo.base.import_attach)
872 		dma_buf_pin(bo->tbo.base.import_attach);
873 #endif
874 
875 	/* force to pin into visible video ram */
876 	if (!(bo->flags & AMDGPU_GEM_CREATE_NO_CPU_ACCESS))
877 		bo->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
878 	amdgpu_bo_placement_from_domain(bo, domain);
879 	for (i = 0; i < bo->placement.num_placement; i++) {
880 		if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS &&
881 		    bo->placements[i].mem_type == TTM_PL_VRAM)
882 			bo->placements[i].flags |= TTM_PL_FLAG_CONTIGUOUS;
883 	}
884 
885 	r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
886 	if (unlikely(r)) {
887 		dev_err(adev->dev, "%p pin failed\n", bo);
888 		goto error;
889 	}
890 
891 	ttm_bo_pin(&bo->tbo);
892 
893 	if (bo->tbo.resource->mem_type == TTM_PL_VRAM) {
894 		atomic64_add(amdgpu_bo_size(bo), &adev->vram_pin_size);
895 		atomic64_add(amdgpu_vram_mgr_bo_visible_size(bo),
896 			     &adev->visible_pin_size);
897 	} else if (bo->tbo.resource->mem_type == TTM_PL_TT) {
898 		atomic64_add(amdgpu_bo_size(bo), &adev->gart_pin_size);
899 	}
900 
901 error:
902 	return r;
903 }
904 
905 /**
906  * amdgpu_bo_unpin - unpin an &amdgpu_bo buffer object
907  * @bo: &amdgpu_bo buffer object to be unpinned
908  *
909  * Decreases the pin_count, and clears the flags if pin_count reaches 0.
910  * Changes placement and pin size accordingly.
911  *
912  * Returns:
913  * 0 for success or a negative error code on failure.
914  */
amdgpu_bo_unpin(struct amdgpu_bo * bo)915 void amdgpu_bo_unpin(struct amdgpu_bo *bo)
916 {
917 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
918 
919 	ttm_bo_unpin(&bo->tbo);
920 	if (bo->tbo.pin_count)
921 		return;
922 
923 #ifdef notyet
924 	if (bo->tbo.base.import_attach)
925 		dma_buf_unpin(bo->tbo.base.import_attach);
926 #endif
927 
928 	if (bo->tbo.resource->mem_type == TTM_PL_VRAM) {
929 		atomic64_sub(amdgpu_bo_size(bo), &adev->vram_pin_size);
930 		atomic64_sub(amdgpu_vram_mgr_bo_visible_size(bo),
931 			     &adev->visible_pin_size);
932 	} else if (bo->tbo.resource->mem_type == TTM_PL_TT) {
933 		atomic64_sub(amdgpu_bo_size(bo), &adev->gart_pin_size);
934 	}
935 
936 }
937 
938 static const char * const amdgpu_vram_names[] = {
939 	"UNKNOWN",
940 	"GDDR1",
941 	"DDR2",
942 	"GDDR3",
943 	"GDDR4",
944 	"GDDR5",
945 	"HBM",
946 	"DDR3",
947 	"DDR4",
948 	"GDDR6",
949 	"DDR5",
950 	"LPDDR4",
951 	"LPDDR5"
952 };
953 
954 /**
955  * amdgpu_bo_init - initialize memory manager
956  * @adev: amdgpu device object
957  *
958  * Calls amdgpu_ttm_init() to initialize amdgpu memory manager.
959  *
960  * Returns:
961  * 0 for success or a negative error code on failure.
962  */
amdgpu_bo_init(struct amdgpu_device * adev)963 int amdgpu_bo_init(struct amdgpu_device *adev)
964 {
965 	/* On A+A platform, VRAM can be mapped as WB */
966 	if (!adev->gmc.xgmi.connected_to_cpu && !adev->gmc.is_app_apu) {
967 #ifdef __linux__
968 		/* reserve PAT memory space to WC for VRAM */
969 		int r = arch_io_reserve_memtype_wc(adev->gmc.aper_base,
970 				adev->gmc.aper_size);
971 
972 		if (r) {
973 			DRM_ERROR("Unable to set WC memtype for the aperture base\n");
974 			return r;
975 		}
976 
977 		/* Add an MTRR for the VRAM */
978 		adev->gmc.vram_mtrr = arch_phys_wc_add(adev->gmc.aper_base,
979 				adev->gmc.aper_size);
980 #else
981 		paddr_t start, end;
982 
983 		drm_mtrr_add(adev->gmc.aper_base, adev->gmc.aper_size, DRM_MTRR_WC);
984 
985 		start = atop(bus_space_mmap(adev->memt, adev->gmc.aper_base, 0, 0, 0));
986 		end = start + atop(adev->gmc.aper_size);
987 		uvm_page_physload(start, end, start, end, PHYSLOAD_DEVICE);
988 #endif
989 	}
990 
991 	DRM_INFO("Detected VRAM RAM=%lluM, BAR=%lluM\n",
992 		 adev->gmc.mc_vram_size >> 20,
993 		 (unsigned long long)adev->gmc.aper_size >> 20);
994 	DRM_INFO("RAM width %dbits %s\n",
995 		 adev->gmc.vram_width, amdgpu_vram_names[adev->gmc.vram_type]);
996 	return amdgpu_ttm_init(adev);
997 }
998 
999 /**
1000  * amdgpu_bo_fini - tear down memory manager
1001  * @adev: amdgpu device object
1002  *
1003  * Reverses amdgpu_bo_init() to tear down memory manager.
1004  */
amdgpu_bo_fini(struct amdgpu_device * adev)1005 void amdgpu_bo_fini(struct amdgpu_device *adev)
1006 {
1007 	int idx;
1008 
1009 	amdgpu_ttm_fini(adev);
1010 
1011 	if (drm_dev_enter(adev_to_drm(adev), &idx)) {
1012 		if (!adev->gmc.xgmi.connected_to_cpu && !adev->gmc.is_app_apu) {
1013 #ifdef __linux__
1014 			arch_phys_wc_del(adev->gmc.vram_mtrr);
1015 			arch_io_free_memtype_wc(adev->gmc.aper_base, adev->gmc.aper_size);
1016 #else
1017 			drm_mtrr_del(0, adev->gmc.aper_base, adev->gmc.aper_size, DRM_MTRR_WC);
1018 #endif
1019 		}
1020 		drm_dev_exit(idx);
1021 	}
1022 }
1023 
1024 /**
1025  * amdgpu_bo_set_tiling_flags - set tiling flags
1026  * @bo: &amdgpu_bo buffer object
1027  * @tiling_flags: new flags
1028  *
1029  * Sets buffer object's tiling flags with the new one. Used by GEM ioctl or
1030  * kernel driver to set the tiling flags on a buffer.
1031  *
1032  * Returns:
1033  * 0 for success or a negative error code on failure.
1034  */
amdgpu_bo_set_tiling_flags(struct amdgpu_bo * bo,u64 tiling_flags)1035 int amdgpu_bo_set_tiling_flags(struct amdgpu_bo *bo, u64 tiling_flags)
1036 {
1037 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1038 	struct amdgpu_bo_user *ubo;
1039 
1040 	BUG_ON(bo->tbo.type == ttm_bo_type_kernel);
1041 	if (adev->family <= AMDGPU_FAMILY_CZ &&
1042 	    AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT) > 6)
1043 		return -EINVAL;
1044 
1045 	ubo = to_amdgpu_bo_user(bo);
1046 	ubo->tiling_flags = tiling_flags;
1047 	return 0;
1048 }
1049 
1050 /**
1051  * amdgpu_bo_get_tiling_flags - get tiling flags
1052  * @bo: &amdgpu_bo buffer object
1053  * @tiling_flags: returned flags
1054  *
1055  * Gets buffer object's tiling flags. Used by GEM ioctl or kernel driver to
1056  * set the tiling flags on a buffer.
1057  */
amdgpu_bo_get_tiling_flags(struct amdgpu_bo * bo,u64 * tiling_flags)1058 void amdgpu_bo_get_tiling_flags(struct amdgpu_bo *bo, u64 *tiling_flags)
1059 {
1060 	struct amdgpu_bo_user *ubo;
1061 
1062 	BUG_ON(bo->tbo.type == ttm_bo_type_kernel);
1063 	dma_resv_assert_held(bo->tbo.base.resv);
1064 	ubo = to_amdgpu_bo_user(bo);
1065 
1066 	if (tiling_flags)
1067 		*tiling_flags = ubo->tiling_flags;
1068 }
1069 
1070 /**
1071  * amdgpu_bo_set_metadata - set metadata
1072  * @bo: &amdgpu_bo buffer object
1073  * @metadata: new metadata
1074  * @metadata_size: size of the new metadata
1075  * @flags: flags of the new metadata
1076  *
1077  * Sets buffer object's metadata, its size and flags.
1078  * Used via GEM ioctl.
1079  *
1080  * Returns:
1081  * 0 for success or a negative error code on failure.
1082  */
amdgpu_bo_set_metadata(struct amdgpu_bo * bo,void * metadata,u32 metadata_size,uint64_t flags)1083 int amdgpu_bo_set_metadata(struct amdgpu_bo *bo, void *metadata,
1084 			   u32 metadata_size, uint64_t flags)
1085 {
1086 	struct amdgpu_bo_user *ubo;
1087 	void *buffer;
1088 
1089 	BUG_ON(bo->tbo.type == ttm_bo_type_kernel);
1090 	ubo = to_amdgpu_bo_user(bo);
1091 	if (!metadata_size) {
1092 		if (ubo->metadata_size) {
1093 			kfree(ubo->metadata);
1094 			ubo->metadata = NULL;
1095 			ubo->metadata_size = 0;
1096 		}
1097 		return 0;
1098 	}
1099 
1100 	if (metadata == NULL)
1101 		return -EINVAL;
1102 
1103 	buffer = kmemdup(metadata, metadata_size, GFP_KERNEL);
1104 	if (buffer == NULL)
1105 		return -ENOMEM;
1106 
1107 	kfree(ubo->metadata);
1108 	ubo->metadata_flags = flags;
1109 	ubo->metadata = buffer;
1110 	ubo->metadata_size = metadata_size;
1111 
1112 	return 0;
1113 }
1114 
1115 /**
1116  * amdgpu_bo_get_metadata - get metadata
1117  * @bo: &amdgpu_bo buffer object
1118  * @buffer: returned metadata
1119  * @buffer_size: size of the buffer
1120  * @metadata_size: size of the returned metadata
1121  * @flags: flags of the returned metadata
1122  *
1123  * Gets buffer object's metadata, its size and flags. buffer_size shall not be
1124  * less than metadata_size.
1125  * Used via GEM ioctl.
1126  *
1127  * Returns:
1128  * 0 for success or a negative error code on failure.
1129  */
amdgpu_bo_get_metadata(struct amdgpu_bo * bo,void * buffer,size_t buffer_size,uint32_t * metadata_size,uint64_t * flags)1130 int amdgpu_bo_get_metadata(struct amdgpu_bo *bo, void *buffer,
1131 			   size_t buffer_size, uint32_t *metadata_size,
1132 			   uint64_t *flags)
1133 {
1134 	struct amdgpu_bo_user *ubo;
1135 
1136 	if (!buffer && !metadata_size)
1137 		return -EINVAL;
1138 
1139 	BUG_ON(bo->tbo.type == ttm_bo_type_kernel);
1140 	ubo = to_amdgpu_bo_user(bo);
1141 	if (metadata_size)
1142 		*metadata_size = ubo->metadata_size;
1143 
1144 	if (buffer) {
1145 		if (buffer_size < ubo->metadata_size)
1146 			return -EINVAL;
1147 
1148 		if (ubo->metadata_size)
1149 			memcpy(buffer, ubo->metadata, ubo->metadata_size);
1150 	}
1151 
1152 	if (flags)
1153 		*flags = ubo->metadata_flags;
1154 
1155 	return 0;
1156 }
1157 
1158 /**
1159  * amdgpu_bo_move_notify - notification about a memory move
1160  * @bo: pointer to a buffer object
1161  * @evict: if this move is evicting the buffer from the graphics address space
1162  * @new_mem: new resource for backing the BO
1163  *
1164  * Marks the corresponding &amdgpu_bo buffer object as invalid, also performs
1165  * bookkeeping.
1166  * TTM driver callback which is called when ttm moves a buffer.
1167  */
amdgpu_bo_move_notify(struct ttm_buffer_object * bo,bool evict,struct ttm_resource * new_mem)1168 void amdgpu_bo_move_notify(struct ttm_buffer_object *bo,
1169 			   bool evict,
1170 			   struct ttm_resource *new_mem)
1171 {
1172 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1173 	struct ttm_resource *old_mem = bo->resource;
1174 	struct amdgpu_bo *abo;
1175 
1176 	if (!amdgpu_bo_is_amdgpu_bo(bo))
1177 		return;
1178 
1179 	abo = ttm_to_amdgpu_bo(bo);
1180 	amdgpu_vm_bo_invalidate(adev, abo, evict);
1181 
1182 	amdgpu_bo_kunmap(abo);
1183 
1184 #ifdef notyet
1185 	if (abo->tbo.base.dma_buf && !abo->tbo.base.import_attach &&
1186 	    old_mem && old_mem->mem_type != TTM_PL_SYSTEM)
1187 		dma_buf_move_notify(abo->tbo.base.dma_buf);
1188 #endif
1189 
1190 	/* move_notify is called before move happens */
1191 	trace_amdgpu_bo_move(abo, new_mem ? new_mem->mem_type : -1,
1192 			     old_mem ? old_mem->mem_type : -1);
1193 }
1194 
amdgpu_bo_get_memory(struct amdgpu_bo * bo,struct amdgpu_mem_stats * stats)1195 void amdgpu_bo_get_memory(struct amdgpu_bo *bo,
1196 			  struct amdgpu_mem_stats *stats)
1197 {
1198 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1199 	struct ttm_resource *res = bo->tbo.resource;
1200 	uint64_t size = amdgpu_bo_size(bo);
1201 	struct drm_gem_object *obj;
1202 	bool shared;
1203 
1204 	/* Abort if the BO doesn't currently have a backing store */
1205 	if (!res)
1206 		return;
1207 
1208 	obj = &bo->tbo.base;
1209 	shared = drm_gem_object_is_shared_for_memory_stats(obj);
1210 
1211 	switch (res->mem_type) {
1212 	case TTM_PL_VRAM:
1213 		stats->vram += size;
1214 		if (amdgpu_res_cpu_visible(adev, res))
1215 			stats->visible_vram += size;
1216 		if (shared)
1217 			stats->vram_shared += size;
1218 		break;
1219 	case TTM_PL_TT:
1220 		stats->gtt += size;
1221 		if (shared)
1222 			stats->gtt_shared += size;
1223 		break;
1224 	case TTM_PL_SYSTEM:
1225 	default:
1226 		stats->cpu += size;
1227 		if (shared)
1228 			stats->cpu_shared += size;
1229 		break;
1230 	}
1231 
1232 	if (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) {
1233 		stats->requested_vram += size;
1234 		if (bo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED)
1235 			stats->requested_visible_vram += size;
1236 
1237 		if (res->mem_type != TTM_PL_VRAM) {
1238 			stats->evicted_vram += size;
1239 			if (bo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED)
1240 				stats->evicted_visible_vram += size;
1241 		}
1242 	} else if (bo->preferred_domains & AMDGPU_GEM_DOMAIN_GTT) {
1243 		stats->requested_gtt += size;
1244 	}
1245 }
1246 
1247 /**
1248  * amdgpu_bo_release_notify - notification about a BO being released
1249  * @bo: pointer to a buffer object
1250  *
1251  * Wipes VRAM buffers whose contents should not be leaked before the
1252  * memory is released.
1253  */
amdgpu_bo_release_notify(struct ttm_buffer_object * bo)1254 void amdgpu_bo_release_notify(struct ttm_buffer_object *bo)
1255 {
1256 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1257 	struct dma_fence *fence = NULL;
1258 	struct amdgpu_bo *abo;
1259 	int r;
1260 
1261 	if (!amdgpu_bo_is_amdgpu_bo(bo))
1262 		return;
1263 
1264 	abo = ttm_to_amdgpu_bo(bo);
1265 
1266 	WARN_ON(abo->vm_bo);
1267 
1268 	if (abo->kfd_bo)
1269 		amdgpu_amdkfd_release_notify(abo);
1270 
1271 	/* We only remove the fence if the resv has individualized. */
1272 	WARN_ON_ONCE(bo->type == ttm_bo_type_kernel
1273 			&& bo->base.resv != &bo->base._resv);
1274 	if (bo->base.resv == &bo->base._resv)
1275 		amdgpu_amdkfd_remove_fence_on_pt_pd_bos(abo);
1276 
1277 	if (!bo->resource || bo->resource->mem_type != TTM_PL_VRAM ||
1278 	    !(abo->flags & AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE) ||
1279 	    adev->in_suspend || drm_dev_is_unplugged(adev_to_drm(adev)))
1280 		return;
1281 
1282 	if (WARN_ON_ONCE(!dma_resv_trylock(bo->base.resv)))
1283 		return;
1284 
1285 	r = amdgpu_fill_buffer(abo, 0, bo->base.resv, &fence, true);
1286 	if (!WARN_ON(r)) {
1287 		amdgpu_vram_mgr_set_cleared(bo->resource);
1288 		amdgpu_bo_fence(abo, fence, false);
1289 		dma_fence_put(fence);
1290 	}
1291 
1292 	dma_resv_unlock(bo->base.resv);
1293 }
1294 
1295 /**
1296  * amdgpu_bo_fault_reserve_notify - notification about a memory fault
1297  * @bo: pointer to a buffer object
1298  *
1299  * Notifies the driver we are taking a fault on this BO and have reserved it,
1300  * also performs bookkeeping.
1301  * TTM driver callback for dealing with vm faults.
1302  *
1303  * Returns:
1304  * 0 for success or a negative error code on failure.
1305  */
amdgpu_bo_fault_reserve_notify(struct ttm_buffer_object * bo)1306 vm_fault_t amdgpu_bo_fault_reserve_notify(struct ttm_buffer_object *bo)
1307 {
1308 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
1309 	struct ttm_operation_ctx ctx = { false, false };
1310 	struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1311 	int r;
1312 
1313 	/* Remember that this BO was accessed by the CPU */
1314 	abo->flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
1315 
1316 	if (amdgpu_res_cpu_visible(adev, bo->resource))
1317 		return 0;
1318 
1319 	/* Can't move a pinned BO to visible VRAM */
1320 	if (abo->tbo.pin_count > 0)
1321 		return VM_FAULT_SIGBUS;
1322 
1323 	/* hurrah the memory is not visible ! */
1324 	atomic64_inc(&adev->num_vram_cpu_page_faults);
1325 	amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
1326 					AMDGPU_GEM_DOMAIN_GTT);
1327 
1328 	/* Avoid costly evictions; only set GTT as a busy placement */
1329 	abo->placements[0].flags |= TTM_PL_FLAG_DESIRED;
1330 
1331 	r = ttm_bo_validate(bo, &abo->placement, &ctx);
1332 	if (unlikely(r == -EBUSY || r == -ERESTARTSYS))
1333 		return VM_FAULT_NOPAGE;
1334 	else if (unlikely(r))
1335 		return VM_FAULT_SIGBUS;
1336 
1337 	/* this should never happen */
1338 	if (bo->resource->mem_type == TTM_PL_VRAM &&
1339 	    !amdgpu_res_cpu_visible(adev, bo->resource))
1340 		return VM_FAULT_SIGBUS;
1341 
1342 	ttm_bo_move_to_lru_tail_unlocked(bo);
1343 	return 0;
1344 }
1345 
1346 /**
1347  * amdgpu_bo_fence - add fence to buffer object
1348  *
1349  * @bo: buffer object in question
1350  * @fence: fence to add
1351  * @shared: true if fence should be added shared
1352  *
1353  */
amdgpu_bo_fence(struct amdgpu_bo * bo,struct dma_fence * fence,bool shared)1354 void amdgpu_bo_fence(struct amdgpu_bo *bo, struct dma_fence *fence,
1355 		     bool shared)
1356 {
1357 	struct dma_resv *resv = bo->tbo.base.resv;
1358 	int r;
1359 
1360 	r = dma_resv_reserve_fences(resv, 1);
1361 	if (r) {
1362 		/* As last resort on OOM we block for the fence */
1363 		dma_fence_wait(fence, false);
1364 		return;
1365 	}
1366 
1367 	dma_resv_add_fence(resv, fence, shared ? DMA_RESV_USAGE_READ :
1368 			   DMA_RESV_USAGE_WRITE);
1369 }
1370 
1371 /**
1372  * amdgpu_bo_sync_wait_resv - Wait for BO reservation fences
1373  *
1374  * @adev: amdgpu device pointer
1375  * @resv: reservation object to sync to
1376  * @sync_mode: synchronization mode
1377  * @owner: fence owner
1378  * @intr: Whether the wait is interruptible
1379  *
1380  * Extract the fences from the reservation object and waits for them to finish.
1381  *
1382  * Returns:
1383  * 0 on success, errno otherwise.
1384  */
amdgpu_bo_sync_wait_resv(struct amdgpu_device * adev,struct dma_resv * resv,enum amdgpu_sync_mode sync_mode,void * owner,bool intr)1385 int amdgpu_bo_sync_wait_resv(struct amdgpu_device *adev, struct dma_resv *resv,
1386 			     enum amdgpu_sync_mode sync_mode, void *owner,
1387 			     bool intr)
1388 {
1389 	struct amdgpu_sync sync;
1390 	int r;
1391 
1392 	amdgpu_sync_create(&sync);
1393 	amdgpu_sync_resv(adev, &sync, resv, sync_mode, owner);
1394 	r = amdgpu_sync_wait(&sync, intr);
1395 	amdgpu_sync_free(&sync);
1396 	return r;
1397 }
1398 
1399 /**
1400  * amdgpu_bo_sync_wait - Wrapper for amdgpu_bo_sync_wait_resv
1401  * @bo: buffer object to wait for
1402  * @owner: fence owner
1403  * @intr: Whether the wait is interruptible
1404  *
1405  * Wrapper to wait for fences in a BO.
1406  * Returns:
1407  * 0 on success, errno otherwise.
1408  */
amdgpu_bo_sync_wait(struct amdgpu_bo * bo,void * owner,bool intr)1409 int amdgpu_bo_sync_wait(struct amdgpu_bo *bo, void *owner, bool intr)
1410 {
1411 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1412 
1413 	return amdgpu_bo_sync_wait_resv(adev, bo->tbo.base.resv,
1414 					AMDGPU_SYNC_NE_OWNER, owner, intr);
1415 }
1416 
1417 /**
1418  * amdgpu_bo_gpu_offset - return GPU offset of bo
1419  * @bo:	amdgpu object for which we query the offset
1420  *
1421  * Note: object should either be pinned or reserved when calling this
1422  * function, it might be useful to add check for this for debugging.
1423  *
1424  * Returns:
1425  * current GPU offset of the object.
1426  */
amdgpu_bo_gpu_offset(struct amdgpu_bo * bo)1427 u64 amdgpu_bo_gpu_offset(struct amdgpu_bo *bo)
1428 {
1429 	WARN_ON_ONCE(bo->tbo.resource->mem_type == TTM_PL_SYSTEM);
1430 	WARN_ON_ONCE(!dma_resv_is_locked(bo->tbo.base.resv) &&
1431 		     !bo->tbo.pin_count && bo->tbo.type != ttm_bo_type_kernel);
1432 	WARN_ON_ONCE(bo->tbo.resource->start == AMDGPU_BO_INVALID_OFFSET);
1433 	WARN_ON_ONCE(bo->tbo.resource->mem_type == TTM_PL_VRAM &&
1434 		     !(bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS));
1435 
1436 	return amdgpu_bo_gpu_offset_no_check(bo);
1437 }
1438 
1439 /**
1440  * amdgpu_bo_gpu_offset_no_check - return GPU offset of bo
1441  * @bo:	amdgpu object for which we query the offset
1442  *
1443  * Returns:
1444  * current GPU offset of the object without raising warnings.
1445  */
amdgpu_bo_gpu_offset_no_check(struct amdgpu_bo * bo)1446 u64 amdgpu_bo_gpu_offset_no_check(struct amdgpu_bo *bo)
1447 {
1448 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1449 	uint64_t offset = AMDGPU_BO_INVALID_OFFSET;
1450 
1451 	if (bo->tbo.resource->mem_type == TTM_PL_TT)
1452 		offset = amdgpu_gmc_agp_addr(&bo->tbo);
1453 
1454 	if (offset == AMDGPU_BO_INVALID_OFFSET)
1455 		offset = (bo->tbo.resource->start << PAGE_SHIFT) +
1456 			amdgpu_ttm_domain_start(adev, bo->tbo.resource->mem_type);
1457 
1458 	return amdgpu_gmc_sign_extend(offset);
1459 }
1460 
1461 /**
1462  * amdgpu_bo_get_preferred_domain - get preferred domain
1463  * @adev: amdgpu device object
1464  * @domain: allowed :ref:`memory domains <amdgpu_memory_domains>`
1465  *
1466  * Returns:
1467  * Which of the allowed domains is preferred for allocating the BO.
1468  */
amdgpu_bo_get_preferred_domain(struct amdgpu_device * adev,uint32_t domain)1469 uint32_t amdgpu_bo_get_preferred_domain(struct amdgpu_device *adev,
1470 					    uint32_t domain)
1471 {
1472 	if ((domain == (AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT)) &&
1473 	    ((adev->asic_type == CHIP_CARRIZO) || (adev->asic_type == CHIP_STONEY))) {
1474 		domain = AMDGPU_GEM_DOMAIN_VRAM;
1475 		if (adev->gmc.real_vram_size <= AMDGPU_SG_THRESHOLD)
1476 			domain = AMDGPU_GEM_DOMAIN_GTT;
1477 	}
1478 	return domain;
1479 }
1480 
1481 #if defined(CONFIG_DEBUG_FS)
1482 #define amdgpu_bo_print_flag(m, bo, flag)		        \
1483 	do {							\
1484 		if (bo->flags & (AMDGPU_GEM_CREATE_ ## flag)) {	\
1485 			seq_printf((m), " " #flag);		\
1486 		}						\
1487 	} while (0)
1488 
1489 /**
1490  * amdgpu_bo_print_info - print BO info in debugfs file
1491  *
1492  * @id: Index or Id of the BO
1493  * @bo: Requested BO for printing info
1494  * @m: debugfs file
1495  *
1496  * Print BO information in debugfs file
1497  *
1498  * Returns:
1499  * Size of the BO in bytes.
1500  */
amdgpu_bo_print_info(int id,struct amdgpu_bo * bo,struct seq_file * m)1501 u64 amdgpu_bo_print_info(int id, struct amdgpu_bo *bo, struct seq_file *m)
1502 {
1503 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1504 	struct dma_buf_attachment *attachment;
1505 	struct dma_buf *dma_buf;
1506 	const char *placement;
1507 	unsigned int pin_count;
1508 	u64 size;
1509 
1510 	if (dma_resv_trylock(bo->tbo.base.resv)) {
1511 		if (!bo->tbo.resource) {
1512 			placement = "NONE";
1513 		} else {
1514 			switch (bo->tbo.resource->mem_type) {
1515 			case TTM_PL_VRAM:
1516 				if (amdgpu_res_cpu_visible(adev, bo->tbo.resource))
1517 					placement = "VRAM VISIBLE";
1518 				else
1519 					placement = "VRAM";
1520 				break;
1521 			case TTM_PL_TT:
1522 				placement = "GTT";
1523 				break;
1524 			case AMDGPU_PL_GDS:
1525 				placement = "GDS";
1526 				break;
1527 			case AMDGPU_PL_GWS:
1528 				placement = "GWS";
1529 				break;
1530 			case AMDGPU_PL_OA:
1531 				placement = "OA";
1532 				break;
1533 			case AMDGPU_PL_PREEMPT:
1534 				placement = "PREEMPTIBLE";
1535 				break;
1536 			case AMDGPU_PL_DOORBELL:
1537 				placement = "DOORBELL";
1538 				break;
1539 			case TTM_PL_SYSTEM:
1540 			default:
1541 				placement = "CPU";
1542 				break;
1543 			}
1544 		}
1545 		dma_resv_unlock(bo->tbo.base.resv);
1546 	} else {
1547 		placement = "UNKNOWN";
1548 	}
1549 
1550 	size = amdgpu_bo_size(bo);
1551 	seq_printf(m, "\t\t0x%08x: %12lld byte %s",
1552 			id, size, placement);
1553 
1554 	pin_count = READ_ONCE(bo->tbo.pin_count);
1555 	if (pin_count)
1556 		seq_printf(m, " pin count %d", pin_count);
1557 
1558 	dma_buf = READ_ONCE(bo->tbo.base.dma_buf);
1559 	attachment = READ_ONCE(bo->tbo.base.import_attach);
1560 
1561 	if (attachment)
1562 		seq_printf(m, " imported from ino:%lu", file_inode(dma_buf->file)->i_ino);
1563 	else if (dma_buf)
1564 		seq_printf(m, " exported as ino:%lu", file_inode(dma_buf->file)->i_ino);
1565 
1566 	amdgpu_bo_print_flag(m, bo, CPU_ACCESS_REQUIRED);
1567 	amdgpu_bo_print_flag(m, bo, NO_CPU_ACCESS);
1568 	amdgpu_bo_print_flag(m, bo, CPU_GTT_USWC);
1569 	amdgpu_bo_print_flag(m, bo, VRAM_CLEARED);
1570 	amdgpu_bo_print_flag(m, bo, VRAM_CONTIGUOUS);
1571 	amdgpu_bo_print_flag(m, bo, VM_ALWAYS_VALID);
1572 	amdgpu_bo_print_flag(m, bo, EXPLICIT_SYNC);
1573 
1574 	seq_puts(m, "\n");
1575 
1576 	return size;
1577 }
1578 #endif
1579