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