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