drm/fb-helper: Remove unused gamma_size variable
[sfrench/cifs-2.6.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/dma-buf.h>
34 #include <linux/kernel.h>
35 #include <linux/sysrq.h>
36 #include <linux/slab.h>
37 #include <linux/module.h>
38 #include <drm/drmP.h>
39 #include <drm/drm_crtc.h>
40 #include <drm/drm_fb_helper.h>
41 #include <drm/drm_crtc_helper.h>
42 #include <drm/drm_atomic.h>
43 #include <drm/drm_atomic_helper.h>
44
45 #include "drm_crtc_internal.h"
46 #include "drm_crtc_helper_internal.h"
47
48 static bool drm_fbdev_emulation = true;
49 module_param_named(fbdev_emulation, drm_fbdev_emulation, bool, 0600);
50 MODULE_PARM_DESC(fbdev_emulation,
51                  "Enable legacy fbdev emulation [default=true]");
52
53 static int drm_fbdev_overalloc = CONFIG_DRM_FBDEV_OVERALLOC;
54 module_param(drm_fbdev_overalloc, int, 0444);
55 MODULE_PARM_DESC(drm_fbdev_overalloc,
56                  "Overallocation of the fbdev buffer (%) [default="
57                  __MODULE_STRING(CONFIG_DRM_FBDEV_OVERALLOC) "]");
58
59 /*
60  * In order to keep user-space compatibility, we want in certain use-cases
61  * to keep leaking the fbdev physical address to the user-space program
62  * handling the fbdev buffer.
63  * This is a bad habit essentially kept into closed source opengl driver
64  * that should really be moved into open-source upstream projects instead
65  * of using legacy physical addresses in user space to communicate with
66  * other out-of-tree kernel modules.
67  *
68  * This module_param *should* be removed as soon as possible and be
69  * considered as a broken and legacy behaviour from a modern fbdev device.
70  */
71 #if IS_ENABLED(CONFIG_DRM_FBDEV_LEAK_PHYS_SMEM)
72 static bool drm_leak_fbdev_smem = false;
73 module_param_unsafe(drm_leak_fbdev_smem, bool, 0600);
74 MODULE_PARM_DESC(drm_leak_fbdev_smem,
75                  "Allow unsafe leaking fbdev physical smem address [default=false]");
76 #endif
77
78 static LIST_HEAD(kernel_fb_helper_list);
79 static DEFINE_MUTEX(kernel_fb_helper_lock);
80
81 /**
82  * DOC: fbdev helpers
83  *
84  * The fb helper functions are useful to provide an fbdev on top of a drm kernel
85  * mode setting driver. They can be used mostly independently from the crtc
86  * helper functions used by many drivers to implement the kernel mode setting
87  * interfaces.
88  *
89  * Drivers that support a dumb buffer with a virtual address and mmap support,
90  * should try out the generic fbdev emulation using drm_fbdev_generic_setup().
91  *
92  * Setup fbdev emulation by calling drm_fb_helper_fbdev_setup() and tear it
93  * down by calling drm_fb_helper_fbdev_teardown().
94  *
95  * Drivers that need to handle connector hotplugging (e.g. dp mst) can't use
96  * the setup helper and will need to do the whole four-step setup process with
97  * drm_fb_helper_prepare(), drm_fb_helper_init(),
98  * drm_fb_helper_single_add_all_connectors(), enable hotplugging and
99  * drm_fb_helper_initial_config() to avoid a possible race window.
100  *
101  * At runtime drivers should restore the fbdev console by using
102  * drm_fb_helper_lastclose() as their &drm_driver.lastclose callback.
103  * They should also notify the fb helper code from updates to the output
104  * configuration by using drm_fb_helper_output_poll_changed() as their
105  * &drm_mode_config_funcs.output_poll_changed callback.
106  *
107  * For suspend/resume consider using drm_mode_config_helper_suspend() and
108  * drm_mode_config_helper_resume() which takes care of fbdev as well.
109  *
110  * All other functions exported by the fb helper library can be used to
111  * implement the fbdev driver interface by the driver.
112  *
113  * It is possible, though perhaps somewhat tricky, to implement race-free
114  * hotplug detection using the fbdev helpers. The drm_fb_helper_prepare()
115  * helper must be called first to initialize the minimum required to make
116  * hotplug detection work. Drivers also need to make sure to properly set up
117  * the &drm_mode_config.funcs member. After calling drm_kms_helper_poll_init()
118  * it is safe to enable interrupts and start processing hotplug events. At the
119  * same time, drivers should initialize all modeset objects such as CRTCs,
120  * encoders and connectors. To finish up the fbdev helper initialization, the
121  * drm_fb_helper_init() function is called. To probe for all attached displays
122  * and set up an initial configuration using the detected hardware, drivers
123  * should call drm_fb_helper_single_add_all_connectors() followed by
124  * drm_fb_helper_initial_config().
125  *
126  * If &drm_framebuffer_funcs.dirty is set, the
127  * drm_fb_helper_{cfb,sys}_{write,fillrect,copyarea,imageblit} functions will
128  * accumulate changes and schedule &drm_fb_helper.dirty_work to run right
129  * away. This worker then calls the dirty() function ensuring that it will
130  * always run in process context since the fb_*() function could be running in
131  * atomic context. If drm_fb_helper_deferred_io() is used as the deferred_io
132  * callback it will also schedule dirty_work with the damage collected from the
133  * mmap page writes. Drivers can use drm_fb_helper_defio_init() to setup
134  * deferred I/O (coupled with drm_fb_helper_fbdev_teardown()).
135  */
136
137 #define drm_fb_helper_for_each_connector(fbh, i__) \
138         for (({ lockdep_assert_held(&(fbh)->lock); }), \
139              i__ = 0; i__ < (fbh)->connector_count; i__++)
140
141 static int __drm_fb_helper_add_one_connector(struct drm_fb_helper *fb_helper,
142                                              struct drm_connector *connector)
143 {
144         struct drm_fb_helper_connector *fb_conn;
145         struct drm_fb_helper_connector **temp;
146         unsigned int count;
147
148         if (!drm_fbdev_emulation)
149                 return 0;
150
151         lockdep_assert_held(&fb_helper->lock);
152
153         count = fb_helper->connector_count + 1;
154
155         if (count > fb_helper->connector_info_alloc_count) {
156                 size_t size = count * sizeof(fb_conn);
157
158                 temp = krealloc(fb_helper->connector_info, size, GFP_KERNEL);
159                 if (!temp)
160                         return -ENOMEM;
161
162                 fb_helper->connector_info_alloc_count = count;
163                 fb_helper->connector_info = temp;
164         }
165
166         fb_conn = kzalloc(sizeof(*fb_conn), GFP_KERNEL);
167         if (!fb_conn)
168                 return -ENOMEM;
169
170         drm_connector_get(connector);
171         fb_conn->connector = connector;
172         fb_helper->connector_info[fb_helper->connector_count++] = fb_conn;
173
174         return 0;
175 }
176
177 int drm_fb_helper_add_one_connector(struct drm_fb_helper *fb_helper,
178                                     struct drm_connector *connector)
179 {
180         int err;
181
182         if (!fb_helper)
183                 return 0;
184
185         mutex_lock(&fb_helper->lock);
186         err = __drm_fb_helper_add_one_connector(fb_helper, connector);
187         mutex_unlock(&fb_helper->lock);
188
189         return err;
190 }
191 EXPORT_SYMBOL(drm_fb_helper_add_one_connector);
192
193 /**
194  * drm_fb_helper_single_add_all_connectors() - add all connectors to fbdev
195  *                                             emulation helper
196  * @fb_helper: fbdev initialized with drm_fb_helper_init, can be NULL
197  *
198  * This functions adds all the available connectors for use with the given
199  * fb_helper. This is a separate step to allow drivers to freely assign
200  * connectors to the fbdev, e.g. if some are reserved for special purposes or
201  * not adequate to be used for the fbcon.
202  *
203  * This function is protected against concurrent connector hotadds/removals
204  * using drm_fb_helper_add_one_connector() and
205  * drm_fb_helper_remove_one_connector().
206  */
207 int drm_fb_helper_single_add_all_connectors(struct drm_fb_helper *fb_helper)
208 {
209         struct drm_device *dev;
210         struct drm_connector *connector;
211         struct drm_connector_list_iter conn_iter;
212         int i, ret = 0;
213
214         if (!drm_fbdev_emulation || !fb_helper)
215                 return 0;
216
217         dev = fb_helper->dev;
218
219         mutex_lock(&fb_helper->lock);
220         drm_connector_list_iter_begin(dev, &conn_iter);
221         drm_for_each_connector_iter(connector, &conn_iter) {
222                 if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
223                         continue;
224
225                 ret = __drm_fb_helper_add_one_connector(fb_helper, connector);
226                 if (ret)
227                         goto fail;
228         }
229         goto out;
230
231 fail:
232         drm_fb_helper_for_each_connector(fb_helper, i) {
233                 struct drm_fb_helper_connector *fb_helper_connector =
234                         fb_helper->connector_info[i];
235
236                 drm_connector_put(fb_helper_connector->connector);
237
238                 kfree(fb_helper_connector);
239                 fb_helper->connector_info[i] = NULL;
240         }
241         fb_helper->connector_count = 0;
242 out:
243         drm_connector_list_iter_end(&conn_iter);
244         mutex_unlock(&fb_helper->lock);
245
246         return ret;
247 }
248 EXPORT_SYMBOL(drm_fb_helper_single_add_all_connectors);
249
250 static int __drm_fb_helper_remove_one_connector(struct drm_fb_helper *fb_helper,
251                                                 struct drm_connector *connector)
252 {
253         struct drm_fb_helper_connector *fb_helper_connector;
254         int i, j;
255
256         if (!drm_fbdev_emulation)
257                 return 0;
258
259         lockdep_assert_held(&fb_helper->lock);
260
261         drm_fb_helper_for_each_connector(fb_helper, i) {
262                 if (fb_helper->connector_info[i]->connector == connector)
263                         break;
264         }
265
266         if (i == fb_helper->connector_count)
267                 return -EINVAL;
268         fb_helper_connector = fb_helper->connector_info[i];
269         drm_connector_put(fb_helper_connector->connector);
270
271         for (j = i + 1; j < fb_helper->connector_count; j++)
272                 fb_helper->connector_info[j - 1] = fb_helper->connector_info[j];
273
274         fb_helper->connector_count--;
275         kfree(fb_helper_connector);
276
277         return 0;
278 }
279
280 int drm_fb_helper_remove_one_connector(struct drm_fb_helper *fb_helper,
281                                        struct drm_connector *connector)
282 {
283         int err;
284
285         if (!fb_helper)
286                 return 0;
287
288         mutex_lock(&fb_helper->lock);
289         err = __drm_fb_helper_remove_one_connector(fb_helper, connector);
290         mutex_unlock(&fb_helper->lock);
291
292         return err;
293 }
294 EXPORT_SYMBOL(drm_fb_helper_remove_one_connector);
295
296 static void drm_fb_helper_restore_lut_atomic(struct drm_crtc *crtc)
297 {
298         uint16_t *r_base, *g_base, *b_base;
299
300         if (crtc->funcs->gamma_set == NULL)
301                 return;
302
303         r_base = crtc->gamma_store;
304         g_base = r_base + crtc->gamma_size;
305         b_base = g_base + crtc->gamma_size;
306
307         crtc->funcs->gamma_set(crtc, r_base, g_base, b_base,
308                                crtc->gamma_size, NULL);
309 }
310
311 /**
312  * drm_fb_helper_debug_enter - implementation for &fb_ops.fb_debug_enter
313  * @info: fbdev registered by the helper
314  */
315 int drm_fb_helper_debug_enter(struct fb_info *info)
316 {
317         struct drm_fb_helper *helper = info->par;
318         const struct drm_crtc_helper_funcs *funcs;
319         int i;
320
321         list_for_each_entry(helper, &kernel_fb_helper_list, kernel_fb_list) {
322                 for (i = 0; i < helper->crtc_count; i++) {
323                         struct drm_mode_set *mode_set =
324                                 &helper->crtc_info[i].mode_set;
325
326                         if (!mode_set->crtc->enabled)
327                                 continue;
328
329                         funcs = mode_set->crtc->helper_private;
330                         if (funcs->mode_set_base_atomic == NULL)
331                                 continue;
332
333                         if (drm_drv_uses_atomic_modeset(mode_set->crtc->dev))
334                                 continue;
335
336                         funcs->mode_set_base_atomic(mode_set->crtc,
337                                                     mode_set->fb,
338                                                     mode_set->x,
339                                                     mode_set->y,
340                                                     ENTER_ATOMIC_MODE_SET);
341                 }
342         }
343
344         return 0;
345 }
346 EXPORT_SYMBOL(drm_fb_helper_debug_enter);
347
348 /**
349  * drm_fb_helper_debug_leave - implementation for &fb_ops.fb_debug_leave
350  * @info: fbdev registered by the helper
351  */
352 int drm_fb_helper_debug_leave(struct fb_info *info)
353 {
354         struct drm_fb_helper *helper = info->par;
355         struct drm_crtc *crtc;
356         const struct drm_crtc_helper_funcs *funcs;
357         struct drm_framebuffer *fb;
358         int i;
359
360         for (i = 0; i < helper->crtc_count; i++) {
361                 struct drm_mode_set *mode_set = &helper->crtc_info[i].mode_set;
362
363                 crtc = mode_set->crtc;
364                 if (drm_drv_uses_atomic_modeset(crtc->dev))
365                         continue;
366
367                 funcs = crtc->helper_private;
368                 fb = crtc->primary->fb;
369
370                 if (!crtc->enabled)
371                         continue;
372
373                 if (!fb) {
374                         DRM_ERROR("no fb to restore??\n");
375                         continue;
376                 }
377
378                 if (funcs->mode_set_base_atomic == NULL)
379                         continue;
380
381                 drm_fb_helper_restore_lut_atomic(mode_set->crtc);
382                 funcs->mode_set_base_atomic(mode_set->crtc, fb, crtc->x,
383                                             crtc->y, LEAVE_ATOMIC_MODE_SET);
384         }
385
386         return 0;
387 }
388 EXPORT_SYMBOL(drm_fb_helper_debug_leave);
389
390 static int restore_fbdev_mode_atomic(struct drm_fb_helper *fb_helper, bool active)
391 {
392         struct drm_device *dev = fb_helper->dev;
393         struct drm_plane_state *plane_state;
394         struct drm_plane *plane;
395         struct drm_atomic_state *state;
396         int i, ret;
397         struct drm_modeset_acquire_ctx ctx;
398
399         drm_modeset_acquire_init(&ctx, 0);
400
401         state = drm_atomic_state_alloc(dev);
402         if (!state) {
403                 ret = -ENOMEM;
404                 goto out_ctx;
405         }
406
407         state->acquire_ctx = &ctx;
408 retry:
409         drm_for_each_plane(plane, dev) {
410                 plane_state = drm_atomic_get_plane_state(state, plane);
411                 if (IS_ERR(plane_state)) {
412                         ret = PTR_ERR(plane_state);
413                         goto out_state;
414                 }
415
416                 plane_state->rotation = DRM_MODE_ROTATE_0;
417
418                 /* disable non-primary: */
419                 if (plane->type == DRM_PLANE_TYPE_PRIMARY)
420                         continue;
421
422                 ret = __drm_atomic_helper_disable_plane(plane, plane_state);
423                 if (ret != 0)
424                         goto out_state;
425         }
426
427         for (i = 0; i < fb_helper->crtc_count; i++) {
428                 struct drm_mode_set *mode_set = &fb_helper->crtc_info[i].mode_set;
429                 struct drm_plane *primary = mode_set->crtc->primary;
430
431                 /* Cannot fail as we've already gotten the plane state above */
432                 plane_state = drm_atomic_get_new_plane_state(state, primary);
433                 plane_state->rotation = fb_helper->crtc_info[i].rotation;
434
435                 ret = __drm_atomic_helper_set_config(mode_set, state);
436                 if (ret != 0)
437                         goto out_state;
438
439                 /*
440                  * __drm_atomic_helper_set_config() sets active when a
441                  * mode is set, unconditionally clear it if we force DPMS off
442                  */
443                 if (!active) {
444                         struct drm_crtc *crtc = mode_set->crtc;
445                         struct drm_crtc_state *crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
446
447                         crtc_state->active = false;
448                 }
449         }
450
451         ret = drm_atomic_commit(state);
452
453 out_state:
454         if (ret == -EDEADLK)
455                 goto backoff;
456
457         drm_atomic_state_put(state);
458 out_ctx:
459         drm_modeset_drop_locks(&ctx);
460         drm_modeset_acquire_fini(&ctx);
461
462         return ret;
463
464 backoff:
465         drm_atomic_state_clear(state);
466         drm_modeset_backoff(&ctx);
467
468         goto retry;
469 }
470
471 static int restore_fbdev_mode_legacy(struct drm_fb_helper *fb_helper)
472 {
473         struct drm_device *dev = fb_helper->dev;
474         struct drm_plane *plane;
475         int i, ret = 0;
476
477         drm_modeset_lock_all(fb_helper->dev);
478         drm_for_each_plane(plane, dev) {
479                 if (plane->type != DRM_PLANE_TYPE_PRIMARY)
480                         drm_plane_force_disable(plane);
481
482                 if (plane->rotation_property)
483                         drm_mode_plane_set_obj_prop(plane,
484                                                     plane->rotation_property,
485                                                     DRM_MODE_ROTATE_0);
486         }
487
488         for (i = 0; i < fb_helper->crtc_count; i++) {
489                 struct drm_mode_set *mode_set = &fb_helper->crtc_info[i].mode_set;
490                 struct drm_crtc *crtc = mode_set->crtc;
491
492                 if (crtc->funcs->cursor_set2) {
493                         ret = crtc->funcs->cursor_set2(crtc, NULL, 0, 0, 0, 0, 0);
494                         if (ret)
495                                 goto out;
496                 } else if (crtc->funcs->cursor_set) {
497                         ret = crtc->funcs->cursor_set(crtc, NULL, 0, 0, 0);
498                         if (ret)
499                                 goto out;
500                 }
501
502                 ret = drm_mode_set_config_internal(mode_set);
503                 if (ret)
504                         goto out;
505         }
506 out:
507         drm_modeset_unlock_all(fb_helper->dev);
508
509         return ret;
510 }
511
512 static int restore_fbdev_mode(struct drm_fb_helper *fb_helper)
513 {
514         struct drm_device *dev = fb_helper->dev;
515
516         if (drm_drv_uses_atomic_modeset(dev))
517                 return restore_fbdev_mode_atomic(fb_helper, true);
518         else
519                 return restore_fbdev_mode_legacy(fb_helper);
520 }
521
522 /**
523  * drm_fb_helper_restore_fbdev_mode_unlocked - restore fbdev configuration
524  * @fb_helper: driver-allocated fbdev helper, can be NULL
525  *
526  * This should be called from driver's drm &drm_driver.lastclose callback
527  * when implementing an fbcon on top of kms using this helper. This ensures that
528  * the user isn't greeted with a black screen when e.g. X dies.
529  *
530  * RETURNS:
531  * Zero if everything went ok, negative error code otherwise.
532  */
533 int drm_fb_helper_restore_fbdev_mode_unlocked(struct drm_fb_helper *fb_helper)
534 {
535         bool do_delayed;
536         int ret;
537
538         if (!drm_fbdev_emulation || !fb_helper)
539                 return -ENODEV;
540
541         if (READ_ONCE(fb_helper->deferred_setup))
542                 return 0;
543
544         mutex_lock(&fb_helper->lock);
545         ret = restore_fbdev_mode(fb_helper);
546
547         do_delayed = fb_helper->delayed_hotplug;
548         if (do_delayed)
549                 fb_helper->delayed_hotplug = false;
550         mutex_unlock(&fb_helper->lock);
551
552         if (do_delayed)
553                 drm_fb_helper_hotplug_event(fb_helper);
554
555         return ret;
556 }
557 EXPORT_SYMBOL(drm_fb_helper_restore_fbdev_mode_unlocked);
558
559 static bool drm_fb_helper_is_bound(struct drm_fb_helper *fb_helper)
560 {
561         struct drm_device *dev = fb_helper->dev;
562         struct drm_crtc *crtc;
563         int bound = 0, crtcs_bound = 0;
564
565         /*
566          * Sometimes user space wants everything disabled, so don't steal the
567          * display if there's a master.
568          */
569         if (READ_ONCE(dev->master))
570                 return false;
571
572         drm_for_each_crtc(crtc, dev) {
573                 drm_modeset_lock(&crtc->mutex, NULL);
574                 if (crtc->primary->fb)
575                         crtcs_bound++;
576                 if (crtc->primary->fb == fb_helper->fb)
577                         bound++;
578                 drm_modeset_unlock(&crtc->mutex);
579         }
580
581         if (bound < crtcs_bound)
582                 return false;
583
584         return true;
585 }
586
587 #ifdef CONFIG_MAGIC_SYSRQ
588 /*
589  * restore fbcon display for all kms driver's using this helper, used for sysrq
590  * and panic handling.
591  */
592 static bool drm_fb_helper_force_kernel_mode(void)
593 {
594         bool ret, error = false;
595         struct drm_fb_helper *helper;
596
597         if (list_empty(&kernel_fb_helper_list))
598                 return false;
599
600         list_for_each_entry(helper, &kernel_fb_helper_list, kernel_fb_list) {
601                 struct drm_device *dev = helper->dev;
602
603                 if (dev->switch_power_state == DRM_SWITCH_POWER_OFF)
604                         continue;
605
606                 mutex_lock(&helper->lock);
607                 ret = restore_fbdev_mode(helper);
608                 if (ret)
609                         error = true;
610                 mutex_unlock(&helper->lock);
611         }
612         return error;
613 }
614
615 static void drm_fb_helper_restore_work_fn(struct work_struct *ignored)
616 {
617         bool ret;
618
619         ret = drm_fb_helper_force_kernel_mode();
620         if (ret == true)
621                 DRM_ERROR("Failed to restore crtc configuration\n");
622 }
623 static DECLARE_WORK(drm_fb_helper_restore_work, drm_fb_helper_restore_work_fn);
624
625 static void drm_fb_helper_sysrq(int dummy1)
626 {
627         schedule_work(&drm_fb_helper_restore_work);
628 }
629
630 static struct sysrq_key_op sysrq_drm_fb_helper_restore_op = {
631         .handler = drm_fb_helper_sysrq,
632         .help_msg = "force-fb(V)",
633         .action_msg = "Restore framebuffer console",
634 };
635 #else
636 static struct sysrq_key_op sysrq_drm_fb_helper_restore_op = { };
637 #endif
638
639 static void dpms_legacy(struct drm_fb_helper *fb_helper, int dpms_mode)
640 {
641         struct drm_device *dev = fb_helper->dev;
642         struct drm_crtc *crtc;
643         struct drm_connector *connector;
644         int i, j;
645
646         drm_modeset_lock_all(dev);
647         for (i = 0; i < fb_helper->crtc_count; i++) {
648                 crtc = fb_helper->crtc_info[i].mode_set.crtc;
649
650                 if (!crtc->enabled)
651                         continue;
652
653                 /* Walk the connectors & encoders on this fb turning them on/off */
654                 drm_fb_helper_for_each_connector(fb_helper, j) {
655                         connector = fb_helper->connector_info[j]->connector;
656                         connector->funcs->dpms(connector, dpms_mode);
657                         drm_object_property_set_value(&connector->base,
658                                 dev->mode_config.dpms_property, dpms_mode);
659                 }
660         }
661         drm_modeset_unlock_all(dev);
662 }
663
664 static void drm_fb_helper_dpms(struct fb_info *info, int dpms_mode)
665 {
666         struct drm_fb_helper *fb_helper = info->par;
667
668         /*
669          * For each CRTC in this fb, turn the connectors on/off.
670          */
671         mutex_lock(&fb_helper->lock);
672         if (!drm_fb_helper_is_bound(fb_helper)) {
673                 mutex_unlock(&fb_helper->lock);
674                 return;
675         }
676
677         if (drm_drv_uses_atomic_modeset(fb_helper->dev))
678                 restore_fbdev_mode_atomic(fb_helper, dpms_mode == DRM_MODE_DPMS_ON);
679         else
680                 dpms_legacy(fb_helper, dpms_mode);
681         mutex_unlock(&fb_helper->lock);
682 }
683
684 /**
685  * drm_fb_helper_blank - implementation for &fb_ops.fb_blank
686  * @blank: desired blanking state
687  * @info: fbdev registered by the helper
688  */
689 int drm_fb_helper_blank(int blank, struct fb_info *info)
690 {
691         if (oops_in_progress)
692                 return -EBUSY;
693
694         switch (blank) {
695         /* Display: On; HSync: On, VSync: On */
696         case FB_BLANK_UNBLANK:
697                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_ON);
698                 break;
699         /* Display: Off; HSync: On, VSync: On */
700         case FB_BLANK_NORMAL:
701                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_STANDBY);
702                 break;
703         /* Display: Off; HSync: Off, VSync: On */
704         case FB_BLANK_HSYNC_SUSPEND:
705                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_STANDBY);
706                 break;
707         /* Display: Off; HSync: On, VSync: Off */
708         case FB_BLANK_VSYNC_SUSPEND:
709                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_SUSPEND);
710                 break;
711         /* Display: Off; HSync: Off, VSync: Off */
712         case FB_BLANK_POWERDOWN:
713                 drm_fb_helper_dpms(info, DRM_MODE_DPMS_OFF);
714                 break;
715         }
716         return 0;
717 }
718 EXPORT_SYMBOL(drm_fb_helper_blank);
719
720 static void drm_fb_helper_modeset_release(struct drm_fb_helper *helper,
721                                           struct drm_mode_set *modeset)
722 {
723         int i;
724
725         for (i = 0; i < modeset->num_connectors; i++) {
726                 drm_connector_put(modeset->connectors[i]);
727                 modeset->connectors[i] = NULL;
728         }
729         modeset->num_connectors = 0;
730
731         drm_mode_destroy(helper->dev, modeset->mode);
732         modeset->mode = NULL;
733
734         /* FIXME should hold a ref? */
735         modeset->fb = NULL;
736 }
737
738 static void drm_fb_helper_crtc_free(struct drm_fb_helper *helper)
739 {
740         int i;
741
742         for (i = 0; i < helper->connector_count; i++) {
743                 drm_connector_put(helper->connector_info[i]->connector);
744                 kfree(helper->connector_info[i]);
745         }
746         kfree(helper->connector_info);
747
748         for (i = 0; i < helper->crtc_count; i++) {
749                 struct drm_mode_set *modeset = &helper->crtc_info[i].mode_set;
750
751                 drm_fb_helper_modeset_release(helper, modeset);
752                 kfree(modeset->connectors);
753         }
754         kfree(helper->crtc_info);
755 }
756
757 static void drm_fb_helper_resume_worker(struct work_struct *work)
758 {
759         struct drm_fb_helper *helper = container_of(work, struct drm_fb_helper,
760                                                     resume_work);
761
762         console_lock();
763         fb_set_suspend(helper->fbdev, 0);
764         console_unlock();
765 }
766
767 static void drm_fb_helper_dirty_blit_real(struct drm_fb_helper *fb_helper,
768                                           struct drm_clip_rect *clip)
769 {
770         struct drm_framebuffer *fb = fb_helper->fb;
771         unsigned int cpp = drm_format_plane_cpp(fb->format->format, 0);
772         size_t offset = clip->y1 * fb->pitches[0] + clip->x1 * cpp;
773         void *src = fb_helper->fbdev->screen_buffer + offset;
774         void *dst = fb_helper->buffer->vaddr + offset;
775         size_t len = (clip->x2 - clip->x1) * cpp;
776         unsigned int y;
777
778         for (y = clip->y1; y < clip->y2; y++) {
779                 memcpy(dst, src, len);
780                 src += fb->pitches[0];
781                 dst += fb->pitches[0];
782         }
783 }
784
785 static void drm_fb_helper_dirty_work(struct work_struct *work)
786 {
787         struct drm_fb_helper *helper = container_of(work, struct drm_fb_helper,
788                                                     dirty_work);
789         struct drm_clip_rect *clip = &helper->dirty_clip;
790         struct drm_clip_rect clip_copy;
791         unsigned long flags;
792
793         spin_lock_irqsave(&helper->dirty_lock, flags);
794         clip_copy = *clip;
795         clip->x1 = clip->y1 = ~0;
796         clip->x2 = clip->y2 = 0;
797         spin_unlock_irqrestore(&helper->dirty_lock, flags);
798
799         /* call dirty callback only when it has been really touched */
800         if (clip_copy.x1 < clip_copy.x2 && clip_copy.y1 < clip_copy.y2) {
801                 /* Generic fbdev uses a shadow buffer */
802                 if (helper->buffer)
803                         drm_fb_helper_dirty_blit_real(helper, &clip_copy);
804                 helper->fb->funcs->dirty(helper->fb, NULL, 0, 0, &clip_copy, 1);
805         }
806 }
807
808 /**
809  * drm_fb_helper_prepare - setup a drm_fb_helper structure
810  * @dev: DRM device
811  * @helper: driver-allocated fbdev helper structure to set up
812  * @funcs: pointer to structure of functions associate with this helper
813  *
814  * Sets up the bare minimum to make the framebuffer helper usable. This is
815  * useful to implement race-free initialization of the polling helpers.
816  */
817 void drm_fb_helper_prepare(struct drm_device *dev, struct drm_fb_helper *helper,
818                            const struct drm_fb_helper_funcs *funcs)
819 {
820         INIT_LIST_HEAD(&helper->kernel_fb_list);
821         spin_lock_init(&helper->dirty_lock);
822         INIT_WORK(&helper->resume_work, drm_fb_helper_resume_worker);
823         INIT_WORK(&helper->dirty_work, drm_fb_helper_dirty_work);
824         helper->dirty_clip.x1 = helper->dirty_clip.y1 = ~0;
825         mutex_init(&helper->lock);
826         helper->funcs = funcs;
827         helper->dev = dev;
828 }
829 EXPORT_SYMBOL(drm_fb_helper_prepare);
830
831 /**
832  * drm_fb_helper_init - initialize a &struct drm_fb_helper
833  * @dev: drm device
834  * @fb_helper: driver-allocated fbdev helper structure to initialize
835  * @max_conn_count: max connector count
836  *
837  * This allocates the structures for the fbdev helper with the given limits.
838  * Note that this won't yet touch the hardware (through the driver interfaces)
839  * nor register the fbdev. This is only done in drm_fb_helper_initial_config()
840  * to allow driver writes more control over the exact init sequence.
841  *
842  * Drivers must call drm_fb_helper_prepare() before calling this function.
843  *
844  * RETURNS:
845  * Zero if everything went ok, nonzero otherwise.
846  */
847 int drm_fb_helper_init(struct drm_device *dev,
848                        struct drm_fb_helper *fb_helper,
849                        int max_conn_count)
850 {
851         struct drm_crtc *crtc;
852         struct drm_mode_config *config = &dev->mode_config;
853         int i;
854
855         if (!drm_fbdev_emulation) {
856                 dev->fb_helper = fb_helper;
857                 return 0;
858         }
859
860         if (!max_conn_count)
861                 return -EINVAL;
862
863         fb_helper->crtc_info = kcalloc(config->num_crtc, sizeof(struct drm_fb_helper_crtc), GFP_KERNEL);
864         if (!fb_helper->crtc_info)
865                 return -ENOMEM;
866
867         fb_helper->crtc_count = config->num_crtc;
868         fb_helper->connector_info = kcalloc(dev->mode_config.num_connector, sizeof(struct drm_fb_helper_connector *), GFP_KERNEL);
869         if (!fb_helper->connector_info) {
870                 kfree(fb_helper->crtc_info);
871                 return -ENOMEM;
872         }
873         fb_helper->connector_info_alloc_count = dev->mode_config.num_connector;
874         fb_helper->connector_count = 0;
875
876         for (i = 0; i < fb_helper->crtc_count; i++) {
877                 fb_helper->crtc_info[i].mode_set.connectors =
878                         kcalloc(max_conn_count,
879                                 sizeof(struct drm_connector *),
880                                 GFP_KERNEL);
881
882                 if (!fb_helper->crtc_info[i].mode_set.connectors)
883                         goto out_free;
884                 fb_helper->crtc_info[i].mode_set.num_connectors = 0;
885                 fb_helper->crtc_info[i].rotation = DRM_MODE_ROTATE_0;
886         }
887
888         i = 0;
889         drm_for_each_crtc(crtc, dev) {
890                 fb_helper->crtc_info[i].mode_set.crtc = crtc;
891                 i++;
892         }
893
894         dev->fb_helper = fb_helper;
895
896         return 0;
897 out_free:
898         drm_fb_helper_crtc_free(fb_helper);
899         return -ENOMEM;
900 }
901 EXPORT_SYMBOL(drm_fb_helper_init);
902
903 /**
904  * drm_fb_helper_alloc_fbi - allocate fb_info and some of its members
905  * @fb_helper: driver-allocated fbdev helper
906  *
907  * A helper to alloc fb_info and the members cmap and apertures. Called
908  * by the driver within the fb_probe fb_helper callback function. Drivers do not
909  * need to release the allocated fb_info structure themselves, this is
910  * automatically done when calling drm_fb_helper_fini().
911  *
912  * RETURNS:
913  * fb_info pointer if things went okay, pointer containing error code
914  * otherwise
915  */
916 struct fb_info *drm_fb_helper_alloc_fbi(struct drm_fb_helper *fb_helper)
917 {
918         struct device *dev = fb_helper->dev->dev;
919         struct fb_info *info;
920         int ret;
921
922         info = framebuffer_alloc(0, dev);
923         if (!info)
924                 return ERR_PTR(-ENOMEM);
925
926         ret = fb_alloc_cmap(&info->cmap, 256, 0);
927         if (ret)
928                 goto err_release;
929
930         info->apertures = alloc_apertures(1);
931         if (!info->apertures) {
932                 ret = -ENOMEM;
933                 goto err_free_cmap;
934         }
935
936         fb_helper->fbdev = info;
937         info->skip_vt_switch = true;
938
939         return info;
940
941 err_free_cmap:
942         fb_dealloc_cmap(&info->cmap);
943 err_release:
944         framebuffer_release(info);
945         return ERR_PTR(ret);
946 }
947 EXPORT_SYMBOL(drm_fb_helper_alloc_fbi);
948
949 /**
950  * drm_fb_helper_unregister_fbi - unregister fb_info framebuffer device
951  * @fb_helper: driver-allocated fbdev helper, can be NULL
952  *
953  * A wrapper around unregister_framebuffer, to release the fb_info
954  * framebuffer device. This must be called before releasing all resources for
955  * @fb_helper by calling drm_fb_helper_fini().
956  */
957 void drm_fb_helper_unregister_fbi(struct drm_fb_helper *fb_helper)
958 {
959         if (fb_helper && fb_helper->fbdev)
960                 unregister_framebuffer(fb_helper->fbdev);
961 }
962 EXPORT_SYMBOL(drm_fb_helper_unregister_fbi);
963
964 /**
965  * drm_fb_helper_fini - finialize a &struct drm_fb_helper
966  * @fb_helper: driver-allocated fbdev helper, can be NULL
967  *
968  * This cleans up all remaining resources associated with @fb_helper. Must be
969  * called after drm_fb_helper_unlink_fbi() was called.
970  */
971 void drm_fb_helper_fini(struct drm_fb_helper *fb_helper)
972 {
973         struct fb_info *info;
974
975         if (!fb_helper)
976                 return;
977
978         fb_helper->dev->fb_helper = NULL;
979
980         if (!drm_fbdev_emulation)
981                 return;
982
983         cancel_work_sync(&fb_helper->resume_work);
984         cancel_work_sync(&fb_helper->dirty_work);
985
986         info = fb_helper->fbdev;
987         if (info) {
988                 if (info->cmap.len)
989                         fb_dealloc_cmap(&info->cmap);
990                 framebuffer_release(info);
991         }
992         fb_helper->fbdev = NULL;
993
994         mutex_lock(&kernel_fb_helper_lock);
995         if (!list_empty(&fb_helper->kernel_fb_list)) {
996                 list_del(&fb_helper->kernel_fb_list);
997                 if (list_empty(&kernel_fb_helper_list))
998                         unregister_sysrq_key('v', &sysrq_drm_fb_helper_restore_op);
999         }
1000         mutex_unlock(&kernel_fb_helper_lock);
1001
1002         mutex_destroy(&fb_helper->lock);
1003         drm_fb_helper_crtc_free(fb_helper);
1004
1005 }
1006 EXPORT_SYMBOL(drm_fb_helper_fini);
1007
1008 /**
1009  * drm_fb_helper_unlink_fbi - wrapper around unlink_framebuffer
1010  * @fb_helper: driver-allocated fbdev helper, can be NULL
1011  *
1012  * A wrapper around unlink_framebuffer implemented by fbdev core
1013  */
1014 void drm_fb_helper_unlink_fbi(struct drm_fb_helper *fb_helper)
1015 {
1016         if (fb_helper && fb_helper->fbdev)
1017                 unlink_framebuffer(fb_helper->fbdev);
1018 }
1019 EXPORT_SYMBOL(drm_fb_helper_unlink_fbi);
1020
1021 static void drm_fb_helper_dirty(struct fb_info *info, u32 x, u32 y,
1022                                 u32 width, u32 height)
1023 {
1024         struct drm_fb_helper *helper = info->par;
1025         struct drm_clip_rect *clip = &helper->dirty_clip;
1026         unsigned long flags;
1027
1028         if (!helper->fb->funcs->dirty)
1029                 return;
1030
1031         spin_lock_irqsave(&helper->dirty_lock, flags);
1032         clip->x1 = min_t(u32, clip->x1, x);
1033         clip->y1 = min_t(u32, clip->y1, y);
1034         clip->x2 = max_t(u32, clip->x2, x + width);
1035         clip->y2 = max_t(u32, clip->y2, y + height);
1036         spin_unlock_irqrestore(&helper->dirty_lock, flags);
1037
1038         schedule_work(&helper->dirty_work);
1039 }
1040
1041 /**
1042  * drm_fb_helper_deferred_io() - fbdev deferred_io callback function
1043  * @info: fb_info struct pointer
1044  * @pagelist: list of dirty mmap framebuffer pages
1045  *
1046  * This function is used as the &fb_deferred_io.deferred_io
1047  * callback function for flushing the fbdev mmap writes.
1048  */
1049 void drm_fb_helper_deferred_io(struct fb_info *info,
1050                                struct list_head *pagelist)
1051 {
1052         unsigned long start, end, min, max;
1053         struct page *page;
1054         u32 y1, y2;
1055
1056         min = ULONG_MAX;
1057         max = 0;
1058         list_for_each_entry(page, pagelist, lru) {
1059                 start = page->index << PAGE_SHIFT;
1060                 end = start + PAGE_SIZE - 1;
1061                 min = min(min, start);
1062                 max = max(max, end);
1063         }
1064
1065         if (min < max) {
1066                 y1 = min / info->fix.line_length;
1067                 y2 = min_t(u32, DIV_ROUND_UP(max, info->fix.line_length),
1068                            info->var.yres);
1069                 drm_fb_helper_dirty(info, 0, y1, info->var.xres, y2 - y1);
1070         }
1071 }
1072 EXPORT_SYMBOL(drm_fb_helper_deferred_io);
1073
1074 /**
1075  * drm_fb_helper_defio_init - fbdev deferred I/O initialization
1076  * @fb_helper: driver-allocated fbdev helper
1077  *
1078  * This function allocates &fb_deferred_io, sets callback to
1079  * drm_fb_helper_deferred_io(), delay to 50ms and calls fb_deferred_io_init().
1080  * It should be called from the &drm_fb_helper_funcs->fb_probe callback.
1081  * drm_fb_helper_fbdev_teardown() cleans up deferred I/O.
1082  *
1083  * NOTE: A copy of &fb_ops is made and assigned to &info->fbops. This is done
1084  * because fb_deferred_io_cleanup() clears &fbops->fb_mmap and would thereby
1085  * affect other instances of that &fb_ops.
1086  *
1087  * Returns:
1088  * 0 on success or a negative error code on failure.
1089  */
1090 int drm_fb_helper_defio_init(struct drm_fb_helper *fb_helper)
1091 {
1092         struct fb_info *info = fb_helper->fbdev;
1093         struct fb_deferred_io *fbdefio;
1094         struct fb_ops *fbops;
1095
1096         fbdefio = kzalloc(sizeof(*fbdefio), GFP_KERNEL);
1097         fbops = kzalloc(sizeof(*fbops), GFP_KERNEL);
1098         if (!fbdefio || !fbops) {
1099                 kfree(fbdefio);
1100                 kfree(fbops);
1101                 return -ENOMEM;
1102         }
1103
1104         info->fbdefio = fbdefio;
1105         fbdefio->delay = msecs_to_jiffies(50);
1106         fbdefio->deferred_io = drm_fb_helper_deferred_io;
1107
1108         *fbops = *info->fbops;
1109         info->fbops = fbops;
1110
1111         fb_deferred_io_init(info);
1112
1113         return 0;
1114 }
1115 EXPORT_SYMBOL(drm_fb_helper_defio_init);
1116
1117 /**
1118  * drm_fb_helper_sys_read - wrapper around fb_sys_read
1119  * @info: fb_info struct pointer
1120  * @buf: userspace buffer to read from framebuffer memory
1121  * @count: number of bytes to read from framebuffer memory
1122  * @ppos: read offset within framebuffer memory
1123  *
1124  * A wrapper around fb_sys_read implemented by fbdev core
1125  */
1126 ssize_t drm_fb_helper_sys_read(struct fb_info *info, char __user *buf,
1127                                size_t count, loff_t *ppos)
1128 {
1129         return fb_sys_read(info, buf, count, ppos);
1130 }
1131 EXPORT_SYMBOL(drm_fb_helper_sys_read);
1132
1133 /**
1134  * drm_fb_helper_sys_write - wrapper around fb_sys_write
1135  * @info: fb_info struct pointer
1136  * @buf: userspace buffer to write to framebuffer memory
1137  * @count: number of bytes to write to framebuffer memory
1138  * @ppos: write offset within framebuffer memory
1139  *
1140  * A wrapper around fb_sys_write implemented by fbdev core
1141  */
1142 ssize_t drm_fb_helper_sys_write(struct fb_info *info, const char __user *buf,
1143                                 size_t count, loff_t *ppos)
1144 {
1145         ssize_t ret;
1146
1147         ret = fb_sys_write(info, buf, count, ppos);
1148         if (ret > 0)
1149                 drm_fb_helper_dirty(info, 0, 0, info->var.xres,
1150                                     info->var.yres);
1151
1152         return ret;
1153 }
1154 EXPORT_SYMBOL(drm_fb_helper_sys_write);
1155
1156 /**
1157  * drm_fb_helper_sys_fillrect - wrapper around sys_fillrect
1158  * @info: fbdev registered by the helper
1159  * @rect: info about rectangle to fill
1160  *
1161  * A wrapper around sys_fillrect implemented by fbdev core
1162  */
1163 void drm_fb_helper_sys_fillrect(struct fb_info *info,
1164                                 const struct fb_fillrect *rect)
1165 {
1166         sys_fillrect(info, rect);
1167         drm_fb_helper_dirty(info, rect->dx, rect->dy,
1168                             rect->width, rect->height);
1169 }
1170 EXPORT_SYMBOL(drm_fb_helper_sys_fillrect);
1171
1172 /**
1173  * drm_fb_helper_sys_copyarea - wrapper around sys_copyarea
1174  * @info: fbdev registered by the helper
1175  * @area: info about area to copy
1176  *
1177  * A wrapper around sys_copyarea implemented by fbdev core
1178  */
1179 void drm_fb_helper_sys_copyarea(struct fb_info *info,
1180                                 const struct fb_copyarea *area)
1181 {
1182         sys_copyarea(info, area);
1183         drm_fb_helper_dirty(info, area->dx, area->dy,
1184                             area->width, area->height);
1185 }
1186 EXPORT_SYMBOL(drm_fb_helper_sys_copyarea);
1187
1188 /**
1189  * drm_fb_helper_sys_imageblit - wrapper around sys_imageblit
1190  * @info: fbdev registered by the helper
1191  * @image: info about image to blit
1192  *
1193  * A wrapper around sys_imageblit implemented by fbdev core
1194  */
1195 void drm_fb_helper_sys_imageblit(struct fb_info *info,
1196                                  const struct fb_image *image)
1197 {
1198         sys_imageblit(info, image);
1199         drm_fb_helper_dirty(info, image->dx, image->dy,
1200                             image->width, image->height);
1201 }
1202 EXPORT_SYMBOL(drm_fb_helper_sys_imageblit);
1203
1204 /**
1205  * drm_fb_helper_cfb_fillrect - wrapper around cfb_fillrect
1206  * @info: fbdev registered by the helper
1207  * @rect: info about rectangle to fill
1208  *
1209  * A wrapper around cfb_fillrect implemented by fbdev core
1210  */
1211 void drm_fb_helper_cfb_fillrect(struct fb_info *info,
1212                                 const struct fb_fillrect *rect)
1213 {
1214         cfb_fillrect(info, rect);
1215         drm_fb_helper_dirty(info, rect->dx, rect->dy,
1216                             rect->width, rect->height);
1217 }
1218 EXPORT_SYMBOL(drm_fb_helper_cfb_fillrect);
1219
1220 /**
1221  * drm_fb_helper_cfb_copyarea - wrapper around cfb_copyarea
1222  * @info: fbdev registered by the helper
1223  * @area: info about area to copy
1224  *
1225  * A wrapper around cfb_copyarea implemented by fbdev core
1226  */
1227 void drm_fb_helper_cfb_copyarea(struct fb_info *info,
1228                                 const struct fb_copyarea *area)
1229 {
1230         cfb_copyarea(info, area);
1231         drm_fb_helper_dirty(info, area->dx, area->dy,
1232                             area->width, area->height);
1233 }
1234 EXPORT_SYMBOL(drm_fb_helper_cfb_copyarea);
1235
1236 /**
1237  * drm_fb_helper_cfb_imageblit - wrapper around cfb_imageblit
1238  * @info: fbdev registered by the helper
1239  * @image: info about image to blit
1240  *
1241  * A wrapper around cfb_imageblit implemented by fbdev core
1242  */
1243 void drm_fb_helper_cfb_imageblit(struct fb_info *info,
1244                                  const struct fb_image *image)
1245 {
1246         cfb_imageblit(info, image);
1247         drm_fb_helper_dirty(info, image->dx, image->dy,
1248                             image->width, image->height);
1249 }
1250 EXPORT_SYMBOL(drm_fb_helper_cfb_imageblit);
1251
1252 /**
1253  * drm_fb_helper_set_suspend - wrapper around fb_set_suspend
1254  * @fb_helper: driver-allocated fbdev helper, can be NULL
1255  * @suspend: whether to suspend or resume
1256  *
1257  * A wrapper around fb_set_suspend implemented by fbdev core.
1258  * Use drm_fb_helper_set_suspend_unlocked() if you don't need to take
1259  * the lock yourself
1260  */
1261 void drm_fb_helper_set_suspend(struct drm_fb_helper *fb_helper, bool suspend)
1262 {
1263         if (fb_helper && fb_helper->fbdev)
1264                 fb_set_suspend(fb_helper->fbdev, suspend);
1265 }
1266 EXPORT_SYMBOL(drm_fb_helper_set_suspend);
1267
1268 /**
1269  * drm_fb_helper_set_suspend_unlocked - wrapper around fb_set_suspend that also
1270  *                                      takes the console lock
1271  * @fb_helper: driver-allocated fbdev helper, can be NULL
1272  * @suspend: whether to suspend or resume
1273  *
1274  * A wrapper around fb_set_suspend() that takes the console lock. If the lock
1275  * isn't available on resume, a worker is tasked with waiting for the lock
1276  * to become available. The console lock can be pretty contented on resume
1277  * due to all the printk activity.
1278  *
1279  * This function can be called multiple times with the same state since
1280  * &fb_info.state is checked to see if fbdev is running or not before locking.
1281  *
1282  * Use drm_fb_helper_set_suspend() if you need to take the lock yourself.
1283  */
1284 void drm_fb_helper_set_suspend_unlocked(struct drm_fb_helper *fb_helper,
1285                                         bool suspend)
1286 {
1287         if (!fb_helper || !fb_helper->fbdev)
1288                 return;
1289
1290         /* make sure there's no pending/ongoing resume */
1291         flush_work(&fb_helper->resume_work);
1292
1293         if (suspend) {
1294                 if (fb_helper->fbdev->state != FBINFO_STATE_RUNNING)
1295                         return;
1296
1297                 console_lock();
1298
1299         } else {
1300                 if (fb_helper->fbdev->state == FBINFO_STATE_RUNNING)
1301                         return;
1302
1303                 if (!console_trylock()) {
1304                         schedule_work(&fb_helper->resume_work);
1305                         return;
1306                 }
1307         }
1308
1309         fb_set_suspend(fb_helper->fbdev, suspend);
1310         console_unlock();
1311 }
1312 EXPORT_SYMBOL(drm_fb_helper_set_suspend_unlocked);
1313
1314 static int setcmap_pseudo_palette(struct fb_cmap *cmap, struct fb_info *info)
1315 {
1316         u32 *palette = (u32 *)info->pseudo_palette;
1317         int i;
1318
1319         if (cmap->start + cmap->len > 16)
1320                 return -EINVAL;
1321
1322         for (i = 0; i < cmap->len; ++i) {
1323                 u16 red = cmap->red[i];
1324                 u16 green = cmap->green[i];
1325                 u16 blue = cmap->blue[i];
1326                 u32 value;
1327
1328                 red >>= 16 - info->var.red.length;
1329                 green >>= 16 - info->var.green.length;
1330                 blue >>= 16 - info->var.blue.length;
1331                 value = (red << info->var.red.offset) |
1332                         (green << info->var.green.offset) |
1333                         (blue << info->var.blue.offset);
1334                 if (info->var.transp.length > 0) {
1335                         u32 mask = (1 << info->var.transp.length) - 1;
1336
1337                         mask <<= info->var.transp.offset;
1338                         value |= mask;
1339                 }
1340                 palette[cmap->start + i] = value;
1341         }
1342
1343         return 0;
1344 }
1345
1346 static int setcmap_legacy(struct fb_cmap *cmap, struct fb_info *info)
1347 {
1348         struct drm_fb_helper *fb_helper = info->par;
1349         struct drm_crtc *crtc;
1350         u16 *r, *g, *b;
1351         int i, ret = 0;
1352
1353         drm_modeset_lock_all(fb_helper->dev);
1354         for (i = 0; i < fb_helper->crtc_count; i++) {
1355                 crtc = fb_helper->crtc_info[i].mode_set.crtc;
1356                 if (!crtc->funcs->gamma_set || !crtc->gamma_size)
1357                         return -EINVAL;
1358
1359                 if (cmap->start + cmap->len > crtc->gamma_size)
1360                         return -EINVAL;
1361
1362                 r = crtc->gamma_store;
1363                 g = r + crtc->gamma_size;
1364                 b = g + crtc->gamma_size;
1365
1366                 memcpy(r + cmap->start, cmap->red, cmap->len * sizeof(*r));
1367                 memcpy(g + cmap->start, cmap->green, cmap->len * sizeof(*g));
1368                 memcpy(b + cmap->start, cmap->blue, cmap->len * sizeof(*b));
1369
1370                 ret = crtc->funcs->gamma_set(crtc, r, g, b,
1371                                              crtc->gamma_size, NULL);
1372                 if (ret)
1373                         return ret;
1374         }
1375         drm_modeset_unlock_all(fb_helper->dev);
1376
1377         return ret;
1378 }
1379
1380 static struct drm_property_blob *setcmap_new_gamma_lut(struct drm_crtc *crtc,
1381                                                        struct fb_cmap *cmap)
1382 {
1383         struct drm_device *dev = crtc->dev;
1384         struct drm_property_blob *gamma_lut;
1385         struct drm_color_lut *lut;
1386         int size = crtc->gamma_size;
1387         int i;
1388
1389         if (!size || cmap->start + cmap->len > size)
1390                 return ERR_PTR(-EINVAL);
1391
1392         gamma_lut = drm_property_create_blob(dev, sizeof(*lut) * size, NULL);
1393         if (IS_ERR(gamma_lut))
1394                 return gamma_lut;
1395
1396         lut = gamma_lut->data;
1397         if (cmap->start || cmap->len != size) {
1398                 u16 *r = crtc->gamma_store;
1399                 u16 *g = r + crtc->gamma_size;
1400                 u16 *b = g + crtc->gamma_size;
1401
1402                 for (i = 0; i < cmap->start; i++) {
1403                         lut[i].red = r[i];
1404                         lut[i].green = g[i];
1405                         lut[i].blue = b[i];
1406                 }
1407                 for (i = cmap->start + cmap->len; i < size; i++) {
1408                         lut[i].red = r[i];
1409                         lut[i].green = g[i];
1410                         lut[i].blue = b[i];
1411                 }
1412         }
1413
1414         for (i = 0; i < cmap->len; i++) {
1415                 lut[cmap->start + i].red = cmap->red[i];
1416                 lut[cmap->start + i].green = cmap->green[i];
1417                 lut[cmap->start + i].blue = cmap->blue[i];
1418         }
1419
1420         return gamma_lut;
1421 }
1422
1423 static int setcmap_atomic(struct fb_cmap *cmap, struct fb_info *info)
1424 {
1425         struct drm_fb_helper *fb_helper = info->par;
1426         struct drm_device *dev = fb_helper->dev;
1427         struct drm_property_blob *gamma_lut = NULL;
1428         struct drm_modeset_acquire_ctx ctx;
1429         struct drm_crtc_state *crtc_state;
1430         struct drm_atomic_state *state;
1431         struct drm_crtc *crtc;
1432         u16 *r, *g, *b;
1433         int i, ret = 0;
1434         bool replaced;
1435
1436         drm_modeset_acquire_init(&ctx, 0);
1437
1438         state = drm_atomic_state_alloc(dev);
1439         if (!state) {
1440                 ret = -ENOMEM;
1441                 goto out_ctx;
1442         }
1443
1444         state->acquire_ctx = &ctx;
1445 retry:
1446         for (i = 0; i < fb_helper->crtc_count; i++) {
1447                 crtc = fb_helper->crtc_info[i].mode_set.crtc;
1448
1449                 if (!gamma_lut)
1450                         gamma_lut = setcmap_new_gamma_lut(crtc, cmap);
1451                 if (IS_ERR(gamma_lut)) {
1452                         ret = PTR_ERR(gamma_lut);
1453                         gamma_lut = NULL;
1454                         goto out_state;
1455                 }
1456
1457                 crtc_state = drm_atomic_get_crtc_state(state, crtc);
1458                 if (IS_ERR(crtc_state)) {
1459                         ret = PTR_ERR(crtc_state);
1460                         goto out_state;
1461                 }
1462
1463                 replaced  = drm_property_replace_blob(&crtc_state->degamma_lut,
1464                                                       NULL);
1465                 replaced |= drm_property_replace_blob(&crtc_state->ctm, NULL);
1466                 replaced |= drm_property_replace_blob(&crtc_state->gamma_lut,
1467                                                       gamma_lut);
1468                 crtc_state->color_mgmt_changed |= replaced;
1469         }
1470
1471         ret = drm_atomic_commit(state);
1472         if (ret)
1473                 goto out_state;
1474
1475         for (i = 0; i < fb_helper->crtc_count; i++) {
1476                 crtc = fb_helper->crtc_info[i].mode_set.crtc;
1477
1478                 r = crtc->gamma_store;
1479                 g = r + crtc->gamma_size;
1480                 b = g + crtc->gamma_size;
1481
1482                 memcpy(r + cmap->start, cmap->red, cmap->len * sizeof(*r));
1483                 memcpy(g + cmap->start, cmap->green, cmap->len * sizeof(*g));
1484                 memcpy(b + cmap->start, cmap->blue, cmap->len * sizeof(*b));
1485         }
1486
1487 out_state:
1488         if (ret == -EDEADLK)
1489                 goto backoff;
1490
1491         drm_property_blob_put(gamma_lut);
1492         drm_atomic_state_put(state);
1493 out_ctx:
1494         drm_modeset_drop_locks(&ctx);
1495         drm_modeset_acquire_fini(&ctx);
1496
1497         return ret;
1498
1499 backoff:
1500         drm_atomic_state_clear(state);
1501         drm_modeset_backoff(&ctx);
1502         goto retry;
1503 }
1504
1505 /**
1506  * drm_fb_helper_setcmap - implementation for &fb_ops.fb_setcmap
1507  * @cmap: cmap to set
1508  * @info: fbdev registered by the helper
1509  */
1510 int drm_fb_helper_setcmap(struct fb_cmap *cmap, struct fb_info *info)
1511 {
1512         struct drm_fb_helper *fb_helper = info->par;
1513         int ret;
1514
1515         if (oops_in_progress)
1516                 return -EBUSY;
1517
1518         mutex_lock(&fb_helper->lock);
1519
1520         if (!drm_fb_helper_is_bound(fb_helper)) {
1521                 ret = -EBUSY;
1522                 goto out;
1523         }
1524
1525         if (info->fix.visual == FB_VISUAL_TRUECOLOR)
1526                 ret = setcmap_pseudo_palette(cmap, info);
1527         else if (drm_drv_uses_atomic_modeset(fb_helper->dev))
1528                 ret = setcmap_atomic(cmap, info);
1529         else
1530                 ret = setcmap_legacy(cmap, info);
1531
1532 out:
1533         mutex_unlock(&fb_helper->lock);
1534
1535         return ret;
1536 }
1537 EXPORT_SYMBOL(drm_fb_helper_setcmap);
1538
1539 /**
1540  * drm_fb_helper_ioctl - legacy ioctl implementation
1541  * @info: fbdev registered by the helper
1542  * @cmd: ioctl command
1543  * @arg: ioctl argument
1544  *
1545  * A helper to implement the standard fbdev ioctl. Only
1546  * FBIO_WAITFORVSYNC is implemented for now.
1547  */
1548 int drm_fb_helper_ioctl(struct fb_info *info, unsigned int cmd,
1549                         unsigned long arg)
1550 {
1551         struct drm_fb_helper *fb_helper = info->par;
1552         struct drm_mode_set *mode_set;
1553         struct drm_crtc *crtc;
1554         int ret = 0;
1555
1556         mutex_lock(&fb_helper->lock);
1557         if (!drm_fb_helper_is_bound(fb_helper)) {
1558                 ret = -EBUSY;
1559                 goto unlock;
1560         }
1561
1562         switch (cmd) {
1563         case FBIO_WAITFORVSYNC:
1564                 /*
1565                  * Only consider the first CRTC.
1566                  *
1567                  * This ioctl is supposed to take the CRTC number as
1568                  * an argument, but in fbdev times, what that number
1569                  * was supposed to be was quite unclear, different
1570                  * drivers were passing that argument differently
1571                  * (some by reference, some by value), and most of the
1572                  * userspace applications were just hardcoding 0 as an
1573                  * argument.
1574                  *
1575                  * The first CRTC should be the integrated panel on
1576                  * most drivers, so this is the best choice we can
1577                  * make. If we're not smart enough here, one should
1578                  * just consider switch the userspace to KMS.
1579                  */
1580                 mode_set = &fb_helper->crtc_info[0].mode_set;
1581                 crtc = mode_set->crtc;
1582
1583                 /*
1584                  * Only wait for a vblank event if the CRTC is
1585                  * enabled, otherwise just don't do anythintg,
1586                  * not even report an error.
1587                  */
1588                 ret = drm_crtc_vblank_get(crtc);
1589                 if (!ret) {
1590                         drm_crtc_wait_one_vblank(crtc);
1591                         drm_crtc_vblank_put(crtc);
1592                 }
1593
1594                 ret = 0;
1595                 goto unlock;
1596         default:
1597                 ret = -ENOTTY;
1598         }
1599
1600 unlock:
1601         mutex_unlock(&fb_helper->lock);
1602         return ret;
1603 }
1604 EXPORT_SYMBOL(drm_fb_helper_ioctl);
1605
1606 static bool drm_fb_pixel_format_equal(const struct fb_var_screeninfo *var_1,
1607                                       const struct fb_var_screeninfo *var_2)
1608 {
1609         return var_1->bits_per_pixel == var_2->bits_per_pixel &&
1610                var_1->grayscale == var_2->grayscale &&
1611                var_1->red.offset == var_2->red.offset &&
1612                var_1->red.length == var_2->red.length &&
1613                var_1->red.msb_right == var_2->red.msb_right &&
1614                var_1->green.offset == var_2->green.offset &&
1615                var_1->green.length == var_2->green.length &&
1616                var_1->green.msb_right == var_2->green.msb_right &&
1617                var_1->blue.offset == var_2->blue.offset &&
1618                var_1->blue.length == var_2->blue.length &&
1619                var_1->blue.msb_right == var_2->blue.msb_right &&
1620                var_1->transp.offset == var_2->transp.offset &&
1621                var_1->transp.length == var_2->transp.length &&
1622                var_1->transp.msb_right == var_2->transp.msb_right;
1623 }
1624
1625 static void drm_fb_helper_fill_pixel_fmt(struct fb_var_screeninfo *var,
1626                                          u8 depth)
1627 {
1628         switch (depth) {
1629         case 8:
1630                 var->red.offset = 0;
1631                 var->green.offset = 0;
1632                 var->blue.offset = 0;
1633                 var->red.length = 8; /* 8bit DAC */
1634                 var->green.length = 8;
1635                 var->blue.length = 8;
1636                 var->transp.offset = 0;
1637                 var->transp.length = 0;
1638                 break;
1639         case 15:
1640                 var->red.offset = 10;
1641                 var->green.offset = 5;
1642                 var->blue.offset = 0;
1643                 var->red.length = 5;
1644                 var->green.length = 5;
1645                 var->blue.length = 5;
1646                 var->transp.offset = 15;
1647                 var->transp.length = 1;
1648                 break;
1649         case 16:
1650                 var->red.offset = 11;
1651                 var->green.offset = 5;
1652                 var->blue.offset = 0;
1653                 var->red.length = 5;
1654                 var->green.length = 6;
1655                 var->blue.length = 5;
1656                 var->transp.offset = 0;
1657                 break;
1658         case 24:
1659                 var->red.offset = 16;
1660                 var->green.offset = 8;
1661                 var->blue.offset = 0;
1662                 var->red.length = 8;
1663                 var->green.length = 8;
1664                 var->blue.length = 8;
1665                 var->transp.offset = 0;
1666                 var->transp.length = 0;
1667                 break;
1668         case 32:
1669                 var->red.offset = 16;
1670                 var->green.offset = 8;
1671                 var->blue.offset = 0;
1672                 var->red.length = 8;
1673                 var->green.length = 8;
1674                 var->blue.length = 8;
1675                 var->transp.offset = 24;
1676                 var->transp.length = 8;
1677                 break;
1678         default:
1679                 break;
1680         }
1681 }
1682
1683 /**
1684  * drm_fb_helper_check_var - implementation for &fb_ops.fb_check_var
1685  * @var: screeninfo to check
1686  * @info: fbdev registered by the helper
1687  */
1688 int drm_fb_helper_check_var(struct fb_var_screeninfo *var,
1689                             struct fb_info *info)
1690 {
1691         struct drm_fb_helper *fb_helper = info->par;
1692         struct drm_framebuffer *fb = fb_helper->fb;
1693
1694         if (in_dbg_master())
1695                 return -EINVAL;
1696
1697         if (var->pixclock != 0) {
1698                 DRM_DEBUG("fbdev emulation doesn't support changing the pixel clock, value of pixclock is ignored\n");
1699                 var->pixclock = 0;
1700         }
1701
1702         if ((drm_format_info_block_width(fb->format, 0) > 1) ||
1703             (drm_format_info_block_height(fb->format, 0) > 1))
1704                 return -EINVAL;
1705
1706         /*
1707          * Changes struct fb_var_screeninfo are currently not pushed back
1708          * to KMS, hence fail if different settings are requested.
1709          */
1710         if (var->bits_per_pixel != fb->format->cpp[0] * 8 ||
1711             var->xres > fb->width || var->yres > fb->height ||
1712             var->xres_virtual > fb->width || var->yres_virtual > fb->height) {
1713                 DRM_DEBUG("fb requested width/height/bpp can't fit in current fb "
1714                           "request %dx%d-%d (virtual %dx%d) > %dx%d-%d\n",
1715                           var->xres, var->yres, var->bits_per_pixel,
1716                           var->xres_virtual, var->yres_virtual,
1717                           fb->width, fb->height, fb->format->cpp[0] * 8);
1718                 return -EINVAL;
1719         }
1720
1721         /*
1722          * Workaround for SDL 1.2, which is known to be setting all pixel format
1723          * fields values to zero in some cases. We treat this situation as a
1724          * kind of "use some reasonable autodetected values".
1725          */
1726         if (!var->red.offset     && !var->green.offset    &&
1727             !var->blue.offset    && !var->transp.offset   &&
1728             !var->red.length     && !var->green.length    &&
1729             !var->blue.length    && !var->transp.length   &&
1730             !var->red.msb_right  && !var->green.msb_right &&
1731             !var->blue.msb_right && !var->transp.msb_right) {
1732                 drm_fb_helper_fill_pixel_fmt(var, fb->format->depth);
1733         }
1734
1735         /*
1736          * drm fbdev emulation doesn't support changing the pixel format at all,
1737          * so reject all pixel format changing requests.
1738          */
1739         if (!drm_fb_pixel_format_equal(var, &info->var)) {
1740                 DRM_DEBUG("fbdev emulation doesn't support changing the pixel format\n");
1741                 return -EINVAL;
1742         }
1743
1744         return 0;
1745 }
1746 EXPORT_SYMBOL(drm_fb_helper_check_var);
1747
1748 /**
1749  * drm_fb_helper_set_par - implementation for &fb_ops.fb_set_par
1750  * @info: fbdev registered by the helper
1751  *
1752  * This will let fbcon do the mode init and is called at initialization time by
1753  * the fbdev core when registering the driver, and later on through the hotplug
1754  * callback.
1755  */
1756 int drm_fb_helper_set_par(struct fb_info *info)
1757 {
1758         struct drm_fb_helper *fb_helper = info->par;
1759         struct fb_var_screeninfo *var = &info->var;
1760
1761         if (oops_in_progress)
1762                 return -EBUSY;
1763
1764         if (var->pixclock != 0) {
1765                 DRM_ERROR("PIXEL CLOCK SET\n");
1766                 return -EINVAL;
1767         }
1768
1769         drm_fb_helper_restore_fbdev_mode_unlocked(fb_helper);
1770
1771         return 0;
1772 }
1773 EXPORT_SYMBOL(drm_fb_helper_set_par);
1774
1775 static void pan_set(struct drm_fb_helper *fb_helper, int x, int y)
1776 {
1777         int i;
1778
1779         for (i = 0; i < fb_helper->crtc_count; i++) {
1780                 struct drm_mode_set *mode_set;
1781
1782                 mode_set = &fb_helper->crtc_info[i].mode_set;
1783
1784                 mode_set->x = x;
1785                 mode_set->y = y;
1786         }
1787 }
1788
1789 static int pan_display_atomic(struct fb_var_screeninfo *var,
1790                               struct fb_info *info)
1791 {
1792         struct drm_fb_helper *fb_helper = info->par;
1793         int ret;
1794
1795         pan_set(fb_helper, var->xoffset, var->yoffset);
1796
1797         ret = restore_fbdev_mode_atomic(fb_helper, true);
1798         if (!ret) {
1799                 info->var.xoffset = var->xoffset;
1800                 info->var.yoffset = var->yoffset;
1801         } else
1802                 pan_set(fb_helper, info->var.xoffset, info->var.yoffset);
1803
1804         return ret;
1805 }
1806
1807 static int pan_display_legacy(struct fb_var_screeninfo *var,
1808                               struct fb_info *info)
1809 {
1810         struct drm_fb_helper *fb_helper = info->par;
1811         struct drm_mode_set *modeset;
1812         int ret = 0;
1813         int i;
1814
1815         drm_modeset_lock_all(fb_helper->dev);
1816         for (i = 0; i < fb_helper->crtc_count; i++) {
1817                 modeset = &fb_helper->crtc_info[i].mode_set;
1818
1819                 modeset->x = var->xoffset;
1820                 modeset->y = var->yoffset;
1821
1822                 if (modeset->num_connectors) {
1823                         ret = drm_mode_set_config_internal(modeset);
1824                         if (!ret) {
1825                                 info->var.xoffset = var->xoffset;
1826                                 info->var.yoffset = var->yoffset;
1827                         }
1828                 }
1829         }
1830         drm_modeset_unlock_all(fb_helper->dev);
1831
1832         return ret;
1833 }
1834
1835 /**
1836  * drm_fb_helper_pan_display - implementation for &fb_ops.fb_pan_display
1837  * @var: updated screen information
1838  * @info: fbdev registered by the helper
1839  */
1840 int drm_fb_helper_pan_display(struct fb_var_screeninfo *var,
1841                               struct fb_info *info)
1842 {
1843         struct drm_fb_helper *fb_helper = info->par;
1844         struct drm_device *dev = fb_helper->dev;
1845         int ret;
1846
1847         if (oops_in_progress)
1848                 return -EBUSY;
1849
1850         mutex_lock(&fb_helper->lock);
1851         if (!drm_fb_helper_is_bound(fb_helper)) {
1852                 mutex_unlock(&fb_helper->lock);
1853                 return -EBUSY;
1854         }
1855
1856         if (drm_drv_uses_atomic_modeset(dev))
1857                 ret = pan_display_atomic(var, info);
1858         else
1859                 ret = pan_display_legacy(var, info);
1860         mutex_unlock(&fb_helper->lock);
1861
1862         return ret;
1863 }
1864 EXPORT_SYMBOL(drm_fb_helper_pan_display);
1865
1866 /*
1867  * Allocates the backing storage and sets up the fbdev info structure through
1868  * the ->fb_probe callback.
1869  */
1870 static int drm_fb_helper_single_fb_probe(struct drm_fb_helper *fb_helper,
1871                                          int preferred_bpp)
1872 {
1873         int ret = 0;
1874         int crtc_count = 0;
1875         int i;
1876         struct drm_fb_helper_surface_size sizes;
1877         int best_depth = 0;
1878
1879         memset(&sizes, 0, sizeof(struct drm_fb_helper_surface_size));
1880         sizes.surface_depth = 24;
1881         sizes.surface_bpp = 32;
1882         sizes.fb_width = (u32)-1;
1883         sizes.fb_height = (u32)-1;
1884
1885         /*
1886          * If driver picks 8 or 16 by default use that for both depth/bpp
1887          * to begin with
1888          */
1889         if (preferred_bpp != sizes.surface_bpp)
1890                 sizes.surface_depth = sizes.surface_bpp = preferred_bpp;
1891
1892         drm_fb_helper_for_each_connector(fb_helper, i) {
1893                 struct drm_fb_helper_connector *fb_helper_conn = fb_helper->connector_info[i];
1894                 struct drm_cmdline_mode *cmdline_mode;
1895
1896                 cmdline_mode = &fb_helper_conn->connector->cmdline_mode;
1897
1898                 if (cmdline_mode->bpp_specified) {
1899                         switch (cmdline_mode->bpp) {
1900                         case 8:
1901                                 sizes.surface_depth = sizes.surface_bpp = 8;
1902                                 break;
1903                         case 15:
1904                                 sizes.surface_depth = 15;
1905                                 sizes.surface_bpp = 16;
1906                                 break;
1907                         case 16:
1908                                 sizes.surface_depth = sizes.surface_bpp = 16;
1909                                 break;
1910                         case 24:
1911                                 sizes.surface_depth = sizes.surface_bpp = 24;
1912                                 break;
1913                         case 32:
1914                                 sizes.surface_depth = 24;
1915                                 sizes.surface_bpp = 32;
1916                                 break;
1917                         }
1918                         break;
1919                 }
1920         }
1921
1922         /*
1923          * If we run into a situation where, for example, the primary plane
1924          * supports RGBA5551 (16 bpp, depth 15) but not RGB565 (16 bpp, depth
1925          * 16) we need to scale down the depth of the sizes we request.
1926          */
1927         for (i = 0; i < fb_helper->crtc_count; i++) {
1928                 struct drm_mode_set *mode_set = &fb_helper->crtc_info[i].mode_set;
1929                 struct drm_crtc *crtc = mode_set->crtc;
1930                 struct drm_plane *plane = crtc->primary;
1931                 int j;
1932
1933                 DRM_DEBUG("test CRTC %d primary plane\n", i);
1934
1935                 for (j = 0; j < plane->format_count; j++) {
1936                         const struct drm_format_info *fmt;
1937
1938                         fmt = drm_format_info(plane->format_types[j]);
1939
1940                         /*
1941                          * Do not consider YUV or other complicated formats
1942                          * for framebuffers. This means only legacy formats
1943                          * are supported (fmt->depth is a legacy field) but
1944                          * the framebuffer emulation can only deal with such
1945                          * formats, specifically RGB/BGA formats.
1946                          */
1947                         if (fmt->depth == 0)
1948                                 continue;
1949
1950                         /* We found a perfect fit, great */
1951                         if (fmt->depth == sizes.surface_depth) {
1952                                 best_depth = fmt->depth;
1953                                 break;
1954                         }
1955
1956                         /* Skip depths above what we're looking for */
1957                         if (fmt->depth > sizes.surface_depth)
1958                                 continue;
1959
1960                         /* Best depth found so far */
1961                         if (fmt->depth > best_depth)
1962                                 best_depth = fmt->depth;
1963                 }
1964         }
1965         if (sizes.surface_depth != best_depth) {
1966                 DRM_INFO("requested bpp %d, scaled depth down to %d",
1967                          sizes.surface_bpp, best_depth);
1968                 sizes.surface_depth = best_depth;
1969         }
1970
1971         /* first up get a count of crtcs now in use and new min/maxes width/heights */
1972         crtc_count = 0;
1973         for (i = 0; i < fb_helper->crtc_count; i++) {
1974                 struct drm_display_mode *desired_mode;
1975                 struct drm_mode_set *mode_set;
1976                 int x, y, j;
1977                 /* in case of tile group, are we the last tile vert or horiz?
1978                  * If no tile group you are always the last one both vertically
1979                  * and horizontally
1980                  */
1981                 bool lastv = true, lasth = true;
1982
1983                 desired_mode = fb_helper->crtc_info[i].desired_mode;
1984                 mode_set = &fb_helper->crtc_info[i].mode_set;
1985
1986                 if (!desired_mode)
1987                         continue;
1988
1989                 crtc_count++;
1990
1991                 x = fb_helper->crtc_info[i].x;
1992                 y = fb_helper->crtc_info[i].y;
1993
1994                 sizes.surface_width  = max_t(u32, desired_mode->hdisplay + x, sizes.surface_width);
1995                 sizes.surface_height = max_t(u32, desired_mode->vdisplay + y, sizes.surface_height);
1996
1997                 for (j = 0; j < mode_set->num_connectors; j++) {
1998                         struct drm_connector *connector = mode_set->connectors[j];
1999
2000                         if (connector->has_tile) {
2001                                 lasth = (connector->tile_h_loc == (connector->num_h_tile - 1));
2002                                 lastv = (connector->tile_v_loc == (connector->num_v_tile - 1));
2003                                 /* cloning to multiple tiles is just crazy-talk, so: */
2004                                 break;
2005                         }
2006                 }
2007
2008                 if (lasth)
2009                         sizes.fb_width  = min_t(u32, desired_mode->hdisplay + x, sizes.fb_width);
2010                 if (lastv)
2011                         sizes.fb_height = min_t(u32, desired_mode->vdisplay + y, sizes.fb_height);
2012         }
2013
2014         if (crtc_count == 0 || sizes.fb_width == -1 || sizes.fb_height == -1) {
2015                 DRM_INFO("Cannot find any crtc or sizes\n");
2016
2017                 /* First time: disable all crtc's.. */
2018                 if (!fb_helper->deferred_setup && !READ_ONCE(fb_helper->dev->master))
2019                         restore_fbdev_mode(fb_helper);
2020                 return -EAGAIN;
2021         }
2022
2023         /* Handle our overallocation */
2024         sizes.surface_height *= drm_fbdev_overalloc;
2025         sizes.surface_height /= 100;
2026
2027         /* push down into drivers */
2028         ret = (*fb_helper->funcs->fb_probe)(fb_helper, &sizes);
2029         if (ret < 0)
2030                 return ret;
2031
2032         strcpy(fb_helper->fb->comm, "[fbcon]");
2033         return 0;
2034 }
2035
2036 static void drm_fb_helper_fill_fix(struct fb_info *info, uint32_t pitch,
2037                                    uint32_t depth)
2038 {
2039         info->fix.type = FB_TYPE_PACKED_PIXELS;
2040         info->fix.visual = depth == 8 ? FB_VISUAL_PSEUDOCOLOR :
2041                 FB_VISUAL_TRUECOLOR;
2042         info->fix.mmio_start = 0;
2043         info->fix.mmio_len = 0;
2044         info->fix.type_aux = 0;
2045         info->fix.xpanstep = 1; /* doing it in hw */
2046         info->fix.ypanstep = 1; /* doing it in hw */
2047         info->fix.ywrapstep = 0;
2048         info->fix.accel = FB_ACCEL_NONE;
2049
2050         info->fix.line_length = pitch;
2051 }
2052
2053 static void drm_fb_helper_fill_var(struct fb_info *info,
2054                                    struct drm_fb_helper *fb_helper,
2055                                    uint32_t fb_width, uint32_t fb_height)
2056 {
2057         struct drm_framebuffer *fb = fb_helper->fb;
2058
2059         WARN_ON((drm_format_info_block_width(fb->format, 0) > 1) ||
2060                 (drm_format_info_block_height(fb->format, 0) > 1));
2061         info->pseudo_palette = fb_helper->pseudo_palette;
2062         info->var.xres_virtual = fb->width;
2063         info->var.yres_virtual = fb->height;
2064         info->var.bits_per_pixel = fb->format->cpp[0] * 8;
2065         info->var.accel_flags = FB_ACCELF_TEXT;
2066         info->var.xoffset = 0;
2067         info->var.yoffset = 0;
2068         info->var.activate = FB_ACTIVATE_NOW;
2069
2070         drm_fb_helper_fill_pixel_fmt(&info->var, fb->format->depth);
2071
2072         info->var.xres = fb_width;
2073         info->var.yres = fb_height;
2074 }
2075
2076 /**
2077  * drm_fb_helper_fill_info - initializes fbdev information
2078  * @info: fbdev instance to set up
2079  * @fb_helper: fb helper instance to use as template
2080  * @sizes: describes fbdev size and scanout surface size
2081  *
2082  * Sets up the variable and fixed fbdev metainformation from the given fb helper
2083  * instance and the drm framebuffer allocated in &drm_fb_helper.fb.
2084  *
2085  * Drivers should call this (or their equivalent setup code) from their
2086  * &drm_fb_helper_funcs.fb_probe callback after having allocated the fbdev
2087  * backing storage framebuffer.
2088  */
2089 void drm_fb_helper_fill_info(struct fb_info *info,
2090                              struct drm_fb_helper *fb_helper,
2091                              struct drm_fb_helper_surface_size *sizes)
2092 {
2093         struct drm_framebuffer *fb = fb_helper->fb;
2094
2095         drm_fb_helper_fill_fix(info, fb->pitches[0], fb->format->depth);
2096         drm_fb_helper_fill_var(info, fb_helper,
2097                                sizes->fb_width, sizes->fb_height);
2098
2099         info->par = fb_helper;
2100         snprintf(info->fix.id, sizeof(info->fix.id), "%sdrmfb",
2101                  fb_helper->dev->driver->name);
2102
2103 }
2104 EXPORT_SYMBOL(drm_fb_helper_fill_info);
2105
2106 static int drm_fb_helper_probe_connector_modes(struct drm_fb_helper *fb_helper,
2107                                                 uint32_t maxX,
2108                                                 uint32_t maxY)
2109 {
2110         struct drm_connector *connector;
2111         int i, count = 0;
2112
2113         drm_fb_helper_for_each_connector(fb_helper, i) {
2114                 connector = fb_helper->connector_info[i]->connector;
2115                 count += connector->funcs->fill_modes(connector, maxX, maxY);
2116         }
2117
2118         return count;
2119 }
2120
2121 struct drm_display_mode *drm_has_preferred_mode(struct drm_fb_helper_connector *fb_connector, int width, int height)
2122 {
2123         struct drm_display_mode *mode;
2124
2125         list_for_each_entry(mode, &fb_connector->connector->modes, head) {
2126                 if (mode->hdisplay > width ||
2127                     mode->vdisplay > height)
2128                         continue;
2129                 if (mode->type & DRM_MODE_TYPE_PREFERRED)
2130                         return mode;
2131         }
2132         return NULL;
2133 }
2134 EXPORT_SYMBOL(drm_has_preferred_mode);
2135
2136 static bool drm_has_cmdline_mode(struct drm_fb_helper_connector *fb_connector)
2137 {
2138         return fb_connector->connector->cmdline_mode.specified;
2139 }
2140
2141 struct drm_display_mode *drm_pick_cmdline_mode(struct drm_fb_helper_connector *fb_helper_conn)
2142 {
2143         struct drm_cmdline_mode *cmdline_mode;
2144         struct drm_display_mode *mode;
2145         bool prefer_non_interlace;
2146
2147         cmdline_mode = &fb_helper_conn->connector->cmdline_mode;
2148         if (cmdline_mode->specified == false)
2149                 return NULL;
2150
2151         /* attempt to find a matching mode in the list of modes
2152          *  we have gotten so far, if not add a CVT mode that conforms
2153          */
2154         if (cmdline_mode->rb || cmdline_mode->margins)
2155                 goto create_mode;
2156
2157         prefer_non_interlace = !cmdline_mode->interlace;
2158 again:
2159         list_for_each_entry(mode, &fb_helper_conn->connector->modes, head) {
2160                 /* check width/height */
2161                 if (mode->hdisplay != cmdline_mode->xres ||
2162                     mode->vdisplay != cmdline_mode->yres)
2163                         continue;
2164
2165                 if (cmdline_mode->refresh_specified) {
2166                         if (mode->vrefresh != cmdline_mode->refresh)
2167                                 continue;
2168                 }
2169
2170                 if (cmdline_mode->interlace) {
2171                         if (!(mode->flags & DRM_MODE_FLAG_INTERLACE))
2172                                 continue;
2173                 } else if (prefer_non_interlace) {
2174                         if (mode->flags & DRM_MODE_FLAG_INTERLACE)
2175                                 continue;
2176                 }
2177                 return mode;
2178         }
2179
2180         if (prefer_non_interlace) {
2181                 prefer_non_interlace = false;
2182                 goto again;
2183         }
2184
2185 create_mode:
2186         mode = drm_mode_create_from_cmdline_mode(fb_helper_conn->connector->dev,
2187                                                  cmdline_mode);
2188         list_add(&mode->head, &fb_helper_conn->connector->modes);
2189         return mode;
2190 }
2191 EXPORT_SYMBOL(drm_pick_cmdline_mode);
2192
2193 static bool drm_connector_enabled(struct drm_connector *connector, bool strict)
2194 {
2195         bool enable;
2196
2197         if (connector->display_info.non_desktop)
2198                 return false;
2199
2200         if (strict)
2201                 enable = connector->status == connector_status_connected;
2202         else
2203                 enable = connector->status != connector_status_disconnected;
2204
2205         return enable;
2206 }
2207
2208 static void drm_enable_connectors(struct drm_fb_helper *fb_helper,
2209                                   bool *enabled)
2210 {
2211         bool any_enabled = false;
2212         struct drm_connector *connector;
2213         int i = 0;
2214
2215         drm_fb_helper_for_each_connector(fb_helper, i) {
2216                 connector = fb_helper->connector_info[i]->connector;
2217                 enabled[i] = drm_connector_enabled(connector, true);
2218                 DRM_DEBUG_KMS("connector %d enabled? %s\n", connector->base.id,
2219                               connector->display_info.non_desktop ? "non desktop" : enabled[i] ? "yes" : "no");
2220
2221                 any_enabled |= enabled[i];
2222         }
2223
2224         if (any_enabled)
2225                 return;
2226
2227         drm_fb_helper_for_each_connector(fb_helper, i) {
2228                 connector = fb_helper->connector_info[i]->connector;
2229                 enabled[i] = drm_connector_enabled(connector, false);
2230         }
2231 }
2232
2233 static bool drm_target_cloned(struct drm_fb_helper *fb_helper,
2234                               struct drm_display_mode **modes,
2235                               struct drm_fb_offset *offsets,
2236                               bool *enabled, int width, int height)
2237 {
2238         int count, i, j;
2239         bool can_clone = false;
2240         struct drm_fb_helper_connector *fb_helper_conn;
2241         struct drm_display_mode *dmt_mode, *mode;
2242
2243         /* only contemplate cloning in the single crtc case */
2244         if (fb_helper->crtc_count > 1)
2245                 return false;
2246
2247         count = 0;
2248         drm_fb_helper_for_each_connector(fb_helper, i) {
2249                 if (enabled[i])
2250                         count++;
2251         }
2252
2253         /* only contemplate cloning if more than one connector is enabled */
2254         if (count <= 1)
2255                 return false;
2256
2257         /* check the command line or if nothing common pick 1024x768 */
2258         can_clone = true;
2259         drm_fb_helper_for_each_connector(fb_helper, i) {
2260                 if (!enabled[i])
2261                         continue;
2262                 fb_helper_conn = fb_helper->connector_info[i];
2263                 modes[i] = drm_pick_cmdline_mode(fb_helper_conn);
2264                 if (!modes[i]) {
2265                         can_clone = false;
2266                         break;
2267                 }
2268                 for (j = 0; j < i; j++) {
2269                         if (!enabled[j])
2270                                 continue;
2271                         if (!drm_mode_match(modes[j], modes[i],
2272                                             DRM_MODE_MATCH_TIMINGS |
2273                                             DRM_MODE_MATCH_CLOCK |
2274                                             DRM_MODE_MATCH_FLAGS |
2275                                             DRM_MODE_MATCH_3D_FLAGS))
2276                                 can_clone = false;
2277                 }
2278         }
2279
2280         if (can_clone) {
2281                 DRM_DEBUG_KMS("can clone using command line\n");
2282                 return true;
2283         }
2284
2285         /* try and find a 1024x768 mode on each connector */
2286         can_clone = true;
2287         dmt_mode = drm_mode_find_dmt(fb_helper->dev, 1024, 768, 60, false);
2288
2289         drm_fb_helper_for_each_connector(fb_helper, i) {
2290                 if (!enabled[i])
2291                         continue;
2292
2293                 fb_helper_conn = fb_helper->connector_info[i];
2294                 list_for_each_entry(mode, &fb_helper_conn->connector->modes, head) {
2295                         if (drm_mode_match(mode, dmt_mode,
2296                                            DRM_MODE_MATCH_TIMINGS |
2297                                            DRM_MODE_MATCH_CLOCK |
2298                                            DRM_MODE_MATCH_FLAGS |
2299                                            DRM_MODE_MATCH_3D_FLAGS))
2300                                 modes[i] = mode;
2301                 }
2302                 if (!modes[i])
2303                         can_clone = false;
2304         }
2305
2306         if (can_clone) {
2307                 DRM_DEBUG_KMS("can clone using 1024x768\n");
2308                 return true;
2309         }
2310         DRM_INFO("kms: can't enable cloning when we probably wanted to.\n");
2311         return false;
2312 }
2313
2314 static int drm_get_tile_offsets(struct drm_fb_helper *fb_helper,
2315                                 struct drm_display_mode **modes,
2316                                 struct drm_fb_offset *offsets,
2317                                 int idx,
2318                                 int h_idx, int v_idx)
2319 {
2320         struct drm_fb_helper_connector *fb_helper_conn;
2321         int i;
2322         int hoffset = 0, voffset = 0;
2323
2324         drm_fb_helper_for_each_connector(fb_helper, i) {
2325                 fb_helper_conn = fb_helper->connector_info[i];
2326                 if (!fb_helper_conn->connector->has_tile)
2327                         continue;
2328
2329                 if (!modes[i] && (h_idx || v_idx)) {
2330                         DRM_DEBUG_KMS("no modes for connector tiled %d %d\n", i,
2331                                       fb_helper_conn->connector->base.id);
2332                         continue;
2333                 }
2334                 if (fb_helper_conn->connector->tile_h_loc < h_idx)
2335                         hoffset += modes[i]->hdisplay;
2336
2337                 if (fb_helper_conn->connector->tile_v_loc < v_idx)
2338                         voffset += modes[i]->vdisplay;
2339         }
2340         offsets[idx].x = hoffset;
2341         offsets[idx].y = voffset;
2342         DRM_DEBUG_KMS("returned %d %d for %d %d\n", hoffset, voffset, h_idx, v_idx);
2343         return 0;
2344 }
2345
2346 static bool drm_target_preferred(struct drm_fb_helper *fb_helper,
2347                                  struct drm_display_mode **modes,
2348                                  struct drm_fb_offset *offsets,
2349                                  bool *enabled, int width, int height)
2350 {
2351         struct drm_fb_helper_connector *fb_helper_conn;
2352         const u64 mask = BIT_ULL(fb_helper->connector_count) - 1;
2353         u64 conn_configured = 0;
2354         int tile_pass = 0;
2355         int i;
2356
2357 retry:
2358         drm_fb_helper_for_each_connector(fb_helper, i) {
2359                 fb_helper_conn = fb_helper->connector_info[i];
2360
2361                 if (conn_configured & BIT_ULL(i))
2362                         continue;
2363
2364                 if (enabled[i] == false) {
2365                         conn_configured |= BIT_ULL(i);
2366                         continue;
2367                 }
2368
2369                 /* first pass over all the untiled connectors */
2370                 if (tile_pass == 0 && fb_helper_conn->connector->has_tile)
2371                         continue;
2372
2373                 if (tile_pass == 1) {
2374                         if (fb_helper_conn->connector->tile_h_loc != 0 ||
2375                             fb_helper_conn->connector->tile_v_loc != 0)
2376                                 continue;
2377
2378                 } else {
2379                         if (fb_helper_conn->connector->tile_h_loc != tile_pass - 1 &&
2380                             fb_helper_conn->connector->tile_v_loc != tile_pass - 1)
2381                         /* if this tile_pass doesn't cover any of the tiles - keep going */
2382                                 continue;
2383
2384                         /*
2385                          * find the tile offsets for this pass - need to find
2386                          * all tiles left and above
2387                          */
2388                         drm_get_tile_offsets(fb_helper, modes, offsets,
2389                                              i, fb_helper_conn->connector->tile_h_loc, fb_helper_conn->connector->tile_v_loc);
2390                 }
2391                 DRM_DEBUG_KMS("looking for cmdline mode on connector %d\n",
2392                               fb_helper_conn->connector->base.id);
2393
2394                 /* got for command line mode first */
2395                 modes[i] = drm_pick_cmdline_mode(fb_helper_conn);
2396                 if (!modes[i]) {
2397                         DRM_DEBUG_KMS("looking for preferred mode on connector %d %d\n",
2398                                       fb_helper_conn->connector->base.id, fb_helper_conn->connector->tile_group ? fb_helper_conn->connector->tile_group->id : 0);
2399                         modes[i] = drm_has_preferred_mode(fb_helper_conn, width, height);
2400                 }
2401                 /* No preferred modes, pick one off the list */
2402                 if (!modes[i] && !list_empty(&fb_helper_conn->connector->modes)) {
2403                         list_for_each_entry(modes[i], &fb_helper_conn->connector->modes, head)
2404                                 break;
2405                 }
2406                 DRM_DEBUG_KMS("found mode %s\n", modes[i] ? modes[i]->name :
2407                           "none");
2408                 conn_configured |= BIT_ULL(i);
2409         }
2410
2411         if ((conn_configured & mask) != mask) {
2412                 tile_pass++;
2413                 goto retry;
2414         }
2415         return true;
2416 }
2417
2418 static bool connector_has_possible_crtc(struct drm_connector *connector,
2419                                         struct drm_crtc *crtc)
2420 {
2421         struct drm_encoder *encoder;
2422         int i;
2423
2424         drm_connector_for_each_possible_encoder(connector, encoder, i) {
2425                 if (encoder->possible_crtcs & drm_crtc_mask(crtc))
2426                         return true;
2427         }
2428
2429         return false;
2430 }
2431
2432 static int drm_pick_crtcs(struct drm_fb_helper *fb_helper,
2433                           struct drm_fb_helper_crtc **best_crtcs,
2434                           struct drm_display_mode **modes,
2435                           int n, int width, int height)
2436 {
2437         int c, o;
2438         struct drm_connector *connector;
2439         int my_score, best_score, score;
2440         struct drm_fb_helper_crtc **crtcs, *crtc;
2441         struct drm_fb_helper_connector *fb_helper_conn;
2442
2443         if (n == fb_helper->connector_count)
2444                 return 0;
2445
2446         fb_helper_conn = fb_helper->connector_info[n];
2447         connector = fb_helper_conn->connector;
2448
2449         best_crtcs[n] = NULL;
2450         best_score = drm_pick_crtcs(fb_helper, best_crtcs, modes, n+1, width, height);
2451         if (modes[n] == NULL)
2452                 return best_score;
2453
2454         crtcs = kcalloc(fb_helper->connector_count,
2455                         sizeof(struct drm_fb_helper_crtc *), GFP_KERNEL);
2456         if (!crtcs)
2457                 return best_score;
2458
2459         my_score = 1;
2460         if (connector->status == connector_status_connected)
2461                 my_score++;
2462         if (drm_has_cmdline_mode(fb_helper_conn))
2463                 my_score++;
2464         if (drm_has_preferred_mode(fb_helper_conn, width, height))
2465                 my_score++;
2466
2467         /*
2468          * select a crtc for this connector and then attempt to configure
2469          * remaining connectors
2470          */
2471         for (c = 0; c < fb_helper->crtc_count; c++) {
2472                 crtc = &fb_helper->crtc_info[c];
2473
2474                 if (!connector_has_possible_crtc(connector,
2475                                                  crtc->mode_set.crtc))
2476                         continue;
2477
2478                 for (o = 0; o < n; o++)
2479                         if (best_crtcs[o] == crtc)
2480                                 break;
2481
2482                 if (o < n) {
2483                         /* ignore cloning unless only a single crtc */
2484                         if (fb_helper->crtc_count > 1)
2485                                 continue;
2486
2487                         if (!drm_mode_equal(modes[o], modes[n]))
2488                                 continue;
2489                 }
2490
2491                 crtcs[n] = crtc;
2492                 memcpy(crtcs, best_crtcs, n * sizeof(struct drm_fb_helper_crtc *));
2493                 score = my_score + drm_pick_crtcs(fb_helper, crtcs, modes, n + 1,
2494                                                   width, height);
2495                 if (score > best_score) {
2496                         best_score = score;
2497                         memcpy(best_crtcs, crtcs,
2498                                fb_helper->connector_count *
2499                                sizeof(struct drm_fb_helper_crtc *));
2500                 }
2501         }
2502
2503         kfree(crtcs);
2504         return best_score;
2505 }
2506
2507 /*
2508  * This function checks if rotation is necessary because of panel orientation
2509  * and if it is, if it is supported.
2510  * If rotation is necessary and supported, it gets set in fb_crtc.rotation.
2511  * If rotation is necessary but not supported, a DRM_MODE_ROTATE_* flag gets
2512  * or-ed into fb_helper->sw_rotations. In drm_setup_crtcs_fb() we check if only
2513  * one bit is set and then we set fb_info.fbcon_rotate_hint to make fbcon do
2514  * the unsupported rotation.
2515  */
2516 static void drm_setup_crtc_rotation(struct drm_fb_helper *fb_helper,
2517                                     struct drm_fb_helper_crtc *fb_crtc,
2518                                     struct drm_connector *connector)
2519 {
2520         struct drm_plane *plane = fb_crtc->mode_set.crtc->primary;
2521         uint64_t valid_mask = 0;
2522         int i, rotation;
2523
2524         fb_crtc->rotation = DRM_MODE_ROTATE_0;
2525
2526         switch (connector->display_info.panel_orientation) {
2527         case DRM_MODE_PANEL_ORIENTATION_BOTTOM_UP:
2528                 rotation = DRM_MODE_ROTATE_180;
2529                 break;
2530         case DRM_MODE_PANEL_ORIENTATION_LEFT_UP:
2531                 rotation = DRM_MODE_ROTATE_90;
2532                 break;
2533         case DRM_MODE_PANEL_ORIENTATION_RIGHT_UP:
2534                 rotation = DRM_MODE_ROTATE_270;
2535                 break;
2536         default:
2537                 rotation = DRM_MODE_ROTATE_0;
2538         }
2539
2540         /*
2541          * TODO: support 90 / 270 degree hardware rotation,
2542          * depending on the hardware this may require the framebuffer
2543          * to be in a specific tiling format.
2544          */
2545         if (rotation != DRM_MODE_ROTATE_180 || !plane->rotation_property) {
2546                 fb_helper->sw_rotations |= rotation;
2547                 return;
2548         }
2549
2550         for (i = 0; i < plane->rotation_property->num_values; i++)
2551                 valid_mask |= (1ULL << plane->rotation_property->values[i]);
2552
2553         if (!(rotation & valid_mask)) {
2554                 fb_helper->sw_rotations |= rotation;
2555                 return;
2556         }
2557
2558         fb_crtc->rotation = rotation;
2559         /* Rotating in hardware, fbcon should not rotate */
2560         fb_helper->sw_rotations |= DRM_MODE_ROTATE_0;
2561 }
2562
2563 static void drm_setup_crtcs(struct drm_fb_helper *fb_helper,
2564                             u32 width, u32 height)
2565 {
2566         struct drm_device *dev = fb_helper->dev;
2567         struct drm_fb_helper_crtc **crtcs;
2568         struct drm_display_mode **modes;
2569         struct drm_fb_offset *offsets;
2570         bool *enabled;
2571         int i;
2572
2573         DRM_DEBUG_KMS("\n");
2574         /* prevent concurrent modification of connector_count by hotplug */
2575         lockdep_assert_held(&fb_helper->lock);
2576
2577         crtcs = kcalloc(fb_helper->connector_count,
2578                         sizeof(struct drm_fb_helper_crtc *), GFP_KERNEL);
2579         modes = kcalloc(fb_helper->connector_count,
2580                         sizeof(struct drm_display_mode *), GFP_KERNEL);
2581         offsets = kcalloc(fb_helper->connector_count,
2582                           sizeof(struct drm_fb_offset), GFP_KERNEL);
2583         enabled = kcalloc(fb_helper->connector_count,
2584                           sizeof(bool), GFP_KERNEL);
2585         if (!crtcs || !modes || !enabled || !offsets) {
2586                 DRM_ERROR("Memory allocation failed\n");
2587                 goto out;
2588         }
2589
2590         mutex_lock(&fb_helper->dev->mode_config.mutex);
2591         if (drm_fb_helper_probe_connector_modes(fb_helper, width, height) == 0)
2592                 DRM_DEBUG_KMS("No connectors reported connected with modes\n");
2593         drm_enable_connectors(fb_helper, enabled);
2594
2595         if (!(fb_helper->funcs->initial_config &&
2596               fb_helper->funcs->initial_config(fb_helper, crtcs, modes,
2597                                                offsets,
2598                                                enabled, width, height))) {
2599                 memset(modes, 0, fb_helper->connector_count*sizeof(modes[0]));
2600                 memset(crtcs, 0, fb_helper->connector_count*sizeof(crtcs[0]));
2601                 memset(offsets, 0, fb_helper->connector_count*sizeof(offsets[0]));
2602
2603                 if (!drm_target_cloned(fb_helper, modes, offsets,
2604                                        enabled, width, height) &&
2605                     !drm_target_preferred(fb_helper, modes, offsets,
2606                                           enabled, width, height))
2607                         DRM_ERROR("Unable to find initial modes\n");
2608
2609                 DRM_DEBUG_KMS("picking CRTCs for %dx%d config\n",
2610                               width, height);
2611
2612                 drm_pick_crtcs(fb_helper, crtcs, modes, 0, width, height);
2613         }
2614         mutex_unlock(&fb_helper->dev->mode_config.mutex);
2615
2616         /* need to set the modesets up here for use later */
2617         /* fill out the connector<->crtc mappings into the modesets */
2618         for (i = 0; i < fb_helper->crtc_count; i++)
2619                 drm_fb_helper_modeset_release(fb_helper,
2620                                               &fb_helper->crtc_info[i].mode_set);
2621
2622         fb_helper->sw_rotations = 0;
2623         drm_fb_helper_for_each_connector(fb_helper, i) {
2624                 struct drm_display_mode *mode = modes[i];
2625                 struct drm_fb_helper_crtc *fb_crtc = crtcs[i];
2626                 struct drm_fb_offset *offset = &offsets[i];
2627
2628                 if (mode && fb_crtc) {
2629                         struct drm_mode_set *modeset = &fb_crtc->mode_set;
2630                         struct drm_connector *connector =
2631                                 fb_helper->connector_info[i]->connector;
2632
2633                         DRM_DEBUG_KMS("desired mode %s set on crtc %d (%d,%d)\n",
2634                                       mode->name, fb_crtc->mode_set.crtc->base.id, offset->x, offset->y);
2635
2636                         fb_crtc->desired_mode = mode;
2637                         fb_crtc->x = offset->x;
2638                         fb_crtc->y = offset->y;
2639                         modeset->mode = drm_mode_duplicate(dev,
2640                                                            fb_crtc->desired_mode);
2641                         drm_connector_get(connector);
2642                         drm_setup_crtc_rotation(fb_helper, fb_crtc, connector);
2643                         modeset->connectors[modeset->num_connectors++] = connector;
2644                         modeset->x = offset->x;
2645                         modeset->y = offset->y;
2646                 }
2647         }
2648 out:
2649         kfree(crtcs);
2650         kfree(modes);
2651         kfree(offsets);
2652         kfree(enabled);
2653 }
2654
2655 /*
2656  * This is a continuation of drm_setup_crtcs() that sets up anything related
2657  * to the framebuffer. During initialization, drm_setup_crtcs() is called before
2658  * the framebuffer has been allocated (fb_helper->fb and fb_helper->fbdev).
2659  * So, any setup that touches those fields needs to be done here instead of in
2660  * drm_setup_crtcs().
2661  */
2662 static void drm_setup_crtcs_fb(struct drm_fb_helper *fb_helper)
2663 {
2664         struct fb_info *info = fb_helper->fbdev;
2665         int i;
2666
2667         for (i = 0; i < fb_helper->crtc_count; i++)
2668                 if (fb_helper->crtc_info[i].mode_set.num_connectors)
2669                         fb_helper->crtc_info[i].mode_set.fb = fb_helper->fb;
2670
2671         mutex_lock(&fb_helper->dev->mode_config.mutex);
2672         drm_fb_helper_for_each_connector(fb_helper, i) {
2673                 struct drm_connector *connector =
2674                                         fb_helper->connector_info[i]->connector;
2675
2676                 /* use first connected connector for the physical dimensions */
2677                 if (connector->status == connector_status_connected) {
2678                         info->var.width = connector->display_info.width_mm;
2679                         info->var.height = connector->display_info.height_mm;
2680                         break;
2681                 }
2682         }
2683         mutex_unlock(&fb_helper->dev->mode_config.mutex);
2684
2685         switch (fb_helper->sw_rotations) {
2686         case DRM_MODE_ROTATE_0:
2687                 info->fbcon_rotate_hint = FB_ROTATE_UR;
2688                 break;
2689         case DRM_MODE_ROTATE_90:
2690                 info->fbcon_rotate_hint = FB_ROTATE_CCW;
2691                 break;
2692         case DRM_MODE_ROTATE_180:
2693                 info->fbcon_rotate_hint = FB_ROTATE_UD;
2694                 break;
2695         case DRM_MODE_ROTATE_270:
2696                 info->fbcon_rotate_hint = FB_ROTATE_CW;
2697                 break;
2698         default:
2699                 /*
2700                  * Multiple bits are set / multiple rotations requested
2701                  * fbcon cannot handle separate rotation settings per
2702                  * output, so fallback to unrotated.
2703                  */
2704                 info->fbcon_rotate_hint = FB_ROTATE_UR;
2705         }
2706 }
2707
2708 /* Note: Drops fb_helper->lock before returning. */
2709 static int
2710 __drm_fb_helper_initial_config_and_unlock(struct drm_fb_helper *fb_helper,
2711                                           int bpp_sel)
2712 {
2713         struct drm_device *dev = fb_helper->dev;
2714         struct fb_info *info;
2715         unsigned int width, height;
2716         int ret;
2717
2718         width = dev->mode_config.max_width;
2719         height = dev->mode_config.max_height;
2720
2721         drm_setup_crtcs(fb_helper, width, height);
2722         ret = drm_fb_helper_single_fb_probe(fb_helper, bpp_sel);
2723         if (ret < 0) {
2724                 if (ret == -EAGAIN) {
2725                         fb_helper->preferred_bpp = bpp_sel;
2726                         fb_helper->deferred_setup = true;
2727                         ret = 0;
2728                 }
2729                 mutex_unlock(&fb_helper->lock);
2730
2731                 return ret;
2732         }
2733         drm_setup_crtcs_fb(fb_helper);
2734
2735         fb_helper->deferred_setup = false;
2736
2737         info = fb_helper->fbdev;
2738         info->var.pixclock = 0;
2739         /* Shamelessly allow physical address leaking to userspace */
2740 #if IS_ENABLED(CONFIG_DRM_FBDEV_LEAK_PHYS_SMEM)
2741         if (!drm_leak_fbdev_smem)
2742 #endif
2743                 /* don't leak any physical addresses to userspace */
2744                 info->flags |= FBINFO_HIDE_SMEM_START;
2745
2746         /* Need to drop locks to avoid recursive deadlock in
2747          * register_framebuffer. This is ok because the only thing left to do is
2748          * register the fbdev emulation instance in kernel_fb_helper_list. */
2749         mutex_unlock(&fb_helper->lock);
2750
2751         ret = register_framebuffer(info);
2752         if (ret < 0)
2753                 return ret;
2754
2755         dev_info(dev->dev, "fb%d: %s frame buffer device\n",
2756                  info->node, info->fix.id);
2757
2758         mutex_lock(&kernel_fb_helper_lock);
2759         if (list_empty(&kernel_fb_helper_list))
2760                 register_sysrq_key('v', &sysrq_drm_fb_helper_restore_op);
2761
2762         list_add(&fb_helper->kernel_fb_list, &kernel_fb_helper_list);
2763         mutex_unlock(&kernel_fb_helper_lock);
2764
2765         return 0;
2766 }
2767
2768 /**
2769  * drm_fb_helper_initial_config - setup a sane initial connector configuration
2770  * @fb_helper: fb_helper device struct
2771  * @bpp_sel: bpp value to use for the framebuffer configuration
2772  *
2773  * Scans the CRTCs and connectors and tries to put together an initial setup.
2774  * At the moment, this is a cloned configuration across all heads with
2775  * a new framebuffer object as the backing store.
2776  *
2777  * Note that this also registers the fbdev and so allows userspace to call into
2778  * the driver through the fbdev interfaces.
2779  *
2780  * This function will call down into the &drm_fb_helper_funcs.fb_probe callback
2781  * to let the driver allocate and initialize the fbdev info structure and the
2782  * drm framebuffer used to back the fbdev. drm_fb_helper_fill_info() is provided
2783  * as a helper to setup simple default values for the fbdev info structure.
2784  *
2785  * HANG DEBUGGING:
2786  *
2787  * When you have fbcon support built-in or already loaded, this function will do
2788  * a full modeset to setup the fbdev console. Due to locking misdesign in the
2789  * VT/fbdev subsystem that entire modeset sequence has to be done while holding
2790  * console_lock. Until console_unlock is called no dmesg lines will be sent out
2791  * to consoles, not even serial console. This means when your driver crashes,
2792  * you will see absolutely nothing else but a system stuck in this function,
2793  * with no further output. Any kind of printk() you place within your own driver
2794  * or in the drm core modeset code will also never show up.
2795  *
2796  * Standard debug practice is to run the fbcon setup without taking the
2797  * console_lock as a hack, to be able to see backtraces and crashes on the
2798  * serial line. This can be done by setting the fb.lockless_register_fb=1 kernel
2799  * cmdline option.
2800  *
2801  * The other option is to just disable fbdev emulation since very likely the
2802  * first modeset from userspace will crash in the same way, and is even easier
2803  * to debug. This can be done by setting the drm_kms_helper.fbdev_emulation=0
2804  * kernel cmdline option.
2805  *
2806  * RETURNS:
2807  * Zero if everything went ok, nonzero otherwise.
2808  */
2809 int drm_fb_helper_initial_config(struct drm_fb_helper *fb_helper, int bpp_sel)
2810 {
2811         int ret;
2812
2813         if (!drm_fbdev_emulation)
2814                 return 0;
2815
2816         mutex_lock(&fb_helper->lock);
2817         ret = __drm_fb_helper_initial_config_and_unlock(fb_helper, bpp_sel);
2818
2819         return ret;
2820 }
2821 EXPORT_SYMBOL(drm_fb_helper_initial_config);
2822
2823 /**
2824  * drm_fb_helper_hotplug_event - respond to a hotplug notification by
2825  *                               probing all the outputs attached to the fb
2826  * @fb_helper: driver-allocated fbdev helper, can be NULL
2827  *
2828  * Scan the connectors attached to the fb_helper and try to put together a
2829  * setup after notification of a change in output configuration.
2830  *
2831  * Called at runtime, takes the mode config locks to be able to check/change the
2832  * modeset configuration. Must be run from process context (which usually means
2833  * either the output polling work or a work item launched from the driver's
2834  * hotplug interrupt).
2835  *
2836  * Note that drivers may call this even before calling
2837  * drm_fb_helper_initial_config but only after drm_fb_helper_init. This allows
2838  * for a race-free fbcon setup and will make sure that the fbdev emulation will
2839  * not miss any hotplug events.
2840  *
2841  * RETURNS:
2842  * 0 on success and a non-zero error code otherwise.
2843  */
2844 int drm_fb_helper_hotplug_event(struct drm_fb_helper *fb_helper)
2845 {
2846         int err = 0;
2847
2848         if (!drm_fbdev_emulation || !fb_helper)
2849                 return 0;
2850
2851         mutex_lock(&fb_helper->lock);
2852         if (fb_helper->deferred_setup) {
2853                 err = __drm_fb_helper_initial_config_and_unlock(fb_helper,
2854                                 fb_helper->preferred_bpp);
2855                 return err;
2856         }
2857
2858         if (!fb_helper->fb || !drm_fb_helper_is_bound(fb_helper)) {
2859                 fb_helper->delayed_hotplug = true;
2860                 mutex_unlock(&fb_helper->lock);
2861                 return err;
2862         }
2863
2864         DRM_DEBUG_KMS("\n");
2865
2866         drm_setup_crtcs(fb_helper, fb_helper->fb->width, fb_helper->fb->height);
2867         drm_setup_crtcs_fb(fb_helper);
2868         mutex_unlock(&fb_helper->lock);
2869
2870         drm_fb_helper_set_par(fb_helper->fbdev);
2871
2872         return 0;
2873 }
2874 EXPORT_SYMBOL(drm_fb_helper_hotplug_event);
2875
2876 /**
2877  * drm_fb_helper_fbdev_setup() - Setup fbdev emulation
2878  * @dev: DRM device
2879  * @fb_helper: fbdev helper structure to set up
2880  * @funcs: fbdev helper functions
2881  * @preferred_bpp: Preferred bits per pixel for the device.
2882  *                 @dev->mode_config.preferred_depth is used if this is zero.
2883  * @max_conn_count: Maximum number of connectors.
2884  *                  @dev->mode_config.num_connector is used if this is zero.
2885  *
2886  * This function sets up fbdev emulation and registers fbdev for access by
2887  * userspace. If all connectors are disconnected, setup is deferred to the next
2888  * time drm_fb_helper_hotplug_event() is called.
2889  * The caller must to provide a &drm_fb_helper_funcs->fb_probe callback
2890  * function.
2891  *
2892  * Use drm_fb_helper_fbdev_teardown() to destroy the fbdev.
2893  *
2894  * See also: drm_fb_helper_initial_config(), drm_fbdev_generic_setup().
2895  *
2896  * Returns:
2897  * Zero on success or negative error code on failure.
2898  */
2899 int drm_fb_helper_fbdev_setup(struct drm_device *dev,
2900                               struct drm_fb_helper *fb_helper,
2901                               const struct drm_fb_helper_funcs *funcs,
2902                               unsigned int preferred_bpp,
2903                               unsigned int max_conn_count)
2904 {
2905         int ret;
2906
2907         if (!preferred_bpp)
2908                 preferred_bpp = dev->mode_config.preferred_depth;
2909         if (!preferred_bpp)
2910                 preferred_bpp = 32;
2911
2912         if (!max_conn_count)
2913                 max_conn_count = dev->mode_config.num_connector;
2914         if (!max_conn_count) {
2915                 DRM_DEV_ERROR(dev->dev, "fbdev: No connectors\n");
2916                 return -EINVAL;
2917         }
2918
2919         drm_fb_helper_prepare(dev, fb_helper, funcs);
2920
2921         ret = drm_fb_helper_init(dev, fb_helper, max_conn_count);
2922         if (ret < 0) {
2923                 DRM_DEV_ERROR(dev->dev, "fbdev: Failed to initialize (ret=%d)\n", ret);
2924                 return ret;
2925         }
2926
2927         ret = drm_fb_helper_single_add_all_connectors(fb_helper);
2928         if (ret < 0) {
2929                 DRM_DEV_ERROR(dev->dev, "fbdev: Failed to add connectors (ret=%d)\n", ret);
2930                 goto err_drm_fb_helper_fini;
2931         }
2932
2933         if (!drm_drv_uses_atomic_modeset(dev))
2934                 drm_helper_disable_unused_functions(dev);
2935
2936         ret = drm_fb_helper_initial_config(fb_helper, preferred_bpp);
2937         if (ret < 0) {
2938                 DRM_DEV_ERROR(dev->dev, "fbdev: Failed to set configuration (ret=%d)\n", ret);
2939                 goto err_drm_fb_helper_fini;
2940         }
2941
2942         return 0;
2943
2944 err_drm_fb_helper_fini:
2945         drm_fb_helper_fbdev_teardown(dev);
2946
2947         return ret;
2948 }
2949 EXPORT_SYMBOL(drm_fb_helper_fbdev_setup);
2950
2951 /**
2952  * drm_fb_helper_fbdev_teardown - Tear down fbdev emulation
2953  * @dev: DRM device
2954  *
2955  * This function unregisters fbdev if not already done and cleans up the
2956  * associated resources including the &drm_framebuffer.
2957  * The driver is responsible for freeing the &drm_fb_helper structure which is
2958  * stored in &drm_device->fb_helper. Do note that this pointer has been cleared
2959  * when this function returns.
2960  *
2961  * In order to support device removal/unplug while file handles are still open,
2962  * drm_fb_helper_unregister_fbi() should be called on device removal and
2963  * drm_fb_helper_fbdev_teardown() in the &drm_driver->release callback when
2964  * file handles are closed.
2965  */
2966 void drm_fb_helper_fbdev_teardown(struct drm_device *dev)
2967 {
2968         struct drm_fb_helper *fb_helper = dev->fb_helper;
2969         struct fb_ops *fbops = NULL;
2970
2971         if (!fb_helper)
2972                 return;
2973
2974         /* Unregister if it hasn't been done already */
2975         if (fb_helper->fbdev && fb_helper->fbdev->dev)
2976                 drm_fb_helper_unregister_fbi(fb_helper);
2977
2978         if (fb_helper->fbdev && fb_helper->fbdev->fbdefio) {
2979                 fb_deferred_io_cleanup(fb_helper->fbdev);
2980                 kfree(fb_helper->fbdev->fbdefio);
2981                 fbops = fb_helper->fbdev->fbops;
2982         }
2983
2984         drm_fb_helper_fini(fb_helper);
2985         kfree(fbops);
2986
2987         if (fb_helper->fb)
2988                 drm_framebuffer_remove(fb_helper->fb);
2989 }
2990 EXPORT_SYMBOL(drm_fb_helper_fbdev_teardown);
2991
2992 /**
2993  * drm_fb_helper_lastclose - DRM driver lastclose helper for fbdev emulation
2994  * @dev: DRM device
2995  *
2996  * This function can be used as the &drm_driver->lastclose callback for drivers
2997  * that only need to call drm_fb_helper_restore_fbdev_mode_unlocked().
2998  */
2999 void drm_fb_helper_lastclose(struct drm_device *dev)
3000 {
3001         drm_fb_helper_restore_fbdev_mode_unlocked(dev->fb_helper);
3002 }
3003 EXPORT_SYMBOL(drm_fb_helper_lastclose);
3004
3005 /**
3006  * drm_fb_helper_output_poll_changed - DRM mode config \.output_poll_changed
3007  *                                     helper for fbdev emulation
3008  * @dev: DRM device
3009  *
3010  * This function can be used as the
3011  * &drm_mode_config_funcs.output_poll_changed callback for drivers that only
3012  * need to call drm_fb_helper_hotplug_event().
3013  */
3014 void drm_fb_helper_output_poll_changed(struct drm_device *dev)
3015 {
3016         drm_fb_helper_hotplug_event(dev->fb_helper);
3017 }
3018 EXPORT_SYMBOL(drm_fb_helper_output_poll_changed);
3019
3020 /* @user: 1=userspace, 0=fbcon */
3021 static int drm_fbdev_fb_open(struct fb_info *info, int user)
3022 {
3023         struct drm_fb_helper *fb_helper = info->par;
3024
3025         /* No need to take a ref for fbcon because it unbinds on unregister */
3026         if (user && !try_module_get(fb_helper->dev->driver->fops->owner))
3027                 return -ENODEV;
3028
3029         return 0;
3030 }
3031
3032 static int drm_fbdev_fb_release(struct fb_info *info, int user)
3033 {
3034         struct drm_fb_helper *fb_helper = info->par;
3035
3036         if (user)
3037                 module_put(fb_helper->dev->driver->fops->owner);
3038
3039         return 0;
3040 }
3041
3042 static void drm_fbdev_cleanup(struct drm_fb_helper *fb_helper)
3043 {
3044         struct fb_info *fbi = fb_helper->fbdev;
3045         struct fb_ops *fbops = NULL;
3046         void *shadow = NULL;
3047
3048         if (!fb_helper->dev)
3049                 return;
3050
3051         if (fbi && fbi->fbdefio) {
3052                 fb_deferred_io_cleanup(fbi);
3053                 shadow = fbi->screen_buffer;
3054                 fbops = fbi->fbops;
3055         }
3056
3057         drm_fb_helper_fini(fb_helper);
3058
3059         if (shadow) {
3060                 vfree(shadow);
3061                 kfree(fbops);
3062         }
3063
3064         drm_client_framebuffer_delete(fb_helper->buffer);
3065 }
3066
3067 static void drm_fbdev_release(struct drm_fb_helper *fb_helper)
3068 {
3069         drm_fbdev_cleanup(fb_helper);
3070         drm_client_release(&fb_helper->client);
3071         kfree(fb_helper);
3072 }
3073
3074 /*
3075  * fb_ops.fb_destroy is called by the last put_fb_info() call at the end of
3076  * unregister_framebuffer() or fb_release().
3077  */
3078 static void drm_fbdev_fb_destroy(struct fb_info *info)
3079 {
3080         drm_fbdev_release(info->par);
3081 }
3082
3083 static int drm_fbdev_fb_mmap(struct fb_info *info, struct vm_area_struct *vma)
3084 {
3085         struct drm_fb_helper *fb_helper = info->par;
3086
3087         if (fb_helper->dev->driver->gem_prime_mmap)
3088                 return fb_helper->dev->driver->gem_prime_mmap(fb_helper->buffer->gem, vma);
3089         else
3090                 return -ENODEV;
3091 }
3092
3093 static struct fb_ops drm_fbdev_fb_ops = {
3094         .owner          = THIS_MODULE,
3095         DRM_FB_HELPER_DEFAULT_OPS,
3096         .fb_open        = drm_fbdev_fb_open,
3097         .fb_release     = drm_fbdev_fb_release,
3098         .fb_destroy     = drm_fbdev_fb_destroy,
3099         .fb_mmap        = drm_fbdev_fb_mmap,
3100         .fb_read        = drm_fb_helper_sys_read,
3101         .fb_write       = drm_fb_helper_sys_write,
3102         .fb_fillrect    = drm_fb_helper_sys_fillrect,
3103         .fb_copyarea    = drm_fb_helper_sys_copyarea,
3104         .fb_imageblit   = drm_fb_helper_sys_imageblit,
3105 };
3106
3107 static struct fb_deferred_io drm_fbdev_defio = {
3108         .delay          = HZ / 20,
3109         .deferred_io    = drm_fb_helper_deferred_io,
3110 };
3111
3112 /**
3113  * drm_fb_helper_generic_probe - Generic fbdev emulation probe helper
3114  * @fb_helper: fbdev helper structure
3115  * @sizes: describes fbdev size and scanout surface size
3116  *
3117  * This function uses the client API to create a framebuffer backed by a dumb buffer.
3118  *
3119  * The _sys_ versions are used for &fb_ops.fb_read, fb_write, fb_fillrect,
3120  * fb_copyarea, fb_imageblit.
3121  *
3122  * Returns:
3123  * Zero on success or negative error code on failure.
3124  */
3125 int drm_fb_helper_generic_probe(struct drm_fb_helper *fb_helper,
3126                                 struct drm_fb_helper_surface_size *sizes)
3127 {
3128         struct drm_client_dev *client = &fb_helper->client;
3129         struct drm_client_buffer *buffer;
3130         struct drm_framebuffer *fb;
3131         struct fb_info *fbi;
3132         u32 format;
3133
3134         DRM_DEBUG_KMS("surface width(%d), height(%d) and bpp(%d)\n",
3135                       sizes->surface_width, sizes->surface_height,
3136                       sizes->surface_bpp);
3137
3138         format = drm_mode_legacy_fb_format(sizes->surface_bpp, sizes->surface_depth);
3139         buffer = drm_client_framebuffer_create(client, sizes->surface_width,
3140                                                sizes->surface_height, format);
3141         if (IS_ERR(buffer))
3142                 return PTR_ERR(buffer);
3143
3144         fb_helper->buffer = buffer;
3145         fb_helper->fb = buffer->fb;
3146         fb = buffer->fb;
3147
3148         fbi = drm_fb_helper_alloc_fbi(fb_helper);
3149         if (IS_ERR(fbi))
3150                 return PTR_ERR(fbi);
3151
3152         fbi->fbops = &drm_fbdev_fb_ops;
3153         fbi->screen_size = fb->height * fb->pitches[0];
3154         fbi->fix.smem_len = fbi->screen_size;
3155         fbi->screen_buffer = buffer->vaddr;
3156         /* Shamelessly leak the physical address to user-space */
3157 #if IS_ENABLED(CONFIG_DRM_FBDEV_LEAK_PHYS_SMEM)
3158         if (drm_leak_fbdev_smem && fbi->fix.smem_start == 0)
3159                 fbi->fix.smem_start =
3160                         page_to_phys(virt_to_page(fbi->screen_buffer));
3161 #endif
3162         drm_fb_helper_fill_info(fbi, fb_helper, sizes);
3163
3164         if (fb->funcs->dirty) {
3165                 struct fb_ops *fbops;
3166                 void *shadow;
3167
3168                 /*
3169                  * fb_deferred_io_cleanup() clears &fbops->fb_mmap so a per
3170                  * instance version is necessary.
3171                  */
3172                 fbops = kzalloc(sizeof(*fbops), GFP_KERNEL);
3173                 shadow = vzalloc(fbi->screen_size);
3174                 if (!fbops || !shadow) {
3175                         kfree(fbops);
3176                         vfree(shadow);
3177                         return -ENOMEM;
3178                 }
3179
3180                 *fbops = *fbi->fbops;
3181                 fbi->fbops = fbops;
3182                 fbi->screen_buffer = shadow;
3183                 fbi->fbdefio = &drm_fbdev_defio;
3184
3185                 fb_deferred_io_init(fbi);
3186         }
3187
3188         return 0;
3189 }
3190 EXPORT_SYMBOL(drm_fb_helper_generic_probe);
3191
3192 static const struct drm_fb_helper_funcs drm_fb_helper_generic_funcs = {
3193         .fb_probe = drm_fb_helper_generic_probe,
3194 };
3195
3196 static void drm_fbdev_client_unregister(struct drm_client_dev *client)
3197 {
3198         struct drm_fb_helper *fb_helper = drm_fb_helper_from_client(client);
3199
3200         if (fb_helper->fbdev)
3201                 /* drm_fbdev_fb_destroy() takes care of cleanup */
3202                 drm_fb_helper_unregister_fbi(fb_helper);
3203         else
3204                 drm_fbdev_release(fb_helper);
3205 }
3206
3207 static int drm_fbdev_client_restore(struct drm_client_dev *client)
3208 {
3209         drm_fb_helper_lastclose(client->dev);
3210
3211         return 0;
3212 }
3213
3214 static int drm_fbdev_client_hotplug(struct drm_client_dev *client)
3215 {
3216         struct drm_fb_helper *fb_helper = drm_fb_helper_from_client(client);
3217         struct drm_device *dev = client->dev;
3218         int ret;
3219
3220         /* Setup is not retried if it has failed */
3221         if (!fb_helper->dev && fb_helper->funcs)
3222                 return 0;
3223
3224         if (dev->fb_helper)
3225                 return drm_fb_helper_hotplug_event(dev->fb_helper);
3226
3227         if (!dev->mode_config.num_connector) {
3228                 DRM_DEV_DEBUG(dev->dev, "No connectors found, will not create framebuffer!\n");
3229                 return 0;
3230         }
3231
3232         drm_fb_helper_prepare(dev, fb_helper, &drm_fb_helper_generic_funcs);
3233
3234         ret = drm_fb_helper_init(dev, fb_helper, dev->mode_config.num_connector);
3235         if (ret)
3236                 goto err;
3237
3238         ret = drm_fb_helper_single_add_all_connectors(fb_helper);
3239         if (ret)
3240                 goto err_cleanup;
3241
3242         if (!drm_drv_uses_atomic_modeset(dev))
3243                 drm_helper_disable_unused_functions(dev);
3244
3245         ret = drm_fb_helper_initial_config(fb_helper, fb_helper->preferred_bpp);
3246         if (ret)
3247                 goto err_cleanup;
3248
3249         return 0;
3250
3251 err_cleanup:
3252         drm_fbdev_cleanup(fb_helper);
3253 err:
3254         fb_helper->dev = NULL;
3255         fb_helper->fbdev = NULL;
3256
3257         DRM_DEV_ERROR(dev->dev, "fbdev: Failed to setup generic emulation (ret=%d)\n", ret);
3258
3259         return ret;
3260 }
3261
3262 static const struct drm_client_funcs drm_fbdev_client_funcs = {
3263         .owner          = THIS_MODULE,
3264         .unregister     = drm_fbdev_client_unregister,
3265         .restore        = drm_fbdev_client_restore,
3266         .hotplug        = drm_fbdev_client_hotplug,
3267 };
3268
3269 /**
3270  * drm_fbdev_generic_setup() - Setup generic fbdev emulation
3271  * @dev: DRM device
3272  * @preferred_bpp: Preferred bits per pixel for the device.
3273  *                 @dev->mode_config.preferred_depth is used if this is zero.
3274  *
3275  * This function sets up generic fbdev emulation for drivers that supports
3276  * dumb buffers with a virtual address and that can be mmap'ed. If the driver
3277  * does not support these functions, it could use drm_fb_helper_fbdev_setup().
3278  *
3279  * Restore, hotplug events and teardown are all taken care of. Drivers that do
3280  * suspend/resume need to call drm_fb_helper_set_suspend_unlocked() themselves.
3281  * Simple drivers might use drm_mode_config_helper_suspend().
3282  *
3283  * Drivers that set the dirty callback on their framebuffer will get a shadow
3284  * fbdev buffer that is blitted onto the real buffer. This is done in order to
3285  * make deferred I/O work with all kinds of buffers.
3286  *
3287  * This function is safe to call even when there are no connectors present.
3288  * Setup will be retried on the next hotplug event.
3289  *
3290  * The fbdev is destroyed by drm_dev_unregister().
3291  *
3292  * Returns:
3293  * Zero on success or negative error code on failure.
3294  */
3295 int drm_fbdev_generic_setup(struct drm_device *dev, unsigned int preferred_bpp)
3296 {
3297         struct drm_fb_helper *fb_helper;
3298         int ret;
3299
3300         WARN(dev->fb_helper, "fb_helper is already set!\n");
3301
3302         if (!drm_fbdev_emulation)
3303                 return 0;
3304
3305         fb_helper = kzalloc(sizeof(*fb_helper), GFP_KERNEL);
3306         if (!fb_helper)
3307                 return -ENOMEM;
3308
3309         ret = drm_client_init(dev, &fb_helper->client, "fbdev", &drm_fbdev_client_funcs);
3310         if (ret) {
3311                 kfree(fb_helper);
3312                 DRM_DEV_ERROR(dev->dev, "Failed to register client: %d\n", ret);
3313                 return ret;
3314         }
3315
3316         drm_client_add(&fb_helper->client);
3317
3318         if (!preferred_bpp)
3319                 preferred_bpp = dev->mode_config.preferred_depth;
3320         if (!preferred_bpp)
3321                 preferred_bpp = 32;
3322         fb_helper->preferred_bpp = preferred_bpp;
3323
3324         ret = drm_fbdev_client_hotplug(&fb_helper->client);
3325         if (ret)
3326                 DRM_DEV_DEBUG(dev->dev, "client hotplug ret=%d\n", ret);
3327
3328         return 0;
3329 }
3330 EXPORT_SYMBOL(drm_fbdev_generic_setup);
3331
3332 /* The Kconfig DRM_KMS_HELPER selects FRAMEBUFFER_CONSOLE (if !EXPERT)
3333  * but the module doesn't depend on any fb console symbols.  At least
3334  * attempt to load fbcon to avoid leaving the system without a usable console.
3335  */
3336 int __init drm_fb_helper_modinit(void)
3337 {
3338 #if defined(CONFIG_FRAMEBUFFER_CONSOLE_MODULE) && !defined(CONFIG_EXPERT)
3339         const char name[] = "fbcon";
3340         struct module *fbcon;
3341
3342         mutex_lock(&module_mutex);
3343         fbcon = find_module(name);
3344         mutex_unlock(&module_mutex);
3345
3346         if (!fbcon)
3347                 request_module_nowait(name);
3348 #endif
3349         return 0;
3350 }
3351 EXPORT_SYMBOL(drm_fb_helper_modinit);