xref: /linux/drivers/gpu/drm/drm_fb_helper.c (revision 5ea5b6ff0d63aef1dc3fb25445acea183f61a934)
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/export.h>
34 
35 #include <drm/drm_atomic.h>
36 #include <drm/drm_drv.h>
37 #include <drm/drm_fb_helper.h>
38 #include <drm/drm_fourcc.h>
39 #include <drm/drm_framebuffer.h>
40 #include <drm/drm_modeset_helper_vtables.h>
41 #include <drm/drm_print.h>
42 #include <drm/drm_vblank.h>
43 
44 #include "drm_internal.h"
45 #include "drm_crtc_internal.h"
46 
47 static bool drm_fbdev_emulation = true;
48 module_param_named(fbdev_emulation, drm_fbdev_emulation, bool, 0600);
49 MODULE_PARM_DESC(fbdev_emulation,
50 		 "Enable legacy fbdev emulation [default=true]");
51 
52 static int drm_fbdev_overalloc = CONFIG_DRM_FBDEV_OVERALLOC;
53 module_param(drm_fbdev_overalloc, int, 0444);
54 MODULE_PARM_DESC(drm_fbdev_overalloc,
55 		 "Overallocation of the fbdev buffer (%) [default="
56 		 __MODULE_STRING(CONFIG_DRM_FBDEV_OVERALLOC) "]");
57 
58 /*
59  * In order to keep user-space compatibility, we want in certain use-cases
60  * to keep leaking the fbdev physical address to the user-space program
61  * handling the fbdev buffer.
62  *
63  * This is a bad habit, essentially kept to support closed-source OpenGL
64  * drivers that should really be moved into open-source upstream projects
65  * instead of using legacy physical addresses in user space to communicate
66  * with other out-of-tree kernel modules.
67  *
68  * This module_param *should* be removed as soon as possible and be
69  * considered as a broken and legacy behaviour from a modern fbdev device.
70  */
71 static bool drm_leak_fbdev_smem;
72 #if IS_ENABLED(CONFIG_DRM_FBDEV_LEAK_PHYS_SMEM)
73 module_param_unsafe(drm_leak_fbdev_smem, bool, 0600);
74 MODULE_PARM_DESC(drm_leak_fbdev_smem,
75 		 "Allow unsafe leaking fbdev physical smem address [default=false]");
76 #endif
77 
78 /**
79  * DOC: fbdev helpers
80  *
81  * The fb helper functions are useful to provide an fbdev on top of a drm kernel
82  * mode setting driver. They can be used mostly independently from the crtc
83  * helper functions used by many drivers to implement the kernel mode setting
84  * interfaces. Drivers that use one of the shared memory managers, TTM, SHMEM,
85  * DMA, should instead use the corresponding fbdev emulation.
86  *
87  * For suspend/resume consider using drm_mode_config_helper_suspend() and
88  * drm_mode_config_helper_resume() which takes care of fbdev as well.
89  *
90  * All other functions exported by the fb helper library can be used to
91  * implement the fbdev driver interface by the driver.
92  *
93  * It is possible, though perhaps somewhat tricky, to implement race-free
94  * hotplug detection using the fbdev helpers. The drm_fb_helper_prepare()
95  * helper must be called first to initialize the minimum required to make
96  * hotplug detection work. Drivers also need to make sure to properly set up
97  * the &drm_mode_config.funcs member. After calling drm_kms_helper_poll_init()
98  * it is safe to enable interrupts and start processing hotplug events. At the
99  * same time, drivers should initialize all modeset objects such as CRTCs,
100  * encoders and connectors. To finish up the fbdev helper initialization, the
101  * drm_fb_helper_init() function is called. To probe for all attached displays
102  * and set up an initial configuration using the detected hardware, drivers
103  * should call drm_fb_helper_initial_config().
104  *
105  * If &drm_framebuffer_funcs.dirty is set, the
106  * drm_fb_helper_{cfb,sys}_{write,fillrect,copyarea,imageblit} functions will
107  * accumulate changes and schedule &drm_fb_helper.dirty_work to run right
108  * away. This worker then calls the dirty() function ensuring that it will
109  * always run in process context since the fb_*() function could be running in
110  * atomic context. If drm_fb_helper_deferred_io() is used as the deferred_io
111  * callback it will also schedule dirty_work with the damage collected from the
112  * mmap page writes.
113  */
114 
115 static int
116 __drm_fb_helper_restore_fbdev_mode_unlocked(struct drm_fb_helper *fb_helper,
117 					    bool force)
118 {
119 	bool do_delayed;
120 	int ret;
121 
122 	if (!drm_fbdev_emulation || !fb_helper)
123 		return -ENODEV;
124 
125 	if (READ_ONCE(fb_helper->deferred_setup))
126 		return 0;
127 
128 	mutex_lock(&fb_helper->lock);
129 	if (force) {
130 		/*
131 		 * Yes this is the _locked version which expects the master lock
132 		 * to be held. But for forced restores we're intentionally
133 		 * racing here, see drm_fb_helper_set_par().
134 		 */
135 		ret = drm_client_modeset_commit_locked(&fb_helper->client);
136 	} else {
137 		ret = drm_client_modeset_commit(&fb_helper->client);
138 	}
139 
140 	do_delayed = fb_helper->delayed_hotplug;
141 	if (do_delayed)
142 		fb_helper->delayed_hotplug = false;
143 	mutex_unlock(&fb_helper->lock);
144 
145 	if (do_delayed)
146 		drm_fb_helper_hotplug_event(fb_helper);
147 
148 	if (fb_helper->funcs->fb_restore)
149 		fb_helper->funcs->fb_restore(fb_helper);
150 
151 	return ret;
152 }
153 
154 /**
155  * drm_fb_helper_restore_fbdev_mode_unlocked - restore fbdev configuration
156  * @fb_helper: driver-allocated fbdev helper, can be NULL
157  * @force: ignore present DRM master
158  *
159  * This helper should be called from fbdev emulation's &drm_client_funcs.restore
160  * callback. It ensures that the user isn't greeted with a black screen when the
161  * userspace compositor releases the display device.
162  *
163  * Returns:
164  * 0 on success, or a negative errno code otherwise.
165  */
166 int drm_fb_helper_restore_fbdev_mode_unlocked(struct drm_fb_helper *fb_helper, bool force)
167 {
168 	return __drm_fb_helper_restore_fbdev_mode_unlocked(fb_helper, force);
169 }
170 EXPORT_SYMBOL(drm_fb_helper_restore_fbdev_mode_unlocked);
171 
172 static void drm_fb_helper_dpms(struct fb_info *info, int dpms_mode)
173 {
174 	struct drm_fb_helper *fb_helper = info->par;
175 
176 	mutex_lock(&fb_helper->lock);
177 	drm_client_modeset_dpms(&fb_helper->client, dpms_mode);
178 	mutex_unlock(&fb_helper->lock);
179 }
180 
181 /**
182  * drm_fb_helper_blank - implementation for &fb_ops.fb_blank
183  * @blank: desired blanking state
184  * @info: fbdev registered by the helper
185  */
186 int drm_fb_helper_blank(int blank, struct fb_info *info)
187 {
188 	if (oops_in_progress)
189 		return -EBUSY;
190 
191 	switch (blank) {
192 	/* Display: On; HSync: On, VSync: On */
193 	case FB_BLANK_UNBLANK:
194 		drm_fb_helper_dpms(info, DRM_MODE_DPMS_ON);
195 		break;
196 	/* Display: Off; HSync: On, VSync: On */
197 	case FB_BLANK_NORMAL:
198 		drm_fb_helper_dpms(info, DRM_MODE_DPMS_STANDBY);
199 		break;
200 	/* Display: Off; HSync: Off, VSync: On */
201 	case FB_BLANK_HSYNC_SUSPEND:
202 		drm_fb_helper_dpms(info, DRM_MODE_DPMS_STANDBY);
203 		break;
204 	/* Display: Off; HSync: On, VSync: Off */
205 	case FB_BLANK_VSYNC_SUSPEND:
206 		drm_fb_helper_dpms(info, DRM_MODE_DPMS_SUSPEND);
207 		break;
208 	/* Display: Off; HSync: Off, VSync: Off */
209 	case FB_BLANK_POWERDOWN:
210 		drm_fb_helper_dpms(info, DRM_MODE_DPMS_OFF);
211 		break;
212 	}
213 	return 0;
214 }
215 EXPORT_SYMBOL(drm_fb_helper_blank);
216 
217 static void drm_fb_helper_resume_worker(struct work_struct *work)
218 {
219 	struct drm_fb_helper *helper = container_of(work, struct drm_fb_helper,
220 						    resume_work);
221 
222 	console_lock();
223 	fb_set_suspend(helper->info, 0);
224 	console_unlock();
225 }
226 
227 static void drm_fb_helper_fb_dirty(struct drm_fb_helper *helper)
228 {
229 	struct drm_device *dev = helper->dev;
230 	struct drm_clip_rect *clip = &helper->damage_clip;
231 	struct drm_clip_rect clip_copy;
232 	unsigned long flags;
233 	int ret;
234 
235 	mutex_lock(&helper->lock);
236 	drm_client_modeset_wait_for_vblank(&helper->client, 0);
237 	mutex_unlock(&helper->lock);
238 
239 	if (drm_WARN_ON_ONCE(dev, !helper->funcs->fb_dirty))
240 		return;
241 
242 	spin_lock_irqsave(&helper->damage_lock, flags);
243 	clip_copy = *clip;
244 	clip->x1 = clip->y1 = ~0;
245 	clip->x2 = clip->y2 = 0;
246 	spin_unlock_irqrestore(&helper->damage_lock, flags);
247 
248 	ret = helper->funcs->fb_dirty(helper, &clip_copy);
249 	if (ret)
250 		goto err;
251 
252 	return;
253 
254 err:
255 	/*
256 	 * Restore damage clip rectangle on errors. The next run
257 	 * of the damage worker will perform the update.
258 	 */
259 	spin_lock_irqsave(&helper->damage_lock, flags);
260 	clip->x1 = min_t(u32, clip->x1, clip_copy.x1);
261 	clip->y1 = min_t(u32, clip->y1, clip_copy.y1);
262 	clip->x2 = max_t(u32, clip->x2, clip_copy.x2);
263 	clip->y2 = max_t(u32, clip->y2, clip_copy.y2);
264 	spin_unlock_irqrestore(&helper->damage_lock, flags);
265 }
266 
267 static void drm_fb_helper_damage_work(struct work_struct *work)
268 {
269 	struct drm_fb_helper *helper = container_of(work, struct drm_fb_helper, damage_work);
270 
271 	if (helper->info->state != FBINFO_STATE_RUNNING)
272 		return;
273 
274 	drm_fb_helper_fb_dirty(helper);
275 }
276 
277 /**
278  * drm_fb_helper_prepare - setup a drm_fb_helper structure
279  * @dev: DRM device
280  * @helper: driver-allocated fbdev helper structure to set up
281  * @preferred_bpp: Preferred bits per pixel for the device.
282  * @funcs: pointer to structure of functions associate with this helper
283  *
284  * Sets up the bare minimum to make the framebuffer helper usable. This is
285  * useful to implement race-free initialization of the polling helpers.
286  */
287 void drm_fb_helper_prepare(struct drm_device *dev, struct drm_fb_helper *helper,
288 			   unsigned int preferred_bpp,
289 			   const struct drm_fb_helper_funcs *funcs)
290 {
291 	/*
292 	 * Pick a preferred bpp of 32 if no value has been given. This
293 	 * will select XRGB8888 for the framebuffer formats. All drivers
294 	 * have to support XRGB8888 for backwards compatibility with legacy
295 	 * userspace, so it's the safe choice here.
296 	 *
297 	 * TODO: Replace struct drm_mode_config.preferred_depth and this
298 	 *       bpp value with a preferred format that is given as struct
299 	 *       drm_format_info. Then derive all other values from the
300 	 *       format.
301 	 */
302 	if (!preferred_bpp)
303 		preferred_bpp = 32;
304 
305 	spin_lock_init(&helper->damage_lock);
306 	INIT_WORK(&helper->resume_work, drm_fb_helper_resume_worker);
307 	INIT_WORK(&helper->damage_work, drm_fb_helper_damage_work);
308 	helper->damage_clip.x1 = helper->damage_clip.y1 = ~0;
309 	mutex_init(&helper->lock);
310 	helper->funcs = funcs;
311 	helper->dev = dev;
312 	helper->preferred_bpp = preferred_bpp;
313 }
314 EXPORT_SYMBOL(drm_fb_helper_prepare);
315 
316 /**
317  * drm_fb_helper_unprepare - clean up a drm_fb_helper structure
318  * @fb_helper: driver-allocated fbdev helper structure to set up
319  *
320  * Cleans up the framebuffer helper. Inverse of drm_fb_helper_prepare().
321  */
322 void drm_fb_helper_unprepare(struct drm_fb_helper *fb_helper)
323 {
324 	mutex_destroy(&fb_helper->lock);
325 }
326 EXPORT_SYMBOL(drm_fb_helper_unprepare);
327 
328 /**
329  * drm_fb_helper_init - initialize a &struct drm_fb_helper
330  * @dev: drm device
331  * @fb_helper: driver-allocated fbdev helper structure to initialize
332  *
333  * This allocates the structures for the fbdev helper with the given limits.
334  * Note that this won't yet touch the hardware (through the driver interfaces)
335  * nor register the fbdev. This is only done in drm_fb_helper_initial_config()
336  * to allow driver writes more control over the exact init sequence.
337  *
338  * Drivers must call drm_fb_helper_prepare() before calling this function.
339  *
340  * RETURNS:
341  * Zero if everything went ok, nonzero otherwise.
342  */
343 int drm_fb_helper_init(struct drm_device *dev,
344 		       struct drm_fb_helper *fb_helper)
345 {
346 	dev->fb_helper = fb_helper;
347 
348 	return 0;
349 }
350 EXPORT_SYMBOL(drm_fb_helper_init);
351 
352 static struct fb_info *drm_fb_helper_alloc_info(struct drm_fb_helper *fb_helper)
353 {
354 	struct device *dev = fb_helper->dev->dev;
355 	struct fb_info *info;
356 	int ret;
357 
358 	info = framebuffer_alloc(0, dev);
359 	if (!info)
360 		return ERR_PTR(-ENOMEM);
361 
362 	if (!drm_leak_fbdev_smem)
363 		info->flags |= FBINFO_HIDE_SMEM_START;
364 
365 	ret = fb_alloc_cmap(&info->cmap, 256, 0);
366 	if (ret)
367 		goto err_release;
368 
369 	fb_helper->info = info;
370 	info->skip_vt_switch = true;
371 
372 	info->skip_panic = drm_panic_is_enabled(fb_helper->dev);
373 	return info;
374 
375 err_release:
376 	framebuffer_release(info);
377 	return ERR_PTR(ret);
378 }
379 
380 static void drm_fb_helper_release_info(struct drm_fb_helper *fb_helper)
381 {
382 	struct fb_info *info = fb_helper->info;
383 
384 	if (!info)
385 		return;
386 
387 	fb_helper->info = NULL;
388 
389 	if (info->cmap.len)
390 		fb_dealloc_cmap(&info->cmap);
391 	framebuffer_release(info);
392 }
393 
394 /**
395  * drm_fb_helper_unregister_info - unregister fb_info framebuffer device
396  * @fb_helper: driver-allocated fbdev helper, must not be NULL
397  *
398  * A wrapper around unregister_framebuffer, to release the fb_info
399  * framebuffer device. This must be called before releasing all resources for
400  * @fb_helper by calling drm_fb_helper_fini().
401  */
402 void drm_fb_helper_unregister_info(struct drm_fb_helper *fb_helper)
403 {
404 	unregister_framebuffer(fb_helper->info);
405 }
406 EXPORT_SYMBOL(drm_fb_helper_unregister_info);
407 
408 /**
409  * drm_fb_helper_fini - finialize a &struct drm_fb_helper
410  * @fb_helper: driver-allocated fbdev helper, can be NULL
411  *
412  * This cleans up all remaining resources associated with @fb_helper.
413  */
414 void drm_fb_helper_fini(struct drm_fb_helper *fb_helper)
415 {
416 	if (!fb_helper)
417 		return;
418 
419 	fb_helper->dev->fb_helper = NULL;
420 
421 	if (!drm_fbdev_emulation)
422 		return;
423 
424 	cancel_work_sync(&fb_helper->resume_work);
425 	cancel_work_sync(&fb_helper->damage_work);
426 
427 	drm_fb_helper_release_info(fb_helper);
428 }
429 EXPORT_SYMBOL(drm_fb_helper_fini);
430 
431 static void drm_fb_helper_add_damage_clip(struct drm_fb_helper *helper, u32 x, u32 y,
432 					  u32 width, u32 height)
433 {
434 	struct drm_clip_rect *clip = &helper->damage_clip;
435 	unsigned long flags;
436 
437 	spin_lock_irqsave(&helper->damage_lock, flags);
438 	clip->x1 = min_t(u32, clip->x1, x);
439 	clip->y1 = min_t(u32, clip->y1, y);
440 	clip->x2 = max_t(u32, clip->x2, x + width);
441 	clip->y2 = max_t(u32, clip->y2, y + height);
442 	spin_unlock_irqrestore(&helper->damage_lock, flags);
443 }
444 
445 static void drm_fb_helper_damage(struct drm_fb_helper *helper, u32 x, u32 y,
446 				 u32 width, u32 height)
447 {
448 	/*
449 	 * This function may be invoked by panic() to flush the frame
450 	 * buffer, where all CPUs except the panic CPU are stopped.
451 	 * During the following schedule_work(), the panic CPU needs
452 	 * the worker_pool lock, which might be held by a stopped CPU,
453 	 * causing schedule_work() and panic() to block. Return early on
454 	 * oops_in_progress to prevent this blocking.
455 	 */
456 	if (oops_in_progress)
457 		return;
458 
459 	drm_fb_helper_add_damage_clip(helper, x, y, width, height);
460 
461 	schedule_work(&helper->damage_work);
462 }
463 
464 /*
465  * Convert memory region into area of scanlines and pixels per
466  * scanline. The parameters off and len must not reach beyond
467  * the end of the framebuffer.
468  */
469 static void drm_fb_helper_memory_range_to_clip(struct fb_info *info, off_t off, size_t len,
470 					       struct drm_rect *clip)
471 {
472 	u32 line_length = info->fix.line_length;
473 	u32 fb_height = info->var.yres;
474 	off_t end = off + len;
475 	u32 x1 = 0;
476 	u32 y1 = off / line_length;
477 	u32 x2 = info->var.xres;
478 	u32 y2 = DIV_ROUND_UP(end, line_length);
479 
480 	/* Don't allow any of them beyond the bottom bound of display area */
481 	if (y1 > fb_height)
482 		y1 = fb_height;
483 	if (y2 > fb_height)
484 		y2 = fb_height;
485 
486 	if ((y2 - y1) == 1) {
487 		/*
488 		 * We've only written to a single scanline. Try to reduce
489 		 * the number of horizontal pixels that need an update.
490 		 */
491 		off_t bit_off = (off % line_length) * 8;
492 		off_t bit_end = (end % line_length) * 8;
493 
494 		x1 = bit_off / info->var.bits_per_pixel;
495 		x2 = DIV_ROUND_UP(bit_end, info->var.bits_per_pixel);
496 	}
497 
498 	drm_rect_init(clip, x1, y1, x2 - x1, y2 - y1);
499 }
500 
501 /* Don't use in new code. */
502 void drm_fb_helper_damage_range(struct fb_info *info, off_t off, size_t len)
503 {
504 	struct drm_fb_helper *fb_helper = info->par;
505 	struct drm_rect damage_area;
506 
507 	drm_fb_helper_memory_range_to_clip(info, off, len, &damage_area);
508 	drm_fb_helper_damage(fb_helper, damage_area.x1, damage_area.y1,
509 			     drm_rect_width(&damage_area),
510 			     drm_rect_height(&damage_area));
511 }
512 EXPORT_SYMBOL(drm_fb_helper_damage_range);
513 
514 /* Don't use in new code. */
515 void drm_fb_helper_damage_area(struct fb_info *info, u32 x, u32 y, u32 width, u32 height)
516 {
517 	struct drm_fb_helper *fb_helper = info->par;
518 
519 	drm_fb_helper_damage(fb_helper, x, y, width, height);
520 }
521 EXPORT_SYMBOL(drm_fb_helper_damage_area);
522 
523 #ifdef CONFIG_FB_DEFERRED_IO
524 /**
525  * drm_fb_helper_deferred_io() - fbdev deferred_io callback function
526  * @info: fb_info struct pointer
527  * @pagereflist: list of mmap framebuffer pages that have to be flushed
528  *
529  * This function is used as the &fb_deferred_io.deferred_io
530  * callback function for flushing the fbdev mmap writes.
531  */
532 void drm_fb_helper_deferred_io(struct fb_info *info, struct list_head *pagereflist)
533 {
534 	struct drm_fb_helper *helper = info->par;
535 	unsigned long start, end, min_off, max_off, total_size;
536 	struct fb_deferred_io_pageref *pageref;
537 	struct drm_rect damage_area;
538 
539 	min_off = ULONG_MAX;
540 	max_off = 0;
541 	list_for_each_entry(pageref, pagereflist, list) {
542 		start = pageref->offset;
543 		end = start + PAGE_SIZE;
544 		min_off = min(min_off, start);
545 		max_off = max(max_off, end);
546 	}
547 
548 	/*
549 	 * As we can only track pages, we might reach beyond the end
550 	 * of the screen and account for non-existing scanlines. Hence,
551 	 * keep the covered memory area within the screen buffer.
552 	 */
553 	if (info->screen_size)
554 		total_size = info->screen_size;
555 	else
556 		total_size = info->fix.smem_len;
557 	max_off = min(max_off, total_size);
558 
559 	if (min_off < max_off) {
560 		drm_fb_helper_memory_range_to_clip(info, min_off, max_off - min_off, &damage_area);
561 		drm_fb_helper_damage(helper, damage_area.x1, damage_area.y1,
562 				     drm_rect_width(&damage_area),
563 				     drm_rect_height(&damage_area));
564 	}
565 }
566 EXPORT_SYMBOL(drm_fb_helper_deferred_io);
567 #endif
568 
569 /**
570  * drm_fb_helper_set_suspend - wrapper around fb_set_suspend
571  * @fb_helper: driver-allocated fbdev helper, can be NULL
572  * @suspend: whether to suspend or resume
573  *
574  * A wrapper around fb_set_suspend implemented by fbdev core.
575  * Use drm_fb_helper_set_suspend_unlocked() if you don't need to take
576  * the lock yourself
577  */
578 void drm_fb_helper_set_suspend(struct drm_fb_helper *fb_helper, bool suspend)
579 {
580 	if (!fb_helper || !fb_helper->info)
581 		return;
582 
583 	if (fb_helper->funcs->fb_set_suspend)
584 		fb_helper->funcs->fb_set_suspend(fb_helper, suspend);
585 	else
586 		fb_set_suspend(fb_helper->info, suspend);
587 }
588 EXPORT_SYMBOL(drm_fb_helper_set_suspend);
589 
590 /**
591  * drm_fb_helper_set_suspend_unlocked - wrapper around fb_set_suspend that also
592  *                                      takes the console lock
593  * @fb_helper: driver-allocated fbdev helper, can be NULL
594  * @suspend: whether to suspend or resume
595  *
596  * A wrapper around fb_set_suspend() that takes the console lock. If the lock
597  * isn't available on resume, a worker is tasked with waiting for the lock
598  * to become available. The console lock can be pretty contented on resume
599  * due to all the printk activity.
600  *
601  * This function can be called multiple times with the same state since
602  * &fb_info.state is checked to see if fbdev is running or not before locking.
603  *
604  * Use drm_fb_helper_set_suspend() if you need to take the lock yourself.
605  */
606 void drm_fb_helper_set_suspend_unlocked(struct drm_fb_helper *fb_helper,
607 					bool suspend)
608 {
609 	if (!fb_helper || !fb_helper->info)
610 		return;
611 
612 	/* make sure there's no pending/ongoing resume */
613 	flush_work(&fb_helper->resume_work);
614 
615 	if (suspend) {
616 		if (fb_helper->info->state != FBINFO_STATE_RUNNING)
617 			return;
618 
619 		/*
620 		 * Cancel pending damage work. During GPU reset, VBlank
621 		 * interrupts are disabled and drm_fb_helper_fb_dirty()
622 		 * would wait for VBlank timeout otherwise.
623 		 */
624 		cancel_work_sync(&fb_helper->damage_work);
625 
626 		console_lock();
627 
628 	} else {
629 		if (fb_helper->info->state == FBINFO_STATE_RUNNING)
630 			return;
631 
632 		if (!console_trylock()) {
633 			schedule_work(&fb_helper->resume_work);
634 			return;
635 		}
636 	}
637 
638 	drm_fb_helper_set_suspend(fb_helper, suspend);
639 	console_unlock();
640 }
641 EXPORT_SYMBOL(drm_fb_helper_set_suspend_unlocked);
642 
643 static int setcmap_pseudo_palette(struct fb_cmap *cmap, struct fb_info *info)
644 {
645 	u32 *palette = (u32 *)info->pseudo_palette;
646 	int i;
647 
648 	if (cmap->start + cmap->len > 16)
649 		return -EINVAL;
650 
651 	for (i = 0; i < cmap->len; ++i) {
652 		u16 red = cmap->red[i];
653 		u16 green = cmap->green[i];
654 		u16 blue = cmap->blue[i];
655 		u32 value;
656 
657 		red >>= 16 - info->var.red.length;
658 		green >>= 16 - info->var.green.length;
659 		blue >>= 16 - info->var.blue.length;
660 		value = (red << info->var.red.offset) |
661 			(green << info->var.green.offset) |
662 			(blue << info->var.blue.offset);
663 		if (info->var.transp.length > 0) {
664 			u32 mask = (1 << info->var.transp.length) - 1;
665 
666 			mask <<= info->var.transp.offset;
667 			value |= mask;
668 		}
669 		palette[cmap->start + i] = value;
670 	}
671 
672 	return 0;
673 }
674 
675 static int setcmap_legacy(struct fb_cmap *cmap, struct fb_info *info)
676 {
677 	struct drm_fb_helper *fb_helper = info->par;
678 	struct drm_mode_set *modeset;
679 	struct drm_crtc *crtc;
680 	u16 *r, *g, *b;
681 	int ret = 0;
682 
683 	drm_modeset_lock_all(fb_helper->dev);
684 	drm_client_for_each_modeset(modeset, &fb_helper->client) {
685 		crtc = modeset->crtc;
686 		if (!crtc->funcs->gamma_set || !crtc->gamma_size) {
687 			ret = -EINVAL;
688 			goto out;
689 		}
690 
691 		if (cmap->start + cmap->len > crtc->gamma_size) {
692 			ret = -EINVAL;
693 			goto out;
694 		}
695 
696 		r = crtc->gamma_store;
697 		g = r + crtc->gamma_size;
698 		b = g + crtc->gamma_size;
699 
700 		memcpy(r + cmap->start, cmap->red, cmap->len * sizeof(*r));
701 		memcpy(g + cmap->start, cmap->green, cmap->len * sizeof(*g));
702 		memcpy(b + cmap->start, cmap->blue, cmap->len * sizeof(*b));
703 
704 		ret = crtc->funcs->gamma_set(crtc, r, g, b,
705 					     crtc->gamma_size, NULL);
706 		if (ret)
707 			goto out;
708 	}
709 out:
710 	drm_modeset_unlock_all(fb_helper->dev);
711 
712 	return ret;
713 }
714 
715 static struct drm_property_blob *setcmap_new_gamma_lut(struct drm_crtc *crtc,
716 						       struct fb_cmap *cmap)
717 {
718 	struct drm_device *dev = crtc->dev;
719 	struct drm_property_blob *gamma_lut;
720 	struct drm_color_lut *lut;
721 	int size = crtc->gamma_size;
722 	int i;
723 
724 	if (!size || cmap->start + cmap->len > size)
725 		return ERR_PTR(-EINVAL);
726 
727 	gamma_lut = drm_property_create_blob(dev, sizeof(*lut) * size, NULL);
728 	if (IS_ERR(gamma_lut))
729 		return gamma_lut;
730 
731 	lut = gamma_lut->data;
732 	if (cmap->start || cmap->len != size) {
733 		u16 *r = crtc->gamma_store;
734 		u16 *g = r + crtc->gamma_size;
735 		u16 *b = g + crtc->gamma_size;
736 
737 		for (i = 0; i < cmap->start; i++) {
738 			lut[i].red = r[i];
739 			lut[i].green = g[i];
740 			lut[i].blue = b[i];
741 		}
742 		for (i = cmap->start + cmap->len; i < size; i++) {
743 			lut[i].red = r[i];
744 			lut[i].green = g[i];
745 			lut[i].blue = b[i];
746 		}
747 	}
748 
749 	for (i = 0; i < cmap->len; i++) {
750 		lut[cmap->start + i].red = cmap->red[i];
751 		lut[cmap->start + i].green = cmap->green[i];
752 		lut[cmap->start + i].blue = cmap->blue[i];
753 	}
754 
755 	return gamma_lut;
756 }
757 
758 static int setcmap_atomic(struct fb_cmap *cmap, struct fb_info *info)
759 {
760 	struct drm_fb_helper *fb_helper = info->par;
761 	struct drm_device *dev = fb_helper->dev;
762 	struct drm_property_blob *gamma_lut = NULL;
763 	struct drm_modeset_acquire_ctx ctx;
764 	struct drm_crtc_state *crtc_state;
765 	struct drm_atomic_state *state;
766 	struct drm_mode_set *modeset;
767 	struct drm_crtc *crtc;
768 	u16 *r, *g, *b;
769 	bool replaced;
770 	int ret = 0;
771 
772 	drm_modeset_acquire_init(&ctx, 0);
773 
774 	state = drm_atomic_state_alloc(dev);
775 	if (!state) {
776 		ret = -ENOMEM;
777 		goto out_ctx;
778 	}
779 
780 	state->acquire_ctx = &ctx;
781 retry:
782 	drm_client_for_each_modeset(modeset, &fb_helper->client) {
783 		crtc = modeset->crtc;
784 
785 		if (!gamma_lut)
786 			gamma_lut = setcmap_new_gamma_lut(crtc, cmap);
787 		if (IS_ERR(gamma_lut)) {
788 			ret = PTR_ERR(gamma_lut);
789 			gamma_lut = NULL;
790 			goto out_state;
791 		}
792 
793 		crtc_state = drm_atomic_get_crtc_state(state, crtc);
794 		if (IS_ERR(crtc_state)) {
795 			ret = PTR_ERR(crtc_state);
796 			goto out_state;
797 		}
798 
799 		/*
800 		 * FIXME: This always uses gamma_lut. Some HW have only
801 		 * degamma_lut, in which case we should reset gamma_lut and set
802 		 * degamma_lut. See drm_crtc_legacy_gamma_set().
803 		 */
804 		replaced  = drm_property_replace_blob(&crtc_state->degamma_lut,
805 						      NULL);
806 		replaced |= drm_property_replace_blob(&crtc_state->ctm, NULL);
807 		replaced |= drm_property_replace_blob(&crtc_state->gamma_lut,
808 						      gamma_lut);
809 		crtc_state->color_mgmt_changed |= replaced;
810 	}
811 
812 	ret = drm_atomic_commit(state);
813 	if (ret)
814 		goto out_state;
815 
816 	drm_client_for_each_modeset(modeset, &fb_helper->client) {
817 		crtc = modeset->crtc;
818 
819 		r = crtc->gamma_store;
820 		g = r + crtc->gamma_size;
821 		b = g + crtc->gamma_size;
822 
823 		memcpy(r + cmap->start, cmap->red, cmap->len * sizeof(*r));
824 		memcpy(g + cmap->start, cmap->green, cmap->len * sizeof(*g));
825 		memcpy(b + cmap->start, cmap->blue, cmap->len * sizeof(*b));
826 	}
827 
828 out_state:
829 	if (ret == -EDEADLK)
830 		goto backoff;
831 
832 	drm_property_blob_put(gamma_lut);
833 	drm_atomic_state_put(state);
834 out_ctx:
835 	drm_modeset_drop_locks(&ctx);
836 	drm_modeset_acquire_fini(&ctx);
837 
838 	return ret;
839 
840 backoff:
841 	drm_atomic_state_clear(state);
842 	drm_modeset_backoff(&ctx);
843 	goto retry;
844 }
845 
846 /**
847  * drm_fb_helper_setcmap - implementation for &fb_ops.fb_setcmap
848  * @cmap: cmap to set
849  * @info: fbdev registered by the helper
850  */
851 int drm_fb_helper_setcmap(struct fb_cmap *cmap, struct fb_info *info)
852 {
853 	struct drm_fb_helper *fb_helper = info->par;
854 	struct drm_device *dev = fb_helper->dev;
855 	int ret;
856 
857 	if (oops_in_progress)
858 		return -EBUSY;
859 
860 	mutex_lock(&fb_helper->lock);
861 
862 	if (!drm_master_internal_acquire(dev)) {
863 		ret = -EBUSY;
864 		goto unlock;
865 	}
866 
867 	mutex_lock(&fb_helper->client.modeset_mutex);
868 	if (info->fix.visual == FB_VISUAL_TRUECOLOR)
869 		ret = setcmap_pseudo_palette(cmap, info);
870 	else if (drm_drv_uses_atomic_modeset(fb_helper->dev))
871 		ret = setcmap_atomic(cmap, info);
872 	else
873 		ret = setcmap_legacy(cmap, info);
874 	mutex_unlock(&fb_helper->client.modeset_mutex);
875 
876 	drm_master_internal_release(dev);
877 unlock:
878 	mutex_unlock(&fb_helper->lock);
879 
880 	return ret;
881 }
882 EXPORT_SYMBOL(drm_fb_helper_setcmap);
883 
884 /**
885  * drm_fb_helper_ioctl - legacy ioctl implementation
886  * @info: fbdev registered by the helper
887  * @cmd: ioctl command
888  * @arg: ioctl argument
889  *
890  * A helper to implement the standard fbdev ioctl. Only
891  * FBIO_WAITFORVSYNC is implemented for now.
892  */
893 int drm_fb_helper_ioctl(struct fb_info *info, unsigned int cmd,
894 			unsigned long arg)
895 {
896 	struct drm_fb_helper *fb_helper = info->par;
897 	int ret = 0;
898 
899 	guard(mutex)(&fb_helper->lock);
900 
901 	switch (cmd) {
902 	case FBIO_WAITFORVSYNC:
903 		/*
904 		 * Only consider the first CRTC.
905 		 *
906 		 * This ioctl is supposed to take the CRTC number as
907 		 * an argument, but in fbdev times, what that number
908 		 * was supposed to be was quite unclear, different
909 		 * drivers were passing that argument differently
910 		 * (some by reference, some by value), and most of the
911 		 * userspace applications were just hardcoding 0 as an
912 		 * argument.
913 		 *
914 		 * The first CRTC should be the integrated panel on
915 		 * most drivers, so this is the best choice we can
916 		 * make. If we're not smart enough here, one should
917 		 * just consider switch the userspace to KMS.
918 		 */
919 		ret = drm_client_modeset_wait_for_vblank(&fb_helper->client, 0);
920 		break;
921 	default:
922 		ret = -ENOTTY;
923 	}
924 
925 	return ret;
926 }
927 EXPORT_SYMBOL(drm_fb_helper_ioctl);
928 
929 static bool drm_fb_pixel_format_equal(const struct fb_var_screeninfo *var_1,
930 				      const struct fb_var_screeninfo *var_2)
931 {
932 	return var_1->bits_per_pixel == var_2->bits_per_pixel &&
933 	       var_1->grayscale == var_2->grayscale &&
934 	       var_1->red.offset == var_2->red.offset &&
935 	       var_1->red.length == var_2->red.length &&
936 	       var_1->red.msb_right == var_2->red.msb_right &&
937 	       var_1->green.offset == var_2->green.offset &&
938 	       var_1->green.length == var_2->green.length &&
939 	       var_1->green.msb_right == var_2->green.msb_right &&
940 	       var_1->blue.offset == var_2->blue.offset &&
941 	       var_1->blue.length == var_2->blue.length &&
942 	       var_1->blue.msb_right == var_2->blue.msb_right &&
943 	       var_1->transp.offset == var_2->transp.offset &&
944 	       var_1->transp.length == var_2->transp.length &&
945 	       var_1->transp.msb_right == var_2->transp.msb_right;
946 }
947 
948 static void drm_fb_helper_fill_pixel_fmt(struct fb_var_screeninfo *var,
949 					 const struct drm_format_info *format)
950 {
951 	u8 depth = format->depth;
952 
953 	if (format->is_color_indexed) {
954 		var->red.offset = 0;
955 		var->green.offset = 0;
956 		var->blue.offset = 0;
957 		var->red.length = depth;
958 		var->green.length = depth;
959 		var->blue.length = depth;
960 		var->transp.offset = 0;
961 		var->transp.length = 0;
962 		return;
963 	}
964 
965 	switch (depth) {
966 	case 15:
967 		var->red.offset = 10;
968 		var->green.offset = 5;
969 		var->blue.offset = 0;
970 		var->red.length = 5;
971 		var->green.length = 5;
972 		var->blue.length = 5;
973 		var->transp.offset = 15;
974 		var->transp.length = 1;
975 		break;
976 	case 16:
977 		var->red.offset = 11;
978 		var->green.offset = 5;
979 		var->blue.offset = 0;
980 		var->red.length = 5;
981 		var->green.length = 6;
982 		var->blue.length = 5;
983 		var->transp.offset = 0;
984 		break;
985 	case 24:
986 		var->red.offset = 16;
987 		var->green.offset = 8;
988 		var->blue.offset = 0;
989 		var->red.length = 8;
990 		var->green.length = 8;
991 		var->blue.length = 8;
992 		var->transp.offset = 0;
993 		var->transp.length = 0;
994 		break;
995 	case 32:
996 		var->red.offset = 16;
997 		var->green.offset = 8;
998 		var->blue.offset = 0;
999 		var->red.length = 8;
1000 		var->green.length = 8;
1001 		var->blue.length = 8;
1002 		var->transp.offset = 24;
1003 		var->transp.length = 8;
1004 		break;
1005 	default:
1006 		break;
1007 	}
1008 }
1009 
1010 static void __fill_var(struct fb_var_screeninfo *var, struct fb_info *info,
1011 		       struct drm_framebuffer *fb)
1012 {
1013 	int i;
1014 
1015 	var->xres_virtual = fb->width;
1016 	var->yres_virtual = fb->height;
1017 	var->accel_flags = 0;
1018 	var->bits_per_pixel = drm_format_info_bpp(fb->format, 0);
1019 
1020 	var->height = info->var.height;
1021 	var->width = info->var.width;
1022 
1023 	var->left_margin = var->right_margin = 0;
1024 	var->upper_margin = var->lower_margin = 0;
1025 	var->hsync_len = var->vsync_len = 0;
1026 	var->sync = var->vmode = 0;
1027 	var->rotate = 0;
1028 	var->colorspace = 0;
1029 	for (i = 0; i < 4; i++)
1030 		var->reserved[i] = 0;
1031 }
1032 
1033 /**
1034  * drm_fb_helper_check_var - implementation for &fb_ops.fb_check_var
1035  * @var: screeninfo to check
1036  * @info: fbdev registered by the helper
1037  */
1038 int drm_fb_helper_check_var(struct fb_var_screeninfo *var,
1039 			    struct fb_info *info)
1040 {
1041 	struct drm_fb_helper *fb_helper = info->par;
1042 	struct drm_framebuffer *fb = fb_helper->fb;
1043 	const struct drm_format_info *format = fb->format;
1044 	struct drm_device *dev = fb_helper->dev;
1045 	unsigned int bpp;
1046 
1047 	if (in_dbg_master())
1048 		return -EINVAL;
1049 
1050 	if (var->pixclock != 0) {
1051 		drm_dbg_kms(dev, "fbdev emulation doesn't support changing the pixel clock, value of pixclock is ignored\n");
1052 		var->pixclock = 0;
1053 	}
1054 
1055 	switch (format->format) {
1056 	case DRM_FORMAT_C1:
1057 	case DRM_FORMAT_C2:
1058 	case DRM_FORMAT_C4:
1059 		/* supported format with sub-byte pixels */
1060 		break;
1061 
1062 	default:
1063 		if ((drm_format_info_block_width(format, 0) > 1) ||
1064 		    (drm_format_info_block_height(format, 0) > 1))
1065 			return -EINVAL;
1066 		break;
1067 	}
1068 
1069 	/*
1070 	 * Changes struct fb_var_screeninfo are currently not pushed back
1071 	 * to KMS, hence fail if different settings are requested.
1072 	 */
1073 	bpp = drm_format_info_bpp(format, 0);
1074 	if (var->bits_per_pixel > bpp ||
1075 	    var->xres > fb->width || var->yres > fb->height ||
1076 	    var->xres_virtual > fb->width || var->yres_virtual > fb->height) {
1077 		drm_dbg_kms(dev, "fb requested width/height/bpp can't fit in current fb "
1078 			  "request %dx%d-%d (virtual %dx%d) > %dx%d-%d\n",
1079 			  var->xres, var->yres, var->bits_per_pixel,
1080 			  var->xres_virtual, var->yres_virtual,
1081 			  fb->width, fb->height, bpp);
1082 		return -EINVAL;
1083 	}
1084 
1085 	__fill_var(var, info, fb);
1086 
1087 	/*
1088 	 * fb_pan_display() validates this, but fb_set_par() doesn't and just
1089 	 * falls over. Note that __fill_var above adjusts y/res_virtual.
1090 	 */
1091 	if (var->yoffset > var->yres_virtual - var->yres ||
1092 	    var->xoffset > var->xres_virtual - var->xres)
1093 		return -EINVAL;
1094 
1095 	/* We neither support grayscale nor FOURCC (also stored in here). */
1096 	if (var->grayscale > 0)
1097 		return -EINVAL;
1098 
1099 	if (var->nonstd)
1100 		return -EINVAL;
1101 
1102 	/*
1103 	 * Workaround for SDL 1.2, which is known to be setting all pixel format
1104 	 * fields values to zero in some cases. We treat this situation as a
1105 	 * kind of "use some reasonable autodetected values".
1106 	 */
1107 	if (!var->red.offset     && !var->green.offset    &&
1108 	    !var->blue.offset    && !var->transp.offset   &&
1109 	    !var->red.length     && !var->green.length    &&
1110 	    !var->blue.length    && !var->transp.length   &&
1111 	    !var->red.msb_right  && !var->green.msb_right &&
1112 	    !var->blue.msb_right && !var->transp.msb_right) {
1113 		drm_fb_helper_fill_pixel_fmt(var, format);
1114 	}
1115 
1116 	/*
1117 	 * drm fbdev emulation doesn't support changing the pixel format at all,
1118 	 * so reject all pixel format changing requests.
1119 	 */
1120 	if (!drm_fb_pixel_format_equal(var, &info->var)) {
1121 		drm_dbg_kms(dev, "fbdev emulation doesn't support changing the pixel format\n");
1122 		return -EINVAL;
1123 	}
1124 
1125 	return 0;
1126 }
1127 EXPORT_SYMBOL(drm_fb_helper_check_var);
1128 
1129 /**
1130  * drm_fb_helper_set_par - implementation for &fb_ops.fb_set_par
1131  * @info: fbdev registered by the helper
1132  *
1133  * This will let fbcon do the mode init and is called at initialization time by
1134  * the fbdev core when registering the driver, and later on through the hotplug
1135  * callback.
1136  */
1137 int drm_fb_helper_set_par(struct fb_info *info)
1138 {
1139 	struct drm_fb_helper *fb_helper = info->par;
1140 	struct fb_var_screeninfo *var = &info->var;
1141 	bool force;
1142 
1143 	if (oops_in_progress)
1144 		return -EBUSY;
1145 
1146 	/*
1147 	 * Normally we want to make sure that a kms master takes precedence over
1148 	 * fbdev, to avoid fbdev flickering and occasionally stealing the
1149 	 * display status. But Xorg first sets the vt back to text mode using
1150 	 * the KDSET IOCTL with KD_TEXT, and only after that drops the master
1151 	 * status when exiting.
1152 	 *
1153 	 * In the past this was caught by drm_fb_helper_restore_fbdev_mode_unlocked(),
1154 	 * but on modern systems where logind always keeps a drm fd open to
1155 	 * orchestrate the vt switching, this doesn't work.
1156 	 *
1157 	 * To not break the userspace ABI we have this special case here, which
1158 	 * is only used for the above case. Everything else uses the normal
1159 	 * commit function, which ensures that we never steal the display from
1160 	 * an active drm master.
1161 	 */
1162 	force = var->activate & FB_ACTIVATE_KD_TEXT;
1163 
1164 	__drm_fb_helper_restore_fbdev_mode_unlocked(fb_helper, force);
1165 
1166 	return 0;
1167 }
1168 EXPORT_SYMBOL(drm_fb_helper_set_par);
1169 
1170 static void pan_set(struct drm_fb_helper *fb_helper, int dx, int dy)
1171 {
1172 	struct drm_mode_set *mode_set;
1173 
1174 	mutex_lock(&fb_helper->client.modeset_mutex);
1175 	drm_client_for_each_modeset(mode_set, &fb_helper->client) {
1176 		mode_set->x += dx;
1177 		mode_set->y += dy;
1178 	}
1179 	mutex_unlock(&fb_helper->client.modeset_mutex);
1180 }
1181 
1182 static int pan_display_atomic(struct fb_var_screeninfo *var,
1183 			      struct fb_info *info)
1184 {
1185 	struct drm_fb_helper *fb_helper = info->par;
1186 	int ret, dx, dy;
1187 
1188 	dx = var->xoffset - info->var.xoffset;
1189 	dy = var->yoffset - info->var.yoffset;
1190 	pan_set(fb_helper, dx, dy);
1191 
1192 	ret = drm_client_modeset_commit_locked(&fb_helper->client);
1193 	if (!ret) {
1194 		info->var.xoffset = var->xoffset;
1195 		info->var.yoffset = var->yoffset;
1196 	} else
1197 		pan_set(fb_helper, -dx, -dy);
1198 
1199 	return ret;
1200 }
1201 
1202 static int pan_display_legacy(struct fb_var_screeninfo *var,
1203 			      struct fb_info *info)
1204 {
1205 	struct drm_fb_helper *fb_helper = info->par;
1206 	struct drm_client_dev *client = &fb_helper->client;
1207 	struct drm_mode_set *modeset;
1208 	int ret = 0;
1209 
1210 	mutex_lock(&client->modeset_mutex);
1211 	drm_modeset_lock_all(fb_helper->dev);
1212 	drm_client_for_each_modeset(modeset, client) {
1213 		modeset->x = var->xoffset;
1214 		modeset->y = var->yoffset;
1215 
1216 		if (modeset->num_connectors) {
1217 			ret = drm_mode_set_config_internal(modeset);
1218 			if (!ret) {
1219 				info->var.xoffset = var->xoffset;
1220 				info->var.yoffset = var->yoffset;
1221 			}
1222 		}
1223 	}
1224 	drm_modeset_unlock_all(fb_helper->dev);
1225 	mutex_unlock(&client->modeset_mutex);
1226 
1227 	return ret;
1228 }
1229 
1230 /**
1231  * drm_fb_helper_pan_display - implementation for &fb_ops.fb_pan_display
1232  * @var: updated screen information
1233  * @info: fbdev registered by the helper
1234  */
1235 int drm_fb_helper_pan_display(struct fb_var_screeninfo *var,
1236 			      struct fb_info *info)
1237 {
1238 	struct drm_fb_helper *fb_helper = info->par;
1239 	struct drm_device *dev = fb_helper->dev;
1240 	int ret;
1241 
1242 	if (oops_in_progress)
1243 		return -EBUSY;
1244 
1245 	mutex_lock(&fb_helper->lock);
1246 	if (!drm_master_internal_acquire(dev)) {
1247 		ret = -EBUSY;
1248 		goto unlock;
1249 	}
1250 
1251 	if (drm_drv_uses_atomic_modeset(dev))
1252 		ret = pan_display_atomic(var, info);
1253 	else
1254 		ret = pan_display_legacy(var, info);
1255 
1256 	drm_master_internal_release(dev);
1257 unlock:
1258 	mutex_unlock(&fb_helper->lock);
1259 
1260 	return ret;
1261 }
1262 EXPORT_SYMBOL(drm_fb_helper_pan_display);
1263 
1264 static uint32_t drm_fb_helper_find_format(struct drm_fb_helper *fb_helper, const uint32_t *formats,
1265 					  size_t format_count, unsigned int color_mode)
1266 {
1267 	struct drm_device *dev = fb_helper->dev;
1268 	uint32_t format;
1269 	size_t i;
1270 
1271 	format = drm_driver_color_mode_format(dev, color_mode);
1272 	if (!format) {
1273 		drm_info(dev, "unsupported color mode of %d\n", color_mode);
1274 		return DRM_FORMAT_INVALID;
1275 	}
1276 
1277 	for (i = 0; i < format_count; ++i) {
1278 		if (formats[i] == format)
1279 			return format;
1280 	}
1281 	drm_warn(dev, "format %p4cc not supported\n", &format);
1282 
1283 	return DRM_FORMAT_INVALID;
1284 }
1285 
1286 static int __drm_fb_helper_find_sizes(struct drm_fb_helper *fb_helper,
1287 				      struct drm_fb_helper_surface_size *sizes)
1288 {
1289 	struct drm_client_dev *client = &fb_helper->client;
1290 	struct drm_device *dev = fb_helper->dev;
1291 	int crtc_count = 0;
1292 	struct drm_connector_list_iter conn_iter;
1293 	struct drm_connector *connector;
1294 	struct drm_mode_set *mode_set;
1295 	uint32_t surface_format = DRM_FORMAT_INVALID;
1296 	const struct drm_format_info *info;
1297 
1298 	memset(sizes, 0, sizeof(*sizes));
1299 	sizes->fb_width = (u32)-1;
1300 	sizes->fb_height = (u32)-1;
1301 
1302 	drm_client_for_each_modeset(mode_set, client) {
1303 		struct drm_crtc *crtc = mode_set->crtc;
1304 		struct drm_plane *plane = crtc->primary;
1305 
1306 		drm_dbg_kms(dev, "test CRTC %u primary plane\n", drm_crtc_index(crtc));
1307 
1308 		drm_connector_list_iter_begin(fb_helper->dev, &conn_iter);
1309 		drm_client_for_each_connector_iter(connector, &conn_iter) {
1310 			struct drm_cmdline_mode *cmdline_mode = &connector->cmdline_mode;
1311 
1312 			if (!cmdline_mode->bpp_specified)
1313 				continue;
1314 
1315 			surface_format = drm_fb_helper_find_format(fb_helper,
1316 								   plane->format_types,
1317 								   plane->format_count,
1318 								   cmdline_mode->bpp);
1319 			if (surface_format != DRM_FORMAT_INVALID)
1320 				break; /* found supported format */
1321 		}
1322 		drm_connector_list_iter_end(&conn_iter);
1323 
1324 		if (surface_format != DRM_FORMAT_INVALID)
1325 			break; /* found supported format */
1326 
1327 		/* try preferred color mode */
1328 		surface_format = drm_fb_helper_find_format(fb_helper,
1329 							   plane->format_types,
1330 							   plane->format_count,
1331 							   fb_helper->preferred_bpp);
1332 		if (surface_format != DRM_FORMAT_INVALID)
1333 			break; /* found supported format */
1334 	}
1335 
1336 	if (surface_format == DRM_FORMAT_INVALID) {
1337 		/*
1338 		 * If none of the given color modes works, fall back
1339 		 * to XRGB8888. Drivers are expected to provide this
1340 		 * format for compatibility with legacy applications.
1341 		 */
1342 		drm_warn(dev, "No compatible format found\n");
1343 		surface_format = drm_driver_legacy_fb_format(dev, 32, 24);
1344 	}
1345 
1346 	info = drm_format_info(surface_format);
1347 	sizes->surface_bpp = drm_format_info_bpp(info, 0);
1348 	sizes->surface_depth = info->depth;
1349 
1350 	/* first up get a count of crtcs now in use and new min/maxes width/heights */
1351 	crtc_count = 0;
1352 	drm_client_for_each_modeset(mode_set, client) {
1353 		struct drm_display_mode *desired_mode;
1354 		int x, y, j;
1355 		/* in case of tile group, are we the last tile vert or horiz?
1356 		 * If no tile group you are always the last one both vertically
1357 		 * and horizontally
1358 		 */
1359 		bool lastv = true, lasth = true;
1360 
1361 		desired_mode = mode_set->mode;
1362 
1363 		if (!desired_mode)
1364 			continue;
1365 
1366 		crtc_count++;
1367 
1368 		x = mode_set->x;
1369 		y = mode_set->y;
1370 
1371 		sizes->surface_width  =
1372 			max_t(u32, desired_mode->hdisplay + x, sizes->surface_width);
1373 		sizes->surface_height =
1374 			max_t(u32, desired_mode->vdisplay + y, sizes->surface_height);
1375 
1376 		for (j = 0; j < mode_set->num_connectors; j++) {
1377 			struct drm_connector *connector = mode_set->connectors[j];
1378 
1379 			if (connector->has_tile &&
1380 			    desired_mode->hdisplay == connector->tile_h_size &&
1381 			    desired_mode->vdisplay == connector->tile_v_size) {
1382 				lasth = (connector->tile_h_loc == (connector->num_h_tile - 1));
1383 				lastv = (connector->tile_v_loc == (connector->num_v_tile - 1));
1384 				/* cloning to multiple tiles is just crazy-talk, so: */
1385 				break;
1386 			}
1387 		}
1388 
1389 		if (lasth)
1390 			sizes->fb_width  = min_t(u32, desired_mode->hdisplay + x, sizes->fb_width);
1391 		if (lastv)
1392 			sizes->fb_height = min_t(u32, desired_mode->vdisplay + y, sizes->fb_height);
1393 	}
1394 
1395 	if (crtc_count == 0 || sizes->fb_width == -1 || sizes->fb_height == -1) {
1396 		drm_info(dev, "Cannot find any crtc or sizes\n");
1397 		return -EAGAIN;
1398 	}
1399 
1400 	return 0;
1401 }
1402 
1403 static int drm_fb_helper_find_sizes(struct drm_fb_helper *fb_helper,
1404 				    struct drm_fb_helper_surface_size *sizes)
1405 {
1406 	struct drm_client_dev *client = &fb_helper->client;
1407 	struct drm_device *dev = fb_helper->dev;
1408 	struct drm_mode_config *config = &dev->mode_config;
1409 	int ret;
1410 
1411 	mutex_lock(&client->modeset_mutex);
1412 	ret = __drm_fb_helper_find_sizes(fb_helper, sizes);
1413 	mutex_unlock(&client->modeset_mutex);
1414 
1415 	if (ret)
1416 		return ret;
1417 
1418 	/* Handle our overallocation */
1419 	sizes->surface_height *= drm_fbdev_overalloc;
1420 	sizes->surface_height /= 100;
1421 	if (sizes->surface_height > config->max_height) {
1422 		drm_dbg_kms(dev, "Fbdev over-allocation too large; clamping height to %d\n",
1423 			    config->max_height);
1424 		sizes->surface_height = config->max_height;
1425 	}
1426 
1427 	return 0;
1428 }
1429 
1430 /*
1431  * Allocates the backing storage and sets up the fbdev info structure through
1432  * the ->fbdev_probe callback.
1433  */
1434 static int drm_fb_helper_single_fb_probe(struct drm_fb_helper *fb_helper)
1435 {
1436 	struct drm_client_dev *client = &fb_helper->client;
1437 	struct drm_device *dev = fb_helper->dev;
1438 	struct drm_fb_helper_surface_size sizes;
1439 	int ret;
1440 
1441 	if (drm_WARN_ON(dev, !dev->driver->fbdev_probe))
1442 		return -EINVAL;
1443 
1444 	ret = drm_fb_helper_find_sizes(fb_helper, &sizes);
1445 	if (ret) {
1446 		/* First time: disable all crtc's.. */
1447 		if (!fb_helper->deferred_setup)
1448 			drm_client_modeset_commit(client);
1449 		return ret;
1450 	}
1451 
1452 	/* push down into drivers */
1453 	ret = dev->driver->fbdev_probe(fb_helper, &sizes);
1454 	if (ret < 0)
1455 		return ret;
1456 
1457 	strcpy(fb_helper->fb->comm, "[fbcon]");
1458 
1459 	return 0;
1460 }
1461 
1462 static void drm_fb_helper_fill_fix(struct fb_info *info, uint32_t pitch,
1463 				   bool is_color_indexed)
1464 {
1465 	info->fix.type = FB_TYPE_PACKED_PIXELS;
1466 	info->fix.visual = is_color_indexed ? FB_VISUAL_PSEUDOCOLOR
1467 					    : FB_VISUAL_TRUECOLOR;
1468 	info->fix.mmio_start = 0;
1469 	info->fix.mmio_len = 0;
1470 	info->fix.type_aux = 0;
1471 	info->fix.xpanstep = 1; /* doing it in hw */
1472 	info->fix.ypanstep = 1; /* doing it in hw */
1473 	info->fix.ywrapstep = 0;
1474 	info->fix.accel = FB_ACCEL_NONE;
1475 
1476 	info->fix.line_length = pitch;
1477 }
1478 
1479 static void drm_fb_helper_fill_var(struct fb_info *info,
1480 				   struct drm_fb_helper *fb_helper,
1481 				   uint32_t fb_width, uint32_t fb_height)
1482 {
1483 	struct drm_framebuffer *fb = fb_helper->fb;
1484 	const struct drm_format_info *format = fb->format;
1485 
1486 	switch (format->format) {
1487 	case DRM_FORMAT_C1:
1488 	case DRM_FORMAT_C2:
1489 	case DRM_FORMAT_C4:
1490 		/* supported format with sub-byte pixels */
1491 		break;
1492 
1493 	default:
1494 		WARN_ON((drm_format_info_block_width(format, 0) > 1) ||
1495 			(drm_format_info_block_height(format, 0) > 1));
1496 		break;
1497 	}
1498 
1499 	info->pseudo_palette = fb_helper->pseudo_palette;
1500 	info->var.xoffset = 0;
1501 	info->var.yoffset = 0;
1502 	__fill_var(&info->var, info, fb);
1503 	info->var.activate = FB_ACTIVATE_NOW;
1504 
1505 	drm_fb_helper_fill_pixel_fmt(&info->var, format);
1506 
1507 	info->var.xres = fb_width;
1508 	info->var.yres = fb_height;
1509 }
1510 
1511 /**
1512  * drm_fb_helper_fill_info - initializes fbdev information
1513  * @info: fbdev instance to set up
1514  * @fb_helper: fb helper instance to use as template
1515  * @sizes: describes fbdev size and scanout surface size
1516  *
1517  * Sets up the variable and fixed fbdev metainformation from the given fb helper
1518  * instance and the drm framebuffer allocated in &drm_fb_helper.fb.
1519  *
1520  * Drivers should call this (or their equivalent setup code) from their
1521  * &drm_driver.fbdev_probe callback after having allocated the fbdev
1522  * backing storage framebuffer.
1523  */
1524 void drm_fb_helper_fill_info(struct fb_info *info,
1525 			     struct drm_fb_helper *fb_helper,
1526 			     struct drm_fb_helper_surface_size *sizes)
1527 {
1528 	struct drm_framebuffer *fb = fb_helper->fb;
1529 
1530 	drm_fb_helper_fill_fix(info, fb->pitches[0],
1531 			       fb->format->is_color_indexed);
1532 	drm_fb_helper_fill_var(info, fb_helper,
1533 			       sizes->fb_width, sizes->fb_height);
1534 
1535 	info->par = fb_helper;
1536 	/*
1537 	 * The DRM drivers fbdev emulation device name can be confusing if the
1538 	 * driver name also has a "drm" suffix on it. Leading to names such as
1539 	 * "simpledrmdrmfb" in /proc/fb. Unfortunately, it's an uAPI and can't
1540 	 * be changed due user-space tools (e.g: pm-utils) matching against it.
1541 	 */
1542 	snprintf(info->fix.id, sizeof(info->fix.id), "%sdrmfb",
1543 		 fb_helper->dev->driver->name);
1544 
1545 }
1546 EXPORT_SYMBOL(drm_fb_helper_fill_info);
1547 
1548 /*
1549  * This is a continuation of drm_setup_crtcs() that sets up anything related
1550  * to the framebuffer. During initialization, drm_setup_crtcs() is called before
1551  * the framebuffer has been allocated (fb_helper->fb and fb_helper->info).
1552  * So, any setup that touches those fields needs to be done here instead of in
1553  * drm_setup_crtcs().
1554  */
1555 static void drm_setup_crtcs_fb(struct drm_fb_helper *fb_helper)
1556 {
1557 	struct drm_client_dev *client = &fb_helper->client;
1558 	struct drm_connector_list_iter conn_iter;
1559 	struct fb_info *info = fb_helper->info;
1560 	unsigned int rotation, sw_rotations = 0;
1561 	struct drm_connector *connector;
1562 	struct drm_mode_set *modeset;
1563 
1564 	mutex_lock(&client->modeset_mutex);
1565 	drm_client_for_each_modeset(modeset, client) {
1566 		if (!modeset->num_connectors)
1567 			continue;
1568 
1569 		modeset->fb = fb_helper->fb;
1570 
1571 		if (drm_client_rotation(modeset, &rotation))
1572 			/* Rotating in hardware, fbcon should not rotate */
1573 			sw_rotations |= DRM_MODE_ROTATE_0;
1574 		else
1575 			sw_rotations |= rotation;
1576 	}
1577 	mutex_unlock(&client->modeset_mutex);
1578 
1579 	drm_connector_list_iter_begin(fb_helper->dev, &conn_iter);
1580 	drm_client_for_each_connector_iter(connector, &conn_iter) {
1581 
1582 		/* use first connected connector for the physical dimensions */
1583 		if (connector->status == connector_status_connected) {
1584 			info->var.width = connector->display_info.width_mm;
1585 			info->var.height = connector->display_info.height_mm;
1586 			break;
1587 		}
1588 	}
1589 	drm_connector_list_iter_end(&conn_iter);
1590 
1591 	switch (sw_rotations) {
1592 	case DRM_MODE_ROTATE_0:
1593 		info->fbcon_rotate_hint = FB_ROTATE_UR;
1594 		break;
1595 	case DRM_MODE_ROTATE_90:
1596 		info->fbcon_rotate_hint = FB_ROTATE_CCW;
1597 		break;
1598 	case DRM_MODE_ROTATE_180:
1599 		info->fbcon_rotate_hint = FB_ROTATE_UD;
1600 		break;
1601 	case DRM_MODE_ROTATE_270:
1602 		info->fbcon_rotate_hint = FB_ROTATE_CW;
1603 		break;
1604 	default:
1605 		/*
1606 		 * Multiple bits are set / multiple rotations requested
1607 		 * fbcon cannot handle separate rotation settings per
1608 		 * output, so fallback to unrotated.
1609 		 */
1610 		info->fbcon_rotate_hint = FB_ROTATE_UR;
1611 	}
1612 }
1613 
1614 /* Note: Drops fb_helper->lock before returning. */
1615 static int
1616 __drm_fb_helper_initial_config_and_unlock(struct drm_fb_helper *fb_helper)
1617 {
1618 	struct drm_device *dev = fb_helper->dev;
1619 	struct fb_info *info;
1620 	unsigned int width, height;
1621 	int ret;
1622 
1623 	width = dev->mode_config.max_width;
1624 	height = dev->mode_config.max_height;
1625 
1626 	drm_client_modeset_probe(&fb_helper->client, width, height);
1627 
1628 	info = drm_fb_helper_alloc_info(fb_helper);
1629 	if (IS_ERR(info))
1630 		return PTR_ERR(info);
1631 
1632 	ret = drm_fb_helper_single_fb_probe(fb_helper);
1633 	if (ret < 0) {
1634 		if (ret == -EAGAIN) {
1635 			fb_helper->deferred_setup = true;
1636 			ret = 0;
1637 		}
1638 		mutex_unlock(&fb_helper->lock);
1639 
1640 		goto err_drm_fb_helper_release_info;
1641 	}
1642 	drm_setup_crtcs_fb(fb_helper);
1643 
1644 	fb_helper->deferred_setup = false;
1645 
1646 	info->var.pixclock = 0;
1647 
1648 	/* Need to drop locks to avoid recursive deadlock in
1649 	 * register_framebuffer. This is ok because the only thing left to do is
1650 	 * register the fbdev emulation instance in kernel_fb_helper_list. */
1651 	mutex_unlock(&fb_helper->lock);
1652 
1653 	ret = register_framebuffer(info);
1654 	if (ret < 0)
1655 		return ret;
1656 
1657 	drm_info(dev, "fb%d: %s frame buffer device\n",
1658 		 info->node, info->fix.id);
1659 
1660 	return 0;
1661 
1662 err_drm_fb_helper_release_info:
1663 	drm_fb_helper_release_info(fb_helper);
1664 	return ret;
1665 }
1666 
1667 /**
1668  * drm_fb_helper_initial_config - setup a sane initial connector configuration
1669  * @fb_helper: fb_helper device struct
1670  *
1671  * Scans the CRTCs and connectors and tries to put together an initial setup.
1672  * At the moment, this is a cloned configuration across all heads with
1673  * a new framebuffer object as the backing store.
1674  *
1675  * Note that this also registers the fbdev and so allows userspace to call into
1676  * the driver through the fbdev interfaces.
1677  *
1678  * This function will call down into the &drm_driver.fbdev_probe callback
1679  * to let the driver allocate and initialize the fbdev info structure and the
1680  * drm framebuffer used to back the fbdev. drm_fb_helper_fill_info() is provided
1681  * as a helper to setup simple default values for the fbdev info structure.
1682  *
1683  * HANG DEBUGGING:
1684  *
1685  * When you have fbcon support built-in or already loaded, this function will do
1686  * a full modeset to setup the fbdev console. Due to locking misdesign in the
1687  * VT/fbdev subsystem that entire modeset sequence has to be done while holding
1688  * console_lock. Until console_unlock is called no dmesg lines will be sent out
1689  * to consoles, not even serial console. This means when your driver crashes,
1690  * you will see absolutely nothing else but a system stuck in this function,
1691  * with no further output. Any kind of printk() you place within your own driver
1692  * or in the drm core modeset code will also never show up.
1693  *
1694  * Standard debug practice is to run the fbcon setup without taking the
1695  * console_lock as a hack, to be able to see backtraces and crashes on the
1696  * serial line. This can be done by setting the fb.lockless_register_fb=1 kernel
1697  * cmdline option.
1698  *
1699  * The other option is to just disable fbdev emulation since very likely the
1700  * first modeset from userspace will crash in the same way, and is even easier
1701  * to debug. This can be done by setting the drm_kms_helper.fbdev_emulation=0
1702  * kernel cmdline option.
1703  *
1704  * RETURNS:
1705  * Zero if everything went ok, nonzero otherwise.
1706  */
1707 int drm_fb_helper_initial_config(struct drm_fb_helper *fb_helper)
1708 {
1709 	int ret;
1710 
1711 	if (!drm_fbdev_emulation)
1712 		return 0;
1713 
1714 	mutex_lock(&fb_helper->lock);
1715 	ret = __drm_fb_helper_initial_config_and_unlock(fb_helper);
1716 
1717 	return ret;
1718 }
1719 EXPORT_SYMBOL(drm_fb_helper_initial_config);
1720 
1721 /**
1722  * drm_fb_helper_hotplug_event - respond to a hotplug notification by
1723  *                               probing all the outputs attached to the fb
1724  * @fb_helper: driver-allocated fbdev helper, can be NULL
1725  *
1726  * Scan the connectors attached to the fb_helper and try to put together a
1727  * setup after notification of a change in output configuration.
1728  *
1729  * Called at runtime, takes the mode config locks to be able to check/change the
1730  * modeset configuration. Must be run from process context (which usually means
1731  * either the output polling work or a work item launched from the driver's
1732  * hotplug interrupt).
1733  *
1734  * Note that drivers may call this even before calling
1735  * drm_fb_helper_initial_config but only after drm_fb_helper_init. This allows
1736  * for a race-free fbcon setup and will make sure that the fbdev emulation will
1737  * not miss any hotplug events.
1738  *
1739  * RETURNS:
1740  * 0 on success and a non-zero error code otherwise.
1741  */
1742 int drm_fb_helper_hotplug_event(struct drm_fb_helper *fb_helper)
1743 {
1744 	int err = 0;
1745 
1746 	if (!drm_fbdev_emulation || !fb_helper)
1747 		return 0;
1748 
1749 	mutex_lock(&fb_helper->lock);
1750 	if (fb_helper->deferred_setup) {
1751 		err = __drm_fb_helper_initial_config_and_unlock(fb_helper);
1752 		return err;
1753 	}
1754 
1755 	if (!fb_helper->fb || !drm_master_internal_acquire(fb_helper->dev)) {
1756 		fb_helper->delayed_hotplug = true;
1757 		mutex_unlock(&fb_helper->lock);
1758 		return err;
1759 	}
1760 
1761 	drm_master_internal_release(fb_helper->dev);
1762 
1763 	drm_dbg_kms(fb_helper->dev, "\n");
1764 
1765 	drm_client_modeset_probe(&fb_helper->client, fb_helper->fb->width, fb_helper->fb->height);
1766 	drm_setup_crtcs_fb(fb_helper);
1767 	mutex_unlock(&fb_helper->lock);
1768 
1769 	drm_fb_helper_set_par(fb_helper->info);
1770 
1771 	return 0;
1772 }
1773 EXPORT_SYMBOL(drm_fb_helper_hotplug_event);
1774