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