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