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