drm/ttm: flip over the range manager to self allocated nodes
[linux-2.6-block.git] / drivers / gpu / drm / drm_gem_vram_helper.c
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 #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 draing 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(dma_buf_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 (!gem)
201                         return ERR_PTR(-ENOMEM);
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->mm_node))
254                 return 0;
255
256         return gbo->bo.resource->start;
257 }
258
259 /**
260  * drm_gem_vram_offset() - \
261         Returns a GEM VRAM object's offset in video memory
262  * @gbo:        the GEM VRAM object
263  *
264  * This function returns the buffer object's offset in the device's video
265  * memory. The buffer object has to be pinned to %TTM_PL_VRAM.
266  *
267  * Returns:
268  * The buffer object's offset in video memory on success, or
269  * a negative errno code otherwise.
270  */
271 s64 drm_gem_vram_offset(struct drm_gem_vram_object *gbo)
272 {
273         if (WARN_ON_ONCE(!gbo->bo.pin_count))
274                 return (s64)-ENODEV;
275         return drm_gem_vram_pg_offset(gbo) << PAGE_SHIFT;
276 }
277 EXPORT_SYMBOL(drm_gem_vram_offset);
278
279 static int drm_gem_vram_pin_locked(struct drm_gem_vram_object *gbo,
280                                    unsigned long pl_flag)
281 {
282         struct ttm_operation_ctx ctx = { false, false };
283         int ret;
284
285         if (gbo->bo.pin_count)
286                 goto out;
287
288         if (pl_flag)
289                 drm_gem_vram_placement(gbo, pl_flag);
290
291         ret = ttm_bo_validate(&gbo->bo, &gbo->placement, &ctx);
292         if (ret < 0)
293                 return ret;
294
295 out:
296         ttm_bo_pin(&gbo->bo);
297
298         return 0;
299 }
300
301 /**
302  * drm_gem_vram_pin() - Pins a GEM VRAM object in a region.
303  * @gbo:        the GEM VRAM object
304  * @pl_flag:    a bitmask of possible memory regions
305  *
306  * Pinning a buffer object ensures that it is not evicted from
307  * a memory region. A pinned buffer object has to be unpinned before
308  * it can be pinned to another region. If the pl_flag argument is 0,
309  * the buffer is pinned at its current location (video RAM or system
310  * memory).
311  *
312  * Small buffer objects, such as cursor images, can lead to memory
313  * fragmentation if they are pinned in the middle of video RAM. This
314  * is especially a problem on devices with only a small amount of
315  * video RAM. Fragmentation can prevent the primary framebuffer from
316  * fitting in, even though there's enough memory overall. The modifier
317  * DRM_GEM_VRAM_PL_FLAG_TOPDOWN marks the buffer object to be pinned
318  * at the high end of the memory region to avoid fragmentation.
319  *
320  * Returns:
321  * 0 on success, or
322  * a negative error code otherwise.
323  */
324 int drm_gem_vram_pin(struct drm_gem_vram_object *gbo, unsigned long pl_flag)
325 {
326         int ret;
327
328         ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
329         if (ret)
330                 return ret;
331         ret = drm_gem_vram_pin_locked(gbo, pl_flag);
332         ttm_bo_unreserve(&gbo->bo);
333
334         return ret;
335 }
336 EXPORT_SYMBOL(drm_gem_vram_pin);
337
338 static void drm_gem_vram_unpin_locked(struct drm_gem_vram_object *gbo)
339 {
340         ttm_bo_unpin(&gbo->bo);
341 }
342
343 /**
344  * drm_gem_vram_unpin() - Unpins a GEM VRAM object
345  * @gbo:        the GEM VRAM object
346  *
347  * Returns:
348  * 0 on success, or
349  * a negative error code otherwise.
350  */
351 int drm_gem_vram_unpin(struct drm_gem_vram_object *gbo)
352 {
353         int ret;
354
355         ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
356         if (ret)
357                 return ret;
358
359         drm_gem_vram_unpin_locked(gbo);
360         ttm_bo_unreserve(&gbo->bo);
361
362         return 0;
363 }
364 EXPORT_SYMBOL(drm_gem_vram_unpin);
365
366 static int drm_gem_vram_kmap_locked(struct drm_gem_vram_object *gbo,
367                                     struct dma_buf_map *map)
368 {
369         int ret;
370
371         if (gbo->vmap_use_count > 0)
372                 goto out;
373
374         /*
375          * VRAM helpers unmap the BO only on demand. So the previous
376          * page mapping might still be around. Only vmap if the there's
377          * no mapping present.
378          */
379         if (dma_buf_map_is_null(&gbo->map)) {
380                 ret = ttm_bo_vmap(&gbo->bo, &gbo->map);
381                 if (ret)
382                         return ret;
383         }
384
385 out:
386         ++gbo->vmap_use_count;
387         *map = gbo->map;
388
389         return 0;
390 }
391
392 static void drm_gem_vram_kunmap_locked(struct drm_gem_vram_object *gbo,
393                                        struct dma_buf_map *map)
394 {
395         struct drm_device *dev = gbo->bo.base.dev;
396
397         if (drm_WARN_ON_ONCE(dev, !gbo->vmap_use_count))
398                 return;
399
400         if (drm_WARN_ON_ONCE(dev, !dma_buf_map_is_equal(&gbo->map, map)))
401                 return; /* BUG: map not mapped from this BO */
402
403         if (--gbo->vmap_use_count > 0)
404                 return;
405
406         /*
407          * Permanently mapping and unmapping buffers adds overhead from
408          * updating the page tables and creates debugging output. Therefore,
409          * we delay the actual unmap operation until the BO gets evicted
410          * from memory. See drm_gem_vram_bo_driver_move_notify().
411          */
412 }
413
414 /**
415  * drm_gem_vram_vmap() - Pins and maps a GEM VRAM object into kernel address
416  *                       space
417  * @gbo: The GEM VRAM object to map
418  * @map: Returns the kernel virtual address of the VRAM GEM object's backing
419  *       store.
420  *
421  * The vmap function pins a GEM VRAM object to its current location, either
422  * system or video memory, and maps its buffer into kernel address space.
423  * As pinned object cannot be relocated, you should avoid pinning objects
424  * permanently. Call drm_gem_vram_vunmap() with the returned address to
425  * unmap and unpin the GEM VRAM object.
426  *
427  * Returns:
428  * 0 on success, or a negative error code otherwise.
429  */
430 int drm_gem_vram_vmap(struct drm_gem_vram_object *gbo, struct dma_buf_map *map)
431 {
432         int ret;
433
434         ret = ttm_bo_reserve(&gbo->bo, true, false, NULL);
435         if (ret)
436                 return ret;
437
438         ret = drm_gem_vram_pin_locked(gbo, 0);
439         if (ret)
440                 goto err_ttm_bo_unreserve;
441         ret = drm_gem_vram_kmap_locked(gbo, map);
442         if (ret)
443                 goto err_drm_gem_vram_unpin_locked;
444
445         ttm_bo_unreserve(&gbo->bo);
446
447         return 0;
448
449 err_drm_gem_vram_unpin_locked:
450         drm_gem_vram_unpin_locked(gbo);
451 err_ttm_bo_unreserve:
452         ttm_bo_unreserve(&gbo->bo);
453         return ret;
454 }
455 EXPORT_SYMBOL(drm_gem_vram_vmap);
456
457 /**
458  * drm_gem_vram_vunmap() - Unmaps and unpins a GEM VRAM object
459  * @gbo: The GEM VRAM object to unmap
460  * @map: Kernel virtual address where the VRAM GEM object was mapped
461  *
462  * A call to drm_gem_vram_vunmap() unmaps and unpins a GEM VRAM buffer. See
463  * the documentation for drm_gem_vram_vmap() for more information.
464  */
465 void drm_gem_vram_vunmap(struct drm_gem_vram_object *gbo, struct dma_buf_map *map)
466 {
467         int ret;
468
469         ret = ttm_bo_reserve(&gbo->bo, false, false, NULL);
470         if (WARN_ONCE(ret, "ttm_bo_reserve_failed(): ret=%d\n", ret))
471                 return;
472
473         drm_gem_vram_kunmap_locked(gbo, map);
474         drm_gem_vram_unpin_locked(gbo);
475
476         ttm_bo_unreserve(&gbo->bo);
477 }
478 EXPORT_SYMBOL(drm_gem_vram_vunmap);
479
480 /**
481  * drm_gem_vram_fill_create_dumb() - \
482         Helper for implementing &struct drm_driver.dumb_create
483  * @file:               the DRM file
484  * @dev:                the DRM device
485  * @pg_align:           the buffer's alignment in multiples of the page size
486  * @pitch_align:        the scanline's alignment in powers of 2
487  * @args:               the arguments as provided to \
488                                 &struct drm_driver.dumb_create
489  *
490  * This helper function fills &struct drm_mode_create_dumb, which is used
491  * by &struct drm_driver.dumb_create. Implementations of this interface
492  * should forwards their arguments to this helper, plus the driver-specific
493  * parameters.
494  *
495  * Returns:
496  * 0 on success, or
497  * a negative error code otherwise.
498  */
499 int drm_gem_vram_fill_create_dumb(struct drm_file *file,
500                                   struct drm_device *dev,
501                                   unsigned long pg_align,
502                                   unsigned long pitch_align,
503                                   struct drm_mode_create_dumb *args)
504 {
505         size_t pitch, size;
506         struct drm_gem_vram_object *gbo;
507         int ret;
508         u32 handle;
509
510         pitch = args->width * DIV_ROUND_UP(args->bpp, 8);
511         if (pitch_align) {
512                 if (WARN_ON_ONCE(!is_power_of_2(pitch_align)))
513                         return -EINVAL;
514                 pitch = ALIGN(pitch, pitch_align);
515         }
516         size = pitch * args->height;
517
518         size = roundup(size, PAGE_SIZE);
519         if (!size)
520                 return -EINVAL;
521
522         gbo = drm_gem_vram_create(dev, size, pg_align);
523         if (IS_ERR(gbo))
524                 return PTR_ERR(gbo);
525
526         ret = drm_gem_handle_create(file, &gbo->bo.base, &handle);
527         if (ret)
528                 goto err_drm_gem_object_put;
529
530         drm_gem_object_put(&gbo->bo.base);
531
532         args->pitch = pitch;
533         args->size = size;
534         args->handle = handle;
535
536         return 0;
537
538 err_drm_gem_object_put:
539         drm_gem_object_put(&gbo->bo.base);
540         return ret;
541 }
542 EXPORT_SYMBOL(drm_gem_vram_fill_create_dumb);
543
544 /*
545  * Helpers for struct ttm_device_funcs
546  */
547
548 static bool drm_is_gem_vram(struct ttm_buffer_object *bo)
549 {
550         return (bo->destroy == ttm_buffer_object_destroy);
551 }
552
553 static void drm_gem_vram_bo_driver_evict_flags(struct drm_gem_vram_object *gbo,
554                                                struct ttm_placement *pl)
555 {
556         drm_gem_vram_placement(gbo, DRM_GEM_VRAM_PL_FLAG_SYSTEM);
557         *pl = gbo->placement;
558 }
559
560 static void drm_gem_vram_bo_driver_move_notify(struct drm_gem_vram_object *gbo)
561 {
562         struct ttm_buffer_object *bo = &gbo->bo;
563         struct drm_device *dev = bo->base.dev;
564
565         if (drm_WARN_ON_ONCE(dev, gbo->vmap_use_count))
566                 return;
567
568         ttm_bo_vunmap(bo, &gbo->map);
569         dma_buf_map_clear(&gbo->map); /* explicitly clear mapping for next vmap call */
570 }
571
572 static int drm_gem_vram_bo_driver_move(struct drm_gem_vram_object *gbo,
573                                        bool evict,
574                                        struct ttm_operation_ctx *ctx,
575                                        struct ttm_resource *new_mem)
576 {
577         drm_gem_vram_bo_driver_move_notify(gbo);
578         return ttm_bo_move_memcpy(&gbo->bo, ctx, new_mem);
579 }
580
581 /*
582  * Helpers for struct drm_gem_object_funcs
583  */
584
585 /**
586  * drm_gem_vram_object_free() - \
587         Implements &struct drm_gem_object_funcs.free
588  * @gem:       GEM object. Refers to &struct drm_gem_vram_object.gem
589  */
590 static void drm_gem_vram_object_free(struct drm_gem_object *gem)
591 {
592         struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
593
594         drm_gem_vram_put(gbo);
595 }
596
597 /*
598  * Helpers for dump buffers
599  */
600
601 /**
602  * drm_gem_vram_driver_dumb_create() - \
603         Implements &struct drm_driver.dumb_create
604  * @file:               the DRM file
605  * @dev:                the DRM device
606  * @args:               the arguments as provided to \
607                                 &struct drm_driver.dumb_create
608  *
609  * This function requires the driver to use @drm_device.vram_mm for its
610  * instance of VRAM MM.
611  *
612  * Returns:
613  * 0 on success, or
614  * a negative error code otherwise.
615  */
616 int drm_gem_vram_driver_dumb_create(struct drm_file *file,
617                                     struct drm_device *dev,
618                                     struct drm_mode_create_dumb *args)
619 {
620         if (WARN_ONCE(!dev->vram_mm, "VRAM MM not initialized"))
621                 return -EINVAL;
622
623         return drm_gem_vram_fill_create_dumb(file, dev, 0, 0, args);
624 }
625 EXPORT_SYMBOL(drm_gem_vram_driver_dumb_create);
626
627 /*
628  * Helpers for struct drm_plane_helper_funcs
629  */
630
631 /**
632  * drm_gem_vram_plane_helper_prepare_fb() - \
633  *      Implements &struct drm_plane_helper_funcs.prepare_fb
634  * @plane:      a DRM plane
635  * @new_state:  the plane's new state
636  *
637  * During plane updates, this function sets the plane's fence and
638  * pins the GEM VRAM objects of the plane's new framebuffer to VRAM.
639  * Call drm_gem_vram_plane_helper_cleanup_fb() to unpin them.
640  *
641  * Returns:
642  *      0 on success, or
643  *      a negative errno code otherwise.
644  */
645 int
646 drm_gem_vram_plane_helper_prepare_fb(struct drm_plane *plane,
647                                      struct drm_plane_state *new_state)
648 {
649         size_t i;
650         struct drm_gem_vram_object *gbo;
651         int ret;
652
653         if (!new_state->fb)
654                 return 0;
655
656         for (i = 0; i < ARRAY_SIZE(new_state->fb->obj); ++i) {
657                 if (!new_state->fb->obj[i])
658                         continue;
659                 gbo = drm_gem_vram_of_gem(new_state->fb->obj[i]);
660                 ret = drm_gem_vram_pin(gbo, DRM_GEM_VRAM_PL_FLAG_VRAM);
661                 if (ret)
662                         goto err_drm_gem_vram_unpin;
663         }
664
665         ret = drm_gem_plane_helper_prepare_fb(plane, new_state);
666         if (ret)
667                 goto err_drm_gem_vram_unpin;
668
669         return 0;
670
671 err_drm_gem_vram_unpin:
672         while (i) {
673                 --i;
674                 gbo = drm_gem_vram_of_gem(new_state->fb->obj[i]);
675                 drm_gem_vram_unpin(gbo);
676         }
677         return ret;
678 }
679 EXPORT_SYMBOL(drm_gem_vram_plane_helper_prepare_fb);
680
681 /**
682  * drm_gem_vram_plane_helper_cleanup_fb() - \
683  *      Implements &struct drm_plane_helper_funcs.cleanup_fb
684  * @plane:      a DRM plane
685  * @old_state:  the plane's old state
686  *
687  * During plane updates, this function unpins the GEM VRAM
688  * objects of the plane's old framebuffer from VRAM. Complements
689  * drm_gem_vram_plane_helper_prepare_fb().
690  */
691 void
692 drm_gem_vram_plane_helper_cleanup_fb(struct drm_plane *plane,
693                                      struct drm_plane_state *old_state)
694 {
695         size_t i;
696         struct drm_gem_vram_object *gbo;
697
698         if (!old_state->fb)
699                 return;
700
701         for (i = 0; i < ARRAY_SIZE(old_state->fb->obj); ++i) {
702                 if (!old_state->fb->obj[i])
703                         continue;
704                 gbo = drm_gem_vram_of_gem(old_state->fb->obj[i]);
705                 drm_gem_vram_unpin(gbo);
706         }
707 }
708 EXPORT_SYMBOL(drm_gem_vram_plane_helper_cleanup_fb);
709
710 /*
711  * Helpers for struct drm_simple_display_pipe_funcs
712  */
713
714 /**
715  * drm_gem_vram_simple_display_pipe_prepare_fb() - \
716  *      Implements &struct drm_simple_display_pipe_funcs.prepare_fb
717  * @pipe:       a simple display pipe
718  * @new_state:  the plane's new state
719  *
720  * During plane updates, this function pins the GEM VRAM
721  * objects of the plane's new framebuffer to VRAM. Call
722  * drm_gem_vram_simple_display_pipe_cleanup_fb() to unpin them.
723  *
724  * Returns:
725  *      0 on success, or
726  *      a negative errno code otherwise.
727  */
728 int drm_gem_vram_simple_display_pipe_prepare_fb(
729         struct drm_simple_display_pipe *pipe,
730         struct drm_plane_state *new_state)
731 {
732         return drm_gem_vram_plane_helper_prepare_fb(&pipe->plane, new_state);
733 }
734 EXPORT_SYMBOL(drm_gem_vram_simple_display_pipe_prepare_fb);
735
736 /**
737  * drm_gem_vram_simple_display_pipe_cleanup_fb() - \
738  *      Implements &struct drm_simple_display_pipe_funcs.cleanup_fb
739  * @pipe:       a simple display pipe
740  * @old_state:  the plane's old state
741  *
742  * During plane updates, this function unpins the GEM VRAM
743  * objects of the plane's old framebuffer from VRAM. Complements
744  * drm_gem_vram_simple_display_pipe_prepare_fb().
745  */
746 void drm_gem_vram_simple_display_pipe_cleanup_fb(
747         struct drm_simple_display_pipe *pipe,
748         struct drm_plane_state *old_state)
749 {
750         drm_gem_vram_plane_helper_cleanup_fb(&pipe->plane, old_state);
751 }
752 EXPORT_SYMBOL(drm_gem_vram_simple_display_pipe_cleanup_fb);
753
754 /*
755  * PRIME helpers
756  */
757
758 /**
759  * drm_gem_vram_object_pin() - \
760         Implements &struct drm_gem_object_funcs.pin
761  * @gem:        The GEM object to pin
762  *
763  * Returns:
764  * 0 on success, or
765  * a negative errno code otherwise.
766  */
767 static int drm_gem_vram_object_pin(struct drm_gem_object *gem)
768 {
769         struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
770
771         /* Fbdev console emulation is the use case of these PRIME
772          * helpers. This may involve updating a hardware buffer from
773          * a shadow FB. We pin the buffer to it's current location
774          * (either video RAM or system memory) to prevent it from
775          * being relocated during the update operation. If you require
776          * the buffer to be pinned to VRAM, implement a callback that
777          * sets the flags accordingly.
778          */
779         return drm_gem_vram_pin(gbo, 0);
780 }
781
782 /**
783  * drm_gem_vram_object_unpin() - \
784         Implements &struct drm_gem_object_funcs.unpin
785  * @gem:        The GEM object to unpin
786  */
787 static void drm_gem_vram_object_unpin(struct drm_gem_object *gem)
788 {
789         struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
790
791         drm_gem_vram_unpin(gbo);
792 }
793
794 /**
795  * drm_gem_vram_object_vmap() -
796  *      Implements &struct drm_gem_object_funcs.vmap
797  * @gem: The GEM object to map
798  * @map: Returns the kernel virtual address of the VRAM GEM object's backing
799  *       store.
800  *
801  * Returns:
802  * 0 on success, or a negative error code otherwise.
803  */
804 static int drm_gem_vram_object_vmap(struct drm_gem_object *gem, struct dma_buf_map *map)
805 {
806         struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
807
808         return drm_gem_vram_vmap(gbo, map);
809 }
810
811 /**
812  * drm_gem_vram_object_vunmap() -
813  *      Implements &struct drm_gem_object_funcs.vunmap
814  * @gem: The GEM object to unmap
815  * @map: Kernel virtual address where the VRAM GEM object was mapped
816  */
817 static void drm_gem_vram_object_vunmap(struct drm_gem_object *gem, struct dma_buf_map *map)
818 {
819         struct drm_gem_vram_object *gbo = drm_gem_vram_of_gem(gem);
820
821         drm_gem_vram_vunmap(gbo, map);
822 }
823
824 /*
825  * GEM object funcs
826  */
827
828 static const struct drm_gem_object_funcs drm_gem_vram_object_funcs = {
829         .free   = drm_gem_vram_object_free,
830         .pin    = drm_gem_vram_object_pin,
831         .unpin  = drm_gem_vram_object_unpin,
832         .vmap   = drm_gem_vram_object_vmap,
833         .vunmap = drm_gem_vram_object_vunmap,
834         .mmap   = drm_gem_ttm_mmap,
835         .print_info = drm_gem_ttm_print_info,
836 };
837
838 /*
839  * VRAM memory manager
840  */
841
842 /*
843  * TTM TT
844  */
845
846 static void bo_driver_ttm_tt_destroy(struct ttm_device *bdev, struct ttm_tt *tt)
847 {
848         ttm_tt_destroy_common(bdev, tt);
849         ttm_tt_fini(tt);
850         kfree(tt);
851 }
852
853 /*
854  * TTM BO device
855  */
856
857 static struct ttm_tt *bo_driver_ttm_tt_create(struct ttm_buffer_object *bo,
858                                               uint32_t page_flags)
859 {
860         struct ttm_tt *tt;
861         int ret;
862
863         tt = kzalloc(sizeof(*tt), GFP_KERNEL);
864         if (!tt)
865                 return NULL;
866
867         ret = ttm_tt_init(tt, bo, page_flags, ttm_cached);
868         if (ret < 0)
869                 goto err_ttm_tt_init;
870
871         return tt;
872
873 err_ttm_tt_init:
874         kfree(tt);
875         return NULL;
876 }
877
878 static void bo_driver_evict_flags(struct ttm_buffer_object *bo,
879                                   struct ttm_placement *placement)
880 {
881         struct drm_gem_vram_object *gbo;
882
883         /* TTM may pass BOs that are not GEM VRAM BOs. */
884         if (!drm_is_gem_vram(bo))
885                 return;
886
887         gbo = drm_gem_vram_of_bo(bo);
888
889         drm_gem_vram_bo_driver_evict_flags(gbo, placement);
890 }
891
892 static void bo_driver_delete_mem_notify(struct ttm_buffer_object *bo)
893 {
894         struct drm_gem_vram_object *gbo;
895
896         /* TTM may pass BOs that are not GEM VRAM BOs. */
897         if (!drm_is_gem_vram(bo))
898                 return;
899
900         gbo = drm_gem_vram_of_bo(bo);
901
902         drm_gem_vram_bo_driver_move_notify(gbo);
903 }
904
905 static int bo_driver_move(struct ttm_buffer_object *bo,
906                           bool evict,
907                           struct ttm_operation_ctx *ctx,
908                           struct ttm_resource *new_mem,
909                           struct ttm_place *hop)
910 {
911         struct drm_gem_vram_object *gbo;
912
913         gbo = drm_gem_vram_of_bo(bo);
914
915         return drm_gem_vram_bo_driver_move(gbo, evict, ctx, new_mem);
916 }
917
918 static int bo_driver_io_mem_reserve(struct ttm_device *bdev,
919                                     struct ttm_resource *mem)
920 {
921         struct drm_vram_mm *vmm = drm_vram_mm_of_bdev(bdev);
922
923         switch (mem->mem_type) {
924         case TTM_PL_SYSTEM:     /* nothing to do */
925                 break;
926         case TTM_PL_VRAM:
927                 mem->bus.offset = (mem->start << PAGE_SHIFT) + vmm->vram_base;
928                 mem->bus.is_iomem = true;
929                 mem->bus.caching = ttm_write_combined;
930                 break;
931         default:
932                 return -EINVAL;
933         }
934
935         return 0;
936 }
937
938 static struct ttm_device_funcs bo_driver = {
939         .ttm_tt_create = bo_driver_ttm_tt_create,
940         .ttm_tt_destroy = bo_driver_ttm_tt_destroy,
941         .eviction_valuable = ttm_bo_eviction_valuable,
942         .evict_flags = bo_driver_evict_flags,
943         .move = bo_driver_move,
944         .delete_mem_notify = bo_driver_delete_mem_notify,
945         .io_mem_reserve = bo_driver_io_mem_reserve,
946 };
947
948 /*
949  * struct drm_vram_mm
950  */
951
952 static int drm_vram_mm_debugfs(struct seq_file *m, void *data)
953 {
954         struct drm_info_node *node = (struct drm_info_node *) m->private;
955         struct drm_vram_mm *vmm = node->minor->dev->vram_mm;
956         struct ttm_resource_manager *man = ttm_manager_type(&vmm->bdev, TTM_PL_VRAM);
957         struct drm_printer p = drm_seq_file_printer(m);
958
959         ttm_resource_manager_debug(man, &p);
960         return 0;
961 }
962
963 static const struct drm_info_list drm_vram_mm_debugfs_list[] = {
964         { "vram-mm", drm_vram_mm_debugfs, 0, NULL },
965 };
966
967 /**
968  * drm_vram_mm_debugfs_init() - Register VRAM MM debugfs file.
969  *
970  * @minor: drm minor device.
971  *
972  */
973 void drm_vram_mm_debugfs_init(struct drm_minor *minor)
974 {
975         drm_debugfs_create_files(drm_vram_mm_debugfs_list,
976                                  ARRAY_SIZE(drm_vram_mm_debugfs_list),
977                                  minor->debugfs_root, minor);
978 }
979 EXPORT_SYMBOL(drm_vram_mm_debugfs_init);
980
981 static int drm_vram_mm_init(struct drm_vram_mm *vmm, struct drm_device *dev,
982                             uint64_t vram_base, size_t vram_size)
983 {
984         int ret;
985
986         vmm->vram_base = vram_base;
987         vmm->vram_size = vram_size;
988
989         ret = ttm_device_init(&vmm->bdev, &bo_driver, dev->dev,
990                                  dev->anon_inode->i_mapping,
991                                  dev->vma_offset_manager,
992                                  false, true);
993         if (ret)
994                 return ret;
995
996         ret = ttm_range_man_init(&vmm->bdev, TTM_PL_VRAM,
997                                  false, vram_size >> PAGE_SHIFT);
998         if (ret)
999                 return ret;
1000
1001         return 0;
1002 }
1003
1004 static void drm_vram_mm_cleanup(struct drm_vram_mm *vmm)
1005 {
1006         ttm_range_man_fini(&vmm->bdev, TTM_PL_VRAM);
1007         ttm_device_fini(&vmm->bdev);
1008 }
1009
1010 /*
1011  * Helpers for integration with struct drm_device
1012  */
1013
1014 /* deprecated; use drmm_vram_mm_init() */
1015 struct drm_vram_mm *drm_vram_helper_alloc_mm(
1016         struct drm_device *dev, uint64_t vram_base, size_t vram_size)
1017 {
1018         int ret;
1019
1020         if (WARN_ON(dev->vram_mm))
1021                 return dev->vram_mm;
1022
1023         dev->vram_mm = kzalloc(sizeof(*dev->vram_mm), GFP_KERNEL);
1024         if (!dev->vram_mm)
1025                 return ERR_PTR(-ENOMEM);
1026
1027         ret = drm_vram_mm_init(dev->vram_mm, dev, vram_base, vram_size);
1028         if (ret)
1029                 goto err_kfree;
1030
1031         return dev->vram_mm;
1032
1033 err_kfree:
1034         kfree(dev->vram_mm);
1035         dev->vram_mm = NULL;
1036         return ERR_PTR(ret);
1037 }
1038 EXPORT_SYMBOL(drm_vram_helper_alloc_mm);
1039
1040 void drm_vram_helper_release_mm(struct drm_device *dev)
1041 {
1042         if (!dev->vram_mm)
1043                 return;
1044
1045         drm_vram_mm_cleanup(dev->vram_mm);
1046         kfree(dev->vram_mm);
1047         dev->vram_mm = NULL;
1048 }
1049 EXPORT_SYMBOL(drm_vram_helper_release_mm);
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");