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