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