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