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