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_framebuffer_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_bo_device *bdev;
191 	int ret;
192 	size_t acc_size;
193 
194 	if (WARN_ONCE(!vmm, "VRAM MM not initialized"))
195 		return ERR_PTR(-EINVAL);
196 
197 	if (dev->driver->gem_create_object) {
198 		gem = dev->driver->gem_create_object(dev, size);
199 		if (!gem)
200 			return ERR_PTR(-ENOMEM);
201 		gbo = drm_gem_vram_of_gem(gem);
202 	} else {
203 		gbo = kzalloc(sizeof(*gbo), GFP_KERNEL);
204 		if (!gbo)
205 			return ERR_PTR(-ENOMEM);
206 		gem = &gbo->bo.base;
207 	}
208 
209 	if (!gem->funcs)
210 		gem->funcs = &drm_gem_vram_object_funcs;
211 
212 	ret = drm_gem_object_init(dev, gem, size);
213 	if (ret) {
214 		kfree(gbo);
215 		return ERR_PTR(ret);
216 	}
217 
218 	bdev = &vmm->bdev;
219 	acc_size = ttm_bo_dma_acc_size(bdev, size, sizeof(*gbo));
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, acc_size,
230 			  NULL, NULL, 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 /**
251  * drm_gem_vram_mmap_offset() - Returns a GEM VRAM object's mmap offset
252  * @gbo:	the GEM VRAM object
253  *
254  * See drm_vma_node_offset_addr() for more information.
255  *
256  * Returns:
257  * The buffer object's offset for userspace mappings on success, or
258  * 0 if no offset is allocated.
259  */
260 u64 drm_gem_vram_mmap_offset(struct drm_gem_vram_object *gbo)
261 {
262 	return drm_vma_node_offset_addr(&gbo->bo.base.vma_node);
263 }
264 EXPORT_SYMBOL(drm_gem_vram_mmap_offset);
265 
266 static u64 drm_gem_vram_pg_offset(struct drm_gem_vram_object *gbo)
267 {
268 	/* Keep TTM behavior for now, remove when drivers are audited */
269 	if (WARN_ON_ONCE(!gbo->bo.mem.mm_node))
270 		return 0;
271 
272 	return gbo->bo.mem.start;
273 }
274 
275 /**
276  * drm_gem_vram_offset() - \
277 	Returns a GEM VRAM object's offset in video memory
278  * @gbo:	the GEM VRAM object
279  *
280  * This function returns the buffer object's offset in the device's video
281  * memory. The buffer object has to be pinned to %TTM_PL_VRAM.
282  *
283  * Returns:
284  * The buffer object's offset in video memory on success, or
285  * a negative errno code otherwise.
286  */
287 s64 drm_gem_vram_offset(struct drm_gem_vram_object *gbo)
288 {
289 	if (WARN_ON_ONCE(!gbo->bo.pin_count))
290 		return (s64)-ENODEV;
291 	return drm_gem_vram_pg_offset(gbo) << PAGE_SHIFT;
292 }
293 EXPORT_SYMBOL(drm_gem_vram_offset);
294 
295 static int drm_gem_vram_pin_locked(struct drm_gem_vram_object *gbo,
296 				   unsigned long pl_flag)
297 {
298 	struct ttm_operation_ctx ctx = { false, false };
299 	int ret;
300 
301 	if (gbo->bo.pin_count)
302 		goto out;
303 
304 	if (pl_flag)
305 		drm_gem_vram_placement(gbo, pl_flag);
306 
307 	ret = ttm_bo_validate(&gbo->bo, &gbo->placement, &ctx);
308 	if (ret < 0)
309 		return ret;
310 
311 out:
312 	ttm_bo_pin(&gbo->bo);
313 
314 	return 0;
315 }
316 
317 /**
318  * drm_gem_vram_pin() - Pins a GEM VRAM object in a region.
319  * @gbo:	the GEM VRAM object
320  * @pl_flag:	a bitmask of possible memory regions
321  *
322  * Pinning a buffer object ensures that it is not evicted from
323  * a memory region. A pinned buffer object has to be unpinned before
324  * it can be pinned to another region. If the pl_flag argument is 0,
325  * the buffer is pinned at its current location (video RAM or system
326  * memory).
327  *
328  * Small buffer objects, such as cursor images, can lead to memory
329  * fragmentation if they are pinned in the middle of video RAM. This
330  * is especially a problem on devices with only a small amount of
331  * video RAM. Fragmentation can prevent the primary framebuffer from
332  * fitting in, even though there's enough memory overall. The modifier
333  * DRM_GEM_VRAM_PL_FLAG_TOPDOWN marks the buffer object to be pinned
334  * at the high end of the memory region to avoid fragmentation.
335  *
336  * Returns:
337  * 0 on success, or
338  * a negative error code otherwise.
339  */
340 int drm_gem_vram_pin(struct drm_gem_vram_object *gbo, unsigned long pl_flag)
341 {
342 	int ret;
343 
344 	ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
345 	if (ret)
346 		return ret;
347 	ret = drm_gem_vram_pin_locked(gbo, pl_flag);
348 	ttm_bo_unreserve(&gbo->bo);
349 
350 	return ret;
351 }
352 EXPORT_SYMBOL(drm_gem_vram_pin);
353 
354 static void drm_gem_vram_unpin_locked(struct drm_gem_vram_object *gbo)
355 {
356 	ttm_bo_unpin(&gbo->bo);
357 }
358 
359 /**
360  * drm_gem_vram_unpin() - Unpins a GEM VRAM object
361  * @gbo:	the GEM VRAM object
362  *
363  * Returns:
364  * 0 on success, or
365  * a negative error code otherwise.
366  */
367 int drm_gem_vram_unpin(struct drm_gem_vram_object *gbo)
368 {
369 	int ret;
370 
371 	ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
372 	if (ret)
373 		return ret;
374 
375 	drm_gem_vram_unpin_locked(gbo);
376 	ttm_bo_unreserve(&gbo->bo);
377 
378 	return 0;
379 }
380 EXPORT_SYMBOL(drm_gem_vram_unpin);
381 
382 static int drm_gem_vram_kmap_locked(struct drm_gem_vram_object *gbo,
383 				    struct dma_buf_map *map)
384 {
385 	int ret;
386 
387 	if (gbo->vmap_use_count > 0)
388 		goto out;
389 
390 	/*
391 	 * VRAM helpers unmap the BO only on demand. So the previous
392 	 * page mapping might still be around. Only vmap if the there's
393 	 * no mapping present.
394 	 */
395 	if (dma_buf_map_is_null(&gbo->map)) {
396 		ret = ttm_bo_vmap(&gbo->bo, &gbo->map);
397 		if (ret)
398 			return ret;
399 	}
400 
401 out:
402 	++gbo->vmap_use_count;
403 	*map = gbo->map;
404 
405 	return 0;
406 }
407 
408 static void drm_gem_vram_kunmap_locked(struct drm_gem_vram_object *gbo,
409 				       struct dma_buf_map *map)
410 {
411 	struct drm_device *dev = gbo->bo.base.dev;
412 
413 	if (drm_WARN_ON_ONCE(dev, !gbo->vmap_use_count))
414 		return;
415 
416 	if (drm_WARN_ON_ONCE(dev, !dma_buf_map_is_equal(&gbo->map, map)))
417 		return; /* BUG: map not mapped from this BO */
418 
419 	if (--gbo->vmap_use_count > 0)
420 		return;
421 
422 	/*
423 	 * Permanently mapping and unmapping buffers adds overhead from
424 	 * updating the page tables and creates debugging output. Therefore,
425 	 * we delay the actual unmap operation until the BO gets evicted
426 	 * from memory. See drm_gem_vram_bo_driver_move_notify().
427 	 */
428 }
429 
430 /**
431  * drm_gem_vram_vmap() - Pins and maps a GEM VRAM object into kernel address
432  *                       space
433  * @gbo: The GEM VRAM object to map
434  * @map: Returns the kernel virtual address of the VRAM GEM object's backing
435  *       store.
436  *
437  * The vmap function pins a GEM VRAM object to its current location, either
438  * system or video memory, and maps its buffer into kernel address space.
439  * As pinned object cannot be relocated, you should avoid pinning objects
440  * permanently. Call drm_gem_vram_vunmap() with the returned address to
441  * unmap and unpin the GEM VRAM object.
442  *
443  * Returns:
444  * 0 on success, or a negative error code otherwise.
445  */
446 int drm_gem_vram_vmap(struct drm_gem_vram_object *gbo, struct dma_buf_map *map)
447 {
448 	int ret;
449 
450 	ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
451 	if (ret)
452 		return ret;
453 
454 	ret = drm_gem_vram_pin_locked(gbo, 0);
455 	if (ret)
456 		goto err_ttm_bo_unreserve;
457 	ret = drm_gem_vram_kmap_locked(gbo, map);
458 	if (ret)
459 		goto err_drm_gem_vram_unpin_locked;
460 
461 	ttm_bo_unreserve(&gbo->bo);
462 
463 	return 0;
464 
465 err_drm_gem_vram_unpin_locked:
466 	drm_gem_vram_unpin_locked(gbo);
467 err_ttm_bo_unreserve:
468 	ttm_bo_unreserve(&gbo->bo);
469 	return ret;
470 }
471 EXPORT_SYMBOL(drm_gem_vram_vmap);
472 
473 /**
474  * drm_gem_vram_vunmap() - Unmaps and unpins a GEM VRAM object
475  * @gbo: The GEM VRAM object to unmap
476  * @map: Kernel virtual address where the VRAM GEM object was mapped
477  *
478  * A call to drm_gem_vram_vunmap() unmaps and unpins a GEM VRAM buffer. See
479  * the documentation for drm_gem_vram_vmap() for more information.
480  */
481 void drm_gem_vram_vunmap(struct drm_gem_vram_object *gbo, struct dma_buf_map *map)
482 {
483 	int ret;
484 
485 	ret = ttm_bo_reserve(&gbo->bo, false, false, NULL);
486 	if (WARN_ONCE(ret, "ttm_bo_reserve_failed(): ret=%d\n", ret))
487 		return;
488 
489 	drm_gem_vram_kunmap_locked(gbo, map);
490 	drm_gem_vram_unpin_locked(gbo);
491 
492 	ttm_bo_unreserve(&gbo->bo);
493 }
494 EXPORT_SYMBOL(drm_gem_vram_vunmap);
495 
496 /**
497  * drm_gem_vram_fill_create_dumb() - \
498 	Helper for implementing &struct drm_driver.dumb_create
499  * @file:		the DRM file
500  * @dev:		the DRM device
501  * @pg_align:		the buffer's alignment in multiples of the page size
502  * @pitch_align:	the scanline's alignment in powers of 2
503  * @args:		the arguments as provided to \
504 				&struct drm_driver.dumb_create
505  *
506  * This helper function fills &struct drm_mode_create_dumb, which is used
507  * by &struct drm_driver.dumb_create. Implementations of this interface
508  * should forwards their arguments to this helper, plus the driver-specific
509  * parameters.
510  *
511  * Returns:
512  * 0 on success, or
513  * a negative error code otherwise.
514  */
515 int drm_gem_vram_fill_create_dumb(struct drm_file *file,
516 				  struct drm_device *dev,
517 				  unsigned long pg_align,
518 				  unsigned long pitch_align,
519 				  struct drm_mode_create_dumb *args)
520 {
521 	size_t pitch, size;
522 	struct drm_gem_vram_object *gbo;
523 	int ret;
524 	u32 handle;
525 
526 	pitch = args->width * DIV_ROUND_UP(args->bpp, 8);
527 	if (pitch_align) {
528 		if (WARN_ON_ONCE(!is_power_of_2(pitch_align)))
529 			return -EINVAL;
530 		pitch = ALIGN(pitch, pitch_align);
531 	}
532 	size = pitch * args->height;
533 
534 	size = roundup(size, PAGE_SIZE);
535 	if (!size)
536 		return -EINVAL;
537 
538 	gbo = drm_gem_vram_create(dev, size, pg_align);
539 	if (IS_ERR(gbo))
540 		return PTR_ERR(gbo);
541 
542 	ret = drm_gem_handle_create(file, &gbo->bo.base, &handle);
543 	if (ret)
544 		goto err_drm_gem_object_put;
545 
546 	drm_gem_object_put(&gbo->bo.base);
547 
548 	args->pitch = pitch;
549 	args->size = size;
550 	args->handle = handle;
551 
552 	return 0;
553 
554 err_drm_gem_object_put:
555 	drm_gem_object_put(&gbo->bo.base);
556 	return ret;
557 }
558 EXPORT_SYMBOL(drm_gem_vram_fill_create_dumb);
559 
560 /*
561  * Helpers for struct ttm_bo_driver
562  */
563 
564 static bool drm_is_gem_vram(struct ttm_buffer_object *bo)
565 {
566 	return (bo->destroy == ttm_buffer_object_destroy);
567 }
568 
569 static void drm_gem_vram_bo_driver_evict_flags(struct drm_gem_vram_object *gbo,
570 					       struct ttm_placement *pl)
571 {
572 	drm_gem_vram_placement(gbo, DRM_GEM_VRAM_PL_FLAG_SYSTEM);
573 	*pl = gbo->placement;
574 }
575 
576 static void drm_gem_vram_bo_driver_move_notify(struct drm_gem_vram_object *gbo,
577 					       bool evict,
578 					       struct ttm_resource *new_mem)
579 {
580 	struct ttm_buffer_object *bo = &gbo->bo;
581 	struct drm_device *dev = bo->base.dev;
582 
583 	if (drm_WARN_ON_ONCE(dev, gbo->vmap_use_count))
584 		return;
585 
586 	ttm_bo_vunmap(bo, &gbo->map);
587 	dma_buf_map_clear(&gbo->map); /* explicitly clear mapping for next vmap call */
588 }
589 
590 static int drm_gem_vram_bo_driver_move(struct drm_gem_vram_object *gbo,
591 				       bool evict,
592 				       struct ttm_operation_ctx *ctx,
593 				       struct ttm_resource *new_mem)
594 {
595 	int ret;
596 
597 	drm_gem_vram_bo_driver_move_notify(gbo, evict, new_mem);
598 	ret = ttm_bo_move_memcpy(&gbo->bo, ctx, new_mem);
599 	if (ret) {
600 		swap(*new_mem, gbo->bo.mem);
601 		drm_gem_vram_bo_driver_move_notify(gbo, false, new_mem);
602 		swap(*new_mem, gbo->bo.mem);
603 	}
604 	return ret;
605 }
606 
607 /*
608  * Helpers for struct drm_gem_object_funcs
609  */
610 
611 /**
612  * drm_gem_vram_object_free() - \
613 	Implements &struct drm_gem_object_funcs.free
614  * @gem:       GEM object. Refers to &struct drm_gem_vram_object.gem
615  */
616 static void drm_gem_vram_object_free(struct drm_gem_object *gem)
617 {
618 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
619 
620 	drm_gem_vram_put(gbo);
621 }
622 
623 /*
624  * Helpers for dump buffers
625  */
626 
627 /**
628  * drm_gem_vram_driver_dumb_create() - \
629 	Implements &struct drm_driver.dumb_create
630  * @file:		the DRM file
631  * @dev:		the DRM device
632  * @args:		the arguments as provided to \
633 				&struct drm_driver.dumb_create
634  *
635  * This function requires the driver to use @drm_device.vram_mm for its
636  * instance of VRAM MM.
637  *
638  * Returns:
639  * 0 on success, or
640  * a negative error code otherwise.
641  */
642 int drm_gem_vram_driver_dumb_create(struct drm_file *file,
643 				    struct drm_device *dev,
644 				    struct drm_mode_create_dumb *args)
645 {
646 	if (WARN_ONCE(!dev->vram_mm, "VRAM MM not initialized"))
647 		return -EINVAL;
648 
649 	return drm_gem_vram_fill_create_dumb(file, dev, 0, 0, args);
650 }
651 EXPORT_SYMBOL(drm_gem_vram_driver_dumb_create);
652 
653 /**
654  * drm_gem_vram_driver_dumb_mmap_offset() - \
655 	Implements &struct drm_driver.dumb_mmap_offset
656  * @file:	DRM file pointer.
657  * @dev:	DRM device.
658  * @handle:	GEM handle
659  * @offset:	Returns the mapping's memory offset on success
660  *
661  * Returns:
662  * 0 on success, or
663  * a negative errno code otherwise.
664  */
665 int drm_gem_vram_driver_dumb_mmap_offset(struct drm_file *file,
666 					 struct drm_device *dev,
667 					 uint32_t handle, uint64_t *offset)
668 {
669 	struct drm_gem_object *gem;
670 	struct drm_gem_vram_object *gbo;
671 
672 	gem = drm_gem_object_lookup(file, handle);
673 	if (!gem)
674 		return -ENOENT;
675 
676 	gbo = drm_gem_vram_of_gem(gem);
677 	*offset = drm_gem_vram_mmap_offset(gbo);
678 
679 	drm_gem_object_put(gem);
680 
681 	return 0;
682 }
683 EXPORT_SYMBOL(drm_gem_vram_driver_dumb_mmap_offset);
684 
685 /*
686  * Helpers for struct drm_plane_helper_funcs
687  */
688 
689 /**
690  * drm_gem_vram_plane_helper_prepare_fb() - \
691  *	Implements &struct drm_plane_helper_funcs.prepare_fb
692  * @plane:	a DRM plane
693  * @new_state:	the plane's new state
694  *
695  * During plane updates, this function sets the plane's fence and
696  * pins the GEM VRAM objects of the plane's new framebuffer to VRAM.
697  * Call drm_gem_vram_plane_helper_cleanup_fb() to unpin them.
698  *
699  * Returns:
700  *	0 on success, or
701  *	a negative errno code otherwise.
702  */
703 int
704 drm_gem_vram_plane_helper_prepare_fb(struct drm_plane *plane,
705 				     struct drm_plane_state *new_state)
706 {
707 	size_t i;
708 	struct drm_gem_vram_object *gbo;
709 	int ret;
710 
711 	if (!new_state->fb)
712 		return 0;
713 
714 	for (i = 0; i < ARRAY_SIZE(new_state->fb->obj); ++i) {
715 		if (!new_state->fb->obj[i])
716 			continue;
717 		gbo = drm_gem_vram_of_gem(new_state->fb->obj[i]);
718 		ret = drm_gem_vram_pin(gbo, DRM_GEM_VRAM_PL_FLAG_VRAM);
719 		if (ret)
720 			goto err_drm_gem_vram_unpin;
721 	}
722 
723 	ret = drm_gem_fb_prepare_fb(plane, new_state);
724 	if (ret)
725 		goto err_drm_gem_vram_unpin;
726 
727 	return 0;
728 
729 err_drm_gem_vram_unpin:
730 	while (i) {
731 		--i;
732 		gbo = drm_gem_vram_of_gem(new_state->fb->obj[i]);
733 		drm_gem_vram_unpin(gbo);
734 	}
735 	return ret;
736 }
737 EXPORT_SYMBOL(drm_gem_vram_plane_helper_prepare_fb);
738 
739 /**
740  * drm_gem_vram_plane_helper_cleanup_fb() - \
741  *	Implements &struct drm_plane_helper_funcs.cleanup_fb
742  * @plane:	a DRM plane
743  * @old_state:	the plane's old state
744  *
745  * During plane updates, this function unpins the GEM VRAM
746  * objects of the plane's old framebuffer from VRAM. Complements
747  * drm_gem_vram_plane_helper_prepare_fb().
748  */
749 void
750 drm_gem_vram_plane_helper_cleanup_fb(struct drm_plane *plane,
751 				     struct drm_plane_state *old_state)
752 {
753 	size_t i;
754 	struct drm_gem_vram_object *gbo;
755 
756 	if (!old_state->fb)
757 		return;
758 
759 	for (i = 0; i < ARRAY_SIZE(old_state->fb->obj); ++i) {
760 		if (!old_state->fb->obj[i])
761 			continue;
762 		gbo = drm_gem_vram_of_gem(old_state->fb->obj[i]);
763 		drm_gem_vram_unpin(gbo);
764 	}
765 }
766 EXPORT_SYMBOL(drm_gem_vram_plane_helper_cleanup_fb);
767 
768 /*
769  * Helpers for struct drm_simple_display_pipe_funcs
770  */
771 
772 /**
773  * drm_gem_vram_simple_display_pipe_prepare_fb() - \
774  *	Implements &struct drm_simple_display_pipe_funcs.prepare_fb
775  * @pipe:	a simple display pipe
776  * @new_state:	the plane's new state
777  *
778  * During plane updates, this function pins the GEM VRAM
779  * objects of the plane's new framebuffer to VRAM. Call
780  * drm_gem_vram_simple_display_pipe_cleanup_fb() to unpin them.
781  *
782  * Returns:
783  *	0 on success, or
784  *	a negative errno code otherwise.
785  */
786 int drm_gem_vram_simple_display_pipe_prepare_fb(
787 	struct drm_simple_display_pipe *pipe,
788 	struct drm_plane_state *new_state)
789 {
790 	return drm_gem_vram_plane_helper_prepare_fb(&pipe->plane, new_state);
791 }
792 EXPORT_SYMBOL(drm_gem_vram_simple_display_pipe_prepare_fb);
793 
794 /**
795  * drm_gem_vram_simple_display_pipe_cleanup_fb() - \
796  *	Implements &struct drm_simple_display_pipe_funcs.cleanup_fb
797  * @pipe:	a simple display pipe
798  * @old_state:	the plane's old state
799  *
800  * During plane updates, this function unpins the GEM VRAM
801  * objects of the plane's old framebuffer from VRAM. Complements
802  * drm_gem_vram_simple_display_pipe_prepare_fb().
803  */
804 void drm_gem_vram_simple_display_pipe_cleanup_fb(
805 	struct drm_simple_display_pipe *pipe,
806 	struct drm_plane_state *old_state)
807 {
808 	drm_gem_vram_plane_helper_cleanup_fb(&pipe->plane, old_state);
809 }
810 EXPORT_SYMBOL(drm_gem_vram_simple_display_pipe_cleanup_fb);
811 
812 /*
813  * PRIME helpers
814  */
815 
816 /**
817  * drm_gem_vram_object_pin() - \
818 	Implements &struct drm_gem_object_funcs.pin
819  * @gem:	The GEM object to pin
820  *
821  * Returns:
822  * 0 on success, or
823  * a negative errno code otherwise.
824  */
825 static int drm_gem_vram_object_pin(struct drm_gem_object *gem)
826 {
827 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
828 
829 	/* Fbdev console emulation is the use case of these PRIME
830 	 * helpers. This may involve updating a hardware buffer from
831 	 * a shadow FB. We pin the buffer to it's current location
832 	 * (either video RAM or system memory) to prevent it from
833 	 * being relocated during the update operation. If you require
834 	 * the buffer to be pinned to VRAM, implement a callback that
835 	 * sets the flags accordingly.
836 	 */
837 	return drm_gem_vram_pin(gbo, 0);
838 }
839 
840 /**
841  * drm_gem_vram_object_unpin() - \
842 	Implements &struct drm_gem_object_funcs.unpin
843  * @gem:	The GEM object to unpin
844  */
845 static void drm_gem_vram_object_unpin(struct drm_gem_object *gem)
846 {
847 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
848 
849 	drm_gem_vram_unpin(gbo);
850 }
851 
852 /**
853  * drm_gem_vram_object_vmap() -
854  *	Implements &struct drm_gem_object_funcs.vmap
855  * @gem: The GEM object to map
856  * @map: Returns the kernel virtual address of the VRAM GEM object's backing
857  *       store.
858  *
859  * Returns:
860  * 0 on success, or a negative error code otherwise.
861  */
862 static int drm_gem_vram_object_vmap(struct drm_gem_object *gem, struct dma_buf_map *map)
863 {
864 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
865 
866 	return drm_gem_vram_vmap(gbo, map);
867 }
868 
869 /**
870  * drm_gem_vram_object_vunmap() -
871  *	Implements &struct drm_gem_object_funcs.vunmap
872  * @gem: The GEM object to unmap
873  * @map: Kernel virtual address where the VRAM GEM object was mapped
874  */
875 static void drm_gem_vram_object_vunmap(struct drm_gem_object *gem, struct dma_buf_map *map)
876 {
877 	struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
878 
879 	drm_gem_vram_vunmap(gbo, map);
880 }
881 
882 /*
883  * GEM object funcs
884  */
885 
886 static const struct drm_gem_object_funcs drm_gem_vram_object_funcs = {
887 	.free	= drm_gem_vram_object_free,
888 	.pin	= drm_gem_vram_object_pin,
889 	.unpin	= drm_gem_vram_object_unpin,
890 	.vmap	= drm_gem_vram_object_vmap,
891 	.vunmap	= drm_gem_vram_object_vunmap,
892 	.mmap   = drm_gem_ttm_mmap,
893 	.print_info = drm_gem_ttm_print_info,
894 };
895 
896 /*
897  * VRAM memory manager
898  */
899 
900 /*
901  * TTM TT
902  */
903 
904 static void bo_driver_ttm_tt_destroy(struct ttm_bo_device *bdev, struct ttm_tt *tt)
905 {
906 	ttm_tt_destroy_common(bdev, tt);
907 	ttm_tt_fini(tt);
908 	kfree(tt);
909 }
910 
911 /*
912  * TTM BO device
913  */
914 
915 static struct ttm_tt *bo_driver_ttm_tt_create(struct ttm_buffer_object *bo,
916 					      uint32_t page_flags)
917 {
918 	struct ttm_tt *tt;
919 	int ret;
920 
921 	tt = kzalloc(sizeof(*tt), GFP_KERNEL);
922 	if (!tt)
923 		return NULL;
924 
925 	ret = ttm_tt_init(tt, bo, page_flags, ttm_cached);
926 	if (ret < 0)
927 		goto err_ttm_tt_init;
928 
929 	return tt;
930 
931 err_ttm_tt_init:
932 	kfree(tt);
933 	return NULL;
934 }
935 
936 static void bo_driver_evict_flags(struct ttm_buffer_object *bo,
937 				  struct ttm_placement *placement)
938 {
939 	struct drm_gem_vram_object *gbo;
940 
941 	/* TTM may pass BOs that are not GEM VRAM BOs. */
942 	if (!drm_is_gem_vram(bo))
943 		return;
944 
945 	gbo = drm_gem_vram_of_bo(bo);
946 
947 	drm_gem_vram_bo_driver_evict_flags(gbo, placement);
948 }
949 
950 static void bo_driver_delete_mem_notify(struct ttm_buffer_object *bo)
951 {
952 	struct drm_gem_vram_object *gbo;
953 
954 	/* TTM may pass BOs that are not GEM VRAM BOs. */
955 	if (!drm_is_gem_vram(bo))
956 		return;
957 
958 	gbo = drm_gem_vram_of_bo(bo);
959 
960 	drm_gem_vram_bo_driver_move_notify(gbo, false, NULL);
961 }
962 
963 static int bo_driver_move(struct ttm_buffer_object *bo,
964 			  bool evict,
965 			  struct ttm_operation_ctx *ctx,
966 			  struct ttm_resource *new_mem,
967 			  struct ttm_place *hop)
968 {
969 	struct drm_gem_vram_object *gbo;
970 
971 	gbo = drm_gem_vram_of_bo(bo);
972 
973 	return drm_gem_vram_bo_driver_move(gbo, evict, ctx, new_mem);
974 }
975 
976 static int bo_driver_io_mem_reserve(struct ttm_bo_device *bdev,
977 				    struct ttm_resource *mem)
978 {
979 	struct drm_vram_mm *vmm = drm_vram_mm_of_bdev(bdev);
980 
981 	switch (mem->mem_type) {
982 	case TTM_PL_SYSTEM:	/* nothing to do */
983 		break;
984 	case TTM_PL_VRAM:
985 		mem->bus.offset = (mem->start << PAGE_SHIFT) + vmm->vram_base;
986 		mem->bus.is_iomem = true;
987 		mem->bus.caching = ttm_write_combined;
988 		break;
989 	default:
990 		return -EINVAL;
991 	}
992 
993 	return 0;
994 }
995 
996 static struct ttm_bo_driver bo_driver = {
997 	.ttm_tt_create = bo_driver_ttm_tt_create,
998 	.ttm_tt_destroy = bo_driver_ttm_tt_destroy,
999 	.eviction_valuable = ttm_bo_eviction_valuable,
1000 	.evict_flags = bo_driver_evict_flags,
1001 	.move = bo_driver_move,
1002 	.delete_mem_notify = bo_driver_delete_mem_notify,
1003 	.io_mem_reserve = bo_driver_io_mem_reserve,
1004 };
1005 
1006 /*
1007  * struct drm_vram_mm
1008  */
1009 
1010 static int drm_vram_mm_debugfs(struct seq_file *m, void *data)
1011 {
1012 	struct drm_info_node *node = (struct drm_info_node *) m->private;
1013 	struct drm_vram_mm *vmm = node->minor->dev->vram_mm;
1014 	struct ttm_resource_manager *man = ttm_manager_type(&vmm->bdev, TTM_PL_VRAM);
1015 	struct drm_printer p = drm_seq_file_printer(m);
1016 
1017 	ttm_resource_manager_debug(man, &p);
1018 	return 0;
1019 }
1020 
1021 static const struct drm_info_list drm_vram_mm_debugfs_list[] = {
1022 	{ "vram-mm", drm_vram_mm_debugfs, 0, NULL },
1023 };
1024 
1025 /**
1026  * drm_vram_mm_debugfs_init() - Register VRAM MM debugfs file.
1027  *
1028  * @minor: drm minor device.
1029  *
1030  */
1031 void drm_vram_mm_debugfs_init(struct drm_minor *minor)
1032 {
1033 	drm_debugfs_create_files(drm_vram_mm_debugfs_list,
1034 				 ARRAY_SIZE(drm_vram_mm_debugfs_list),
1035 				 minor->debugfs_root, minor);
1036 }
1037 EXPORT_SYMBOL(drm_vram_mm_debugfs_init);
1038 
1039 static int drm_vram_mm_init(struct drm_vram_mm *vmm, struct drm_device *dev,
1040 			    uint64_t vram_base, size_t vram_size)
1041 {
1042 	int ret;
1043 
1044 	vmm->vram_base = vram_base;
1045 	vmm->vram_size = vram_size;
1046 
1047 	ret = ttm_bo_device_init(&vmm->bdev, &bo_driver, dev->dev,
1048 				 dev->anon_inode->i_mapping,
1049 				 dev->vma_offset_manager,
1050 				 false, true);
1051 	if (ret)
1052 		return ret;
1053 
1054 	ret = ttm_range_man_init(&vmm->bdev, TTM_PL_VRAM,
1055 				 false, vram_size >> PAGE_SHIFT);
1056 	if (ret)
1057 		return ret;
1058 
1059 	return 0;
1060 }
1061 
1062 static void drm_vram_mm_cleanup(struct drm_vram_mm *vmm)
1063 {
1064 	ttm_range_man_fini(&vmm->bdev, TTM_PL_VRAM);
1065 	ttm_bo_device_release(&vmm->bdev);
1066 }
1067 
1068 /*
1069  * Helpers for integration with struct drm_device
1070  */
1071 
1072 /* deprecated; use drmm_vram_mm_init() */
1073 struct drm_vram_mm *drm_vram_helper_alloc_mm(
1074 	struct drm_device *dev, uint64_t vram_base, size_t vram_size)
1075 {
1076 	int ret;
1077 
1078 	if (WARN_ON(dev->vram_mm))
1079 		return dev->vram_mm;
1080 
1081 	dev->vram_mm = kzalloc(sizeof(*dev->vram_mm), GFP_KERNEL);
1082 	if (!dev->vram_mm)
1083 		return ERR_PTR(-ENOMEM);
1084 
1085 	ret = drm_vram_mm_init(dev->vram_mm, dev, vram_base, vram_size);
1086 	if (ret)
1087 		goto err_kfree;
1088 
1089 	return dev->vram_mm;
1090 
1091 err_kfree:
1092 	kfree(dev->vram_mm);
1093 	dev->vram_mm = NULL;
1094 	return ERR_PTR(ret);
1095 }
1096 EXPORT_SYMBOL(drm_vram_helper_alloc_mm);
1097 
1098 void drm_vram_helper_release_mm(struct drm_device *dev)
1099 {
1100 	if (!dev->vram_mm)
1101 		return;
1102 
1103 	drm_vram_mm_cleanup(dev->vram_mm);
1104 	kfree(dev->vram_mm);
1105 	dev->vram_mm = NULL;
1106 }
1107 EXPORT_SYMBOL(drm_vram_helper_release_mm);
1108 
1109 static void drm_vram_mm_release(struct drm_device *dev, void *ptr)
1110 {
1111 	drm_vram_helper_release_mm(dev);
1112 }
1113 
1114 /**
1115  * drmm_vram_helper_init - Initializes a device's instance of
1116  *                         &struct drm_vram_mm
1117  * @dev:	the DRM device
1118  * @vram_base:	the base address of the video memory
1119  * @vram_size:	the size of the video memory in bytes
1120  *
1121  * Creates a new instance of &struct drm_vram_mm and stores it in
1122  * struct &drm_device.vram_mm. The instance is auto-managed and cleaned
1123  * up as part of device cleanup. Calling this function multiple times
1124  * will generate an error message.
1125  *
1126  * Returns:
1127  * 0 on success, or a negative errno code otherwise.
1128  */
1129 int drmm_vram_helper_init(struct drm_device *dev, uint64_t vram_base,
1130 			  size_t vram_size)
1131 {
1132 	struct drm_vram_mm *vram_mm;
1133 
1134 	if (drm_WARN_ON_ONCE(dev, dev->vram_mm))
1135 		return 0;
1136 
1137 	vram_mm = drm_vram_helper_alloc_mm(dev, vram_base, vram_size);
1138 	if (IS_ERR(vram_mm))
1139 		return PTR_ERR(vram_mm);
1140 	return drmm_add_action_or_reset(dev, drm_vram_mm_release, NULL);
1141 }
1142 EXPORT_SYMBOL(drmm_vram_helper_init);
1143 
1144 /*
1145  * Mode-config helpers
1146  */
1147 
1148 static enum drm_mode_status
1149 drm_vram_helper_mode_valid_internal(struct drm_device *dev,
1150 				    const struct drm_display_mode *mode,
1151 				    unsigned long max_bpp)
1152 {
1153 	struct drm_vram_mm *vmm = dev->vram_mm;
1154 	unsigned long fbsize, fbpages, max_fbpages;
1155 
1156 	if (WARN_ON(!dev->vram_mm))
1157 		return MODE_BAD;
1158 
1159 	max_fbpages = (vmm->vram_size / 2) >> PAGE_SHIFT;
1160 
1161 	fbsize = mode->hdisplay * mode->vdisplay * max_bpp;
1162 	fbpages = DIV_ROUND_UP(fbsize, PAGE_SIZE);
1163 
1164 	if (fbpages > max_fbpages)
1165 		return MODE_MEM;
1166 
1167 	return MODE_OK;
1168 }
1169 
1170 /**
1171  * drm_vram_helper_mode_valid - Tests if a display mode's
1172  *	framebuffer fits into the available video memory.
1173  * @dev:	the DRM device
1174  * @mode:	the mode to test
1175  *
1176  * This function tests if enough video memory is available for using the
1177  * specified display mode. Atomic modesetting requires importing the
1178  * designated framebuffer into video memory before evicting the active
1179  * one. Hence, any framebuffer may consume at most half of the available
1180  * VRAM. Display modes that require a larger framebuffer can not be used,
1181  * even if the CRTC does support them. Each framebuffer is assumed to
1182  * have 32-bit color depth.
1183  *
1184  * Note:
1185  * The function can only test if the display mode is supported in
1186  * general. If there are too many framebuffers pinned to video memory,
1187  * a display mode may still not be usable in practice. The color depth of
1188  * 32-bit fits all current use case. A more flexible test can be added
1189  * when necessary.
1190  *
1191  * Returns:
1192  * MODE_OK if the display mode is supported, or an error code of type
1193  * enum drm_mode_status otherwise.
1194  */
1195 enum drm_mode_status
1196 drm_vram_helper_mode_valid(struct drm_device *dev,
1197 			   const struct drm_display_mode *mode)
1198 {
1199 	static const unsigned long max_bpp = 4; /* DRM_FORMAT_XRGB8888 */
1200 
1201 	return drm_vram_helper_mode_valid_internal(dev, mode, max_bpp);
1202 }
1203 EXPORT_SYMBOL(drm_vram_helper_mode_valid);
1204 
1205 MODULE_DESCRIPTION("DRM VRAM memory-management helpers");
1206 MODULE_LICENSE("GPL");
1207