xref: /linux/drivers/gpu/drm/drm_gem_vram_helper.c (revision bf62221e9d0e1e4ba50ab2b331a0008c15de97be)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <linux/dma-buf-map.h>
4 #include <linux/module.h>
5 
6 #include <drm/drm_debugfs.h>
7 #include <drm/drm_device.h>
8 #include <drm/drm_drv.h>
9 #include <drm/drm_file.h>
10 #include <drm/drm_framebuffer.h>
11 #include <drm/drm_gem_atomic_helper.h>
12 #include <drm/drm_gem_ttm_helper.h>
13 #include <drm/drm_gem_vram_helper.h>
14 #include <drm/drm_managed.h>
15 #include <drm/drm_mode.h>
16 #include <drm/drm_plane.h>
17 #include <drm/drm_prime.h>
18 #include <drm/drm_simple_kms_helper.h>
19 
20 static const struct drm_gem_object_funcs drm_gem_vram_object_funcs;
21 
22 /**
23  * DOC: overview
24  *
25  * This library provides &struct drm_gem_vram_object (GEM VRAM), a GEM
26  * buffer object that is backed by video RAM (VRAM). It can be used for
27  * framebuffer devices with dedicated memory.
28  *
29  * The data structure &struct drm_vram_mm and its helpers implement a memory
30  * manager for simple framebuffer devices with dedicated video memory. GEM
31  * VRAM buffer objects are either placed in the video memory or remain evicted
32  * to system memory.
33  *
34  * With the GEM interface userspace applications create, manage and destroy
35  * graphics buffers, such as an on-screen framebuffer. GEM does not provide
36  * an implementation of these interfaces. It's up to the DRM driver to
37  * provide an implementation that suits the hardware. If the hardware device
38  * contains dedicated video memory, the DRM driver can use the VRAM helper
39  * library. Each active buffer object is stored in video RAM. Active
40  * buffer are used for drawing the current frame, typically something like
41  * the frame's scanout buffer or the cursor image. If there's no more space
42  * left in VRAM, inactive GEM objects can be moved to system memory.
43  *
44  * To initialize the VRAM helper library call drmm_vram_helper_alloc_mm().
45  * The function allocates and initializes an instance of &struct drm_vram_mm
46  * in &struct drm_device.vram_mm . Use &DRM_GEM_VRAM_DRIVER to initialize
47  * &struct drm_driver and  &DRM_VRAM_MM_FILE_OPERATIONS to initialize
48  * &struct file_operations; as illustrated below.
49  *
50  * .. code-block:: c
51  *
52  *	struct file_operations fops ={
53  *		.owner = THIS_MODULE,
54  *		DRM_VRAM_MM_FILE_OPERATION
55  *	};
56  *	struct drm_driver drv = {
57  *		.driver_feature = DRM_ ... ,
58  *		.fops = &fops,
59  *		DRM_GEM_VRAM_DRIVER
60  *	};
61  *
62  *	int init_drm_driver()
63  *	{
64  *		struct drm_device *dev;
65  *		uint64_t vram_base;
66  *		unsigned long vram_size;
67  *		int ret;
68  *
69  *		// setup device, vram base and size
70  *		// ...
71  *
72  *		ret = drmm_vram_helper_alloc_mm(dev, vram_base, vram_size);
73  *		if (ret)
74  *			return ret;
75  *		return 0;
76  *	}
77  *
78  * This creates an instance of &struct drm_vram_mm, exports DRM userspace
79  * interfaces for GEM buffer management and initializes file operations to
80  * allow for accessing created GEM buffers. With this setup, the DRM driver
81  * manages an area of video RAM with VRAM MM and provides GEM VRAM objects
82  * to userspace.
83  *
84  * You don't have to clean up the instance of VRAM MM.
85  * drmm_vram_helper_alloc_mm() is a managed interface that installs a
86  * clean-up handler to run during the DRM device's release.
87  *
88  * For drawing or scanout operations, rsp. buffer objects have to be pinned
89  * in video RAM. Call drm_gem_vram_pin() with &DRM_GEM_VRAM_PL_FLAG_VRAM or
90  * &DRM_GEM_VRAM_PL_FLAG_SYSTEM to pin a buffer object in video RAM or system
91  * memory. Call drm_gem_vram_unpin() to release the pinned object afterwards.
92  *
93  * A buffer object that is pinned in video RAM has a fixed address within that
94  * memory region. Call drm_gem_vram_offset() to retrieve this value. Typically
95  * it's used to program the hardware's scanout engine for framebuffers, set
96  * the cursor overlay's image for a mouse cursor, or use it as input to the
97  * hardware's draing engine.
98  *
99  * To access a buffer object's memory from the DRM driver, call
100  * drm_gem_vram_vmap(). It maps the buffer into kernel address
101  * space and returns the memory address. Use drm_gem_vram_vunmap() to
102  * release the mapping.
103  */
104 
105 /*
106  * Buffer-objects helpers
107  */
108 
109 static void drm_gem_vram_cleanup(struct drm_gem_vram_object *gbo)
110 {
111 	/* We got here via ttm_bo_put(), which means that the
112 	 * TTM buffer object in 'bo' has already been cleaned
113 	 * up; only release the GEM object.
114 	 */
115 
116 	WARN_ON(gbo->vmap_use_count);
117 	WARN_ON(dma_buf_map_is_set(&gbo->map));
118 
119 	drm_gem_object_release(&gbo->bo.base);
120 }
121 
122 static void drm_gem_vram_destroy(struct drm_gem_vram_object *gbo)
123 {
124 	drm_gem_vram_cleanup(gbo);
125 	kfree(gbo);
126 }
127 
128 static void ttm_buffer_object_destroy(struct ttm_buffer_object *bo)
129 {
130 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_bo(bo);
131 
132 	drm_gem_vram_destroy(gbo);
133 }
134 
135 static void drm_gem_vram_placement(struct drm_gem_vram_object *gbo,
136 				   unsigned long pl_flag)
137 {
138 	u32 invariant_flags = 0;
139 	unsigned int i;
140 	unsigned int c = 0;
141 
142 	if (pl_flag & DRM_GEM_VRAM_PL_FLAG_TOPDOWN)
143 		invariant_flags = TTM_PL_FLAG_TOPDOWN;
144 
145 	gbo->placement.placement = gbo->placements;
146 	gbo->placement.busy_placement = gbo->placements;
147 
148 	if (pl_flag & DRM_GEM_VRAM_PL_FLAG_VRAM) {
149 		gbo->placements[c].mem_type = TTM_PL_VRAM;
150 		gbo->placements[c++].flags = invariant_flags;
151 	}
152 
153 	if (pl_flag & DRM_GEM_VRAM_PL_FLAG_SYSTEM || !c) {
154 		gbo->placements[c].mem_type = TTM_PL_SYSTEM;
155 		gbo->placements[c++].flags = invariant_flags;
156 	}
157 
158 	gbo->placement.num_placement = c;
159 	gbo->placement.num_busy_placement = c;
160 
161 	for (i = 0; i < c; ++i) {
162 		gbo->placements[i].fpfn = 0;
163 		gbo->placements[i].lpfn = 0;
164 	}
165 }
166 
167 /**
168  * drm_gem_vram_create() - Creates a VRAM-backed GEM object
169  * @dev:		the DRM device
170  * @size:		the buffer size in bytes
171  * @pg_align:		the buffer's alignment in multiples of the page size
172  *
173  * GEM objects are allocated by calling struct drm_driver.gem_create_object,
174  * if set. Otherwise kzalloc() will be used. Drivers can set their own GEM
175  * object functions in struct drm_driver.gem_create_object. If no functions
176  * are set, the new GEM object will use the default functions from GEM VRAM
177  * helpers.
178  *
179  * Returns:
180  * A new instance of &struct drm_gem_vram_object on success, or
181  * an ERR_PTR()-encoded error code otherwise.
182  */
183 struct drm_gem_vram_object *drm_gem_vram_create(struct drm_device *dev,
184 						size_t size,
185 						unsigned long pg_align)
186 {
187 	struct drm_gem_vram_object *gbo;
188 	struct drm_gem_object *gem;
189 	struct drm_vram_mm *vmm = dev->vram_mm;
190 	struct ttm_device *bdev;
191 	int ret;
192 
193 	if (WARN_ONCE(!vmm, "VRAM MM not initialized"))
194 		return ERR_PTR(-EINVAL);
195 
196 	if (dev->driver->gem_create_object) {
197 		gem = dev->driver->gem_create_object(dev, size);
198 		if (!gem)
199 			return ERR_PTR(-ENOMEM);
200 		gbo = drm_gem_vram_of_gem(gem);
201 	} else {
202 		gbo = kzalloc(sizeof(*gbo), GFP_KERNEL);
203 		if (!gbo)
204 			return ERR_PTR(-ENOMEM);
205 		gem = &gbo->bo.base;
206 	}
207 
208 	if (!gem->funcs)
209 		gem->funcs = &drm_gem_vram_object_funcs;
210 
211 	ret = drm_gem_object_init(dev, gem, size);
212 	if (ret) {
213 		kfree(gbo);
214 		return ERR_PTR(ret);
215 	}
216 
217 	bdev = &vmm->bdev;
218 
219 	gbo->bo.bdev = bdev;
220 	drm_gem_vram_placement(gbo, DRM_GEM_VRAM_PL_FLAG_SYSTEM);
221 
222 	/*
223 	 * A failing ttm_bo_init will call ttm_buffer_object_destroy
224 	 * to release gbo->bo.base and kfree gbo.
225 	 */
226 	ret = ttm_bo_init(bdev, &gbo->bo, size, ttm_bo_type_device,
227 			  &gbo->placement, pg_align, false, NULL, NULL,
228 			  ttm_buffer_object_destroy);
229 	if (ret)
230 		return ERR_PTR(ret);
231 
232 	return gbo;
233 }
234 EXPORT_SYMBOL(drm_gem_vram_create);
235 
236 /**
237  * drm_gem_vram_put() - Releases a reference to a VRAM-backed GEM object
238  * @gbo:	the GEM VRAM object
239  *
240  * See ttm_bo_put() for more information.
241  */
242 void drm_gem_vram_put(struct drm_gem_vram_object *gbo)
243 {
244 	ttm_bo_put(&gbo->bo);
245 }
246 EXPORT_SYMBOL(drm_gem_vram_put);
247 
248 static u64 drm_gem_vram_pg_offset(struct drm_gem_vram_object *gbo)
249 {
250 	/* Keep TTM behavior for now, remove when drivers are audited */
251 	if (WARN_ON_ONCE(!gbo->bo.mem.mm_node))
252 		return 0;
253 
254 	return gbo->bo.mem.start;
255 }
256 
257 /**
258  * drm_gem_vram_offset() - \
259 	Returns a GEM VRAM object's offset in video memory
260  * @gbo:	the GEM VRAM object
261  *
262  * This function returns the buffer object's offset in the device's video
263  * memory. The buffer object has to be pinned to %TTM_PL_VRAM.
264  *
265  * Returns:
266  * The buffer object's offset in video memory on success, or
267  * a negative errno code otherwise.
268  */
269 s64 drm_gem_vram_offset(struct drm_gem_vram_object *gbo)
270 {
271 	if (WARN_ON_ONCE(!gbo->bo.pin_count))
272 		return (s64)-ENODEV;
273 	return drm_gem_vram_pg_offset(gbo) << PAGE_SHIFT;
274 }
275 EXPORT_SYMBOL(drm_gem_vram_offset);
276 
277 static int drm_gem_vram_pin_locked(struct drm_gem_vram_object *gbo,
278 				   unsigned long pl_flag)
279 {
280 	struct ttm_operation_ctx ctx = { false, false };
281 	int ret;
282 
283 	if (gbo->bo.pin_count)
284 		goto out;
285 
286 	if (pl_flag)
287 		drm_gem_vram_placement(gbo, pl_flag);
288 
289 	ret = ttm_bo_validate(&gbo->bo, &gbo->placement, &ctx);
290 	if (ret < 0)
291 		return ret;
292 
293 out:
294 	ttm_bo_pin(&gbo->bo);
295 
296 	return 0;
297 }
298 
299 /**
300  * drm_gem_vram_pin() - Pins a GEM VRAM object in a region.
301  * @gbo:	the GEM VRAM object
302  * @pl_flag:	a bitmask of possible memory regions
303  *
304  * Pinning a buffer object ensures that it is not evicted from
305  * a memory region. A pinned buffer object has to be unpinned before
306  * it can be pinned to another region. If the pl_flag argument is 0,
307  * the buffer is pinned at its current location (video RAM or system
308  * memory).
309  *
310  * Small buffer objects, such as cursor images, can lead to memory
311  * fragmentation if they are pinned in the middle of video RAM. This
312  * is especially a problem on devices with only a small amount of
313  * video RAM. Fragmentation can prevent the primary framebuffer from
314  * fitting in, even though there's enough memory overall. The modifier
315  * DRM_GEM_VRAM_PL_FLAG_TOPDOWN marks the buffer object to be pinned
316  * at the high end of the memory region to avoid fragmentation.
317  *
318  * Returns:
319  * 0 on success, or
320  * a negative error code otherwise.
321  */
322 int drm_gem_vram_pin(struct drm_gem_vram_object *gbo, unsigned long pl_flag)
323 {
324 	int ret;
325 
326 	ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
327 	if (ret)
328 		return ret;
329 	ret = drm_gem_vram_pin_locked(gbo, pl_flag);
330 	ttm_bo_unreserve(&gbo->bo);
331 
332 	return ret;
333 }
334 EXPORT_SYMBOL(drm_gem_vram_pin);
335 
336 static void drm_gem_vram_unpin_locked(struct drm_gem_vram_object *gbo)
337 {
338 	ttm_bo_unpin(&gbo->bo);
339 }
340 
341 /**
342  * drm_gem_vram_unpin() - Unpins a GEM VRAM object
343  * @gbo:	the GEM VRAM object
344  *
345  * Returns:
346  * 0 on success, or
347  * a negative error code otherwise.
348  */
349 int drm_gem_vram_unpin(struct drm_gem_vram_object *gbo)
350 {
351 	int ret;
352 
353 	ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
354 	if (ret)
355 		return ret;
356 
357 	drm_gem_vram_unpin_locked(gbo);
358 	ttm_bo_unreserve(&gbo->bo);
359 
360 	return 0;
361 }
362 EXPORT_SYMBOL(drm_gem_vram_unpin);
363 
364 static int drm_gem_vram_kmap_locked(struct drm_gem_vram_object *gbo,
365 				    struct dma_buf_map *map)
366 {
367 	int ret;
368 
369 	if (gbo->vmap_use_count > 0)
370 		goto out;
371 
372 	/*
373 	 * VRAM helpers unmap the BO only on demand. So the previous
374 	 * page mapping might still be around. Only vmap if the there's
375 	 * no mapping present.
376 	 */
377 	if (dma_buf_map_is_null(&gbo->map)) {
378 		ret = ttm_bo_vmap(&gbo->bo, &gbo->map);
379 		if (ret)
380 			return ret;
381 	}
382 
383 out:
384 	++gbo->vmap_use_count;
385 	*map = gbo->map;
386 
387 	return 0;
388 }
389 
390 static void drm_gem_vram_kunmap_locked(struct drm_gem_vram_object *gbo,
391 				       struct dma_buf_map *map)
392 {
393 	struct drm_device *dev = gbo->bo.base.dev;
394 
395 	if (drm_WARN_ON_ONCE(dev, !gbo->vmap_use_count))
396 		return;
397 
398 	if (drm_WARN_ON_ONCE(dev, !dma_buf_map_is_equal(&gbo->map, map)))
399 		return; /* BUG: map not mapped from this BO */
400 
401 	if (--gbo->vmap_use_count > 0)
402 		return;
403 
404 	/*
405 	 * Permanently mapping and unmapping buffers adds overhead from
406 	 * updating the page tables and creates debugging output. Therefore,
407 	 * we delay the actual unmap operation until the BO gets evicted
408 	 * from memory. See drm_gem_vram_bo_driver_move_notify().
409 	 */
410 }
411 
412 /**
413  * drm_gem_vram_vmap() - Pins and maps a GEM VRAM object into kernel address
414  *                       space
415  * @gbo: The GEM VRAM object to map
416  * @map: Returns the kernel virtual address of the VRAM GEM object's backing
417  *       store.
418  *
419  * The vmap function pins a GEM VRAM object to its current location, either
420  * system or video memory, and maps its buffer into kernel address space.
421  * As pinned object cannot be relocated, you should avoid pinning objects
422  * permanently. Call drm_gem_vram_vunmap() with the returned address to
423  * unmap and unpin the GEM VRAM object.
424  *
425  * Returns:
426  * 0 on success, or a negative error code otherwise.
427  */
428 int drm_gem_vram_vmap(struct drm_gem_vram_object *gbo, struct dma_buf_map *map)
429 {
430 	int ret;
431 
432 	ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
433 	if (ret)
434 		return ret;
435 
436 	ret = drm_gem_vram_pin_locked(gbo, 0);
437 	if (ret)
438 		goto err_ttm_bo_unreserve;
439 	ret = drm_gem_vram_kmap_locked(gbo, map);
440 	if (ret)
441 		goto err_drm_gem_vram_unpin_locked;
442 
443 	ttm_bo_unreserve(&gbo->bo);
444 
445 	return 0;
446 
447 err_drm_gem_vram_unpin_locked:
448 	drm_gem_vram_unpin_locked(gbo);
449 err_ttm_bo_unreserve:
450 	ttm_bo_unreserve(&gbo->bo);
451 	return ret;
452 }
453 EXPORT_SYMBOL(drm_gem_vram_vmap);
454 
455 /**
456  * drm_gem_vram_vunmap() - Unmaps and unpins a GEM VRAM object
457  * @gbo: The GEM VRAM object to unmap
458  * @map: Kernel virtual address where the VRAM GEM object was mapped
459  *
460  * A call to drm_gem_vram_vunmap() unmaps and unpins a GEM VRAM buffer. See
461  * the documentation for drm_gem_vram_vmap() for more information.
462  */
463 void drm_gem_vram_vunmap(struct drm_gem_vram_object *gbo, struct dma_buf_map *map)
464 {
465 	int ret;
466 
467 	ret = ttm_bo_reserve(&gbo->bo, false, false, NULL);
468 	if (WARN_ONCE(ret, "ttm_bo_reserve_failed(): ret=%d\n", ret))
469 		return;
470 
471 	drm_gem_vram_kunmap_locked(gbo, map);
472 	drm_gem_vram_unpin_locked(gbo);
473 
474 	ttm_bo_unreserve(&gbo->bo);
475 }
476 EXPORT_SYMBOL(drm_gem_vram_vunmap);
477 
478 /**
479  * drm_gem_vram_fill_create_dumb() - \
480 	Helper for implementing &struct drm_driver.dumb_create
481  * @file:		the DRM file
482  * @dev:		the DRM device
483  * @pg_align:		the buffer's alignment in multiples of the page size
484  * @pitch_align:	the scanline's alignment in powers of 2
485  * @args:		the arguments as provided to \
486 				&struct drm_driver.dumb_create
487  *
488  * This helper function fills &struct drm_mode_create_dumb, which is used
489  * by &struct drm_driver.dumb_create. Implementations of this interface
490  * should forwards their arguments to this helper, plus the driver-specific
491  * parameters.
492  *
493  * Returns:
494  * 0 on success, or
495  * a negative error code otherwise.
496  */
497 int drm_gem_vram_fill_create_dumb(struct drm_file *file,
498 				  struct drm_device *dev,
499 				  unsigned long pg_align,
500 				  unsigned long pitch_align,
501 				  struct drm_mode_create_dumb *args)
502 {
503 	size_t pitch, size;
504 	struct drm_gem_vram_object *gbo;
505 	int ret;
506 	u32 handle;
507 
508 	pitch = args->width * DIV_ROUND_UP(args->bpp, 8);
509 	if (pitch_align) {
510 		if (WARN_ON_ONCE(!is_power_of_2(pitch_align)))
511 			return -EINVAL;
512 		pitch = ALIGN(pitch, pitch_align);
513 	}
514 	size = pitch * args->height;
515 
516 	size = roundup(size, PAGE_SIZE);
517 	if (!size)
518 		return -EINVAL;
519 
520 	gbo = drm_gem_vram_create(dev, size, pg_align);
521 	if (IS_ERR(gbo))
522 		return PTR_ERR(gbo);
523 
524 	ret = drm_gem_handle_create(file, &gbo->bo.base, &handle);
525 	if (ret)
526 		goto err_drm_gem_object_put;
527 
528 	drm_gem_object_put(&gbo->bo.base);
529 
530 	args->pitch = pitch;
531 	args->size = size;
532 	args->handle = handle;
533 
534 	return 0;
535 
536 err_drm_gem_object_put:
537 	drm_gem_object_put(&gbo->bo.base);
538 	return ret;
539 }
540 EXPORT_SYMBOL(drm_gem_vram_fill_create_dumb);
541 
542 /*
543  * Helpers for struct ttm_device_funcs
544  */
545 
546 static bool drm_is_gem_vram(struct ttm_buffer_object *bo)
547 {
548 	return (bo->destroy == ttm_buffer_object_destroy);
549 }
550 
551 static void drm_gem_vram_bo_driver_evict_flags(struct drm_gem_vram_object *gbo,
552 					       struct ttm_placement *pl)
553 {
554 	drm_gem_vram_placement(gbo, DRM_GEM_VRAM_PL_FLAG_SYSTEM);
555 	*pl = gbo->placement;
556 }
557 
558 static void drm_gem_vram_bo_driver_move_notify(struct drm_gem_vram_object *gbo)
559 {
560 	struct ttm_buffer_object *bo = &gbo->bo;
561 	struct drm_device *dev = bo->base.dev;
562 
563 	if (drm_WARN_ON_ONCE(dev, gbo->vmap_use_count))
564 		return;
565 
566 	ttm_bo_vunmap(bo, &gbo->map);
567 	dma_buf_map_clear(&gbo->map); /* explicitly clear mapping for next vmap call */
568 }
569 
570 static int drm_gem_vram_bo_driver_move(struct drm_gem_vram_object *gbo,
571 				       bool evict,
572 				       struct ttm_operation_ctx *ctx,
573 				       struct ttm_resource *new_mem)
574 {
575 	drm_gem_vram_bo_driver_move_notify(gbo);
576 	return ttm_bo_move_memcpy(&gbo->bo, ctx, new_mem);
577 }
578 
579 /*
580  * Helpers for struct drm_gem_object_funcs
581  */
582 
583 /**
584  * drm_gem_vram_object_free() - \
585 	Implements &struct drm_gem_object_funcs.free
586  * @gem:       GEM object. Refers to &struct drm_gem_vram_object.gem
587  */
588 static void drm_gem_vram_object_free(struct drm_gem_object *gem)
589 {
590 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
591 
592 	drm_gem_vram_put(gbo);
593 }
594 
595 /*
596  * Helpers for dump buffers
597  */
598 
599 /**
600  * drm_gem_vram_driver_dumb_create() - \
601 	Implements &struct drm_driver.dumb_create
602  * @file:		the DRM file
603  * @dev:		the DRM device
604  * @args:		the arguments as provided to \
605 				&struct drm_driver.dumb_create
606  *
607  * This function requires the driver to use @drm_device.vram_mm for its
608  * instance of VRAM MM.
609  *
610  * Returns:
611  * 0 on success, or
612  * a negative error code otherwise.
613  */
614 int drm_gem_vram_driver_dumb_create(struct drm_file *file,
615 				    struct drm_device *dev,
616 				    struct drm_mode_create_dumb *args)
617 {
618 	if (WARN_ONCE(!dev->vram_mm, "VRAM MM not initialized"))
619 		return -EINVAL;
620 
621 	return drm_gem_vram_fill_create_dumb(file, dev, 0, 0, args);
622 }
623 EXPORT_SYMBOL(drm_gem_vram_driver_dumb_create);
624 
625 /*
626  * Helpers for struct drm_plane_helper_funcs
627  */
628 
629 /**
630  * drm_gem_vram_plane_helper_prepare_fb() - \
631  *	Implements &struct drm_plane_helper_funcs.prepare_fb
632  * @plane:	a DRM plane
633  * @new_state:	the plane's new state
634  *
635  * During plane updates, this function sets the plane's fence and
636  * pins the GEM VRAM objects of the plane's new framebuffer to VRAM.
637  * Call drm_gem_vram_plane_helper_cleanup_fb() to unpin them.
638  *
639  * Returns:
640  *	0 on success, or
641  *	a negative errno code otherwise.
642  */
643 int
644 drm_gem_vram_plane_helper_prepare_fb(struct drm_plane *plane,
645 				     struct drm_plane_state *new_state)
646 {
647 	size_t i;
648 	struct drm_gem_vram_object *gbo;
649 	int ret;
650 
651 	if (!new_state->fb)
652 		return 0;
653 
654 	for (i = 0; i < ARRAY_SIZE(new_state->fb->obj); ++i) {
655 		if (!new_state->fb->obj[i])
656 			continue;
657 		gbo = drm_gem_vram_of_gem(new_state->fb->obj[i]);
658 		ret = drm_gem_vram_pin(gbo, DRM_GEM_VRAM_PL_FLAG_VRAM);
659 		if (ret)
660 			goto err_drm_gem_vram_unpin;
661 	}
662 
663 	ret = drm_gem_plane_helper_prepare_fb(plane, new_state);
664 	if (ret)
665 		goto err_drm_gem_vram_unpin;
666 
667 	return 0;
668 
669 err_drm_gem_vram_unpin:
670 	while (i) {
671 		--i;
672 		gbo = drm_gem_vram_of_gem(new_state->fb->obj[i]);
673 		drm_gem_vram_unpin(gbo);
674 	}
675 	return ret;
676 }
677 EXPORT_SYMBOL(drm_gem_vram_plane_helper_prepare_fb);
678 
679 /**
680  * drm_gem_vram_plane_helper_cleanup_fb() - \
681  *	Implements &struct drm_plane_helper_funcs.cleanup_fb
682  * @plane:	a DRM plane
683  * @old_state:	the plane's old state
684  *
685  * During plane updates, this function unpins the GEM VRAM
686  * objects of the plane's old framebuffer from VRAM. Complements
687  * drm_gem_vram_plane_helper_prepare_fb().
688  */
689 void
690 drm_gem_vram_plane_helper_cleanup_fb(struct drm_plane *plane,
691 				     struct drm_plane_state *old_state)
692 {
693 	size_t i;
694 	struct drm_gem_vram_object *gbo;
695 
696 	if (!old_state->fb)
697 		return;
698 
699 	for (i = 0; i < ARRAY_SIZE(old_state->fb->obj); ++i) {
700 		if (!old_state->fb->obj[i])
701 			continue;
702 		gbo = drm_gem_vram_of_gem(old_state->fb->obj[i]);
703 		drm_gem_vram_unpin(gbo);
704 	}
705 }
706 EXPORT_SYMBOL(drm_gem_vram_plane_helper_cleanup_fb);
707 
708 /*
709  * Helpers for struct drm_simple_display_pipe_funcs
710  */
711 
712 /**
713  * drm_gem_vram_simple_display_pipe_prepare_fb() - \
714  *	Implements &struct drm_simple_display_pipe_funcs.prepare_fb
715  * @pipe:	a simple display pipe
716  * @new_state:	the plane's new state
717  *
718  * During plane updates, this function pins the GEM VRAM
719  * objects of the plane's new framebuffer to VRAM. Call
720  * drm_gem_vram_simple_display_pipe_cleanup_fb() to unpin them.
721  *
722  * Returns:
723  *	0 on success, or
724  *	a negative errno code otherwise.
725  */
726 int drm_gem_vram_simple_display_pipe_prepare_fb(
727 	struct drm_simple_display_pipe *pipe,
728 	struct drm_plane_state *new_state)
729 {
730 	return drm_gem_vram_plane_helper_prepare_fb(&pipe->plane, new_state);
731 }
732 EXPORT_SYMBOL(drm_gem_vram_simple_display_pipe_prepare_fb);
733 
734 /**
735  * drm_gem_vram_simple_display_pipe_cleanup_fb() - \
736  *	Implements &struct drm_simple_display_pipe_funcs.cleanup_fb
737  * @pipe:	a simple display pipe
738  * @old_state:	the plane's old state
739  *
740  * During plane updates, this function unpins the GEM VRAM
741  * objects of the plane's old framebuffer from VRAM. Complements
742  * drm_gem_vram_simple_display_pipe_prepare_fb().
743  */
744 void drm_gem_vram_simple_display_pipe_cleanup_fb(
745 	struct drm_simple_display_pipe *pipe,
746 	struct drm_plane_state *old_state)
747 {
748 	drm_gem_vram_plane_helper_cleanup_fb(&pipe->plane, old_state);
749 }
750 EXPORT_SYMBOL(drm_gem_vram_simple_display_pipe_cleanup_fb);
751 
752 /*
753  * PRIME helpers
754  */
755 
756 /**
757  * drm_gem_vram_object_pin() - \
758 	Implements &struct drm_gem_object_funcs.pin
759  * @gem:	The GEM object to pin
760  *
761  * Returns:
762  * 0 on success, or
763  * a negative errno code otherwise.
764  */
765 static int drm_gem_vram_object_pin(struct drm_gem_object *gem)
766 {
767 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
768 
769 	/* Fbdev console emulation is the use case of these PRIME
770 	 * helpers. This may involve updating a hardware buffer from
771 	 * a shadow FB. We pin the buffer to it's current location
772 	 * (either video RAM or system memory) to prevent it from
773 	 * being relocated during the update operation. If you require
774 	 * the buffer to be pinned to VRAM, implement a callback that
775 	 * sets the flags accordingly.
776 	 */
777 	return drm_gem_vram_pin(gbo, 0);
778 }
779 
780 /**
781  * drm_gem_vram_object_unpin() - \
782 	Implements &struct drm_gem_object_funcs.unpin
783  * @gem:	The GEM object to unpin
784  */
785 static void drm_gem_vram_object_unpin(struct drm_gem_object *gem)
786 {
787 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
788 
789 	drm_gem_vram_unpin(gbo);
790 }
791 
792 /**
793  * drm_gem_vram_object_vmap() -
794  *	Implements &struct drm_gem_object_funcs.vmap
795  * @gem: The GEM object to map
796  * @map: Returns the kernel virtual address of the VRAM GEM object's backing
797  *       store.
798  *
799  * Returns:
800  * 0 on success, or a negative error code otherwise.
801  */
802 static int drm_gem_vram_object_vmap(struct drm_gem_object *gem, struct dma_buf_map *map)
803 {
804 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
805 
806 	return drm_gem_vram_vmap(gbo, map);
807 }
808 
809 /**
810  * drm_gem_vram_object_vunmap() -
811  *	Implements &struct drm_gem_object_funcs.vunmap
812  * @gem: The GEM object to unmap
813  * @map: Kernel virtual address where the VRAM GEM object was mapped
814  */
815 static void drm_gem_vram_object_vunmap(struct drm_gem_object *gem, struct dma_buf_map *map)
816 {
817 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
818 
819 	drm_gem_vram_vunmap(gbo, map);
820 }
821 
822 /*
823  * GEM object funcs
824  */
825 
826 static const struct drm_gem_object_funcs drm_gem_vram_object_funcs = {
827 	.free	= drm_gem_vram_object_free,
828 	.pin	= drm_gem_vram_object_pin,
829 	.unpin	= drm_gem_vram_object_unpin,
830 	.vmap	= drm_gem_vram_object_vmap,
831 	.vunmap	= drm_gem_vram_object_vunmap,
832 	.mmap   = drm_gem_ttm_mmap,
833 	.print_info = drm_gem_ttm_print_info,
834 };
835 
836 /*
837  * VRAM memory manager
838  */
839 
840 /*
841  * TTM TT
842  */
843 
844 static void bo_driver_ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *tt)
845 {
846 	ttm_tt_destroy_common(bdev, tt);
847 	ttm_tt_fini(tt);
848 	kfree(tt);
849 }
850 
851 /*
852  * TTM BO device
853  */
854 
855 static struct ttm_tt *bo_driver_ttm_tt_create(struct ttm_buffer_object *bo,
856 					      uint32_t page_flags)
857 {
858 	struct ttm_tt *tt;
859 	int ret;
860 
861 	tt = kzalloc(sizeof(*tt), GFP_KERNEL);
862 	if (!tt)
863 		return NULL;
864 
865 	ret = ttm_tt_init(tt, bo, page_flags, ttm_cached);
866 	if (ret < 0)
867 		goto err_ttm_tt_init;
868 
869 	return tt;
870 
871 err_ttm_tt_init:
872 	kfree(tt);
873 	return NULL;
874 }
875 
876 static void bo_driver_evict_flags(struct ttm_buffer_object *bo,
877 				  struct ttm_placement *placement)
878 {
879 	struct drm_gem_vram_object *gbo;
880 
881 	/* TTM may pass BOs that are not GEM VRAM BOs. */
882 	if (!drm_is_gem_vram(bo))
883 		return;
884 
885 	gbo = drm_gem_vram_of_bo(bo);
886 
887 	drm_gem_vram_bo_driver_evict_flags(gbo, placement);
888 }
889 
890 static void bo_driver_delete_mem_notify(struct ttm_buffer_object *bo)
891 {
892 	struct drm_gem_vram_object *gbo;
893 
894 	/* TTM may pass BOs that are not GEM VRAM BOs. */
895 	if (!drm_is_gem_vram(bo))
896 		return;
897 
898 	gbo = drm_gem_vram_of_bo(bo);
899 
900 	drm_gem_vram_bo_driver_move_notify(gbo);
901 }
902 
903 static int bo_driver_move(struct ttm_buffer_object *bo,
904 			  bool evict,
905 			  struct ttm_operation_ctx *ctx,
906 			  struct ttm_resource *new_mem,
907 			  struct ttm_place *hop)
908 {
909 	struct drm_gem_vram_object *gbo;
910 
911 	gbo = drm_gem_vram_of_bo(bo);
912 
913 	return drm_gem_vram_bo_driver_move(gbo, evict, ctx, new_mem);
914 }
915 
916 static int bo_driver_io_mem_reserve(struct ttm_device *bdev,
917 				    struct ttm_resource *mem)
918 {
919 	struct drm_vram_mm *vmm = drm_vram_mm_of_bdev(bdev);
920 
921 	switch (mem->mem_type) {
922 	case TTM_PL_SYSTEM:	/* nothing to do */
923 		break;
924 	case TTM_PL_VRAM:
925 		mem->bus.offset = (mem->start << PAGE_SHIFT) + vmm->vram_base;
926 		mem->bus.is_iomem = true;
927 		mem->bus.caching = ttm_write_combined;
928 		break;
929 	default:
930 		return -EINVAL;
931 	}
932 
933 	return 0;
934 }
935 
936 static struct ttm_device_funcs bo_driver = {
937 	.ttm_tt_create = bo_driver_ttm_tt_create,
938 	.ttm_tt_destroy = bo_driver_ttm_tt_destroy,
939 	.eviction_valuable = ttm_bo_eviction_valuable,
940 	.evict_flags = bo_driver_evict_flags,
941 	.move = bo_driver_move,
942 	.delete_mem_notify = bo_driver_delete_mem_notify,
943 	.io_mem_reserve = bo_driver_io_mem_reserve,
944 };
945 
946 /*
947  * struct drm_vram_mm
948  */
949 
950 static int drm_vram_mm_debugfs(struct seq_file *m, void *data)
951 {
952 	struct drm_info_node *node = (struct drm_info_node *) m->private;
953 	struct drm_vram_mm *vmm = node->minor->dev->vram_mm;
954 	struct ttm_resource_manager *man = ttm_manager_type(&vmm->bdev, TTM_PL_VRAM);
955 	struct drm_printer p = drm_seq_file_printer(m);
956 
957 	ttm_resource_manager_debug(man, &p);
958 	return 0;
959 }
960 
961 static const struct drm_info_list drm_vram_mm_debugfs_list[] = {
962 	{ "vram-mm", drm_vram_mm_debugfs, 0, NULL },
963 };
964 
965 /**
966  * drm_vram_mm_debugfs_init() - Register VRAM MM debugfs file.
967  *
968  * @minor: drm minor device.
969  *
970  */
971 void drm_vram_mm_debugfs_init(struct drm_minor *minor)
972 {
973 	drm_debugfs_create_files(drm_vram_mm_debugfs_list,
974 				 ARRAY_SIZE(drm_vram_mm_debugfs_list),
975 				 minor->debugfs_root, minor);
976 }
977 EXPORT_SYMBOL(drm_vram_mm_debugfs_init);
978 
979 static int drm_vram_mm_init(struct drm_vram_mm *vmm, struct drm_device *dev,
980 			    uint64_t vram_base, size_t vram_size)
981 {
982 	int ret;
983 
984 	vmm->vram_base = vram_base;
985 	vmm->vram_size = vram_size;
986 
987 	ret = ttm_device_init(&vmm->bdev, &bo_driver, dev->dev,
988 				 dev->anon_inode->i_mapping,
989 				 dev->vma_offset_manager,
990 				 false, true);
991 	if (ret)
992 		return ret;
993 
994 	ret = ttm_range_man_init(&vmm->bdev, TTM_PL_VRAM,
995 				 false, vram_size >> PAGE_SHIFT);
996 	if (ret)
997 		return ret;
998 
999 	return 0;
1000 }
1001 
1002 static void drm_vram_mm_cleanup(struct drm_vram_mm *vmm)
1003 {
1004 	ttm_range_man_fini(&vmm->bdev, TTM_PL_VRAM);
1005 	ttm_device_fini(&vmm->bdev);
1006 }
1007 
1008 /*
1009  * Helpers for integration with struct drm_device
1010  */
1011 
1012 /* deprecated; use drmm_vram_mm_init() */
1013 struct drm_vram_mm *drm_vram_helper_alloc_mm(
1014 	struct drm_device *dev, uint64_t vram_base, size_t vram_size)
1015 {
1016 	int ret;
1017 
1018 	if (WARN_ON(dev->vram_mm))
1019 		return dev->vram_mm;
1020 
1021 	dev->vram_mm = kzalloc(sizeof(*dev->vram_mm), GFP_KERNEL);
1022 	if (!dev->vram_mm)
1023 		return ERR_PTR(-ENOMEM);
1024 
1025 	ret = drm_vram_mm_init(dev->vram_mm, dev, vram_base, vram_size);
1026 	if (ret)
1027 		goto err_kfree;
1028 
1029 	return dev->vram_mm;
1030 
1031 err_kfree:
1032 	kfree(dev->vram_mm);
1033 	dev->vram_mm = NULL;
1034 	return ERR_PTR(ret);
1035 }
1036 EXPORT_SYMBOL(drm_vram_helper_alloc_mm);
1037 
1038 void drm_vram_helper_release_mm(struct drm_device *dev)
1039 {
1040 	if (!dev->vram_mm)
1041 		return;
1042 
1043 	drm_vram_mm_cleanup(dev->vram_mm);
1044 	kfree(dev->vram_mm);
1045 	dev->vram_mm = NULL;
1046 }
1047 EXPORT_SYMBOL(drm_vram_helper_release_mm);
1048 
1049 static void drm_vram_mm_release(struct drm_device *dev, void *ptr)
1050 {
1051 	drm_vram_helper_release_mm(dev);
1052 }
1053 
1054 /**
1055  * drmm_vram_helper_init - Initializes a device's instance of
1056  *                         &struct drm_vram_mm
1057  * @dev:	the DRM device
1058  * @vram_base:	the base address of the video memory
1059  * @vram_size:	the size of the video memory in bytes
1060  *
1061  * Creates a new instance of &struct drm_vram_mm and stores it in
1062  * struct &drm_device.vram_mm. The instance is auto-managed and cleaned
1063  * up as part of device cleanup. Calling this function multiple times
1064  * will generate an error message.
1065  *
1066  * Returns:
1067  * 0 on success, or a negative errno code otherwise.
1068  */
1069 int drmm_vram_helper_init(struct drm_device *dev, uint64_t vram_base,
1070 			  size_t vram_size)
1071 {
1072 	struct drm_vram_mm *vram_mm;
1073 
1074 	if (drm_WARN_ON_ONCE(dev, dev->vram_mm))
1075 		return 0;
1076 
1077 	vram_mm = drm_vram_helper_alloc_mm(dev, vram_base, vram_size);
1078 	if (IS_ERR(vram_mm))
1079 		return PTR_ERR(vram_mm);
1080 	return drmm_add_action_or_reset(dev, drm_vram_mm_release, NULL);
1081 }
1082 EXPORT_SYMBOL(drmm_vram_helper_init);
1083 
1084 /*
1085  * Mode-config helpers
1086  */
1087 
1088 static enum drm_mode_status
1089 drm_vram_helper_mode_valid_internal(struct drm_device *dev,
1090 				    const struct drm_display_mode *mode,
1091 				    unsigned long max_bpp)
1092 {
1093 	struct drm_vram_mm *vmm = dev->vram_mm;
1094 	unsigned long fbsize, fbpages, max_fbpages;
1095 
1096 	if (WARN_ON(!dev->vram_mm))
1097 		return MODE_BAD;
1098 
1099 	max_fbpages = (vmm->vram_size / 2) >> PAGE_SHIFT;
1100 
1101 	fbsize = mode->hdisplay * mode->vdisplay * max_bpp;
1102 	fbpages = DIV_ROUND_UP(fbsize, PAGE_SIZE);
1103 
1104 	if (fbpages > max_fbpages)
1105 		return MODE_MEM;
1106 
1107 	return MODE_OK;
1108 }
1109 
1110 /**
1111  * drm_vram_helper_mode_valid - Tests if a display mode's
1112  *	framebuffer fits into the available video memory.
1113  * @dev:	the DRM device
1114  * @mode:	the mode to test
1115  *
1116  * This function tests if enough video memory is available for using the
1117  * specified display mode. Atomic modesetting requires importing the
1118  * designated framebuffer into video memory before evicting the active
1119  * one. Hence, any framebuffer may consume at most half of the available
1120  * VRAM. Display modes that require a larger framebuffer can not be used,
1121  * even if the CRTC does support them. Each framebuffer is assumed to
1122  * have 32-bit color depth.
1123  *
1124  * Note:
1125  * The function can only test if the display mode is supported in
1126  * general. If there are too many framebuffers pinned to video memory,
1127  * a display mode may still not be usable in practice. The color depth of
1128  * 32-bit fits all current use case. A more flexible test can be added
1129  * when necessary.
1130  *
1131  * Returns:
1132  * MODE_OK if the display mode is supported, or an error code of type
1133  * enum drm_mode_status otherwise.
1134  */
1135 enum drm_mode_status
1136 drm_vram_helper_mode_valid(struct drm_device *dev,
1137 			   const struct drm_display_mode *mode)
1138 {
1139 	static const unsigned long max_bpp = 4; /* DRM_FORMAT_XRGB8888 */
1140 
1141 	return drm_vram_helper_mode_valid_internal(dev, mode, max_bpp);
1142 }
1143 EXPORT_SYMBOL(drm_vram_helper_mode_valid);
1144 
1145 MODULE_DESCRIPTION("DRM VRAM memory-management helpers");
1146 MODULE_LICENSE("GPL");
1147