xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_vram_mgr.c (revision c2aa3089ad7e7fec3ec4a58d8d0904b5e9b392a1)
1 /*
2  * Copyright 2016 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: Christian König
23  */
24 
25 #include <linux/dma-mapping.h>
26 #include <drm/ttm/ttm_range_manager.h>
27 #include <drm/drm_drv.h>
28 
29 #include "amdgpu.h"
30 #include "amdgpu_vm.h"
31 #include "amdgpu_res_cursor.h"
32 #include "atom.h"
33 
34 #define AMDGPU_MAX_SG_SEGMENT_SIZE	(2UL << 30)
35 
36 struct amdgpu_vram_reservation {
37 	u64 start;
38 	u64 size;
39 	struct list_head allocated;
40 	struct list_head blocks;
41 };
42 
43 static inline struct amdgpu_vram_mgr *
44 to_vram_mgr(struct ttm_resource_manager *man)
45 {
46 	return container_of(man, struct amdgpu_vram_mgr, manager);
47 }
48 
49 static inline struct amdgpu_device *
50 to_amdgpu_device(struct amdgpu_vram_mgr *mgr)
51 {
52 	return container_of(mgr, struct amdgpu_device, mman.vram_mgr);
53 }
54 
55 static inline struct drm_buddy_block *
56 amdgpu_vram_mgr_first_block(struct list_head *list)
57 {
58 	return list_first_entry_or_null(list, struct drm_buddy_block, link);
59 }
60 
61 static inline bool amdgpu_is_vram_mgr_blocks_contiguous(struct list_head *head)
62 {
63 	struct drm_buddy_block *block;
64 	u64 start, size;
65 
66 	block = amdgpu_vram_mgr_first_block(head);
67 	if (!block)
68 		return false;
69 
70 	while (head != block->link.next) {
71 		start = amdgpu_vram_mgr_block_start(block);
72 		size = amdgpu_vram_mgr_block_size(block);
73 
74 		block = list_entry(block->link.next, struct drm_buddy_block, link);
75 		if (start + size != amdgpu_vram_mgr_block_start(block))
76 			return false;
77 	}
78 
79 	return true;
80 }
81 
82 static inline u64 amdgpu_vram_mgr_blocks_size(struct list_head *head)
83 {
84 	struct drm_buddy_block *block;
85 	u64 size = 0;
86 
87 	list_for_each_entry(block, head, link)
88 		size += amdgpu_vram_mgr_block_size(block);
89 
90 	return size;
91 }
92 
93 /**
94  * DOC: mem_info_vram_total
95  *
96  * The amdgpu driver provides a sysfs API for reporting current total VRAM
97  * available on the device
98  * The file mem_info_vram_total is used for this and returns the total
99  * amount of VRAM in bytes
100  */
101 static ssize_t amdgpu_mem_info_vram_total_show(struct device *dev,
102 		struct device_attribute *attr, char *buf)
103 {
104 	struct drm_device *ddev = dev_get_drvdata(dev);
105 	struct amdgpu_device *adev = drm_to_adev(ddev);
106 
107 	return sysfs_emit(buf, "%llu\n", adev->gmc.real_vram_size);
108 }
109 
110 /**
111  * DOC: mem_info_vis_vram_total
112  *
113  * The amdgpu driver provides a sysfs API for reporting current total
114  * visible VRAM available on the device
115  * The file mem_info_vis_vram_total is used for this and returns the total
116  * amount of visible VRAM in bytes
117  */
118 static ssize_t amdgpu_mem_info_vis_vram_total_show(struct device *dev,
119 		struct device_attribute *attr, char *buf)
120 {
121 	struct drm_device *ddev = dev_get_drvdata(dev);
122 	struct amdgpu_device *adev = drm_to_adev(ddev);
123 
124 	return sysfs_emit(buf, "%llu\n", adev->gmc.visible_vram_size);
125 }
126 
127 /**
128  * DOC: mem_info_vram_used
129  *
130  * The amdgpu driver provides a sysfs API for reporting current total VRAM
131  * available on the device
132  * The file mem_info_vram_used is used for this and returns the total
133  * amount of currently used VRAM in bytes
134  */
135 static ssize_t amdgpu_mem_info_vram_used_show(struct device *dev,
136 					      struct device_attribute *attr,
137 					      char *buf)
138 {
139 	struct drm_device *ddev = dev_get_drvdata(dev);
140 	struct amdgpu_device *adev = drm_to_adev(ddev);
141 	struct ttm_resource_manager *man = &adev->mman.vram_mgr.manager;
142 
143 	return sysfs_emit(buf, "%llu\n", ttm_resource_manager_usage(man));
144 }
145 
146 /**
147  * DOC: mem_info_vis_vram_used
148  *
149  * The amdgpu driver provides a sysfs API for reporting current total of
150  * used visible VRAM
151  * The file mem_info_vis_vram_used is used for this and returns the total
152  * amount of currently used visible VRAM in bytes
153  */
154 static ssize_t amdgpu_mem_info_vis_vram_used_show(struct device *dev,
155 						  struct device_attribute *attr,
156 						  char *buf)
157 {
158 	struct drm_device *ddev = dev_get_drvdata(dev);
159 	struct amdgpu_device *adev = drm_to_adev(ddev);
160 
161 	return sysfs_emit(buf, "%llu\n",
162 			  amdgpu_vram_mgr_vis_usage(&adev->mman.vram_mgr));
163 }
164 
165 /**
166  * DOC: mem_info_vram_vendor
167  *
168  * The amdgpu driver provides a sysfs API for reporting the vendor of the
169  * installed VRAM
170  * The file mem_info_vram_vendor is used for this and returns the name of the
171  * vendor.
172  */
173 static ssize_t amdgpu_mem_info_vram_vendor(struct device *dev,
174 					   struct device_attribute *attr,
175 					   char *buf)
176 {
177 	struct drm_device *ddev = dev_get_drvdata(dev);
178 	struct amdgpu_device *adev = drm_to_adev(ddev);
179 
180 	switch (adev->gmc.vram_vendor) {
181 	case SAMSUNG:
182 		return sysfs_emit(buf, "samsung\n");
183 	case INFINEON:
184 		return sysfs_emit(buf, "infineon\n");
185 	case ELPIDA:
186 		return sysfs_emit(buf, "elpida\n");
187 	case ETRON:
188 		return sysfs_emit(buf, "etron\n");
189 	case NANYA:
190 		return sysfs_emit(buf, "nanya\n");
191 	case HYNIX:
192 		return sysfs_emit(buf, "hynix\n");
193 	case MOSEL:
194 		return sysfs_emit(buf, "mosel\n");
195 	case WINBOND:
196 		return sysfs_emit(buf, "winbond\n");
197 	case ESMT:
198 		return sysfs_emit(buf, "esmt\n");
199 	case MICRON:
200 		return sysfs_emit(buf, "micron\n");
201 	default:
202 		return sysfs_emit(buf, "unknown\n");
203 	}
204 }
205 
206 static DEVICE_ATTR(mem_info_vram_total, S_IRUGO,
207 		   amdgpu_mem_info_vram_total_show, NULL);
208 static DEVICE_ATTR(mem_info_vis_vram_total, S_IRUGO,
209 		   amdgpu_mem_info_vis_vram_total_show,NULL);
210 static DEVICE_ATTR(mem_info_vram_used, S_IRUGO,
211 		   amdgpu_mem_info_vram_used_show, NULL);
212 static DEVICE_ATTR(mem_info_vis_vram_used, S_IRUGO,
213 		   amdgpu_mem_info_vis_vram_used_show, NULL);
214 static DEVICE_ATTR(mem_info_vram_vendor, S_IRUGO,
215 		   amdgpu_mem_info_vram_vendor, NULL);
216 
217 static struct attribute *amdgpu_vram_mgr_attributes[] = {
218 	&dev_attr_mem_info_vram_total.attr,
219 	&dev_attr_mem_info_vis_vram_total.attr,
220 	&dev_attr_mem_info_vram_used.attr,
221 	&dev_attr_mem_info_vis_vram_used.attr,
222 	&dev_attr_mem_info_vram_vendor.attr,
223 	NULL
224 };
225 
226 static umode_t amdgpu_vram_attrs_is_visible(struct kobject *kobj,
227 					    struct attribute *attr, int i)
228 {
229 	struct device *dev = kobj_to_dev(kobj);
230 	struct drm_device *ddev = dev_get_drvdata(dev);
231 	struct amdgpu_device *adev = drm_to_adev(ddev);
232 
233 	if (attr == &dev_attr_mem_info_vram_vendor.attr &&
234 	    !adev->gmc.vram_vendor)
235 		return 0;
236 
237 	return attr->mode;
238 }
239 
240 const struct attribute_group amdgpu_vram_mgr_attr_group = {
241 	.attrs = amdgpu_vram_mgr_attributes,
242 	.is_visible = amdgpu_vram_attrs_is_visible
243 };
244 
245 /**
246  * amdgpu_vram_mgr_vis_size - Calculate visible block size
247  *
248  * @adev: amdgpu_device pointer
249  * @block: DRM BUDDY block structure
250  *
251  * Calculate how many bytes of the DRM BUDDY block are inside visible VRAM
252  */
253 static u64 amdgpu_vram_mgr_vis_size(struct amdgpu_device *adev,
254 				    struct drm_buddy_block *block)
255 {
256 	u64 start = amdgpu_vram_mgr_block_start(block);
257 	u64 end = start + amdgpu_vram_mgr_block_size(block);
258 
259 	if (start >= adev->gmc.visible_vram_size)
260 		return 0;
261 
262 	return (end > adev->gmc.visible_vram_size ?
263 		adev->gmc.visible_vram_size : end) - start;
264 }
265 
266 /**
267  * amdgpu_vram_mgr_bo_visible_size - CPU visible BO size
268  *
269  * @bo: &amdgpu_bo buffer object (must be in VRAM)
270  *
271  * Returns:
272  * How much of the given &amdgpu_bo buffer object lies in CPU visible VRAM.
273  */
274 u64 amdgpu_vram_mgr_bo_visible_size(struct amdgpu_bo *bo)
275 {
276 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
277 	struct ttm_resource *res = bo->tbo.resource;
278 	struct amdgpu_vram_mgr_resource *vres = to_amdgpu_vram_mgr_resource(res);
279 	struct drm_buddy_block *block;
280 	u64 usage = 0;
281 
282 	if (amdgpu_gmc_vram_full_visible(&adev->gmc))
283 		return amdgpu_bo_size(bo);
284 
285 	if (res->start >= adev->gmc.visible_vram_size >> PAGE_SHIFT)
286 		return 0;
287 
288 	list_for_each_entry(block, &vres->blocks, link)
289 		usage += amdgpu_vram_mgr_vis_size(adev, block);
290 
291 	return usage;
292 }
293 
294 /* Commit the reservation of VRAM pages */
295 static void amdgpu_vram_mgr_do_reserve(struct ttm_resource_manager *man)
296 {
297 	struct amdgpu_vram_mgr *mgr = to_vram_mgr(man);
298 	struct amdgpu_device *adev = to_amdgpu_device(mgr);
299 	struct drm_buddy *mm = &mgr->mm;
300 	struct amdgpu_vram_reservation *rsv, *temp;
301 	struct drm_buddy_block *block;
302 	uint64_t vis_usage;
303 
304 	list_for_each_entry_safe(rsv, temp, &mgr->reservations_pending, blocks) {
305 		if (drm_buddy_alloc_blocks(mm, rsv->start, rsv->start + rsv->size,
306 					   rsv->size, mm->chunk_size, &rsv->allocated,
307 					   DRM_BUDDY_RANGE_ALLOCATION))
308 			continue;
309 
310 		block = amdgpu_vram_mgr_first_block(&rsv->allocated);
311 		if (!block)
312 			continue;
313 
314 		dev_dbg(adev->dev, "Reservation 0x%llx - %lld, Succeeded\n",
315 			rsv->start, rsv->size);
316 
317 		vis_usage = amdgpu_vram_mgr_vis_size(adev, block);
318 		atomic64_add(vis_usage, &mgr->vis_usage);
319 		spin_lock(&man->bdev->lru_lock);
320 		man->usage += rsv->size;
321 		spin_unlock(&man->bdev->lru_lock);
322 		list_move(&rsv->blocks, &mgr->reserved_pages);
323 	}
324 }
325 
326 /**
327  * amdgpu_vram_mgr_reserve_range - Reserve a range from VRAM
328  *
329  * @mgr: amdgpu_vram_mgr pointer
330  * @start: start address of the range in VRAM
331  * @size: size of the range
332  *
333  * Reserve memory from start address with the specified size in VRAM
334  */
335 int amdgpu_vram_mgr_reserve_range(struct amdgpu_vram_mgr *mgr,
336 				  uint64_t start, uint64_t size)
337 {
338 	struct amdgpu_vram_reservation *rsv;
339 
340 	rsv = kzalloc(sizeof(*rsv), GFP_KERNEL);
341 	if (!rsv)
342 		return -ENOMEM;
343 
344 	INIT_LIST_HEAD(&rsv->allocated);
345 	INIT_LIST_HEAD(&rsv->blocks);
346 
347 	rsv->start = start;
348 	rsv->size = size;
349 
350 	mutex_lock(&mgr->lock);
351 	list_add_tail(&rsv->blocks, &mgr->reservations_pending);
352 	amdgpu_vram_mgr_do_reserve(&mgr->manager);
353 	mutex_unlock(&mgr->lock);
354 
355 	return 0;
356 }
357 
358 /**
359  * amdgpu_vram_mgr_query_page_status - query the reservation status
360  *
361  * @mgr: amdgpu_vram_mgr pointer
362  * @start: start address of a page in VRAM
363  *
364  * Returns:
365  *	-EBUSY: the page is still hold and in pending list
366  *	0: the page has been reserved
367  *	-ENOENT: the input page is not a reservation
368  */
369 int amdgpu_vram_mgr_query_page_status(struct amdgpu_vram_mgr *mgr,
370 				      uint64_t start)
371 {
372 	struct amdgpu_vram_reservation *rsv;
373 	int ret;
374 
375 	mutex_lock(&mgr->lock);
376 
377 	list_for_each_entry(rsv, &mgr->reservations_pending, blocks) {
378 		if (rsv->start <= start &&
379 		    (start < (rsv->start + rsv->size))) {
380 			ret = -EBUSY;
381 			goto out;
382 		}
383 	}
384 
385 	list_for_each_entry(rsv, &mgr->reserved_pages, blocks) {
386 		if (rsv->start <= start &&
387 		    (start < (rsv->start + rsv->size))) {
388 			ret = 0;
389 			goto out;
390 		}
391 	}
392 
393 	ret = -ENOENT;
394 out:
395 	mutex_unlock(&mgr->lock);
396 	return ret;
397 }
398 
399 int amdgpu_vram_mgr_query_address_block_info(struct amdgpu_vram_mgr *mgr,
400 			uint64_t address, struct amdgpu_vram_block_info *info)
401 {
402 	struct amdgpu_vram_mgr_resource *vres;
403 	struct drm_buddy_block *block;
404 	u64 start, size;
405 	int ret = -ENOENT;
406 
407 	mutex_lock(&mgr->lock);
408 	list_for_each_entry(vres, &mgr->allocated_vres_list, vres_node) {
409 		list_for_each_entry(block, &vres->blocks, link) {
410 			start = amdgpu_vram_mgr_block_start(block);
411 			size = amdgpu_vram_mgr_block_size(block);
412 			if ((start <= address) && (address < (start + size))) {
413 				info->start = start;
414 				info->size = size;
415 				memcpy(&info->task, &vres->task, sizeof(vres->task));
416 				ret = 0;
417 				goto out;
418 			}
419 		}
420 	}
421 
422 out:
423 	mutex_unlock(&mgr->lock);
424 
425 	return ret;
426 }
427 
428 static void amdgpu_dummy_vram_mgr_debug(struct ttm_resource_manager *man,
429 				  struct drm_printer *printer)
430 {
431 	DRM_DEBUG_DRIVER("Dummy vram mgr debug\n");
432 }
433 
434 static bool amdgpu_dummy_vram_mgr_compatible(struct ttm_resource_manager *man,
435 				       struct ttm_resource *res,
436 				       const struct ttm_place *place,
437 				       size_t size)
438 {
439 	DRM_DEBUG_DRIVER("Dummy vram mgr compatible\n");
440 	return false;
441 }
442 
443 static bool amdgpu_dummy_vram_mgr_intersects(struct ttm_resource_manager *man,
444 				       struct ttm_resource *res,
445 				       const struct ttm_place *place,
446 				       size_t size)
447 {
448 	DRM_DEBUG_DRIVER("Dummy vram mgr intersects\n");
449 	return true;
450 }
451 
452 static void amdgpu_dummy_vram_mgr_del(struct ttm_resource_manager *man,
453 				struct ttm_resource *res)
454 {
455 	DRM_DEBUG_DRIVER("Dummy vram mgr deleted\n");
456 }
457 
458 static int amdgpu_dummy_vram_mgr_new(struct ttm_resource_manager *man,
459 			       struct ttm_buffer_object *tbo,
460 			       const struct ttm_place *place,
461 			       struct ttm_resource **res)
462 {
463 	DRM_DEBUG_DRIVER("Dummy vram mgr new\n");
464 	return -ENOSPC;
465 }
466 
467 /**
468  * amdgpu_vram_mgr_new - allocate new ranges
469  *
470  * @man: TTM memory type manager
471  * @tbo: TTM BO we need this range for
472  * @place: placement flags and restrictions
473  * @res: the resulting mem object
474  *
475  * Allocate VRAM for the given BO.
476  */
477 static int amdgpu_vram_mgr_new(struct ttm_resource_manager *man,
478 			       struct ttm_buffer_object *tbo,
479 			       const struct ttm_place *place,
480 			       struct ttm_resource **res)
481 {
482 	struct amdgpu_vram_mgr *mgr = to_vram_mgr(man);
483 	struct amdgpu_device *adev = to_amdgpu_device(mgr);
484 	struct amdgpu_bo *bo = ttm_to_amdgpu_bo(tbo);
485 	u64 vis_usage = 0, max_bytes, min_block_size;
486 	struct amdgpu_vram_mgr_resource *vres;
487 	u64 size, remaining_size, lpfn, fpfn;
488 	unsigned int adjust_dcc_size = 0;
489 	struct drm_buddy *mm = &mgr->mm;
490 	struct drm_buddy_block *block;
491 	unsigned long pages_per_block;
492 	int r;
493 
494 	lpfn = (u64)place->lpfn << PAGE_SHIFT;
495 	if (!lpfn || lpfn > man->size)
496 		lpfn = man->size;
497 
498 	fpfn = (u64)place->fpfn << PAGE_SHIFT;
499 
500 	max_bytes = adev->gmc.mc_vram_size;
501 	if (tbo->type != ttm_bo_type_kernel)
502 		max_bytes -= AMDGPU_VM_RESERVED_VRAM;
503 
504 	if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS) {
505 		pages_per_block = ~0ul;
506 	} else {
507 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
508 		pages_per_block = HPAGE_PMD_NR;
509 #else
510 		/* default to 2MB */
511 		pages_per_block = 2UL << (20UL - PAGE_SHIFT);
512 #endif
513 		pages_per_block = max_t(u32, pages_per_block,
514 					tbo->page_alignment);
515 	}
516 
517 	vres = kzalloc(sizeof(*vres), GFP_KERNEL);
518 	if (!vres)
519 		return -ENOMEM;
520 
521 	ttm_resource_init(tbo, place, &vres->base);
522 
523 	/* bail out quickly if there's likely not enough VRAM for this BO */
524 	if (ttm_resource_manager_usage(man) > max_bytes) {
525 		r = -ENOSPC;
526 		goto error_fini;
527 	}
528 
529 	INIT_LIST_HEAD(&vres->blocks);
530 
531 	if (place->flags & TTM_PL_FLAG_TOPDOWN)
532 		vres->flags |= DRM_BUDDY_TOPDOWN_ALLOCATION;
533 
534 	if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS)
535 		vres->flags |= DRM_BUDDY_CONTIGUOUS_ALLOCATION;
536 
537 	if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CLEARED)
538 		vres->flags |= DRM_BUDDY_CLEAR_ALLOCATION;
539 
540 	if (fpfn || lpfn != mgr->mm.size)
541 		/* Allocate blocks in desired range */
542 		vres->flags |= DRM_BUDDY_RANGE_ALLOCATION;
543 
544 	if (bo->flags & AMDGPU_GEM_CREATE_GFX12_DCC &&
545 	    adev->gmc.gmc_funcs->get_dcc_alignment)
546 		adjust_dcc_size = amdgpu_gmc_get_dcc_alignment(adev);
547 
548 	remaining_size = (u64)vres->base.size;
549 	if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS && adjust_dcc_size) {
550 		unsigned int dcc_size;
551 
552 		dcc_size = roundup_pow_of_two(vres->base.size + adjust_dcc_size);
553 		remaining_size = (u64)dcc_size;
554 
555 		vres->flags |= DRM_BUDDY_TRIM_DISABLE;
556 	}
557 
558 	mutex_lock(&mgr->lock);
559 	while (remaining_size) {
560 		if (tbo->page_alignment)
561 			min_block_size = (u64)tbo->page_alignment << PAGE_SHIFT;
562 		else
563 			min_block_size = mgr->default_page_size;
564 
565 		size = remaining_size;
566 
567 		if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS && adjust_dcc_size)
568 			min_block_size = size;
569 		else if ((size >= (u64)pages_per_block << PAGE_SHIFT) &&
570 			 !(size & (((u64)pages_per_block << PAGE_SHIFT) - 1)))
571 			min_block_size = (u64)pages_per_block << PAGE_SHIFT;
572 
573 		BUG_ON(min_block_size < mm->chunk_size);
574 
575 		r = drm_buddy_alloc_blocks(mm, fpfn,
576 					   lpfn,
577 					   size,
578 					   min_block_size,
579 					   &vres->blocks,
580 					   vres->flags);
581 
582 		if (unlikely(r == -ENOSPC) && pages_per_block == ~0ul &&
583 		    !(place->flags & TTM_PL_FLAG_CONTIGUOUS)) {
584 			vres->flags &= ~DRM_BUDDY_CONTIGUOUS_ALLOCATION;
585 			pages_per_block = max_t(u32, 2UL << (20UL - PAGE_SHIFT),
586 						tbo->page_alignment);
587 
588 			continue;
589 		}
590 
591 		if (unlikely(r))
592 			goto error_free_blocks;
593 
594 		if (size > remaining_size)
595 			remaining_size = 0;
596 		else
597 			remaining_size -= size;
598 	}
599 
600 	vres->task.pid = task_pid_nr(current);
601 	get_task_comm(vres->task.comm, current);
602 	list_add_tail(&vres->vres_node, &mgr->allocated_vres_list);
603 
604 	if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS && adjust_dcc_size) {
605 		struct drm_buddy_block *dcc_block;
606 		unsigned long dcc_start;
607 		u64 trim_start;
608 
609 		dcc_block = amdgpu_vram_mgr_first_block(&vres->blocks);
610 		/* Adjust the start address for DCC buffers only */
611 		dcc_start =
612 			roundup((unsigned long)amdgpu_vram_mgr_block_start(dcc_block),
613 				adjust_dcc_size);
614 		trim_start = (u64)dcc_start;
615 		drm_buddy_block_trim(mm, &trim_start,
616 				     (u64)vres->base.size,
617 				     &vres->blocks);
618 	}
619 	mutex_unlock(&mgr->lock);
620 
621 	vres->base.start = 0;
622 	size = max_t(u64, amdgpu_vram_mgr_blocks_size(&vres->blocks),
623 		     vres->base.size);
624 	list_for_each_entry(block, &vres->blocks, link) {
625 		unsigned long start;
626 
627 		start = amdgpu_vram_mgr_block_start(block) +
628 			amdgpu_vram_mgr_block_size(block);
629 		start >>= PAGE_SHIFT;
630 
631 		if (start > PFN_UP(size))
632 			start -= PFN_UP(size);
633 		else
634 			start = 0;
635 		vres->base.start = max(vres->base.start, start);
636 
637 		vis_usage += amdgpu_vram_mgr_vis_size(adev, block);
638 	}
639 
640 	if (amdgpu_is_vram_mgr_blocks_contiguous(&vres->blocks))
641 		vres->base.placement |= TTM_PL_FLAG_CONTIGUOUS;
642 
643 	if (adev->gmc.xgmi.connected_to_cpu)
644 		vres->base.bus.caching = ttm_cached;
645 	else
646 		vres->base.bus.caching = ttm_write_combined;
647 
648 	atomic64_add(vis_usage, &mgr->vis_usage);
649 	*res = &vres->base;
650 	return 0;
651 
652 error_free_blocks:
653 	drm_buddy_free_list(mm, &vres->blocks, 0);
654 	mutex_unlock(&mgr->lock);
655 error_fini:
656 	ttm_resource_fini(man, &vres->base);
657 	kfree(vres);
658 
659 	return r;
660 }
661 
662 /**
663  * amdgpu_vram_mgr_del - free ranges
664  *
665  * @man: TTM memory type manager
666  * @res: TTM memory object
667  *
668  * Free the allocated VRAM again.
669  */
670 static void amdgpu_vram_mgr_del(struct ttm_resource_manager *man,
671 				struct ttm_resource *res)
672 {
673 	struct amdgpu_vram_mgr_resource *vres = to_amdgpu_vram_mgr_resource(res);
674 	struct amdgpu_vram_mgr *mgr = to_vram_mgr(man);
675 	struct amdgpu_device *adev = to_amdgpu_device(mgr);
676 	struct drm_buddy *mm = &mgr->mm;
677 	struct drm_buddy_block *block;
678 	uint64_t vis_usage = 0;
679 
680 	mutex_lock(&mgr->lock);
681 
682 	list_del(&vres->vres_node);
683 	memset(&vres->task, 0, sizeof(vres->task));
684 
685 	list_for_each_entry(block, &vres->blocks, link)
686 		vis_usage += amdgpu_vram_mgr_vis_size(adev, block);
687 
688 	amdgpu_vram_mgr_do_reserve(man);
689 
690 	drm_buddy_free_list(mm, &vres->blocks, vres->flags);
691 	mutex_unlock(&mgr->lock);
692 
693 	atomic64_sub(vis_usage, &mgr->vis_usage);
694 
695 	ttm_resource_fini(man, res);
696 	kfree(vres);
697 }
698 
699 /**
700  * amdgpu_vram_mgr_alloc_sgt - allocate and fill a sg table
701  *
702  * @adev: amdgpu device pointer
703  * @res: TTM memory object
704  * @offset: byte offset from the base of VRAM BO
705  * @length: number of bytes to export in sg_table
706  * @dev: the other device
707  * @dir: dma direction
708  * @sgt: resulting sg table
709  *
710  * Allocate and fill a sg table from a VRAM allocation.
711  */
712 int amdgpu_vram_mgr_alloc_sgt(struct amdgpu_device *adev,
713 			      struct ttm_resource *res,
714 			      u64 offset, u64 length,
715 			      struct device *dev,
716 			      enum dma_data_direction dir,
717 			      struct sg_table **sgt)
718 {
719 	struct amdgpu_res_cursor cursor;
720 	struct scatterlist *sg;
721 	int num_entries = 0;
722 	int i, r;
723 
724 	*sgt = kmalloc(sizeof(**sgt), GFP_KERNEL);
725 	if (!*sgt)
726 		return -ENOMEM;
727 
728 	/* Determine the number of DRM_BUDDY blocks to export */
729 	amdgpu_res_first(res, offset, length, &cursor);
730 	while (cursor.remaining) {
731 		num_entries++;
732 		amdgpu_res_next(&cursor, min(cursor.size, AMDGPU_MAX_SG_SEGMENT_SIZE));
733 	}
734 
735 	r = sg_alloc_table(*sgt, num_entries, GFP_KERNEL);
736 	if (r)
737 		goto error_free;
738 
739 	/* Initialize scatterlist nodes of sg_table */
740 	for_each_sgtable_sg((*sgt), sg, i)
741 		sg->length = 0;
742 
743 	/*
744 	 * Walk down DRM_BUDDY blocks to populate scatterlist nodes
745 	 * @note: Use iterator api to get first the DRM_BUDDY block
746 	 * and the number of bytes from it. Access the following
747 	 * DRM_BUDDY block(s) if more buffer needs to exported
748 	 */
749 	amdgpu_res_first(res, offset, length, &cursor);
750 	for_each_sgtable_sg((*sgt), sg, i) {
751 		phys_addr_t phys = cursor.start + adev->gmc.aper_base;
752 		unsigned long size = min(cursor.size, AMDGPU_MAX_SG_SEGMENT_SIZE);
753 		dma_addr_t addr;
754 
755 		addr = dma_map_resource(dev, phys, size, dir,
756 					DMA_ATTR_SKIP_CPU_SYNC);
757 		r = dma_mapping_error(dev, addr);
758 		if (r)
759 			goto error_unmap;
760 
761 		sg_set_page(sg, NULL, size, 0);
762 		sg_dma_address(sg) = addr;
763 		sg_dma_len(sg) = size;
764 
765 		amdgpu_res_next(&cursor, size);
766 	}
767 
768 	return 0;
769 
770 error_unmap:
771 	for_each_sgtable_sg((*sgt), sg, i) {
772 		if (!sg->length)
773 			continue;
774 
775 		dma_unmap_resource(dev, sg->dma_address,
776 				   sg->length, dir,
777 				   DMA_ATTR_SKIP_CPU_SYNC);
778 	}
779 	sg_free_table(*sgt);
780 
781 error_free:
782 	kfree(*sgt);
783 	return r;
784 }
785 
786 /**
787  * amdgpu_vram_mgr_free_sgt - allocate and fill a sg table
788  *
789  * @dev: device pointer
790  * @dir: data direction of resource to unmap
791  * @sgt: sg table to free
792  *
793  * Free a previously allocate sg table.
794  */
795 void amdgpu_vram_mgr_free_sgt(struct device *dev,
796 			      enum dma_data_direction dir,
797 			      struct sg_table *sgt)
798 {
799 	struct scatterlist *sg;
800 	int i;
801 
802 	for_each_sgtable_sg(sgt, sg, i)
803 		dma_unmap_resource(dev, sg->dma_address,
804 				   sg->length, dir,
805 				   DMA_ATTR_SKIP_CPU_SYNC);
806 	sg_free_table(sgt);
807 	kfree(sgt);
808 }
809 
810 /**
811  * amdgpu_vram_mgr_vis_usage - how many bytes are used in the visible part
812  *
813  * @mgr: amdgpu_vram_mgr pointer
814  *
815  * Returns how many bytes are used in the visible part of VRAM
816  */
817 uint64_t amdgpu_vram_mgr_vis_usage(struct amdgpu_vram_mgr *mgr)
818 {
819 	return atomic64_read(&mgr->vis_usage);
820 }
821 
822 /**
823  * amdgpu_vram_mgr_intersects - test each drm buddy block for intersection
824  *
825  * @man: TTM memory type manager
826  * @res: The resource to test
827  * @place: The place to test against
828  * @size: Size of the new allocation
829  *
830  * Test each drm buddy block for intersection for eviction decision.
831  */
832 static bool amdgpu_vram_mgr_intersects(struct ttm_resource_manager *man,
833 				       struct ttm_resource *res,
834 				       const struct ttm_place *place,
835 				       size_t size)
836 {
837 	struct amdgpu_vram_mgr_resource *mgr = to_amdgpu_vram_mgr_resource(res);
838 	struct drm_buddy_block *block;
839 
840 	/* Check each drm buddy block individually */
841 	list_for_each_entry(block, &mgr->blocks, link) {
842 		unsigned long fpfn =
843 			amdgpu_vram_mgr_block_start(block) >> PAGE_SHIFT;
844 		unsigned long lpfn = fpfn +
845 			(amdgpu_vram_mgr_block_size(block) >> PAGE_SHIFT);
846 
847 		if (place->fpfn < lpfn &&
848 		    (!place->lpfn || place->lpfn > fpfn))
849 			return true;
850 	}
851 
852 	return false;
853 }
854 
855 /**
856  * amdgpu_vram_mgr_compatible - test each drm buddy block for compatibility
857  *
858  * @man: TTM memory type manager
859  * @res: The resource to test
860  * @place: The place to test against
861  * @size: Size of the new allocation
862  *
863  * Test each drm buddy block for placement compatibility.
864  */
865 static bool amdgpu_vram_mgr_compatible(struct ttm_resource_manager *man,
866 				       struct ttm_resource *res,
867 				       const struct ttm_place *place,
868 				       size_t size)
869 {
870 	struct amdgpu_vram_mgr_resource *mgr = to_amdgpu_vram_mgr_resource(res);
871 	struct drm_buddy_block *block;
872 
873 	/* Check each drm buddy block individually */
874 	list_for_each_entry(block, &mgr->blocks, link) {
875 		unsigned long fpfn =
876 			amdgpu_vram_mgr_block_start(block) >> PAGE_SHIFT;
877 		unsigned long lpfn = fpfn +
878 			(amdgpu_vram_mgr_block_size(block) >> PAGE_SHIFT);
879 
880 		if (fpfn < place->fpfn ||
881 		    (place->lpfn && lpfn > place->lpfn))
882 			return false;
883 	}
884 
885 	return true;
886 }
887 
888 /**
889  * amdgpu_vram_mgr_debug - dump VRAM table
890  *
891  * @man: TTM memory type manager
892  * @printer: DRM printer to use
893  *
894  * Dump the table content using printk.
895  */
896 static void amdgpu_vram_mgr_debug(struct ttm_resource_manager *man,
897 				  struct drm_printer *printer)
898 {
899 	struct amdgpu_vram_mgr *mgr = to_vram_mgr(man);
900 	struct drm_buddy *mm = &mgr->mm;
901 	struct amdgpu_vram_reservation *rsv;
902 
903 	drm_printf(printer, "  vis usage:%llu\n",
904 		   amdgpu_vram_mgr_vis_usage(mgr));
905 
906 	mutex_lock(&mgr->lock);
907 	drm_printf(printer, "default_page_size: %lluKiB\n",
908 		   mgr->default_page_size >> 10);
909 
910 	drm_buddy_print(mm, printer);
911 
912 	drm_printf(printer, "reserved:\n");
913 	list_for_each_entry(rsv, &mgr->reserved_pages, blocks)
914 		drm_printf(printer, "%#018llx-%#018llx: %llu\n",
915 			rsv->start, rsv->start + rsv->size, rsv->size);
916 	mutex_unlock(&mgr->lock);
917 }
918 
919 static const struct ttm_resource_manager_func amdgpu_dummy_vram_mgr_func = {
920 	.alloc	= amdgpu_dummy_vram_mgr_new,
921 	.free	= amdgpu_dummy_vram_mgr_del,
922 	.intersects = amdgpu_dummy_vram_mgr_intersects,
923 	.compatible = amdgpu_dummy_vram_mgr_compatible,
924 	.debug	= amdgpu_dummy_vram_mgr_debug
925 };
926 
927 static const struct ttm_resource_manager_func amdgpu_vram_mgr_func = {
928 	.alloc	= amdgpu_vram_mgr_new,
929 	.free	= amdgpu_vram_mgr_del,
930 	.intersects = amdgpu_vram_mgr_intersects,
931 	.compatible = amdgpu_vram_mgr_compatible,
932 	.debug	= amdgpu_vram_mgr_debug
933 };
934 
935 /**
936  * amdgpu_vram_mgr_init - init VRAM manager and DRM MM
937  *
938  * @adev: amdgpu_device pointer
939  *
940  * Allocate and initialize the VRAM manager.
941  */
942 int amdgpu_vram_mgr_init(struct amdgpu_device *adev)
943 {
944 	struct amdgpu_vram_mgr *mgr = &adev->mman.vram_mgr;
945 	struct ttm_resource_manager *man = &mgr->manager;
946 	int err;
947 
948 	man->cg = drmm_cgroup_register_region(adev_to_drm(adev), "vram", adev->gmc.real_vram_size);
949 	if (IS_ERR(man->cg))
950 		return PTR_ERR(man->cg);
951 	ttm_resource_manager_init(man, &adev->mman.bdev,
952 				  adev->gmc.real_vram_size);
953 
954 	mutex_init(&mgr->lock);
955 	INIT_LIST_HEAD(&mgr->reservations_pending);
956 	INIT_LIST_HEAD(&mgr->reserved_pages);
957 	INIT_LIST_HEAD(&mgr->allocated_vres_list);
958 	mgr->default_page_size = PAGE_SIZE;
959 
960 	if (!adev->gmc.is_app_apu) {
961 		man->func = &amdgpu_vram_mgr_func;
962 
963 		err = drm_buddy_init(&mgr->mm, man->size, PAGE_SIZE);
964 		if (err)
965 			return err;
966 	} else {
967 		man->func = &amdgpu_dummy_vram_mgr_func;
968 		DRM_INFO("Setup dummy vram mgr\n");
969 	}
970 
971 	ttm_set_driver_manager(&adev->mman.bdev, TTM_PL_VRAM, &mgr->manager);
972 	ttm_resource_manager_set_used(man, true);
973 	return 0;
974 }
975 
976 /**
977  * amdgpu_vram_mgr_fini - free and destroy VRAM manager
978  *
979  * @adev: amdgpu_device pointer
980  *
981  * Destroy and free the VRAM manager, returns -EBUSY if ranges are still
982  * allocated inside it.
983  */
984 void amdgpu_vram_mgr_fini(struct amdgpu_device *adev)
985 {
986 	struct amdgpu_vram_mgr *mgr = &adev->mman.vram_mgr;
987 	struct ttm_resource_manager *man = &mgr->manager;
988 	int ret;
989 	struct amdgpu_vram_reservation *rsv, *temp;
990 
991 	ttm_resource_manager_set_used(man, false);
992 
993 	ret = ttm_resource_manager_evict_all(&adev->mman.bdev, man);
994 	if (ret)
995 		return;
996 
997 	mutex_lock(&mgr->lock);
998 	list_for_each_entry_safe(rsv, temp, &mgr->reservations_pending, blocks)
999 		kfree(rsv);
1000 
1001 	list_for_each_entry_safe(rsv, temp, &mgr->reserved_pages, blocks) {
1002 		drm_buddy_free_list(&mgr->mm, &rsv->allocated, 0);
1003 		kfree(rsv);
1004 	}
1005 	if (!adev->gmc.is_app_apu)
1006 		drm_buddy_fini(&mgr->mm);
1007 	mutex_unlock(&mgr->lock);
1008 
1009 	ttm_resource_manager_cleanup(man);
1010 	ttm_set_driver_manager(&adev->mman.bdev, TTM_PL_VRAM, NULL);
1011 }
1012