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