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