drm/fb-helper: Move generic fbdev emulation into separate source file
[platform/kernel/linux-rpi.git] / drivers / gpu / drm / drm_fb_helper.c
1 /*
2  * Copyright (c) 2006-2009 Red Hat Inc.
3  * Copyright (c) 2006-2008 Intel Corporation
4  * Copyright (c) 2007 Dave Airlie <airlied@linux.ie>
5  *
6  * DRM framebuffer helper functions
7  *
8  * Permission to use, copy, modify, distribute, and sell this software and its
9  * documentation for any purpose is hereby granted without fee, provided that
10  * the above copyright notice appear in all copies and that both that copyright
11  * notice and this permission notice appear in supporting documentation, and
12  * that the name of the copyright holders not be used in advertising or
13  * publicity pertaining to distribution of the software without specific,
14  * written prior permission.  The copyright holders make no representations
15  * about the suitability of this software for any purpose.  It is provided "as
16  * is" without express or implied warranty.
17  *
18  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
19  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
20  * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
21  * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
22  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
23  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24  * OF THIS SOFTWARE.
25  *
26  * Authors:
27  *      Dave Airlie <airlied@linux.ie>
28  *      Jesse Barnes <jesse.barnes@intel.com>
29  */
30 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31
32 #include <linux/console.h>
33 #include <linux/sysrq.h>
34
35 #include <drm/drm_atomic.h>
36 #include <drm/drm_drv.h>
37 #include <drm/drm_fb_helper.h>
38 #include <drm/drm_fourcc.h>
39 #include <drm/drm_framebuffer.h>
40 #include <drm/drm_modeset_helper_vtables.h>
41 #include <drm/drm_print.h>
42 #include <drm/drm_vblank.h>
43
44 #include "drm_internal.h"
45
46 static bool drm_fbdev_emulation = true;
47 module_param_named(fbdev_emulation, drm_fbdev_emulation, bool, 0600);
48 MODULE_PARM_DESC(fbdev_emulation,
49                  "Enable legacy fbdev emulation [default=true]");
50
51 static int drm_fbdev_overalloc = CONFIG_DRM_FBDEV_OVERALLOC;
52 module_param(drm_fbdev_overalloc, int, 0444);
53 MODULE_PARM_DESC(drm_fbdev_overalloc,
54                  "Overallocation of the fbdev buffer (%) [default="
55                  __MODULE_STRING(CONFIG_DRM_FBDEV_OVERALLOC) "]");
56
57 /*
58  * In order to keep user-space compatibility, we want in certain use-cases
59  * to keep leaking the fbdev physical address to the user-space program
60  * handling the fbdev buffer.
61  * This is a bad habit essentially kept into closed source opengl driver
62  * that should really be moved into open-source upstream projects instead
63  * of using legacy physical addresses in user space to communicate with
64  * other out-of-tree kernel modules.
65  *
66  * This module_param *should* be removed as soon as possible and be
67  * considered as a broken and legacy behaviour from a modern fbdev device.
68  */
69 #if IS_ENABLED(CONFIG_DRM_FBDEV_LEAK_PHYS_SMEM)
70 static bool drm_leak_fbdev_smem;
71 module_param_unsafe(drm_leak_fbdev_smem, bool, 0600);
72 MODULE_PARM_DESC(drm_leak_fbdev_smem,
73                  "Allow unsafe leaking fbdev physical smem address [default=false]");
74 #endif
75
76 static LIST_HEAD(kernel_fb_helper_list);
77 static DEFINE_MUTEX(kernel_fb_helper_lock);
78
79 /**
80  * DOC: fbdev helpers
81  *
82  * The fb helper functions are useful to provide an fbdev on top of a drm kernel
83  * mode setting driver. They can be used mostly independently from the crtc
84  * helper functions used by many drivers to implement the kernel mode setting
85  * interfaces.
86  *
87  * Drivers that support a dumb buffer with a virtual address and mmap support,
88  * should try out the generic fbdev emulation using drm_fbdev_generic_setup().
89  * It will automatically set up deferred I/O if the driver requires a shadow
90  * buffer.
91  *
92  * At runtime drivers should restore the fbdev console by using
93  * drm_fb_helper_lastclose() as their &drm_driver.lastclose callback.
94  * They should also notify the fb helper code from updates to the output
95  * configuration by using drm_fb_helper_output_poll_changed() as their
96  * &drm_mode_config_funcs.output_poll_changed callback.
97  *
98  * For suspend/resume consider using drm_mode_config_helper_suspend() and
99  * drm_mode_config_helper_resume() which takes care of fbdev as well.
100  *
101  * All other functions exported by the fb helper library can be used to
102  * implement the fbdev driver interface by the driver.
103  *
104  * It is possible, though perhaps somewhat tricky, to implement race-free
105  * hotplug detection using the fbdev helpers. The drm_fb_helper_prepare()
106  * helper must be called first to initialize the minimum required to make
107  * hotplug detection work. Drivers also need to make sure to properly set up
108  * the &drm_mode_config.funcs member. After calling drm_kms_helper_poll_init()
109  * it is safe to enable interrupts and start processing hotplug events. At the
110  * same time, drivers should initialize all modeset objects such as CRTCs,
111  * encoders and connectors. To finish up the fbdev helper initialization, the
112  * drm_fb_helper_init() function is called. To probe for all attached displays
113  * and set up an initial configuration using the detected hardware, drivers
114  * should call drm_fb_helper_initial_config().
115  *
116  * If &drm_framebuffer_funcs.dirty is set, the
117  * drm_fb_helper_{cfb,sys}_{write,fillrect,copyarea,imageblit} functions will
118  * accumulate changes and schedule &drm_fb_helper.dirty_work to run right
119  * away. This worker then calls the dirty() function ensuring that it will
120  * always run in process context since the fb_*() function could be running in
121  * atomic context. If drm_fb_helper_deferred_io() is used as the deferred_io
122  * callback it will also schedule dirty_work with the damage collected from the
123  * mmap page writes.
124  *
125  * Deferred I/O is not compatible with SHMEM. Such drivers should request an
126  * fbdev shadow buffer and call drm_fbdev_generic_setup() instead.
127  */
128
129 static void drm_fb_helper_restore_lut_atomic(struct drm_crtc *crtc)
130 {
131         uint16_t *r_base, *g_base, *b_base;
132
133         if (crtc->funcs->gamma_set == NULL)
134                 return;
135
136         r_base = crtc->gamma_store;
137         g_base = r_base + crtc->gamma_size;
138         b_base = g_base + crtc->gamma_size;
139
140         crtc->funcs->gamma_set(crtc, r_base, g_base, b_base,
141                                crtc->gamma_size, NULL);
142 }
143
144 /**
145  * drm_fb_helper_debug_enter - implementation for &fb_ops.fb_debug_enter
146  * @info: fbdev registered by the helper
147  */
148 int drm_fb_helper_debug_enter(struct fb_info *info)
149 {
150         struct drm_fb_helper *helper = info->par;
151         const struct drm_crtc_helper_funcs *funcs;
152         struct drm_mode_set *mode_set;
153
154         list_for_each_entry(helper, &kernel_fb_helper_list, kernel_fb_list) {
155                 mutex_lock(&helper->client.modeset_mutex);
156                 drm_client_for_each_modeset(mode_set, &helper->client) {
157                         if (!mode_set->crtc->enabled)
158                                 continue;
159
160                         funcs = mode_set->crtc->helper_private;
161                         if (funcs->mode_set_base_atomic == NULL)
162                                 continue;
163
164                         if (drm_drv_uses_atomic_modeset(mode_set->crtc->dev))
165                                 continue;
166
167                         funcs->mode_set_base_atomic(mode_set->crtc,
168                                                     mode_set->fb,
169                                                     mode_set->x,
170                                                     mode_set->y,
171                                                     ENTER_ATOMIC_MODE_SET);
172                 }
173                 mutex_unlock(&helper->client.modeset_mutex);
174         }
175
176         return 0;
177 }
178 EXPORT_SYMBOL(drm_fb_helper_debug_enter);
179
180 /**
181  * drm_fb_helper_debug_leave - implementation for &fb_ops.fb_debug_leave
182  * @info: fbdev registered by the helper
183  */
184 int drm_fb_helper_debug_leave(struct fb_info *info)
185 {
186         struct drm_fb_helper *helper = info->par;
187         struct drm_client_dev *client = &helper->client;
188         struct drm_device *dev = helper->dev;
189         struct drm_crtc *crtc;
190         const struct drm_crtc_helper_funcs *funcs;
191         struct drm_mode_set *mode_set;
192         struct drm_framebuffer *fb;
193
194         mutex_lock(&client->modeset_mutex);
195         drm_client_for_each_modeset(mode_set, client) {
196                 crtc = mode_set->crtc;
197                 if (drm_drv_uses_atomic_modeset(crtc->dev))
198                         continue;
199
200                 funcs = crtc->helper_private;
201                 fb = crtc->primary->fb;
202
203                 if (!crtc->enabled)
204                         continue;
205
206                 if (!fb) {
207                         drm_err(dev, "no fb to restore?\n");
208                         continue;
209                 }
210
211                 if (funcs->mode_set_base_atomic == NULL)
212                         continue;
213
214                 drm_fb_helper_restore_lut_atomic(mode_set->crtc);
215                 funcs->mode_set_base_atomic(mode_set->crtc, fb, crtc->x,
216                                             crtc->y, LEAVE_ATOMIC_MODE_SET);
217         }
218         mutex_unlock(&client->modeset_mutex);
219
220         return 0;
221 }
222 EXPORT_SYMBOL(drm_fb_helper_debug_leave);
223
224 static int
225 __drm_fb_helper_restore_fbdev_mode_unlocked(struct drm_fb_helper *fb_helper,
226                                             bool force)
227 {
228         bool do_delayed;
229         int ret;
230
231         if (!drm_fbdev_emulation || !fb_helper)
232                 return -ENODEV;
233
234         if (READ_ONCE(fb_helper->deferred_setup))
235                 return 0;
236
237         mutex_lock(&fb_helper->lock);
238         if (force) {
239                 /*
240                  * Yes this is the _locked version which expects the master lock
241                  * to be held. But for forced restores we're intentionally
242                  * racing here, see drm_fb_helper_set_par().
243                  */
244                 ret = drm_client_modeset_commit_locked(&fb_helper->client);
245         } else {
246                 ret = drm_client_modeset_commit(&fb_helper->client);
247         }
248
249         do_delayed = fb_helper->delayed_hotplug;
250         if (do_delayed)
251                 fb_helper->delayed_hotplug = false;
252         mutex_unlock(&fb_helper->lock);
253
254         if (do_delayed)
255                 drm_fb_helper_hotplug_event(fb_helper);
256
257         return ret;
258 }
259
260 /**
261  * drm_fb_helper_restore_fbdev_mode_unlocked - restore fbdev configuration
262  * @fb_helper: driver-allocated fbdev helper, can be NULL
263  *
264  * This should be called from driver's drm &drm_driver.lastclose callback
265  * when implementing an fbcon on top of kms using this helper. This ensures that
266  * the user isn't greeted with a black screen when e.g. X dies.
267  *
268  * RETURNS:
269  * Zero if everything went ok, negative error code otherwise.
270  */
271 int drm_fb_helper_restore_fbdev_mode_unlocked(struct drm_fb_helper *fb_helper)
272 {
273         return __drm_fb_helper_restore_fbdev_mode_unlocked(fb_helper, false);
274 }
275 EXPORT_SYMBOL(drm_fb_helper_restore_fbdev_mode_unlocked);
276
277 #ifdef CONFIG_MAGIC_SYSRQ
278 /* emergency restore, don't bother with error reporting */
279 static void drm_fb_helper_restore_work_fn(struct work_struct *ignored)
280 {
281         struct drm_fb_helper *helper;
282
283         mutex_lock(&kernel_fb_helper_lock);
284         list_for_each_entry(helper, &kernel_fb_helper_list, kernel_fb_list) {
285                 struct drm_device *dev = helper->dev;
286
287                 if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
288                         continue;
289
290                 mutex_lock(&helper->lock);
291                 drm_client_modeset_commit_locked(&helper->client);
292                 mutex_unlock(&helper->lock);
293         }
294         mutex_unlock(&kernel_fb_helper_lock);
295 }
296
297 static DECLARE_WORK(drm_fb_helper_restore_work, drm_fb_helper_restore_work_fn);
298
299 static void drm_fb_helper_sysrq(int dummy1)
300 {
301         schedule_work(&drm_fb_helper_restore_work);
302 }
303
304 static const struct sysrq_key_op sysrq_drm_fb_helper_restore_op = {
305         .handler = drm_fb_helper_sysrq,
306         .help_msg = "force-fb(v)",
307         .action_msg = "Restore framebuffer console",
308 };
309 #else
310 static const struct sysrq_key_op sysrq_drm_fb_helper_restore_op = { };
311 #endif
312
313 static void drm_fb_helper_dpms(struct fb_info *info, int dpms_mode)
314 {
315         struct drm_fb_helper *fb_helper = info->par;
316
317         mutex_lock(&fb_helper->lock);
318         drm_client_modeset_dpms(&fb_helper->client, dpms_mode);
319         mutex_unlock(&fb_helper->lock);
320 }
321
322 /**
323  * drm_fb_helper_blank - implementation for &fb_ops.fb_blank
324  * @blank: desired blanking state
325  * @info: fbdev registered by the helper
326  */
327 int drm_fb_helper_blank(int blank, struct fb_info *info)
328 {
329         if (oops_in_progress)
330                 return -EBUSY;
331
332         switch (blank) {
333         /* Display: On; HSync: On, VSync: On */
334         case FB_BLANK_UNBLANK:
335                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_ON);
336                 break;
337         /* Display: Off; HSync: On, VSync: On */
338         case FB_BLANK_NORMAL:
339                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_STANDBY);
340                 break;
341         /* Display: Off; HSync: Off, VSync: On */
342         case FB_BLANK_HSYNC_SUSPEND:
343                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_STANDBY);
344                 break;
345         /* Display: Off; HSync: On, VSync: Off */
346         case FB_BLANK_VSYNC_SUSPEND:
347                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_SUSPEND);
348                 break;
349         /* Display: Off; HSync: Off, VSync: Off */
350         case FB_BLANK_POWERDOWN:
351                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_OFF);
352                 break;
353         }
354         return 0;
355 }
356 EXPORT_SYMBOL(drm_fb_helper_blank);
357
358 static void drm_fb_helper_resume_worker(struct work_struct *work)
359 {
360         struct drm_fb_helper *helper = container_of(work, struct drm_fb_helper,
361                                                     resume_work);
362
363         console_lock();
364         fb_set_suspend(helper->info, 0);
365         console_unlock();
366 }
367
368 static void drm_fb_helper_damage_work(struct work_struct *work)
369 {
370         struct drm_fb_helper *helper = container_of(work, struct drm_fb_helper, damage_work);
371         struct drm_device *dev = helper->dev;
372         struct drm_clip_rect *clip = &helper->damage_clip;
373         struct drm_clip_rect clip_copy;
374         unsigned long flags;
375         int ret;
376
377         if (drm_WARN_ON_ONCE(dev, !helper->funcs->fb_dirty))
378                 return;
379
380         spin_lock_irqsave(&helper->damage_lock, flags);
381         clip_copy = *clip;
382         clip->x1 = clip->y1 = ~0;
383         clip->x2 = clip->y2 = 0;
384         spin_unlock_irqrestore(&helper->damage_lock, flags);
385
386         ret = helper->funcs->fb_dirty(helper, &clip_copy);
387         if (ret)
388                 goto err;
389
390         return;
391
392 err:
393         /*
394          * Restore damage clip rectangle on errors. The next run
395          * of the damage worker will perform the update.
396          */
397         spin_lock_irqsave(&helper->damage_lock, flags);
398         clip->x1 = min_t(u32, clip->x1, clip_copy.x1);
399         clip->y1 = min_t(u32, clip->y1, clip_copy.y1);
400         clip->x2 = max_t(u32, clip->x2, clip_copy.x2);
401         clip->y2 = max_t(u32, clip->y2, clip_copy.y2);
402         spin_unlock_irqrestore(&helper->damage_lock, flags);
403 }
404
405 /**
406  * drm_fb_helper_prepare - setup a drm_fb_helper structure
407  * @dev: DRM device
408  * @helper: driver-allocated fbdev helper structure to set up
409  * @funcs: pointer to structure of functions associate with this helper
410  *
411  * Sets up the bare minimum to make the framebuffer helper usable. This is
412  * useful to implement race-free initialization of the polling helpers.
413  */
414 void drm_fb_helper_prepare(struct drm_device *dev, struct drm_fb_helper *helper,
415                            const struct drm_fb_helper_funcs *funcs)
416 {
417         INIT_LIST_HEAD(&helper->kernel_fb_list);
418         spin_lock_init(&helper->damage_lock);
419         INIT_WORK(&helper->resume_work, drm_fb_helper_resume_worker);
420         INIT_WORK(&helper->damage_work, drm_fb_helper_damage_work);
421         helper->damage_clip.x1 = helper->damage_clip.y1 = ~0;
422         mutex_init(&helper->lock);
423         helper->funcs = funcs;
424         helper->dev = dev;
425 }
426 EXPORT_SYMBOL(drm_fb_helper_prepare);
427
428 /**
429  * drm_fb_helper_init - initialize a &struct drm_fb_helper
430  * @dev: drm device
431  * @fb_helper: driver-allocated fbdev helper structure to initialize
432  *
433  * This allocates the structures for the fbdev helper with the given limits.
434  * Note that this won't yet touch the hardware (through the driver interfaces)
435  * nor register the fbdev. This is only done in drm_fb_helper_initial_config()
436  * to allow driver writes more control over the exact init sequence.
437  *
438  * Drivers must call drm_fb_helper_prepare() before calling this function.
439  *
440  * RETURNS:
441  * Zero if everything went ok, nonzero otherwise.
442  */
443 int drm_fb_helper_init(struct drm_device *dev,
444                        struct drm_fb_helper *fb_helper)
445 {
446         int ret;
447
448         /*
449          * If this is not the generic fbdev client, initialize a drm_client
450          * without callbacks so we can use the modesets.
451          */
452         if (!fb_helper->client.funcs) {
453                 ret = drm_client_init(dev, &fb_helper->client, "drm_fb_helper", NULL);
454                 if (ret)
455                         return ret;
456         }
457
458         dev->fb_helper = fb_helper;
459
460         return 0;
461 }
462 EXPORT_SYMBOL(drm_fb_helper_init);
463
464 /**
465  * drm_fb_helper_alloc_info - allocate fb_info and some of its members
466  * @fb_helper: driver-allocated fbdev helper
467  *
468  * A helper to alloc fb_info and the members cmap and apertures. Called
469  * by the driver within the fb_probe fb_helper callback function. Drivers do not
470  * need to release the allocated fb_info structure themselves, this is
471  * automatically done when calling drm_fb_helper_fini().
472  *
473  * RETURNS:
474  * fb_info pointer if things went okay, pointer containing error code
475  * otherwise
476  */
477 struct fb_info *drm_fb_helper_alloc_info(struct drm_fb_helper *fb_helper)
478 {
479         struct device *dev = fb_helper->dev->dev;
480         struct fb_info *info;
481         int ret;
482
483         info = framebuffer_alloc(0, dev);
484         if (!info)
485                 return ERR_PTR(-ENOMEM);
486
487         ret = fb_alloc_cmap(&info->cmap, 256, 0);
488         if (ret)
489                 goto err_release;
490
491         /*
492          * TODO: We really should be smarter here and alloc an aperture
493          * for each IORESOURCE_MEM resource helper->dev->dev has and also
494          * init the ranges of the appertures based on the resources.
495          * Note some drivers currently count on there being only 1 empty
496          * aperture and fill this themselves, these will need to be dealt
497          * with somehow when fixing this.
498          */
499         info->apertures = alloc_apertures(1);
500         if (!info->apertures) {
501                 ret = -ENOMEM;
502                 goto err_free_cmap;
503         }
504
505         fb_helper->info = info;
506         info->skip_vt_switch = true;
507
508         return info;
509
510 err_free_cmap:
511         fb_dealloc_cmap(&info->cmap);
512 err_release:
513         framebuffer_release(info);
514         return ERR_PTR(ret);
515 }
516 EXPORT_SYMBOL(drm_fb_helper_alloc_info);
517
518 /**
519  * drm_fb_helper_unregister_info - unregister fb_info framebuffer device
520  * @fb_helper: driver-allocated fbdev helper, can be NULL
521  *
522  * A wrapper around unregister_framebuffer, to release the fb_info
523  * framebuffer device. This must be called before releasing all resources for
524  * @fb_helper by calling drm_fb_helper_fini().
525  */
526 void drm_fb_helper_unregister_info(struct drm_fb_helper *fb_helper)
527 {
528         if (fb_helper && fb_helper->info)
529                 unregister_framebuffer(fb_helper->info);
530 }
531 EXPORT_SYMBOL(drm_fb_helper_unregister_info);
532
533 /**
534  * drm_fb_helper_fini - finialize a &struct drm_fb_helper
535  * @fb_helper: driver-allocated fbdev helper, can be NULL
536  *
537  * This cleans up all remaining resources associated with @fb_helper.
538  */
539 void drm_fb_helper_fini(struct drm_fb_helper *fb_helper)
540 {
541         struct fb_info *info;
542
543         if (!fb_helper)
544                 return;
545
546         fb_helper->dev->fb_helper = NULL;
547
548         if (!drm_fbdev_emulation)
549                 return;
550
551         cancel_work_sync(&fb_helper->resume_work);
552         cancel_work_sync(&fb_helper->damage_work);
553
554         info = fb_helper->info;
555         if (info) {
556                 if (info->cmap.len)
557                         fb_dealloc_cmap(&info->cmap);
558                 framebuffer_release(info);
559         }
560         fb_helper->info = NULL;
561
562         mutex_lock(&kernel_fb_helper_lock);
563         if (!list_empty(&fb_helper->kernel_fb_list)) {
564                 list_del(&fb_helper->kernel_fb_list);
565                 if (list_empty(&kernel_fb_helper_list))
566                         unregister_sysrq_key('v', &sysrq_drm_fb_helper_restore_op);
567         }
568         mutex_unlock(&kernel_fb_helper_lock);
569
570         mutex_destroy(&fb_helper->lock);
571
572         if (!fb_helper->client.funcs)
573                 drm_client_release(&fb_helper->client);
574 }
575 EXPORT_SYMBOL(drm_fb_helper_fini);
576
577 static void drm_fb_helper_damage(struct drm_fb_helper *helper, u32 x, u32 y,
578                                  u32 width, u32 height)
579 {
580         struct drm_clip_rect *clip = &helper->damage_clip;
581         unsigned long flags;
582
583         spin_lock_irqsave(&helper->damage_lock, flags);
584         clip->x1 = min_t(u32, clip->x1, x);
585         clip->y1 = min_t(u32, clip->y1, y);
586         clip->x2 = max_t(u32, clip->x2, x + width);
587         clip->y2 = max_t(u32, clip->y2, y + height);
588         spin_unlock_irqrestore(&helper->damage_lock, flags);
589
590         schedule_work(&helper->damage_work);
591 }
592
593 /*
594  * Convert memory region into area of scanlines and pixels per
595  * scanline. The parameters off and len must not reach beyond
596  * the end of the framebuffer.
597  */
598 static void drm_fb_helper_memory_range_to_clip(struct fb_info *info, off_t off, size_t len,
599                                                struct drm_rect *clip)
600 {
601         off_t end = off + len;
602         u32 x1 = 0;
603         u32 y1 = off / info->fix.line_length;
604         u32 x2 = info->var.xres;
605         u32 y2 = DIV_ROUND_UP(end, info->fix.line_length);
606
607         if ((y2 - y1) == 1) {
608                 /*
609                  * We've only written to a single scanline. Try to reduce
610                  * the number of horizontal pixels that need an update.
611                  */
612                 off_t bit_off = (off % info->fix.line_length) * 8;
613                 off_t bit_end = (end % info->fix.line_length) * 8;
614
615                 x1 = bit_off / info->var.bits_per_pixel;
616                 x2 = DIV_ROUND_UP(bit_end, info->var.bits_per_pixel);
617         }
618
619         drm_rect_init(clip, x1, y1, x2 - x1, y2 - y1);
620 }
621
622 /**
623  * drm_fb_helper_deferred_io() - fbdev deferred_io callback function
624  * @info: fb_info struct pointer
625  * @pagereflist: list of mmap framebuffer pages that have to be flushed
626  *
627  * This function is used as the &fb_deferred_io.deferred_io
628  * callback function for flushing the fbdev mmap writes.
629  */
630 void drm_fb_helper_deferred_io(struct fb_info *info, struct list_head *pagereflist)
631 {
632         struct drm_fb_helper *helper = info->par;
633         unsigned long start, end, min_off, max_off;
634         struct fb_deferred_io_pageref *pageref;
635         struct drm_rect damage_area;
636
637         min_off = ULONG_MAX;
638         max_off = 0;
639         list_for_each_entry(pageref, pagereflist, list) {
640                 start = pageref->offset;
641                 end = start + PAGE_SIZE;
642                 min_off = min(min_off, start);
643                 max_off = max(max_off, end);
644         }
645         if (min_off >= max_off)
646                 return;
647
648         if (helper->funcs->fb_dirty) {
649                 /*
650                  * As we can only track pages, we might reach beyond the end
651                  * of the screen and account for non-existing scanlines. Hence,
652                  * keep the covered memory area within the screen buffer.
653                  */
654                 max_off = min(max_off, info->screen_size);
655
656                 drm_fb_helper_memory_range_to_clip(info, min_off, max_off - min_off, &damage_area);
657                 drm_fb_helper_damage(helper, damage_area.x1, damage_area.y1,
658                                      drm_rect_width(&damage_area),
659                                      drm_rect_height(&damage_area));
660         }
661 }
662 EXPORT_SYMBOL(drm_fb_helper_deferred_io);
663
664 typedef ssize_t (*drm_fb_helper_read_screen)(struct fb_info *info, char __user *buf,
665                                              size_t count, loff_t pos);
666
667 static ssize_t __drm_fb_helper_read(struct fb_info *info, char __user *buf, size_t count,
668                                     loff_t *ppos, drm_fb_helper_read_screen read_screen)
669 {
670         loff_t pos = *ppos;
671         size_t total_size;
672         ssize_t ret;
673
674         if (info->screen_size)
675                 total_size = info->screen_size;
676         else
677                 total_size = info->fix.smem_len;
678
679         if (pos >= total_size)
680                 return 0;
681         if (count >= total_size)
682                 count = total_size;
683         if (total_size - count < pos)
684                 count = total_size - pos;
685
686         if (info->fbops->fb_sync)
687                 info->fbops->fb_sync(info);
688
689         ret = read_screen(info, buf, count, pos);
690         if (ret > 0)
691                 *ppos += ret;
692
693         return ret;
694 }
695
696 typedef ssize_t (*drm_fb_helper_write_screen)(struct fb_info *info, const char __user *buf,
697                                               size_t count, loff_t pos);
698
699 static ssize_t __drm_fb_helper_write(struct fb_info *info, const char __user *buf, size_t count,
700                                      loff_t *ppos, drm_fb_helper_write_screen write_screen)
701 {
702         loff_t pos = *ppos;
703         size_t total_size;
704         ssize_t ret;
705         int err = 0;
706
707         if (info->screen_size)
708                 total_size = info->screen_size;
709         else
710                 total_size = info->fix.smem_len;
711
712         if (pos > total_size)
713                 return -EFBIG;
714         if (count > total_size) {
715                 err = -EFBIG;
716                 count = total_size;
717         }
718         if (total_size - count < pos) {
719                 if (!err)
720                         err = -ENOSPC;
721                 count = total_size - pos;
722         }
723
724         if (info->fbops->fb_sync)
725                 info->fbops->fb_sync(info);
726
727         /*
728          * Copy to framebuffer even if we already logged an error. Emulates
729          * the behavior of the original fbdev implementation.
730          */
731         ret = write_screen(info, buf, count, pos);
732         if (ret < 0)
733                 return ret; /* return last error, if any */
734         else if (!ret)
735                 return err; /* return previous error, if any */
736
737         *ppos += ret;
738
739         return ret;
740 }
741
742 static ssize_t drm_fb_helper_read_screen_buffer(struct fb_info *info, char __user *buf,
743                                                 size_t count, loff_t pos)
744 {
745         const char *src = info->screen_buffer + pos;
746
747         if (copy_to_user(buf, src, count))
748                 return -EFAULT;
749
750         return count;
751 }
752
753 /**
754  * drm_fb_helper_sys_read - Implements struct &fb_ops.fb_read for system memory
755  * @info: fb_info struct pointer
756  * @buf: userspace buffer to read from framebuffer memory
757  * @count: number of bytes to read from framebuffer memory
758  * @ppos: read offset within framebuffer memory
759  *
760  * Returns:
761  * The number of bytes read on success, or an error code otherwise.
762  */
763 ssize_t drm_fb_helper_sys_read(struct fb_info *info, char __user *buf,
764                                size_t count, loff_t *ppos)
765 {
766         return __drm_fb_helper_read(info, buf, count, ppos, drm_fb_helper_read_screen_buffer);
767 }
768 EXPORT_SYMBOL(drm_fb_helper_sys_read);
769
770 static ssize_t drm_fb_helper_write_screen_buffer(struct fb_info *info, const char __user *buf,
771                                                  size_t count, loff_t pos)
772 {
773         char *dst = info->screen_buffer + pos;
774
775         if (copy_from_user(dst, buf, count))
776                 return -EFAULT;
777
778         return count;
779 }
780
781 /**
782  * drm_fb_helper_sys_write - Implements struct &fb_ops.fb_write for system memory
783  * @info: fb_info struct pointer
784  * @buf: userspace buffer to write to framebuffer memory
785  * @count: number of bytes to write to framebuffer memory
786  * @ppos: write offset within framebuffer memory
787  *
788  * Returns:
789  * The number of bytes written on success, or an error code otherwise.
790  */
791 ssize_t drm_fb_helper_sys_write(struct fb_info *info, const char __user *buf,
792                                 size_t count, loff_t *ppos)
793 {
794         struct drm_fb_helper *helper = info->par;
795         loff_t pos = *ppos;
796         ssize_t ret;
797         struct drm_rect damage_area;
798
799         ret = __drm_fb_helper_write(info, buf, count, ppos, drm_fb_helper_write_screen_buffer);
800         if (ret <= 0)
801                 return ret;
802
803         if (helper->funcs->fb_dirty) {
804                 drm_fb_helper_memory_range_to_clip(info, pos, ret, &damage_area);
805                 drm_fb_helper_damage(helper, damage_area.x1, damage_area.y1,
806                                      drm_rect_width(&damage_area),
807                                      drm_rect_height(&damage_area));
808         }
809
810         return ret;
811 }
812 EXPORT_SYMBOL(drm_fb_helper_sys_write);
813
814 /**
815  * drm_fb_helper_sys_fillrect - wrapper around sys_fillrect
816  * @info: fbdev registered by the helper
817  * @rect: info about rectangle to fill
818  *
819  * A wrapper around sys_fillrect implemented by fbdev core
820  */
821 void drm_fb_helper_sys_fillrect(struct fb_info *info,
822                                 const struct fb_fillrect *rect)
823 {
824         struct drm_fb_helper *helper = info->par;
825
826         sys_fillrect(info, rect);
827
828         if (helper->funcs->fb_dirty)
829                 drm_fb_helper_damage(helper, rect->dx, rect->dy, rect->width, rect->height);
830 }
831 EXPORT_SYMBOL(drm_fb_helper_sys_fillrect);
832
833 /**
834  * drm_fb_helper_sys_copyarea - wrapper around sys_copyarea
835  * @info: fbdev registered by the helper
836  * @area: info about area to copy
837  *
838  * A wrapper around sys_copyarea implemented by fbdev core
839  */
840 void drm_fb_helper_sys_copyarea(struct fb_info *info,
841                                 const struct fb_copyarea *area)
842 {
843         struct drm_fb_helper *helper = info->par;
844
845         sys_copyarea(info, area);
846
847         if (helper->funcs->fb_dirty)
848                 drm_fb_helper_damage(helper, area->dx, area->dy, area->width, area->height);
849 }
850 EXPORT_SYMBOL(drm_fb_helper_sys_copyarea);
851
852 /**
853  * drm_fb_helper_sys_imageblit - wrapper around sys_imageblit
854  * @info: fbdev registered by the helper
855  * @image: info about image to blit
856  *
857  * A wrapper around sys_imageblit implemented by fbdev core
858  */
859 void drm_fb_helper_sys_imageblit(struct fb_info *info,
860                                  const struct fb_image *image)
861 {
862         struct drm_fb_helper *helper = info->par;
863
864         sys_imageblit(info, image);
865
866         if (helper->funcs->fb_dirty)
867                 drm_fb_helper_damage(helper, image->dx, image->dy, image->width, image->height);
868 }
869 EXPORT_SYMBOL(drm_fb_helper_sys_imageblit);
870
871 static ssize_t fb_read_screen_base(struct fb_info *info, char __user *buf, size_t count,
872                                    loff_t pos)
873 {
874         const char __iomem *src = info->screen_base + pos;
875         size_t alloc_size = min_t(size_t, count, PAGE_SIZE);
876         ssize_t ret = 0;
877         int err = 0;
878         char *tmp;
879
880         tmp = kmalloc(alloc_size, GFP_KERNEL);
881         if (!tmp)
882                 return -ENOMEM;
883
884         while (count) {
885                 size_t c = min_t(size_t, count, alloc_size);
886
887                 memcpy_fromio(tmp, src, c);
888                 if (copy_to_user(buf, tmp, c)) {
889                         err = -EFAULT;
890                         break;
891                 }
892
893                 src += c;
894                 buf += c;
895                 ret += c;
896                 count -= c;
897         }
898
899         kfree(tmp);
900
901         return ret ? ret : err;
902 }
903
904 /**
905  * drm_fb_helper_cfb_read - Implements struct &fb_ops.fb_read for I/O memory
906  * @info: fb_info struct pointer
907  * @buf: userspace buffer to read from framebuffer memory
908  * @count: number of bytes to read from framebuffer memory
909  * @ppos: read offset within framebuffer memory
910  *
911  * Returns:
912  * The number of bytes read on success, or an error code otherwise.
913  */
914 ssize_t drm_fb_helper_cfb_read(struct fb_info *info, char __user *buf,
915                                size_t count, loff_t *ppos)
916 {
917         return __drm_fb_helper_read(info, buf, count, ppos, fb_read_screen_base);
918 }
919 EXPORT_SYMBOL(drm_fb_helper_cfb_read);
920
921 static ssize_t fb_write_screen_base(struct fb_info *info, const char __user *buf, size_t count,
922                                     loff_t pos)
923 {
924         char __iomem *dst = info->screen_base + pos;
925         size_t alloc_size = min_t(size_t, count, PAGE_SIZE);
926         ssize_t ret = 0;
927         int err = 0;
928         u8 *tmp;
929
930         tmp = kmalloc(alloc_size, GFP_KERNEL);
931         if (!tmp)
932                 return -ENOMEM;
933
934         while (count) {
935                 size_t c = min_t(size_t, count, alloc_size);
936
937                 if (copy_from_user(tmp, buf, c)) {
938                         err = -EFAULT;
939                         break;
940                 }
941                 memcpy_toio(dst, tmp, c);
942
943                 dst += c;
944                 buf += c;
945                 ret += c;
946                 count -= c;
947         }
948
949         kfree(tmp);
950
951         return ret ? ret : err;
952 }
953
954 /**
955  * drm_fb_helper_cfb_write - Implements struct &fb_ops.fb_write for I/O memory
956  * @info: fb_info struct pointer
957  * @buf: userspace buffer to write to framebuffer memory
958  * @count: number of bytes to write to framebuffer memory
959  * @ppos: write offset within framebuffer memory
960  *
961  * Returns:
962  * The number of bytes written on success, or an error code otherwise.
963  */
964 ssize_t drm_fb_helper_cfb_write(struct fb_info *info, const char __user *buf,
965                                 size_t count, loff_t *ppos)
966 {
967         struct drm_fb_helper *helper = info->par;
968         loff_t pos = *ppos;
969         ssize_t ret;
970         struct drm_rect damage_area;
971
972         ret = __drm_fb_helper_write(info, buf, count, ppos, fb_write_screen_base);
973         if (ret <= 0)
974                 return ret;
975
976         if (helper->funcs->fb_dirty) {
977                 drm_fb_helper_memory_range_to_clip(info, pos, ret, &damage_area);
978                 drm_fb_helper_damage(helper, damage_area.x1, damage_area.y1,
979                                      drm_rect_width(&damage_area),
980                                      drm_rect_height(&damage_area));
981         }
982
983         return ret;
984 }
985 EXPORT_SYMBOL(drm_fb_helper_cfb_write);
986
987 /**
988  * drm_fb_helper_cfb_fillrect - wrapper around cfb_fillrect
989  * @info: fbdev registered by the helper
990  * @rect: info about rectangle to fill
991  *
992  * A wrapper around cfb_fillrect implemented by fbdev core
993  */
994 void drm_fb_helper_cfb_fillrect(struct fb_info *info,
995                                 const struct fb_fillrect *rect)
996 {
997         struct drm_fb_helper *helper = info->par;
998
999         cfb_fillrect(info, rect);
1000
1001         if (helper->funcs->fb_dirty)
1002                 drm_fb_helper_damage(helper, rect->dx, rect->dy, rect->width, rect->height);
1003 }
1004 EXPORT_SYMBOL(drm_fb_helper_cfb_fillrect);
1005
1006 /**
1007  * drm_fb_helper_cfb_copyarea - wrapper around cfb_copyarea
1008  * @info: fbdev registered by the helper
1009  * @area: info about area to copy
1010  *
1011  * A wrapper around cfb_copyarea implemented by fbdev core
1012  */
1013 void drm_fb_helper_cfb_copyarea(struct fb_info *info,
1014                                 const struct fb_copyarea *area)
1015 {
1016         struct drm_fb_helper *helper = info->par;
1017
1018         cfb_copyarea(info, area);
1019
1020         if (helper->funcs->fb_dirty)
1021                 drm_fb_helper_damage(helper, area->dx, area->dy, area->width, area->height);
1022 }
1023 EXPORT_SYMBOL(drm_fb_helper_cfb_copyarea);
1024
1025 /**
1026  * drm_fb_helper_cfb_imageblit - wrapper around cfb_imageblit
1027  * @info: fbdev registered by the helper
1028  * @image: info about image to blit
1029  *
1030  * A wrapper around cfb_imageblit implemented by fbdev core
1031  */
1032 void drm_fb_helper_cfb_imageblit(struct fb_info *info,
1033                                  const struct fb_image *image)
1034 {
1035         struct drm_fb_helper *helper = info->par;
1036
1037         cfb_imageblit(info, image);
1038
1039         if (helper->funcs->fb_dirty)
1040                 drm_fb_helper_damage(helper, image->dx, image->dy, image->width, image->height);
1041 }
1042 EXPORT_SYMBOL(drm_fb_helper_cfb_imageblit);
1043
1044 /**
1045  * drm_fb_helper_set_suspend - wrapper around fb_set_suspend
1046  * @fb_helper: driver-allocated fbdev helper, can be NULL
1047  * @suspend: whether to suspend or resume
1048  *
1049  * A wrapper around fb_set_suspend implemented by fbdev core.
1050  * Use drm_fb_helper_set_suspend_unlocked() if you don't need to take
1051  * the lock yourself
1052  */
1053 void drm_fb_helper_set_suspend(struct drm_fb_helper *fb_helper, bool suspend)
1054 {
1055         if (fb_helper && fb_helper->info)
1056                 fb_set_suspend(fb_helper->info, suspend);
1057 }
1058 EXPORT_SYMBOL(drm_fb_helper_set_suspend);
1059
1060 /**
1061  * drm_fb_helper_set_suspend_unlocked - wrapper around fb_set_suspend that also
1062  *                                      takes the console lock
1063  * @fb_helper: driver-allocated fbdev helper, can be NULL
1064  * @suspend: whether to suspend or resume
1065  *
1066  * A wrapper around fb_set_suspend() that takes the console lock. If the lock
1067  * isn't available on resume, a worker is tasked with waiting for the lock
1068  * to become available. The console lock can be pretty contented on resume
1069  * due to all the printk activity.
1070  *
1071  * This function can be called multiple times with the same state since
1072  * &fb_info.state is checked to see if fbdev is running or not before locking.
1073  *
1074  * Use drm_fb_helper_set_suspend() if you need to take the lock yourself.
1075  */
1076 void drm_fb_helper_set_suspend_unlocked(struct drm_fb_helper *fb_helper,
1077                                         bool suspend)
1078 {
1079         if (!fb_helper || !fb_helper->info)
1080                 return;
1081
1082         /* make sure there's no pending/ongoing resume */
1083         flush_work(&fb_helper->resume_work);
1084
1085         if (suspend) {
1086                 if (fb_helper->info->state != FBINFO_STATE_RUNNING)
1087                         return;
1088
1089                 console_lock();
1090
1091         } else {
1092                 if (fb_helper->info->state == FBINFO_STATE_RUNNING)
1093                         return;
1094
1095                 if (!console_trylock()) {
1096                         schedule_work(&fb_helper->resume_work);
1097                         return;
1098                 }
1099         }
1100
1101         fb_set_suspend(fb_helper->info, suspend);
1102         console_unlock();
1103 }
1104 EXPORT_SYMBOL(drm_fb_helper_set_suspend_unlocked);
1105
1106 static int setcmap_pseudo_palette(struct fb_cmap *cmap, struct fb_info *info)
1107 {
1108         u32 *palette = (u32 *)info->pseudo_palette;
1109         int i;
1110
1111         if (cmap->start + cmap->len > 16)
1112                 return -EINVAL;
1113
1114         for (i = 0; i < cmap->len; ++i) {
1115                 u16 red = cmap->red[i];
1116                 u16 green = cmap->green[i];
1117                 u16 blue = cmap->blue[i];
1118                 u32 value;
1119
1120                 red >>= 16 - info->var.red.length;
1121                 green >>= 16 - info->var.green.length;
1122                 blue >>= 16 - info->var.blue.length;
1123                 value = (red << info->var.red.offset) |
1124                         (green << info->var.green.offset) |
1125                         (blue << info->var.blue.offset);
1126                 if (info->var.transp.length > 0) {
1127                         u32 mask = (1 << info->var.transp.length) - 1;
1128
1129                         mask <<= info->var.transp.offset;
1130                         value |= mask;
1131                 }
1132                 palette[cmap->start + i] = value;
1133         }
1134
1135         return 0;
1136 }
1137
1138 static int setcmap_legacy(struct fb_cmap *cmap, struct fb_info *info)
1139 {
1140         struct drm_fb_helper *fb_helper = info->par;
1141         struct drm_mode_set *modeset;
1142         struct drm_crtc *crtc;
1143         u16 *r, *g, *b;
1144         int ret = 0;
1145
1146         drm_modeset_lock_all(fb_helper->dev);
1147         drm_client_for_each_modeset(modeset, &fb_helper->client) {
1148                 crtc = modeset->crtc;
1149                 if (!crtc->funcs->gamma_set || !crtc->gamma_size) {
1150                         ret = -EINVAL;
1151                         goto out;
1152                 }
1153
1154                 if (cmap->start + cmap->len > crtc->gamma_size) {
1155                         ret = -EINVAL;
1156                         goto out;
1157                 }
1158
1159                 r = crtc->gamma_store;
1160                 g = r + crtc->gamma_size;
1161                 b = g + crtc->gamma_size;
1162
1163                 memcpy(r + cmap->start, cmap->red, cmap->len * sizeof(*r));
1164                 memcpy(g + cmap->start, cmap->green, cmap->len * sizeof(*g));
1165                 memcpy(b + cmap->start, cmap->blue, cmap->len * sizeof(*b));
1166
1167                 ret = crtc->funcs->gamma_set(crtc, r, g, b,
1168                                              crtc->gamma_size, NULL);
1169                 if (ret)
1170                         goto out;
1171         }
1172 out:
1173         drm_modeset_unlock_all(fb_helper->dev);
1174
1175         return ret;
1176 }
1177
1178 static struct drm_property_blob *setcmap_new_gamma_lut(struct drm_crtc *crtc,
1179                                                        struct fb_cmap *cmap)
1180 {
1181         struct drm_device *dev = crtc->dev;
1182         struct drm_property_blob *gamma_lut;
1183         struct drm_color_lut *lut;
1184         int size = crtc->gamma_size;
1185         int i;
1186
1187         if (!size || cmap->start + cmap->len > size)
1188                 return ERR_PTR(-EINVAL);
1189
1190         gamma_lut = drm_property_create_blob(dev, sizeof(*lut) * size, NULL);
1191         if (IS_ERR(gamma_lut))
1192                 return gamma_lut;
1193
1194         lut = gamma_lut->data;
1195         if (cmap->start || cmap->len != size) {
1196                 u16 *r = crtc->gamma_store;
1197                 u16 *g = r + crtc->gamma_size;
1198                 u16 *b = g + crtc->gamma_size;
1199
1200                 for (i = 0; i < cmap->start; i++) {
1201                         lut[i].red = r[i];
1202                         lut[i].green = g[i];
1203                         lut[i].blue = b[i];
1204                 }
1205                 for (i = cmap->start + cmap->len; i < size; i++) {
1206                         lut[i].red = r[i];
1207                         lut[i].green = g[i];
1208                         lut[i].blue = b[i];
1209                 }
1210         }
1211
1212         for (i = 0; i < cmap->len; i++) {
1213                 lut[cmap->start + i].red = cmap->red[i];
1214                 lut[cmap->start + i].green = cmap->green[i];
1215                 lut[cmap->start + i].blue = cmap->blue[i];
1216         }
1217
1218         return gamma_lut;
1219 }
1220
1221 static int setcmap_atomic(struct fb_cmap *cmap, struct fb_info *info)
1222 {
1223         struct drm_fb_helper *fb_helper = info->par;
1224         struct drm_device *dev = fb_helper->dev;
1225         struct drm_property_blob *gamma_lut = NULL;
1226         struct drm_modeset_acquire_ctx ctx;
1227         struct drm_crtc_state *crtc_state;
1228         struct drm_atomic_state *state;
1229         struct drm_mode_set *modeset;
1230         struct drm_crtc *crtc;
1231         u16 *r, *g, *b;
1232         bool replaced;
1233         int ret = 0;
1234
1235         drm_modeset_acquire_init(&ctx, 0);
1236
1237         state = drm_atomic_state_alloc(dev);
1238         if (!state) {
1239                 ret = -ENOMEM;
1240                 goto out_ctx;
1241         }
1242
1243         state->acquire_ctx = &ctx;
1244 retry:
1245         drm_client_for_each_modeset(modeset, &fb_helper->client) {
1246                 crtc = modeset->crtc;
1247
1248                 if (!gamma_lut)
1249                         gamma_lut = setcmap_new_gamma_lut(crtc, cmap);
1250                 if (IS_ERR(gamma_lut)) {
1251                         ret = PTR_ERR(gamma_lut);
1252                         gamma_lut = NULL;
1253                         goto out_state;
1254                 }
1255
1256                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
1257                 if (IS_ERR(crtc_state)) {
1258                         ret = PTR_ERR(crtc_state);
1259                         goto out_state;
1260                 }
1261
1262                 /*
1263                  * FIXME: This always uses gamma_lut. Some HW have only
1264                  * degamma_lut, in which case we should reset gamma_lut and set
1265                  * degamma_lut. See drm_crtc_legacy_gamma_set().
1266                  */
1267                 replaced  = drm_property_replace_blob(&crtc_state->degamma_lut,
1268                                                       NULL);
1269                 replaced |= drm_property_replace_blob(&crtc_state->ctm, NULL);
1270                 replaced |= drm_property_replace_blob(&crtc_state->gamma_lut,
1271                                                       gamma_lut);
1272                 crtc_state->color_mgmt_changed |= replaced;
1273         }
1274
1275         ret = drm_atomic_commit(state);
1276         if (ret)
1277                 goto out_state;
1278
1279         drm_client_for_each_modeset(modeset, &fb_helper->client) {
1280                 crtc = modeset->crtc;
1281
1282                 r = crtc->gamma_store;
1283                 g = r + crtc->gamma_size;
1284                 b = g + crtc->gamma_size;
1285
1286                 memcpy(r + cmap->start, cmap->red, cmap->len * sizeof(*r));
1287                 memcpy(g + cmap->start, cmap->green, cmap->len * sizeof(*g));
1288                 memcpy(b + cmap->start, cmap->blue, cmap->len * sizeof(*b));
1289         }
1290
1291 out_state:
1292         if (ret == -EDEADLK)
1293                 goto backoff;
1294
1295         drm_property_blob_put(gamma_lut);
1296         drm_atomic_state_put(state);
1297 out_ctx:
1298         drm_modeset_drop_locks(&ctx);
1299         drm_modeset_acquire_fini(&ctx);
1300
1301         return ret;
1302
1303 backoff:
1304         drm_atomic_state_clear(state);
1305         drm_modeset_backoff(&ctx);
1306         goto retry;
1307 }
1308
1309 /**
1310  * drm_fb_helper_setcmap - implementation for &fb_ops.fb_setcmap
1311  * @cmap: cmap to set
1312  * @info: fbdev registered by the helper
1313  */
1314 int drm_fb_helper_setcmap(struct fb_cmap *cmap, struct fb_info *info)
1315 {
1316         struct drm_fb_helper *fb_helper = info->par;
1317         struct drm_device *dev = fb_helper->dev;
1318         int ret;
1319
1320         if (oops_in_progress)
1321                 return -EBUSY;
1322
1323         mutex_lock(&fb_helper->lock);
1324
1325         if (!drm_master_internal_acquire(dev)) {
1326                 ret = -EBUSY;
1327                 goto unlock;
1328         }
1329
1330         mutex_lock(&fb_helper->client.modeset_mutex);
1331         if (info->fix.visual == FB_VISUAL_TRUECOLOR)
1332                 ret = setcmap_pseudo_palette(cmap, info);
1333         else if (drm_drv_uses_atomic_modeset(fb_helper->dev))
1334                 ret = setcmap_atomic(cmap, info);
1335         else
1336                 ret = setcmap_legacy(cmap, info);
1337         mutex_unlock(&fb_helper->client.modeset_mutex);
1338
1339         drm_master_internal_release(dev);
1340 unlock:
1341         mutex_unlock(&fb_helper->lock);
1342
1343         return ret;
1344 }
1345 EXPORT_SYMBOL(drm_fb_helper_setcmap);
1346
1347 /**
1348  * drm_fb_helper_ioctl - legacy ioctl implementation
1349  * @info: fbdev registered by the helper
1350  * @cmd: ioctl command
1351  * @arg: ioctl argument
1352  *
1353  * A helper to implement the standard fbdev ioctl. Only
1354  * FBIO_WAITFORVSYNC is implemented for now.
1355  */
1356 int drm_fb_helper_ioctl(struct fb_info *info, unsigned int cmd,
1357                         unsigned long arg)
1358 {
1359         struct drm_fb_helper *fb_helper = info->par;
1360         struct drm_device *dev = fb_helper->dev;
1361         struct drm_crtc *crtc;
1362         int ret = 0;
1363
1364         mutex_lock(&fb_helper->lock);
1365         if (!drm_master_internal_acquire(dev)) {
1366                 ret = -EBUSY;
1367                 goto unlock;
1368         }
1369
1370         switch (cmd) {
1371         case FBIO_WAITFORVSYNC:
1372                 /*
1373                  * Only consider the first CRTC.
1374                  *
1375                  * This ioctl is supposed to take the CRTC number as
1376                  * an argument, but in fbdev times, what that number
1377                  * was supposed to be was quite unclear, different
1378                  * drivers were passing that argument differently
1379                  * (some by reference, some by value), and most of the
1380                  * userspace applications were just hardcoding 0 as an
1381                  * argument.
1382                  *
1383                  * The first CRTC should be the integrated panel on
1384                  * most drivers, so this is the best choice we can
1385                  * make. If we're not smart enough here, one should
1386                  * just consider switch the userspace to KMS.
1387                  */
1388                 crtc = fb_helper->client.modesets[0].crtc;
1389
1390                 /*
1391                  * Only wait for a vblank event if the CRTC is
1392                  * enabled, otherwise just don't do anythintg,
1393                  * not even report an error.
1394                  */
1395                 ret = drm_crtc_vblank_get(crtc);
1396                 if (!ret) {
1397                         drm_crtc_wait_one_vblank(crtc);
1398                         drm_crtc_vblank_put(crtc);
1399                 }
1400
1401                 ret = 0;
1402                 break;
1403         default:
1404                 ret = -ENOTTY;
1405         }
1406
1407         drm_master_internal_release(dev);
1408 unlock:
1409         mutex_unlock(&fb_helper->lock);
1410         return ret;
1411 }
1412 EXPORT_SYMBOL(drm_fb_helper_ioctl);
1413
1414 static bool drm_fb_pixel_format_equal(const struct fb_var_screeninfo *var_1,
1415                                       const struct fb_var_screeninfo *var_2)
1416 {
1417         return var_1->bits_per_pixel == var_2->bits_per_pixel &&
1418                var_1->grayscale == var_2->grayscale &&
1419                var_1->red.offset == var_2->red.offset &&
1420                var_1->red.length == var_2->red.length &&
1421                var_1->red.msb_right == var_2->red.msb_right &&
1422                var_1->green.offset == var_2->green.offset &&
1423                var_1->green.length == var_2->green.length &&
1424                var_1->green.msb_right == var_2->green.msb_right &&
1425                var_1->blue.offset == var_2->blue.offset &&
1426                var_1->blue.length == var_2->blue.length &&
1427                var_1->blue.msb_right == var_2->blue.msb_right &&
1428                var_1->transp.offset == var_2->transp.offset &&
1429                var_1->transp.length == var_2->transp.length &&
1430                var_1->transp.msb_right == var_2->transp.msb_right;
1431 }
1432
1433 static void drm_fb_helper_fill_pixel_fmt(struct fb_var_screeninfo *var,
1434                                          const struct drm_format_info *format)
1435 {
1436         u8 depth = format->depth;
1437
1438         if (format->is_color_indexed) {
1439                 var->red.offset = 0;
1440                 var->green.offset = 0;
1441                 var->blue.offset = 0;
1442                 var->red.length = depth;
1443                 var->green.length = depth;
1444                 var->blue.length = depth;
1445                 var->transp.offset = 0;
1446                 var->transp.length = 0;
1447                 return;
1448         }
1449
1450         switch (depth) {
1451         case 15:
1452                 var->red.offset = 10;
1453                 var->green.offset = 5;
1454                 var->blue.offset = 0;
1455                 var->red.length = 5;
1456                 var->green.length = 5;
1457                 var->blue.length = 5;
1458                 var->transp.offset = 15;
1459                 var->transp.length = 1;
1460                 break;
1461         case 16:
1462                 var->red.offset = 11;
1463                 var->green.offset = 5;
1464                 var->blue.offset = 0;
1465                 var->red.length = 5;
1466                 var->green.length = 6;
1467                 var->blue.length = 5;
1468                 var->transp.offset = 0;
1469                 break;
1470         case 24:
1471                 var->red.offset = 16;
1472                 var->green.offset = 8;
1473                 var->blue.offset = 0;
1474                 var->red.length = 8;
1475                 var->green.length = 8;
1476                 var->blue.length = 8;
1477                 var->transp.offset = 0;
1478                 var->transp.length = 0;
1479                 break;
1480         case 32:
1481                 var->red.offset = 16;
1482                 var->green.offset = 8;
1483                 var->blue.offset = 0;
1484                 var->red.length = 8;
1485                 var->green.length = 8;
1486                 var->blue.length = 8;
1487                 var->transp.offset = 24;
1488                 var->transp.length = 8;
1489                 break;
1490         default:
1491                 break;
1492         }
1493 }
1494
1495 /**
1496  * drm_fb_helper_check_var - implementation for &fb_ops.fb_check_var
1497  * @var: screeninfo to check
1498  * @info: fbdev registered by the helper
1499  */
1500 int drm_fb_helper_check_var(struct fb_var_screeninfo *var,
1501                             struct fb_info *info)
1502 {
1503         struct drm_fb_helper *fb_helper = info->par;
1504         struct drm_framebuffer *fb = fb_helper->fb;
1505         const struct drm_format_info *format = fb->format;
1506         struct drm_device *dev = fb_helper->dev;
1507         unsigned int bpp;
1508
1509         if (in_dbg_master())
1510                 return -EINVAL;
1511
1512         if (var->pixclock != 0) {
1513                 drm_dbg_kms(dev, "fbdev emulation doesn't support changing the pixel clock, value of pixclock is ignored\n");
1514                 var->pixclock = 0;
1515         }
1516
1517         switch (format->format) {
1518         case DRM_FORMAT_C1:
1519         case DRM_FORMAT_C2:
1520         case DRM_FORMAT_C4:
1521                 /* supported format with sub-byte pixels */
1522                 break;
1523
1524         default:
1525                 if ((drm_format_info_block_width(format, 0) > 1) ||
1526                     (drm_format_info_block_height(format, 0) > 1))
1527                         return -EINVAL;
1528                 break;
1529         }
1530
1531         /*
1532          * Changes struct fb_var_screeninfo are currently not pushed back
1533          * to KMS, hence fail if different settings are requested.
1534          */
1535         bpp = drm_format_info_bpp(format, 0);
1536         if (var->bits_per_pixel > bpp ||
1537             var->xres > fb->width || var->yres > fb->height ||
1538             var->xres_virtual > fb->width || var->yres_virtual > fb->height) {
1539                 drm_dbg_kms(dev, "fb requested width/height/bpp can't fit in current fb "
1540                           "request %dx%d-%d (virtual %dx%d) > %dx%d-%d\n",
1541                           var->xres, var->yres, var->bits_per_pixel,
1542                           var->xres_virtual, var->yres_virtual,
1543                           fb->width, fb->height, bpp);
1544                 return -EINVAL;
1545         }
1546
1547         /*
1548          * Workaround for SDL 1.2, which is known to be setting all pixel format
1549          * fields values to zero in some cases. We treat this situation as a
1550          * kind of "use some reasonable autodetected values".
1551          */
1552         if (!var->red.offset     && !var->green.offset    &&
1553             !var->blue.offset    && !var->transp.offset   &&
1554             !var->red.length     && !var->green.length    &&
1555             !var->blue.length    && !var->transp.length   &&
1556             !var->red.msb_right  && !var->green.msb_right &&
1557             !var->blue.msb_right && !var->transp.msb_right) {
1558                 drm_fb_helper_fill_pixel_fmt(var, format);
1559         }
1560
1561         /*
1562          * Likewise, bits_per_pixel should be rounded up to a supported value.
1563          */
1564         var->bits_per_pixel = bpp;
1565
1566         /*
1567          * drm fbdev emulation doesn't support changing the pixel format at all,
1568          * so reject all pixel format changing requests.
1569          */
1570         if (!drm_fb_pixel_format_equal(var, &info->var)) {
1571                 drm_dbg_kms(dev, "fbdev emulation doesn't support changing the pixel format\n");
1572                 return -EINVAL;
1573         }
1574
1575         return 0;
1576 }
1577 EXPORT_SYMBOL(drm_fb_helper_check_var);
1578
1579 /**
1580  * drm_fb_helper_set_par - implementation for &fb_ops.fb_set_par
1581  * @info: fbdev registered by the helper
1582  *
1583  * This will let fbcon do the mode init and is called at initialization time by
1584  * the fbdev core when registering the driver, and later on through the hotplug
1585  * callback.
1586  */
1587 int drm_fb_helper_set_par(struct fb_info *info)
1588 {
1589         struct drm_fb_helper *fb_helper = info->par;
1590         struct fb_var_screeninfo *var = &info->var;
1591         bool force;
1592
1593         if (oops_in_progress)
1594                 return -EBUSY;
1595
1596         if (var->pixclock != 0) {
1597                 drm_err(fb_helper->dev, "PIXEL CLOCK SET\n");
1598                 return -EINVAL;
1599         }
1600
1601         /*
1602          * Normally we want to make sure that a kms master takes precedence over
1603          * fbdev, to avoid fbdev flickering and occasionally stealing the
1604          * display status. But Xorg first sets the vt back to text mode using
1605          * the KDSET IOCTL with KD_TEXT, and only after that drops the master
1606          * status when exiting.
1607          *
1608          * In the past this was caught by drm_fb_helper_lastclose(), but on
1609          * modern systems where logind always keeps a drm fd open to orchestrate
1610          * the vt switching, this doesn't work.
1611          *
1612          * To not break the userspace ABI we have this special case here, which
1613          * is only used for the above case. Everything else uses the normal
1614          * commit function, which ensures that we never steal the display from
1615          * an active drm master.
1616          */
1617         force = var->activate & FB_ACTIVATE_KD_TEXT;
1618
1619         __drm_fb_helper_restore_fbdev_mode_unlocked(fb_helper, force);
1620
1621         return 0;
1622 }
1623 EXPORT_SYMBOL(drm_fb_helper_set_par);
1624
1625 static void pan_set(struct drm_fb_helper *fb_helper, int x, int y)
1626 {
1627         struct drm_mode_set *mode_set;
1628
1629         mutex_lock(&fb_helper->client.modeset_mutex);
1630         drm_client_for_each_modeset(mode_set, &fb_helper->client) {
1631                 mode_set->x = x;
1632                 mode_set->y = y;
1633         }
1634         mutex_unlock(&fb_helper->client.modeset_mutex);
1635 }
1636
1637 static int pan_display_atomic(struct fb_var_screeninfo *var,
1638                               struct fb_info *info)
1639 {
1640         struct drm_fb_helper *fb_helper = info->par;
1641         int ret;
1642
1643         pan_set(fb_helper, var->xoffset, var->yoffset);
1644
1645         ret = drm_client_modeset_commit_locked(&fb_helper->client);
1646         if (!ret) {
1647                 info->var.xoffset = var->xoffset;
1648                 info->var.yoffset = var->yoffset;
1649         } else
1650                 pan_set(fb_helper, info->var.xoffset, info->var.yoffset);
1651
1652         return ret;
1653 }
1654
1655 static int pan_display_legacy(struct fb_var_screeninfo *var,
1656                               struct fb_info *info)
1657 {
1658         struct drm_fb_helper *fb_helper = info->par;
1659         struct drm_client_dev *client = &fb_helper->client;
1660         struct drm_mode_set *modeset;
1661         int ret = 0;
1662
1663         mutex_lock(&client->modeset_mutex);
1664         drm_modeset_lock_all(fb_helper->dev);
1665         drm_client_for_each_modeset(modeset, client) {
1666                 modeset->x = var->xoffset;
1667                 modeset->y = var->yoffset;
1668
1669                 if (modeset->num_connectors) {
1670                         ret = drm_mode_set_config_internal(modeset);
1671                         if (!ret) {
1672                                 info->var.xoffset = var->xoffset;
1673                                 info->var.yoffset = var->yoffset;
1674                         }
1675                 }
1676         }
1677         drm_modeset_unlock_all(fb_helper->dev);
1678         mutex_unlock(&client->modeset_mutex);
1679
1680         return ret;
1681 }
1682
1683 /**
1684  * drm_fb_helper_pan_display - implementation for &fb_ops.fb_pan_display
1685  * @var: updated screen information
1686  * @info: fbdev registered by the helper
1687  */
1688 int drm_fb_helper_pan_display(struct fb_var_screeninfo *var,
1689                               struct fb_info *info)
1690 {
1691         struct drm_fb_helper *fb_helper = info->par;
1692         struct drm_device *dev = fb_helper->dev;
1693         int ret;
1694
1695         if (oops_in_progress)
1696                 return -EBUSY;
1697
1698         mutex_lock(&fb_helper->lock);
1699         if (!drm_master_internal_acquire(dev)) {
1700                 ret = -EBUSY;
1701                 goto unlock;
1702         }
1703
1704         if (drm_drv_uses_atomic_modeset(dev))
1705                 ret = pan_display_atomic(var, info);
1706         else
1707                 ret = pan_display_legacy(var, info);
1708
1709         drm_master_internal_release(dev);
1710 unlock:
1711         mutex_unlock(&fb_helper->lock);
1712
1713         return ret;
1714 }
1715 EXPORT_SYMBOL(drm_fb_helper_pan_display);
1716
1717 /*
1718  * Allocates the backing storage and sets up the fbdev info structure through
1719  * the ->fb_probe callback.
1720  */
1721 static int drm_fb_helper_single_fb_probe(struct drm_fb_helper *fb_helper,
1722                                          int preferred_bpp)
1723 {
1724         struct drm_client_dev *client = &fb_helper->client;
1725         struct drm_device *dev = fb_helper->dev;
1726         struct drm_mode_config *config = &dev->mode_config;
1727         int ret = 0;
1728         int crtc_count = 0;
1729         struct drm_connector_list_iter conn_iter;
1730         struct drm_fb_helper_surface_size sizes;
1731         struct drm_connector *connector;
1732         struct drm_mode_set *mode_set;
1733         int best_depth = 0;
1734
1735         memset(&sizes, 0, sizeof(struct drm_fb_helper_surface_size));
1736         sizes.surface_depth = 24;
1737         sizes.surface_bpp = 32;
1738         sizes.fb_width = (u32)-1;
1739         sizes.fb_height = (u32)-1;
1740
1741         /*
1742          * If driver picks 8 or 16 by default use that for both depth/bpp
1743          * to begin with
1744          */
1745         if (preferred_bpp != sizes.surface_bpp)
1746                 sizes.surface_depth = sizes.surface_bpp = preferred_bpp;
1747
1748         drm_connector_list_iter_begin(fb_helper->dev, &conn_iter);
1749         drm_client_for_each_connector_iter(connector, &conn_iter) {
1750                 struct drm_cmdline_mode *cmdline_mode;
1751
1752                 cmdline_mode = &connector->cmdline_mode;
1753
1754                 if (cmdline_mode->bpp_specified) {
1755                         switch (cmdline_mode->bpp) {
1756                         case 8:
1757                                 sizes.surface_depth = sizes.surface_bpp = 8;
1758                                 break;
1759                         case 15:
1760                                 sizes.surface_depth = 15;
1761                                 sizes.surface_bpp = 16;
1762                                 break;
1763                         case 16:
1764                                 sizes.surface_depth = sizes.surface_bpp = 16;
1765                                 break;
1766                         case 24:
1767                                 sizes.surface_depth = sizes.surface_bpp = 24;
1768                                 break;
1769                         case 32:
1770                                 sizes.surface_depth = 24;
1771                                 sizes.surface_bpp = 32;
1772                                 break;
1773                         }
1774                         break;
1775                 }
1776         }
1777         drm_connector_list_iter_end(&conn_iter);
1778
1779         /*
1780          * If we run into a situation where, for example, the primary plane
1781          * supports RGBA5551 (16 bpp, depth 15) but not RGB565 (16 bpp, depth
1782          * 16) we need to scale down the depth of the sizes we request.
1783          */
1784         mutex_lock(&client->modeset_mutex);
1785         drm_client_for_each_modeset(mode_set, client) {
1786                 struct drm_crtc *crtc = mode_set->crtc;
1787                 struct drm_plane *plane = crtc->primary;
1788                 int j;
1789
1790                 drm_dbg_kms(dev, "test CRTC %u primary plane\n", drm_crtc_index(crtc));
1791
1792                 for (j = 0; j < plane->format_count; j++) {
1793                         const struct drm_format_info *fmt;
1794
1795                         fmt = drm_format_info(plane->format_types[j]);
1796
1797                         /*
1798                          * Do not consider YUV or other complicated formats
1799                          * for framebuffers. This means only legacy formats
1800                          * are supported (fmt->depth is a legacy field) but
1801                          * the framebuffer emulation can only deal with such
1802                          * formats, specifically RGB/BGA formats.
1803                          */
1804                         if (fmt->depth == 0)
1805                                 continue;
1806
1807                         /* We found a perfect fit, great */
1808                         if (fmt->depth == sizes.surface_depth) {
1809                                 best_depth = fmt->depth;
1810                                 break;
1811                         }
1812
1813                         /* Skip depths above what we're looking for */
1814                         if (fmt->depth > sizes.surface_depth)
1815                                 continue;
1816
1817                         /* Best depth found so far */
1818                         if (fmt->depth > best_depth)
1819                                 best_depth = fmt->depth;
1820                 }
1821         }
1822         if (sizes.surface_depth != best_depth && best_depth) {
1823                 drm_info(dev, "requested bpp %d, scaled depth down to %d",
1824                          sizes.surface_bpp, best_depth);
1825                 sizes.surface_depth = best_depth;
1826         }
1827
1828         /* first up get a count of crtcs now in use and new min/maxes width/heights */
1829         crtc_count = 0;
1830         drm_client_for_each_modeset(mode_set, client) {
1831                 struct drm_display_mode *desired_mode;
1832                 int x, y, j;
1833                 /* in case of tile group, are we the last tile vert or horiz?
1834                  * If no tile group you are always the last one both vertically
1835                  * and horizontally
1836                  */
1837                 bool lastv = true, lasth = true;
1838
1839                 desired_mode = mode_set->mode;
1840
1841                 if (!desired_mode)
1842                         continue;
1843
1844                 crtc_count++;
1845
1846                 x = mode_set->x;
1847                 y = mode_set->y;
1848
1849                 sizes.surface_width  = max_t(u32, desired_mode->hdisplay + x, sizes.surface_width);
1850                 sizes.surface_height = max_t(u32, desired_mode->vdisplay + y, sizes.surface_height);
1851
1852                 for (j = 0; j < mode_set->num_connectors; j++) {
1853                         struct drm_connector *connector = mode_set->connectors[j];
1854
1855                         if (connector->has_tile &&
1856                             desired_mode->hdisplay == connector->tile_h_size &&
1857                             desired_mode->vdisplay == connector->tile_v_size) {
1858                                 lasth = (connector->tile_h_loc == (connector->num_h_tile - 1));
1859                                 lastv = (connector->tile_v_loc == (connector->num_v_tile - 1));
1860                                 /* cloning to multiple tiles is just crazy-talk, so: */
1861                                 break;
1862                         }
1863                 }
1864
1865                 if (lasth)
1866                         sizes.fb_width  = min_t(u32, desired_mode->hdisplay + x, sizes.fb_width);
1867                 if (lastv)
1868                         sizes.fb_height = min_t(u32, desired_mode->vdisplay + y, sizes.fb_height);
1869         }
1870         mutex_unlock(&client->modeset_mutex);
1871
1872         if (crtc_count == 0 || sizes.fb_width == -1 || sizes.fb_height == -1) {
1873                 drm_info(dev, "Cannot find any crtc or sizes\n");
1874
1875                 /* First time: disable all crtc's.. */
1876                 if (!fb_helper->deferred_setup)
1877                         drm_client_modeset_commit(client);
1878                 return -EAGAIN;
1879         }
1880
1881         /* Handle our overallocation */
1882         sizes.surface_height *= drm_fbdev_overalloc;
1883         sizes.surface_height /= 100;
1884         if (sizes.surface_height > config->max_height) {
1885                 drm_dbg_kms(dev, "Fbdev over-allocation too large; clamping height to %d\n",
1886                             config->max_height);
1887                 sizes.surface_height = config->max_height;
1888         }
1889
1890 #if IS_ENABLED(CONFIG_DRM_FBDEV_LEAK_PHYS_SMEM)
1891         fb_helper->hint_leak_smem_start = drm_leak_fbdev_smem;
1892 #endif
1893
1894         /* push down into drivers */
1895         ret = (*fb_helper->funcs->fb_probe)(fb_helper, &sizes);
1896         if (ret < 0)
1897                 return ret;
1898
1899         strcpy(fb_helper->fb->comm, "[fbcon]");
1900         return 0;
1901 }
1902
1903 static void drm_fb_helper_fill_fix(struct fb_info *info, uint32_t pitch,
1904                                    bool is_color_indexed)
1905 {
1906         info->fix.type = FB_TYPE_PACKED_PIXELS;
1907         info->fix.visual = is_color_indexed ? FB_VISUAL_PSEUDOCOLOR
1908                                             : FB_VISUAL_TRUECOLOR;
1909         info->fix.mmio_start = 0;
1910         info->fix.mmio_len = 0;
1911         info->fix.type_aux = 0;
1912         info->fix.xpanstep = 1; /* doing it in hw */
1913         info->fix.ypanstep = 1; /* doing it in hw */
1914         info->fix.ywrapstep = 0;
1915         info->fix.accel = FB_ACCEL_NONE;
1916
1917         info->fix.line_length = pitch;
1918 }
1919
1920 static void drm_fb_helper_fill_var(struct fb_info *info,
1921                                    struct drm_fb_helper *fb_helper,
1922                                    uint32_t fb_width, uint32_t fb_height)
1923 {
1924         struct drm_framebuffer *fb = fb_helper->fb;
1925         const struct drm_format_info *format = fb->format;
1926
1927         switch (format->format) {
1928         case DRM_FORMAT_C1:
1929         case DRM_FORMAT_C2:
1930         case DRM_FORMAT_C4:
1931                 /* supported format with sub-byte pixels */
1932                 break;
1933
1934         default:
1935                 WARN_ON((drm_format_info_block_width(format, 0) > 1) ||
1936                         (drm_format_info_block_height(format, 0) > 1));
1937                 break;
1938         }
1939
1940         info->pseudo_palette = fb_helper->pseudo_palette;
1941         info->var.xres_virtual = fb->width;
1942         info->var.yres_virtual = fb->height;
1943         info->var.bits_per_pixel = drm_format_info_bpp(format, 0);
1944         info->var.accel_flags = FB_ACCELF_TEXT;
1945         info->var.xoffset = 0;
1946         info->var.yoffset = 0;
1947         info->var.activate = FB_ACTIVATE_NOW;
1948
1949         drm_fb_helper_fill_pixel_fmt(&info->var, format);
1950
1951         info->var.xres = fb_width;
1952         info->var.yres = fb_height;
1953 }
1954
1955 /**
1956  * drm_fb_helper_fill_info - initializes fbdev information
1957  * @info: fbdev instance to set up
1958  * @fb_helper: fb helper instance to use as template
1959  * @sizes: describes fbdev size and scanout surface size
1960  *
1961  * Sets up the variable and fixed fbdev metainformation from the given fb helper
1962  * instance and the drm framebuffer allocated in &drm_fb_helper.fb.
1963  *
1964  * Drivers should call this (or their equivalent setup code) from their
1965  * &drm_fb_helper_funcs.fb_probe callback after having allocated the fbdev
1966  * backing storage framebuffer.
1967  */
1968 void drm_fb_helper_fill_info(struct fb_info *info,
1969                              struct drm_fb_helper *fb_helper,
1970                              struct drm_fb_helper_surface_size *sizes)
1971 {
1972         struct drm_framebuffer *fb = fb_helper->fb;
1973
1974         drm_fb_helper_fill_fix(info, fb->pitches[0],
1975                                fb->format->is_color_indexed);
1976         drm_fb_helper_fill_var(info, fb_helper,
1977                                sizes->fb_width, sizes->fb_height);
1978
1979         info->par = fb_helper;
1980         /*
1981          * The DRM drivers fbdev emulation device name can be confusing if the
1982          * driver name also has a "drm" suffix on it. Leading to names such as
1983          * "simpledrmdrmfb" in /proc/fb. Unfortunately, it's an uAPI and can't
1984          * be changed due user-space tools (e.g: pm-utils) matching against it.
1985          */
1986         snprintf(info->fix.id, sizeof(info->fix.id), "%sdrmfb",
1987                  fb_helper->dev->driver->name);
1988
1989 }
1990 EXPORT_SYMBOL(drm_fb_helper_fill_info);
1991
1992 /*
1993  * This is a continuation of drm_setup_crtcs() that sets up anything related
1994  * to the framebuffer. During initialization, drm_setup_crtcs() is called before
1995  * the framebuffer has been allocated (fb_helper->fb and fb_helper->info).
1996  * So, any setup that touches those fields needs to be done here instead of in
1997  * drm_setup_crtcs().
1998  */
1999 static void drm_setup_crtcs_fb(struct drm_fb_helper *fb_helper)
2000 {
2001         struct drm_client_dev *client = &fb_helper->client;
2002         struct drm_connector_list_iter conn_iter;
2003         struct fb_info *info = fb_helper->info;
2004         unsigned int rotation, sw_rotations = 0;
2005         struct drm_connector *connector;
2006         struct drm_mode_set *modeset;
2007
2008         mutex_lock(&client->modeset_mutex);
2009         drm_client_for_each_modeset(modeset, client) {
2010                 if (!modeset->num_connectors)
2011                         continue;
2012
2013                 modeset->fb = fb_helper->fb;
2014
2015                 if (drm_client_rotation(modeset, &rotation))
2016                         /* Rotating in hardware, fbcon should not rotate */
2017                         sw_rotations |= DRM_MODE_ROTATE_0;
2018                 else
2019                         sw_rotations |= rotation;
2020         }
2021         mutex_unlock(&client->modeset_mutex);
2022
2023         drm_connector_list_iter_begin(fb_helper->dev, &conn_iter);
2024         drm_client_for_each_connector_iter(connector, &conn_iter) {
2025
2026                 /* use first connected connector for the physical dimensions */
2027                 if (connector->status == connector_status_connected) {
2028                         info->var.width = connector->display_info.width_mm;
2029                         info->var.height = connector->display_info.height_mm;
2030                         break;
2031                 }
2032         }
2033         drm_connector_list_iter_end(&conn_iter);
2034
2035         switch (sw_rotations) {
2036         case DRM_MODE_ROTATE_0:
2037                 info->fbcon_rotate_hint = FB_ROTATE_UR;
2038                 break;
2039         case DRM_MODE_ROTATE_90:
2040                 info->fbcon_rotate_hint = FB_ROTATE_CCW;
2041                 break;
2042         case DRM_MODE_ROTATE_180:
2043                 info->fbcon_rotate_hint = FB_ROTATE_UD;
2044                 break;
2045         case DRM_MODE_ROTATE_270:
2046                 info->fbcon_rotate_hint = FB_ROTATE_CW;
2047                 break;
2048         default:
2049                 /*
2050                  * Multiple bits are set / multiple rotations requested
2051                  * fbcon cannot handle separate rotation settings per
2052                  * output, so fallback to unrotated.
2053                  */
2054                 info->fbcon_rotate_hint = FB_ROTATE_UR;
2055         }
2056 }
2057
2058 /* Note: Drops fb_helper->lock before returning. */
2059 static int
2060 __drm_fb_helper_initial_config_and_unlock(struct drm_fb_helper *fb_helper,
2061                                           int bpp_sel)
2062 {
2063         struct drm_device *dev = fb_helper->dev;
2064         struct fb_info *info;
2065         unsigned int width, height;
2066         int ret;
2067
2068         width = dev->mode_config.max_width;
2069         height = dev->mode_config.max_height;
2070
2071         drm_client_modeset_probe(&fb_helper->client, width, height);
2072         ret = drm_fb_helper_single_fb_probe(fb_helper, bpp_sel);
2073         if (ret < 0) {
2074                 if (ret == -EAGAIN) {
2075                         fb_helper->preferred_bpp = bpp_sel;
2076                         fb_helper->deferred_setup = true;
2077                         ret = 0;
2078                 }
2079                 mutex_unlock(&fb_helper->lock);
2080
2081                 return ret;
2082         }
2083         drm_setup_crtcs_fb(fb_helper);
2084
2085         fb_helper->deferred_setup = false;
2086
2087         info = fb_helper->info;
2088         info->var.pixclock = 0;
2089         /* Shamelessly allow physical address leaking to userspace */
2090 #if IS_ENABLED(CONFIG_DRM_FBDEV_LEAK_PHYS_SMEM)
2091         if (!fb_helper->hint_leak_smem_start)
2092 #endif
2093                 /* don't leak any physical addresses to userspace */
2094                 info->flags |= FBINFO_HIDE_SMEM_START;
2095
2096         /* Need to drop locks to avoid recursive deadlock in
2097          * register_framebuffer. This is ok because the only thing left to do is
2098          * register the fbdev emulation instance in kernel_fb_helper_list. */
2099         mutex_unlock(&fb_helper->lock);
2100
2101         ret = register_framebuffer(info);
2102         if (ret < 0)
2103                 return ret;
2104
2105         drm_info(dev, "fb%d: %s frame buffer device\n",
2106                  info->node, info->fix.id);
2107
2108         mutex_lock(&kernel_fb_helper_lock);
2109         if (list_empty(&kernel_fb_helper_list))
2110                 register_sysrq_key('v', &sysrq_drm_fb_helper_restore_op);
2111
2112         list_add(&fb_helper->kernel_fb_list, &kernel_fb_helper_list);
2113         mutex_unlock(&kernel_fb_helper_lock);
2114
2115         return 0;
2116 }
2117
2118 /**
2119  * drm_fb_helper_initial_config - setup a sane initial connector configuration
2120  * @fb_helper: fb_helper device struct
2121  * @bpp_sel: bpp value to use for the framebuffer configuration
2122  *
2123  * Scans the CRTCs and connectors and tries to put together an initial setup.
2124  * At the moment, this is a cloned configuration across all heads with
2125  * a new framebuffer object as the backing store.
2126  *
2127  * Note that this also registers the fbdev and so allows userspace to call into
2128  * the driver through the fbdev interfaces.
2129  *
2130  * This function will call down into the &drm_fb_helper_funcs.fb_probe callback
2131  * to let the driver allocate and initialize the fbdev info structure and the
2132  * drm framebuffer used to back the fbdev. drm_fb_helper_fill_info() is provided
2133  * as a helper to setup simple default values for the fbdev info structure.
2134  *
2135  * HANG DEBUGGING:
2136  *
2137  * When you have fbcon support built-in or already loaded, this function will do
2138  * a full modeset to setup the fbdev console. Due to locking misdesign in the
2139  * VT/fbdev subsystem that entire modeset sequence has to be done while holding
2140  * console_lock. Until console_unlock is called no dmesg lines will be sent out
2141  * to consoles, not even serial console. This means when your driver crashes,
2142  * you will see absolutely nothing else but a system stuck in this function,
2143  * with no further output. Any kind of printk() you place within your own driver
2144  * or in the drm core modeset code will also never show up.
2145  *
2146  * Standard debug practice is to run the fbcon setup without taking the
2147  * console_lock as a hack, to be able to see backtraces and crashes on the
2148  * serial line. This can be done by setting the fb.lockless_register_fb=1 kernel
2149  * cmdline option.
2150  *
2151  * The other option is to just disable fbdev emulation since very likely the
2152  * first modeset from userspace will crash in the same way, and is even easier
2153  * to debug. This can be done by setting the drm_kms_helper.fbdev_emulation=0
2154  * kernel cmdline option.
2155  *
2156  * RETURNS:
2157  * Zero if everything went ok, nonzero otherwise.
2158  */
2159 int drm_fb_helper_initial_config(struct drm_fb_helper *fb_helper, int bpp_sel)
2160 {
2161         int ret;
2162
2163         if (!drm_fbdev_emulation)
2164                 return 0;
2165
2166         mutex_lock(&fb_helper->lock);
2167         ret = __drm_fb_helper_initial_config_and_unlock(fb_helper, bpp_sel);
2168
2169         return ret;
2170 }
2171 EXPORT_SYMBOL(drm_fb_helper_initial_config);
2172
2173 /**
2174  * drm_fb_helper_hotplug_event - respond to a hotplug notification by
2175  *                               probing all the outputs attached to the fb
2176  * @fb_helper: driver-allocated fbdev helper, can be NULL
2177  *
2178  * Scan the connectors attached to the fb_helper and try to put together a
2179  * setup after notification of a change in output configuration.
2180  *
2181  * Called at runtime, takes the mode config locks to be able to check/change the
2182  * modeset configuration. Must be run from process context (which usually means
2183  * either the output polling work or a work item launched from the driver's
2184  * hotplug interrupt).
2185  *
2186  * Note that drivers may call this even before calling
2187  * drm_fb_helper_initial_config but only after drm_fb_helper_init. This allows
2188  * for a race-free fbcon setup and will make sure that the fbdev emulation will
2189  * not miss any hotplug events.
2190  *
2191  * RETURNS:
2192  * 0 on success and a non-zero error code otherwise.
2193  */
2194 int drm_fb_helper_hotplug_event(struct drm_fb_helper *fb_helper)
2195 {
2196         int err = 0;
2197
2198         if (!drm_fbdev_emulation || !fb_helper)
2199                 return 0;
2200
2201         mutex_lock(&fb_helper->lock);
2202         if (fb_helper->deferred_setup) {
2203                 err = __drm_fb_helper_initial_config_and_unlock(fb_helper,
2204                                 fb_helper->preferred_bpp);
2205                 return err;
2206         }
2207
2208         if (!fb_helper->fb || !drm_master_internal_acquire(fb_helper->dev)) {
2209                 fb_helper->delayed_hotplug = true;
2210                 mutex_unlock(&fb_helper->lock);
2211                 return err;
2212         }
2213
2214         drm_master_internal_release(fb_helper->dev);
2215
2216         drm_dbg_kms(fb_helper->dev, "\n");
2217
2218         drm_client_modeset_probe(&fb_helper->client, fb_helper->fb->width, fb_helper->fb->height);
2219         drm_setup_crtcs_fb(fb_helper);
2220         mutex_unlock(&fb_helper->lock);
2221
2222         drm_fb_helper_set_par(fb_helper->info);
2223
2224         return 0;
2225 }
2226 EXPORT_SYMBOL(drm_fb_helper_hotplug_event);
2227
2228 /**
2229  * drm_fb_helper_lastclose - DRM driver lastclose helper for fbdev emulation
2230  * @dev: DRM device
2231  *
2232  * This function can be used as the &drm_driver->lastclose callback for drivers
2233  * that only need to call drm_fb_helper_restore_fbdev_mode_unlocked().
2234  */
2235 void drm_fb_helper_lastclose(struct drm_device *dev)
2236 {
2237         drm_fb_helper_restore_fbdev_mode_unlocked(dev->fb_helper);
2238 }
2239 EXPORT_SYMBOL(drm_fb_helper_lastclose);
2240
2241 /**
2242  * drm_fb_helper_output_poll_changed - DRM mode config \.output_poll_changed
2243  *                                     helper for fbdev emulation
2244  * @dev: DRM device
2245  *
2246  * This function can be used as the
2247  * &drm_mode_config_funcs.output_poll_changed callback for drivers that only
2248  * need to call drm_fbdev.hotplug_event().
2249  */
2250 void drm_fb_helper_output_poll_changed(struct drm_device *dev)
2251 {
2252         drm_fb_helper_hotplug_event(dev->fb_helper);
2253 }
2254 EXPORT_SYMBOL(drm_fb_helper_output_poll_changed);