xref: /netbsd/sys/external/bsd/drm2/dist/drm/drm_modes.c (revision 50bace18)
1 /*	$NetBSD: drm_modes.c,v 1.11 2021/12/19 01:13:59 riastradh Exp $	*/
2 
3 /*
4  * Copyright © 1997-2003 by The XFree86 Project, Inc.
5  * Copyright © 2007 Dave Airlie
6  * Copyright © 2007-2008 Intel Corporation
7  *   Jesse Barnes <jesse.barnes@intel.com>
8  * Copyright 2005-2006 Luc Verhaegen
9  * Copyright (c) 2001, Andy Ritger  aritger@nvidia.com
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included in
19  * all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
24  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
25  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
26  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27  * OTHER DEALINGS IN THE SOFTWARE.
28  *
29  * Except as contained in this notice, the name of the copyright holder(s)
30  * and author(s) shall not be used in advertising or otherwise to promote
31  * the sale, use or other dealings in this Software without prior written
32  * authorization from the copyright holder(s) and author(s).
33  */
34 
35 #include <sys/cdefs.h>
36 __KERNEL_RCSID(0, "$NetBSD: drm_modes.c,v 1.11 2021/12/19 01:13:59 riastradh Exp $");
37 
38 #include <linux/ctype.h>
39 #include <linux/list.h>
40 #include <linux/list_sort.h>
41 #include <linux/export.h>
42 #include <asm/div64.h>
43 
44 #ifdef CONFIG_VIDEOMODE_HELPERS
45 #ifdef CONFIG_OF
46 #include <video/of_videomode.h>
47 #endif
48 #include <video/videomode.h>
49 #endif
50 
51 #include <drm/drm_crtc.h>
52 #include <drm/drm_device.h>
53 #include <drm/drm_modes.h>
54 #include <drm/drm_print.h>
55 
56 #include "drm_crtc_internal.h"
57 
58 /**
59  * drm_mode_debug_printmodeline - print a mode to dmesg
60  * @mode: mode to print
61  *
62  * Describe @mode using DRM_DEBUG.
63  */
drm_mode_debug_printmodeline(const struct drm_display_mode * mode)64 void drm_mode_debug_printmodeline(const struct drm_display_mode *mode)
65 {
66 	DRM_DEBUG_KMS("Modeline " DRM_MODE_FMT "\n", DRM_MODE_ARG(mode));
67 }
68 EXPORT_SYMBOL(drm_mode_debug_printmodeline);
69 
70 /**
71  * drm_mode_create - create a new display mode
72  * @dev: DRM device
73  *
74  * Create a new, cleared drm_display_mode with kzalloc, allocate an ID for it
75  * and return it.
76  *
77  * Returns:
78  * Pointer to new mode on success, NULL on error.
79  */
drm_mode_create(struct drm_device * dev)80 struct drm_display_mode *drm_mode_create(struct drm_device *dev)
81 {
82 	struct drm_display_mode *nmode;
83 
84 	nmode = kzalloc(sizeof(struct drm_display_mode), GFP_KERNEL);
85 	if (!nmode)
86 		return NULL;
87 
88 	return nmode;
89 }
90 EXPORT_SYMBOL(drm_mode_create);
91 
92 /**
93  * drm_mode_destroy - remove a mode
94  * @dev: DRM device
95  * @mode: mode to remove
96  *
97  * Release @mode's unique ID, then free it @mode structure itself using kfree.
98  */
drm_mode_destroy(struct drm_device * dev,struct drm_display_mode * mode)99 void drm_mode_destroy(struct drm_device *dev, struct drm_display_mode *mode)
100 {
101 	if (!mode)
102 		return;
103 
104 	kfree(mode);
105 }
106 EXPORT_SYMBOL(drm_mode_destroy);
107 
108 /**
109  * drm_mode_probed_add - add a mode to a connector's probed_mode list
110  * @connector: connector the new mode
111  * @mode: mode data
112  *
113  * Add @mode to @connector's probed_mode list for later use. This list should
114  * then in a second step get filtered and all the modes actually supported by
115  * the hardware moved to the @connector's modes list.
116  */
drm_mode_probed_add(struct drm_connector * connector,struct drm_display_mode * mode)117 void drm_mode_probed_add(struct drm_connector *connector,
118 			 struct drm_display_mode *mode)
119 {
120 	WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex));
121 
122 	list_add_tail(&mode->head, &connector->probed_modes);
123 }
124 EXPORT_SYMBOL(drm_mode_probed_add);
125 
126 /**
127  * drm_cvt_mode -create a modeline based on the CVT algorithm
128  * @dev: drm device
129  * @hdisplay: hdisplay size
130  * @vdisplay: vdisplay size
131  * @vrefresh: vrefresh rate
132  * @reduced: whether to use reduced blanking
133  * @interlaced: whether to compute an interlaced mode
134  * @margins: whether to add margins (borders)
135  *
136  * This function is called to generate the modeline based on CVT algorithm
137  * according to the hdisplay, vdisplay, vrefresh.
138  * It is based from the VESA(TM) Coordinated Video Timing Generator by
139  * Graham Loveridge April 9, 2003 available at
140  * http://www.elo.utfsm.cl/~elo212/docs/CVTd6r1.xls
141  *
142  * And it is copied from xf86CVTmode in xserver/hw/xfree86/modes/xf86cvt.c.
143  * What I have done is to translate it by using integer calculation.
144  *
145  * Returns:
146  * The modeline based on the CVT algorithm stored in a drm_display_mode object.
147  * The display mode object is allocated with drm_mode_create(). Returns NULL
148  * when no mode could be allocated.
149  */
drm_cvt_mode(struct drm_device * dev,int hdisplay,int vdisplay,int vrefresh,bool reduced,bool interlaced,bool margins)150 struct drm_display_mode *drm_cvt_mode(struct drm_device *dev, int hdisplay,
151 				      int vdisplay, int vrefresh,
152 				      bool reduced, bool interlaced, bool margins)
153 {
154 #define HV_FACTOR			1000
155 	/* 1) top/bottom margin size (% of height) - default: 1.8, */
156 #define	CVT_MARGIN_PERCENTAGE		18
157 	/* 2) character cell horizontal granularity (pixels) - default 8 */
158 #define	CVT_H_GRANULARITY		8
159 	/* 3) Minimum vertical porch (lines) - default 3 */
160 #define	CVT_MIN_V_PORCH			3
161 	/* 4) Minimum number of vertical back porch lines - default 6 */
162 #define	CVT_MIN_V_BPORCH		6
163 	/* Pixel Clock step (kHz) */
164 #define CVT_CLOCK_STEP			250
165 	struct drm_display_mode *drm_mode;
166 	unsigned int vfieldrate, hperiod;
167 	int hdisplay_rnd, hmargin, vdisplay_rnd, vmargin, vsync;
168 	int interlace;
169 	u64 tmp;
170 
171 	if (!hdisplay || !vdisplay)
172 		return NULL;
173 
174 	/* allocate the drm_display_mode structure. If failure, we will
175 	 * return directly
176 	 */
177 	drm_mode = drm_mode_create(dev);
178 	if (!drm_mode)
179 		return NULL;
180 
181 	/* the CVT default refresh rate is 60Hz */
182 	if (!vrefresh)
183 		vrefresh = 60;
184 
185 	/* the required field fresh rate */
186 	if (interlaced)
187 		vfieldrate = vrefresh * 2;
188 	else
189 		vfieldrate = vrefresh;
190 
191 	/* horizontal pixels */
192 	hdisplay_rnd = hdisplay - (hdisplay % CVT_H_GRANULARITY);
193 
194 	/* determine the left&right borders */
195 	hmargin = 0;
196 	if (margins) {
197 		hmargin = hdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
198 		hmargin -= hmargin % CVT_H_GRANULARITY;
199 	}
200 	/* find the total active pixels */
201 	drm_mode->hdisplay = hdisplay_rnd + 2 * hmargin;
202 
203 	/* find the number of lines per field */
204 	if (interlaced)
205 		vdisplay_rnd = vdisplay / 2;
206 	else
207 		vdisplay_rnd = vdisplay;
208 
209 	/* find the top & bottom borders */
210 	vmargin = 0;
211 	if (margins)
212 		vmargin = vdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
213 
214 	drm_mode->vdisplay = vdisplay + 2 * vmargin;
215 
216 	/* Interlaced */
217 	if (interlaced)
218 		interlace = 1;
219 	else
220 		interlace = 0;
221 
222 	/* Determine VSync Width from aspect ratio */
223 	if (!(vdisplay % 3) && ((vdisplay * 4 / 3) == hdisplay))
224 		vsync = 4;
225 	else if (!(vdisplay % 9) && ((vdisplay * 16 / 9) == hdisplay))
226 		vsync = 5;
227 	else if (!(vdisplay % 10) && ((vdisplay * 16 / 10) == hdisplay))
228 		vsync = 6;
229 	else if (!(vdisplay % 4) && ((vdisplay * 5 / 4) == hdisplay))
230 		vsync = 7;
231 	else if (!(vdisplay % 9) && ((vdisplay * 15 / 9) == hdisplay))
232 		vsync = 7;
233 	else /* custom */
234 		vsync = 10;
235 
236 	if (!reduced) {
237 		/* simplify the GTF calculation */
238 		/* 4) Minimum time of vertical sync + back porch interval (µs)
239 		 * default 550.0
240 		 */
241 		int tmp1, tmp2;
242 #define CVT_MIN_VSYNC_BP	550
243 		/* 3) Nominal HSync width (% of line period) - default 8 */
244 #define CVT_HSYNC_PERCENTAGE	8
245 		unsigned int hblank_percentage;
246 		int vsyncandback_porch, __maybe_unused vback_porch, hblank;
247 
248 		/* estimated the horizontal period */
249 		tmp1 = HV_FACTOR * 1000000  -
250 				CVT_MIN_VSYNC_BP * HV_FACTOR * vfieldrate;
251 		tmp2 = (vdisplay_rnd + 2 * vmargin + CVT_MIN_V_PORCH) * 2 +
252 				interlace;
253 		hperiod = tmp1 * 2 / (tmp2 * vfieldrate);
254 
255 		tmp1 = CVT_MIN_VSYNC_BP * HV_FACTOR / hperiod + 1;
256 		/* 9. Find number of lines in sync + backporch */
257 		if (tmp1 < (vsync + CVT_MIN_V_PORCH))
258 			vsyncandback_porch = vsync + CVT_MIN_V_PORCH;
259 		else
260 			vsyncandback_porch = tmp1;
261 		/* 10. Find number of lines in back porch */
262 		vback_porch = vsyncandback_porch - vsync;
263 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin +
264 				vsyncandback_porch + CVT_MIN_V_PORCH;
265 		/* 5) Definition of Horizontal blanking time limitation */
266 		/* Gradient (%/kHz) - default 600 */
267 #define CVT_M_FACTOR	600
268 		/* Offset (%) - default 40 */
269 #define CVT_C_FACTOR	40
270 		/* Blanking time scaling factor - default 128 */
271 #define CVT_K_FACTOR	128
272 		/* Scaling factor weighting - default 20 */
273 #define CVT_J_FACTOR	20
274 #define CVT_M_PRIME	(CVT_M_FACTOR * CVT_K_FACTOR / 256)
275 #define CVT_C_PRIME	((CVT_C_FACTOR - CVT_J_FACTOR) * CVT_K_FACTOR / 256 + \
276 			 CVT_J_FACTOR)
277 		/* 12. Find ideal blanking duty cycle from formula */
278 		hblank_percentage = CVT_C_PRIME * HV_FACTOR - CVT_M_PRIME *
279 					hperiod / 1000;
280 		/* 13. Blanking time */
281 		if (hblank_percentage < 20 * HV_FACTOR)
282 			hblank_percentage = 20 * HV_FACTOR;
283 		hblank = drm_mode->hdisplay * hblank_percentage /
284 			 (100 * HV_FACTOR - hblank_percentage);
285 		hblank -= hblank % (2 * CVT_H_GRANULARITY);
286 		/* 14. find the total pixels per line */
287 		drm_mode->htotal = drm_mode->hdisplay + hblank;
288 		drm_mode->hsync_end = drm_mode->hdisplay + hblank / 2;
289 		drm_mode->hsync_start = drm_mode->hsync_end -
290 			(drm_mode->htotal * CVT_HSYNC_PERCENTAGE) / 100;
291 		drm_mode->hsync_start += CVT_H_GRANULARITY -
292 			drm_mode->hsync_start % CVT_H_GRANULARITY;
293 		/* fill the Vsync values */
294 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_MIN_V_PORCH;
295 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
296 	} else {
297 		/* Reduced blanking */
298 		/* Minimum vertical blanking interval time (µs)- default 460 */
299 #define CVT_RB_MIN_VBLANK	460
300 		/* Fixed number of clocks for horizontal sync */
301 #define CVT_RB_H_SYNC		32
302 		/* Fixed number of clocks for horizontal blanking */
303 #define CVT_RB_H_BLANK		160
304 		/* Fixed number of lines for vertical front porch - default 3*/
305 #define CVT_RB_VFPORCH		3
306 		int vbilines;
307 		int tmp1, tmp2;
308 		/* 8. Estimate Horizontal period. */
309 		tmp1 = HV_FACTOR * 1000000 -
310 			CVT_RB_MIN_VBLANK * HV_FACTOR * vfieldrate;
311 		tmp2 = vdisplay_rnd + 2 * vmargin;
312 		hperiod = tmp1 / (tmp2 * vfieldrate);
313 		/* 9. Find number of lines in vertical blanking */
314 		vbilines = CVT_RB_MIN_VBLANK * HV_FACTOR / hperiod + 1;
315 		/* 10. Check if vertical blanking is sufficient */
316 		if (vbilines < (CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH))
317 			vbilines = CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH;
318 		/* 11. Find total number of lines in vertical field */
319 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin + vbilines;
320 		/* 12. Find total number of pixels in a line */
321 		drm_mode->htotal = drm_mode->hdisplay + CVT_RB_H_BLANK;
322 		/* Fill in HSync values */
323 		drm_mode->hsync_end = drm_mode->hdisplay + CVT_RB_H_BLANK / 2;
324 		drm_mode->hsync_start = drm_mode->hsync_end - CVT_RB_H_SYNC;
325 		/* Fill in VSync values */
326 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_RB_VFPORCH;
327 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
328 	}
329 	/* 15/13. Find pixel clock frequency (kHz for xf86) */
330 	tmp = drm_mode->htotal; /* perform intermediate calcs in u64 */
331 	tmp *= HV_FACTOR * 1000;
332 	do_div(tmp, hperiod);
333 	tmp -= drm_mode->clock % CVT_CLOCK_STEP;
334 	drm_mode->clock = tmp;
335 	/* 18/16. Find actual vertical frame frequency */
336 	/* ignore - just set the mode flag for interlaced */
337 	if (interlaced) {
338 		drm_mode->vtotal *= 2;
339 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
340 	}
341 	/* Fill the mode line name */
342 	drm_mode_set_name(drm_mode);
343 	if (reduced)
344 		drm_mode->flags |= (DRM_MODE_FLAG_PHSYNC |
345 					DRM_MODE_FLAG_NVSYNC);
346 	else
347 		drm_mode->flags |= (DRM_MODE_FLAG_PVSYNC |
348 					DRM_MODE_FLAG_NHSYNC);
349 
350 	return drm_mode;
351 }
352 EXPORT_SYMBOL(drm_cvt_mode);
353 
354 /**
355  * drm_gtf_mode_complex - create the modeline based on the full GTF algorithm
356  * @dev: drm device
357  * @hdisplay: hdisplay size
358  * @vdisplay: vdisplay size
359  * @vrefresh: vrefresh rate.
360  * @interlaced: whether to compute an interlaced mode
361  * @margins: desired margin (borders) size
362  * @GTF_M: extended GTF formula parameters
363  * @GTF_2C: extended GTF formula parameters
364  * @GTF_K: extended GTF formula parameters
365  * @GTF_2J: extended GTF formula parameters
366  *
367  * GTF feature blocks specify C and J in multiples of 0.5, so we pass them
368  * in here multiplied by two.  For a C of 40, pass in 80.
369  *
370  * Returns:
371  * The modeline based on the full GTF algorithm stored in a drm_display_mode object.
372  * The display mode object is allocated with drm_mode_create(). Returns NULL
373  * when no mode could be allocated.
374  */
375 struct drm_display_mode *
drm_gtf_mode_complex(struct drm_device * dev,int hdisplay,int vdisplay,int vrefresh,bool interlaced,int margins,int GTF_M,int GTF_2C,int GTF_K,int GTF_2J)376 drm_gtf_mode_complex(struct drm_device *dev, int hdisplay, int vdisplay,
377 		     int vrefresh, bool interlaced, int margins,
378 		     int GTF_M, int GTF_2C, int GTF_K, int GTF_2J)
379 {	/* 1) top/bottom margin size (% of height) - default: 1.8, */
380 #define	GTF_MARGIN_PERCENTAGE		18
381 	/* 2) character cell horizontal granularity (pixels) - default 8 */
382 #define	GTF_CELL_GRAN			8
383 	/* 3) Minimum vertical porch (lines) - default 3 */
384 #define	GTF_MIN_V_PORCH			1
385 	/* width of vsync in lines */
386 #define V_SYNC_RQD			3
387 	/* width of hsync as % of total line */
388 #define H_SYNC_PERCENT			8
389 	/* min time of vsync + back porch (microsec) */
390 #define MIN_VSYNC_PLUS_BP		550
391 	/* C' and M' are part of the Blanking Duty Cycle computation */
392 #define GTF_C_PRIME	((((GTF_2C - GTF_2J) * GTF_K / 256) + GTF_2J) / 2)
393 #define GTF_M_PRIME	(GTF_K * GTF_M / 256)
394 	struct drm_display_mode *drm_mode;
395 	unsigned int hdisplay_rnd, vdisplay_rnd, vfieldrate_rqd;
396 	int top_margin, bottom_margin;
397 	int interlace;
398 	unsigned int hfreq_est;
399 	int vsync_plus_bp, __maybe_unused vback_porch;
400 	unsigned int vtotal_lines, __maybe_unused vfieldrate_est;
401 	unsigned int __maybe_unused hperiod;
402 	unsigned int vfield_rate, __maybe_unused vframe_rate;
403 	int left_margin, right_margin;
404 	unsigned int total_active_pixels, ideal_duty_cycle;
405 	unsigned int hblank, total_pixels, pixel_freq;
406 	int hsync, hfront_porch, vodd_front_porch_lines;
407 	unsigned int tmp1, tmp2;
408 
409 	if (!hdisplay || !vdisplay)
410 		return NULL;
411 
412 	drm_mode = drm_mode_create(dev);
413 	if (!drm_mode)
414 		return NULL;
415 
416 	/* 1. In order to give correct results, the number of horizontal
417 	 * pixels requested is first processed to ensure that it is divisible
418 	 * by the character size, by rounding it to the nearest character
419 	 * cell boundary:
420 	 */
421 	hdisplay_rnd = (hdisplay + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
422 	hdisplay_rnd = hdisplay_rnd * GTF_CELL_GRAN;
423 
424 	/* 2. If interlace is requested, the number of vertical lines assumed
425 	 * by the calculation must be halved, as the computation calculates
426 	 * the number of vertical lines per field.
427 	 */
428 	if (interlaced)
429 		vdisplay_rnd = vdisplay / 2;
430 	else
431 		vdisplay_rnd = vdisplay;
432 
433 	/* 3. Find the frame rate required: */
434 	if (interlaced)
435 		vfieldrate_rqd = vrefresh * 2;
436 	else
437 		vfieldrate_rqd = vrefresh;
438 
439 	/* 4. Find number of lines in Top margin: */
440 	top_margin = 0;
441 	if (margins)
442 		top_margin = (vdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
443 				1000;
444 	/* 5. Find number of lines in bottom margin: */
445 	bottom_margin = top_margin;
446 
447 	/* 6. If interlace is required, then set variable interlace: */
448 	if (interlaced)
449 		interlace = 1;
450 	else
451 		interlace = 0;
452 
453 	/* 7. Estimate the Horizontal frequency */
454 	{
455 		tmp1 = (1000000  - MIN_VSYNC_PLUS_BP * vfieldrate_rqd) / 500;
456 		tmp2 = (vdisplay_rnd + 2 * top_margin + GTF_MIN_V_PORCH) *
457 				2 + interlace;
458 		hfreq_est = (tmp2 * 1000 * vfieldrate_rqd) / tmp1;
459 	}
460 
461 	/* 8. Find the number of lines in V sync + back porch */
462 	/* [V SYNC+BP] = RINT(([MIN VSYNC+BP] * hfreq_est / 1000000)) */
463 	vsync_plus_bp = MIN_VSYNC_PLUS_BP * hfreq_est / 1000;
464 	vsync_plus_bp = (vsync_plus_bp + 500) / 1000;
465 	/*  9. Find the number of lines in V back porch alone: */
466 	vback_porch = vsync_plus_bp - V_SYNC_RQD;
467 	/*  10. Find the total number of lines in Vertical field period: */
468 	vtotal_lines = vdisplay_rnd + top_margin + bottom_margin +
469 			vsync_plus_bp + GTF_MIN_V_PORCH;
470 	/*  11. Estimate the Vertical field frequency: */
471 	vfieldrate_est = hfreq_est / vtotal_lines;
472 	/*  12. Find the actual horizontal period: */
473 	hperiod = 1000000 / (vfieldrate_rqd * vtotal_lines);
474 
475 	/*  13. Find the actual Vertical field frequency: */
476 	vfield_rate = hfreq_est / vtotal_lines;
477 	/*  14. Find the Vertical frame frequency: */
478 	if (interlaced)
479 		vframe_rate = vfield_rate / 2;
480 	else
481 		vframe_rate = vfield_rate;
482 	/*  15. Find number of pixels in left margin: */
483 	if (margins)
484 		left_margin = (hdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
485 				1000;
486 	else
487 		left_margin = 0;
488 
489 	/* 16.Find number of pixels in right margin: */
490 	right_margin = left_margin;
491 	/* 17.Find total number of active pixels in image and left and right */
492 	total_active_pixels = hdisplay_rnd + left_margin + right_margin;
493 	/* 18.Find the ideal blanking duty cycle from blanking duty cycle */
494 	ideal_duty_cycle = GTF_C_PRIME * 1000 -
495 				(GTF_M_PRIME * 1000000 / hfreq_est);
496 	/* 19.Find the number of pixels in the blanking time to the nearest
497 	 * double character cell: */
498 	hblank = total_active_pixels * ideal_duty_cycle /
499 			(100000 - ideal_duty_cycle);
500 	hblank = (hblank + GTF_CELL_GRAN) / (2 * GTF_CELL_GRAN);
501 	hblank = hblank * 2 * GTF_CELL_GRAN;
502 	/* 20.Find total number of pixels: */
503 	total_pixels = total_active_pixels + hblank;
504 	/* 21.Find pixel clock frequency: */
505 	pixel_freq = total_pixels * hfreq_est / 1000;
506 	/* Stage 1 computations are now complete; I should really pass
507 	 * the results to another function and do the Stage 2 computations,
508 	 * but I only need a few more values so I'll just append the
509 	 * computations here for now */
510 	/* 17. Find the number of pixels in the horizontal sync period: */
511 	hsync = H_SYNC_PERCENT * total_pixels / 100;
512 	hsync = (hsync + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
513 	hsync = hsync * GTF_CELL_GRAN;
514 	/* 18. Find the number of pixels in horizontal front porch period */
515 	hfront_porch = hblank / 2 - hsync;
516 	/*  36. Find the number of lines in the odd front porch period: */
517 	vodd_front_porch_lines = GTF_MIN_V_PORCH ;
518 
519 	/* finally, pack the results in the mode struct */
520 	drm_mode->hdisplay = hdisplay_rnd;
521 	drm_mode->hsync_start = hdisplay_rnd + hfront_porch;
522 	drm_mode->hsync_end = drm_mode->hsync_start + hsync;
523 	drm_mode->htotal = total_pixels;
524 	drm_mode->vdisplay = vdisplay_rnd;
525 	drm_mode->vsync_start = vdisplay_rnd + vodd_front_porch_lines;
526 	drm_mode->vsync_end = drm_mode->vsync_start + V_SYNC_RQD;
527 	drm_mode->vtotal = vtotal_lines;
528 
529 	drm_mode->clock = pixel_freq;
530 
531 	if (interlaced) {
532 		drm_mode->vtotal *= 2;
533 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
534 	}
535 
536 	drm_mode_set_name(drm_mode);
537 	if (GTF_M == 600 && GTF_2C == 80 && GTF_K == 128 && GTF_2J == 40)
538 		drm_mode->flags = DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC;
539 	else
540 		drm_mode->flags = DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC;
541 
542 	return drm_mode;
543 }
544 EXPORT_SYMBOL(drm_gtf_mode_complex);
545 
546 /**
547  * drm_gtf_mode - create the modeline based on the GTF algorithm
548  * @dev: drm device
549  * @hdisplay: hdisplay size
550  * @vdisplay: vdisplay size
551  * @vrefresh: vrefresh rate.
552  * @interlaced: whether to compute an interlaced mode
553  * @margins: desired margin (borders) size
554  *
555  * return the modeline based on GTF algorithm
556  *
557  * This function is to create the modeline based on the GTF algorithm.
558  * Generalized Timing Formula is derived from:
559  *
560  *	GTF Spreadsheet by Andy Morrish (1/5/97)
561  *	available at http://www.vesa.org
562  *
563  * And it is copied from the file of xserver/hw/xfree86/modes/xf86gtf.c.
564  * What I have done is to translate it by using integer calculation.
565  * I also refer to the function of fb_get_mode in the file of
566  * drivers/video/fbmon.c
567  *
568  * Standard GTF parameters::
569  *
570  *     M = 600
571  *     C = 40
572  *     K = 128
573  *     J = 20
574  *
575  * Returns:
576  * The modeline based on the GTF algorithm stored in a drm_display_mode object.
577  * The display mode object is allocated with drm_mode_create(). Returns NULL
578  * when no mode could be allocated.
579  */
580 struct drm_display_mode *
drm_gtf_mode(struct drm_device * dev,int hdisplay,int vdisplay,int vrefresh,bool interlaced,int margins)581 drm_gtf_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh,
582 	     bool interlaced, int margins)
583 {
584 	return drm_gtf_mode_complex(dev, hdisplay, vdisplay, vrefresh,
585 				    interlaced, margins,
586 				    600, 40 * 2, 128, 20 * 2);
587 }
588 EXPORT_SYMBOL(drm_gtf_mode);
589 
590 #ifdef CONFIG_VIDEOMODE_HELPERS
591 /**
592  * drm_display_mode_from_videomode - fill in @dmode using @vm,
593  * @vm: videomode structure to use as source
594  * @dmode: drm_display_mode structure to use as destination
595  *
596  * Fills out @dmode using the display mode specified in @vm.
597  */
drm_display_mode_from_videomode(const struct videomode * vm,struct drm_display_mode * dmode)598 void drm_display_mode_from_videomode(const struct videomode *vm,
599 				     struct drm_display_mode *dmode)
600 {
601 	dmode->hdisplay = vm->hactive;
602 	dmode->hsync_start = dmode->hdisplay + vm->hfront_porch;
603 	dmode->hsync_end = dmode->hsync_start + vm->hsync_len;
604 	dmode->htotal = dmode->hsync_end + vm->hback_porch;
605 
606 	dmode->vdisplay = vm->vactive;
607 	dmode->vsync_start = dmode->vdisplay + vm->vfront_porch;
608 	dmode->vsync_end = dmode->vsync_start + vm->vsync_len;
609 	dmode->vtotal = dmode->vsync_end + vm->vback_porch;
610 
611 	dmode->clock = vm->pixelclock / 1000;
612 
613 	dmode->flags = 0;
614 	if (vm->flags & DISPLAY_FLAGS_HSYNC_HIGH)
615 		dmode->flags |= DRM_MODE_FLAG_PHSYNC;
616 	else if (vm->flags & DISPLAY_FLAGS_HSYNC_LOW)
617 		dmode->flags |= DRM_MODE_FLAG_NHSYNC;
618 	if (vm->flags & DISPLAY_FLAGS_VSYNC_HIGH)
619 		dmode->flags |= DRM_MODE_FLAG_PVSYNC;
620 	else if (vm->flags & DISPLAY_FLAGS_VSYNC_LOW)
621 		dmode->flags |= DRM_MODE_FLAG_NVSYNC;
622 	if (vm->flags & DISPLAY_FLAGS_INTERLACED)
623 		dmode->flags |= DRM_MODE_FLAG_INTERLACE;
624 	if (vm->flags & DISPLAY_FLAGS_DOUBLESCAN)
625 		dmode->flags |= DRM_MODE_FLAG_DBLSCAN;
626 	if (vm->flags & DISPLAY_FLAGS_DOUBLECLK)
627 		dmode->flags |= DRM_MODE_FLAG_DBLCLK;
628 	drm_mode_set_name(dmode);
629 }
630 EXPORT_SYMBOL_GPL(drm_display_mode_from_videomode);
631 
632 /**
633  * drm_display_mode_to_videomode - fill in @vm using @dmode,
634  * @dmode: drm_display_mode structure to use as source
635  * @vm: videomode structure to use as destination
636  *
637  * Fills out @vm using the display mode specified in @dmode.
638  */
drm_display_mode_to_videomode(const struct drm_display_mode * dmode,struct videomode * vm)639 void drm_display_mode_to_videomode(const struct drm_display_mode *dmode,
640 				   struct videomode *vm)
641 {
642 	vm->hactive = dmode->hdisplay;
643 	vm->hfront_porch = dmode->hsync_start - dmode->hdisplay;
644 	vm->hsync_len = dmode->hsync_end - dmode->hsync_start;
645 	vm->hback_porch = dmode->htotal - dmode->hsync_end;
646 
647 	vm->vactive = dmode->vdisplay;
648 	vm->vfront_porch = dmode->vsync_start - dmode->vdisplay;
649 	vm->vsync_len = dmode->vsync_end - dmode->vsync_start;
650 	vm->vback_porch = dmode->vtotal - dmode->vsync_end;
651 
652 	vm->pixelclock = dmode->clock * 1000;
653 
654 	vm->flags = 0;
655 	if (dmode->flags & DRM_MODE_FLAG_PHSYNC)
656 		vm->flags |= DISPLAY_FLAGS_HSYNC_HIGH;
657 	else if (dmode->flags & DRM_MODE_FLAG_NHSYNC)
658 		vm->flags |= DISPLAY_FLAGS_HSYNC_LOW;
659 	if (dmode->flags & DRM_MODE_FLAG_PVSYNC)
660 		vm->flags |= DISPLAY_FLAGS_VSYNC_HIGH;
661 	else if (dmode->flags & DRM_MODE_FLAG_NVSYNC)
662 		vm->flags |= DISPLAY_FLAGS_VSYNC_LOW;
663 	if (dmode->flags & DRM_MODE_FLAG_INTERLACE)
664 		vm->flags |= DISPLAY_FLAGS_INTERLACED;
665 	if (dmode->flags & DRM_MODE_FLAG_DBLSCAN)
666 		vm->flags |= DISPLAY_FLAGS_DOUBLESCAN;
667 	if (dmode->flags & DRM_MODE_FLAG_DBLCLK)
668 		vm->flags |= DISPLAY_FLAGS_DOUBLECLK;
669 }
670 EXPORT_SYMBOL_GPL(drm_display_mode_to_videomode);
671 
672 /**
673  * drm_bus_flags_from_videomode - extract information about pixelclk and
674  * DE polarity from videomode and store it in a separate variable
675  * @vm: videomode structure to use
676  * @bus_flags: information about pixelclk, sync and DE polarity will be stored
677  * here
678  *
679  * Sets DRM_BUS_FLAG_DE_(LOW|HIGH),  DRM_BUS_FLAG_PIXDATA_DRIVE_(POS|NEG)EDGE
680  * and DISPLAY_FLAGS_SYNC_(POS|NEG)EDGE in @bus_flags according to DISPLAY_FLAGS
681  * found in @vm
682  */
drm_bus_flags_from_videomode(const struct videomode * vm,u32 * bus_flags)683 void drm_bus_flags_from_videomode(const struct videomode *vm, u32 *bus_flags)
684 {
685 	*bus_flags = 0;
686 	if (vm->flags & DISPLAY_FLAGS_PIXDATA_POSEDGE)
687 		*bus_flags |= DRM_BUS_FLAG_PIXDATA_DRIVE_POSEDGE;
688 	if (vm->flags & DISPLAY_FLAGS_PIXDATA_NEGEDGE)
689 		*bus_flags |= DRM_BUS_FLAG_PIXDATA_DRIVE_NEGEDGE;
690 
691 	if (vm->flags & DISPLAY_FLAGS_SYNC_POSEDGE)
692 		*bus_flags |= DRM_BUS_FLAG_SYNC_DRIVE_POSEDGE;
693 	if (vm->flags & DISPLAY_FLAGS_SYNC_NEGEDGE)
694 		*bus_flags |= DRM_BUS_FLAG_SYNC_DRIVE_NEGEDGE;
695 
696 	if (vm->flags & DISPLAY_FLAGS_DE_LOW)
697 		*bus_flags |= DRM_BUS_FLAG_DE_LOW;
698 	if (vm->flags & DISPLAY_FLAGS_DE_HIGH)
699 		*bus_flags |= DRM_BUS_FLAG_DE_HIGH;
700 }
701 EXPORT_SYMBOL_GPL(drm_bus_flags_from_videomode);
702 
703 #ifdef CONFIG_OF
704 /**
705  * of_get_drm_display_mode - get a drm_display_mode from devicetree
706  * @np: device_node with the timing specification
707  * @dmode: will be set to the return value
708  * @bus_flags: information about pixelclk, sync and DE polarity
709  * @index: index into the list of display timings in devicetree
710  *
711  * This function is expensive and should only be used, if only one mode is to be
712  * read from DT. To get multiple modes start with of_get_display_timings and
713  * work with that instead.
714  *
715  * Returns:
716  * 0 on success, a negative errno code when no of videomode node was found.
717  */
of_get_drm_display_mode(struct device_node * np,struct drm_display_mode * dmode,u32 * bus_flags,int index)718 int of_get_drm_display_mode(struct device_node *np,
719 			    struct drm_display_mode *dmode, u32 *bus_flags,
720 			    int index)
721 {
722 	struct videomode vm;
723 	int ret;
724 
725 	ret = of_get_videomode(np, &vm, index);
726 	if (ret)
727 		return ret;
728 
729 	drm_display_mode_from_videomode(&vm, dmode);
730 	if (bus_flags)
731 		drm_bus_flags_from_videomode(&vm, bus_flags);
732 
733 	pr_debug("%pOF: got %dx%d display mode\n",
734 		np, vm.hactive, vm.vactive);
735 	drm_mode_debug_printmodeline(dmode);
736 
737 	return 0;
738 }
739 EXPORT_SYMBOL_GPL(of_get_drm_display_mode);
740 #endif /* CONFIG_OF */
741 #endif /* CONFIG_VIDEOMODE_HELPERS */
742 
743 /**
744  * drm_mode_set_name - set the name on a mode
745  * @mode: name will be set in this mode
746  *
747  * Set the name of @mode to a standard format which is <hdisplay>x<vdisplay>
748  * with an optional 'i' suffix for interlaced modes.
749  */
drm_mode_set_name(struct drm_display_mode * mode)750 void drm_mode_set_name(struct drm_display_mode *mode)
751 {
752 	bool interlaced = !!(mode->flags & DRM_MODE_FLAG_INTERLACE);
753 
754 	snprintf(mode->name, DRM_DISPLAY_MODE_LEN, "%dx%d%s",
755 		 mode->hdisplay, mode->vdisplay,
756 		 interlaced ? "i" : "");
757 }
758 EXPORT_SYMBOL(drm_mode_set_name);
759 
760 /**
761  * drm_mode_hsync - get the hsync of a mode
762  * @mode: mode
763  *
764  * Returns:
765  * @modes's hsync rate in kHz, rounded to the nearest integer. Calculates the
766  * value first if it is not yet set.
767  */
drm_mode_hsync(const struct drm_display_mode * mode)768 int drm_mode_hsync(const struct drm_display_mode *mode)
769 {
770 	unsigned int calc_val;
771 
772 	if (mode->hsync)
773 		return mode->hsync;
774 
775 	if (mode->htotal <= 0)
776 		return 0;
777 
778 	calc_val = (mode->clock * 1000) / mode->htotal; /* hsync in Hz */
779 	calc_val += 500;				/* round to 1000Hz */
780 	calc_val /= 1000;				/* truncate to kHz */
781 
782 	return calc_val;
783 }
784 EXPORT_SYMBOL(drm_mode_hsync);
785 
786 /**
787  * drm_mode_vrefresh - get the vrefresh of a mode
788  * @mode: mode
789  *
790  * Returns:
791  * @modes's vrefresh rate in Hz, rounded to the nearest integer. Calculates the
792  * value first if it is not yet set.
793  */
drm_mode_vrefresh(const struct drm_display_mode * mode)794 int drm_mode_vrefresh(const struct drm_display_mode *mode)
795 {
796 	int refresh = 0;
797 
798 	if (mode->vrefresh > 0)
799 		refresh = mode->vrefresh;
800 	else if (mode->htotal > 0 && mode->vtotal > 0) {
801 		unsigned int num, den;
802 
803 		num = mode->clock * 1000;
804 		den = mode->htotal * mode->vtotal;
805 
806 		if (mode->flags & DRM_MODE_FLAG_INTERLACE)
807 			num *= 2;
808 		if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
809 			den *= 2;
810 		if (mode->vscan > 1)
811 			den *= mode->vscan;
812 
813 		refresh = DIV_ROUND_CLOSEST(num, den);
814 	}
815 	return refresh;
816 }
817 EXPORT_SYMBOL(drm_mode_vrefresh);
818 
819 /**
820  * drm_mode_get_hv_timing - Fetches hdisplay/vdisplay for given mode
821  * @mode: mode to query
822  * @hdisplay: hdisplay value to fill in
823  * @vdisplay: vdisplay value to fill in
824  *
825  * The vdisplay value will be doubled if the specified mode is a stereo mode of
826  * the appropriate layout.
827  */
drm_mode_get_hv_timing(const struct drm_display_mode * mode,int * hdisplay,int * vdisplay)828 void drm_mode_get_hv_timing(const struct drm_display_mode *mode,
829 			    int *hdisplay, int *vdisplay)
830 {
831 	struct drm_display_mode adjusted = *mode;
832 
833 	drm_mode_set_crtcinfo(&adjusted, CRTC_STEREO_DOUBLE_ONLY);
834 	*hdisplay = adjusted.crtc_hdisplay;
835 	*vdisplay = adjusted.crtc_vdisplay;
836 }
837 EXPORT_SYMBOL(drm_mode_get_hv_timing);
838 
839 /**
840  * drm_mode_set_crtcinfo - set CRTC modesetting timing parameters
841  * @p: mode
842  * @adjust_flags: a combination of adjustment flags
843  *
844  * Setup the CRTC modesetting timing parameters for @p, adjusting if necessary.
845  *
846  * - The CRTC_INTERLACE_HALVE_V flag can be used to halve vertical timings of
847  *   interlaced modes.
848  * - The CRTC_STEREO_DOUBLE flag can be used to compute the timings for
849  *   buffers containing two eyes (only adjust the timings when needed, eg. for
850  *   "frame packing" or "side by side full").
851  * - The CRTC_NO_DBLSCAN and CRTC_NO_VSCAN flags request that adjustment *not*
852  *   be performed for doublescan and vscan > 1 modes respectively.
853  */
drm_mode_set_crtcinfo(struct drm_display_mode * p,int adjust_flags)854 void drm_mode_set_crtcinfo(struct drm_display_mode *p, int adjust_flags)
855 {
856 	if (!p)
857 		return;
858 
859 	p->crtc_clock = p->clock;
860 	p->crtc_hdisplay = p->hdisplay;
861 	p->crtc_hsync_start = p->hsync_start;
862 	p->crtc_hsync_end = p->hsync_end;
863 	p->crtc_htotal = p->htotal;
864 	p->crtc_hskew = p->hskew;
865 	p->crtc_vdisplay = p->vdisplay;
866 	p->crtc_vsync_start = p->vsync_start;
867 	p->crtc_vsync_end = p->vsync_end;
868 	p->crtc_vtotal = p->vtotal;
869 
870 	if (p->flags & DRM_MODE_FLAG_INTERLACE) {
871 		if (adjust_flags & CRTC_INTERLACE_HALVE_V) {
872 			p->crtc_vdisplay /= 2;
873 			p->crtc_vsync_start /= 2;
874 			p->crtc_vsync_end /= 2;
875 			p->crtc_vtotal /= 2;
876 		}
877 	}
878 
879 	if (!(adjust_flags & CRTC_NO_DBLSCAN)) {
880 		if (p->flags & DRM_MODE_FLAG_DBLSCAN) {
881 			p->crtc_vdisplay *= 2;
882 			p->crtc_vsync_start *= 2;
883 			p->crtc_vsync_end *= 2;
884 			p->crtc_vtotal *= 2;
885 		}
886 	}
887 
888 	if (!(adjust_flags & CRTC_NO_VSCAN)) {
889 		if (p->vscan > 1) {
890 			p->crtc_vdisplay *= p->vscan;
891 			p->crtc_vsync_start *= p->vscan;
892 			p->crtc_vsync_end *= p->vscan;
893 			p->crtc_vtotal *= p->vscan;
894 		}
895 	}
896 
897 	if (adjust_flags & CRTC_STEREO_DOUBLE) {
898 		unsigned int layout = p->flags & DRM_MODE_FLAG_3D_MASK;
899 
900 		switch (layout) {
901 		case DRM_MODE_FLAG_3D_FRAME_PACKING:
902 			p->crtc_clock *= 2;
903 			p->crtc_vdisplay += p->crtc_vtotal;
904 			p->crtc_vsync_start += p->crtc_vtotal;
905 			p->crtc_vsync_end += p->crtc_vtotal;
906 			p->crtc_vtotal += p->crtc_vtotal;
907 			break;
908 		}
909 	}
910 
911 	p->crtc_vblank_start = min(p->crtc_vsync_start, p->crtc_vdisplay);
912 	p->crtc_vblank_end = max(p->crtc_vsync_end, p->crtc_vtotal);
913 	p->crtc_hblank_start = min(p->crtc_hsync_start, p->crtc_hdisplay);
914 	p->crtc_hblank_end = max(p->crtc_hsync_end, p->crtc_htotal);
915 }
916 EXPORT_SYMBOL(drm_mode_set_crtcinfo);
917 
918 /**
919  * drm_mode_copy - copy the mode
920  * @dst: mode to overwrite
921  * @src: mode to copy
922  *
923  * Copy an existing mode into another mode, preserving the object id and
924  * list head of the destination mode.
925  */
drm_mode_copy(struct drm_display_mode * dst,const struct drm_display_mode * src)926 void drm_mode_copy(struct drm_display_mode *dst, const struct drm_display_mode *src)
927 {
928 	struct list_head head = dst->head;
929 
930 	*dst = *src;
931 	dst->head = head;
932 }
933 EXPORT_SYMBOL(drm_mode_copy);
934 
935 /**
936  * drm_mode_duplicate - allocate and duplicate an existing mode
937  * @dev: drm_device to allocate the duplicated mode for
938  * @mode: mode to duplicate
939  *
940  * Just allocate a new mode, copy the existing mode into it, and return
941  * a pointer to it.  Used to create new instances of established modes.
942  *
943  * Returns:
944  * Pointer to duplicated mode on success, NULL on error.
945  */
drm_mode_duplicate(struct drm_device * dev,const struct drm_display_mode * mode)946 struct drm_display_mode *drm_mode_duplicate(struct drm_device *dev,
947 					    const struct drm_display_mode *mode)
948 {
949 	struct drm_display_mode *nmode;
950 
951 	nmode = drm_mode_create(dev);
952 	if (!nmode)
953 		return NULL;
954 
955 	drm_mode_copy(nmode, mode);
956 
957 	return nmode;
958 }
959 EXPORT_SYMBOL(drm_mode_duplicate);
960 
drm_mode_match_timings(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)961 static bool drm_mode_match_timings(const struct drm_display_mode *mode1,
962 				   const struct drm_display_mode *mode2)
963 {
964 	return mode1->hdisplay == mode2->hdisplay &&
965 		mode1->hsync_start == mode2->hsync_start &&
966 		mode1->hsync_end == mode2->hsync_end &&
967 		mode1->htotal == mode2->htotal &&
968 		mode1->hskew == mode2->hskew &&
969 		mode1->vdisplay == mode2->vdisplay &&
970 		mode1->vsync_start == mode2->vsync_start &&
971 		mode1->vsync_end == mode2->vsync_end &&
972 		mode1->vtotal == mode2->vtotal &&
973 		mode1->vscan == mode2->vscan;
974 }
975 
drm_mode_match_clock(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)976 static bool drm_mode_match_clock(const struct drm_display_mode *mode1,
977 				  const struct drm_display_mode *mode2)
978 {
979 	/*
980 	 * do clock check convert to PICOS
981 	 * so fb modes get matched the same
982 	 */
983 	if (mode1->clock && mode2->clock)
984 		return KHZ2PICOS(mode1->clock) == KHZ2PICOS(mode2->clock);
985 	else
986 		return mode1->clock == mode2->clock;
987 }
988 
drm_mode_match_flags(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)989 static bool drm_mode_match_flags(const struct drm_display_mode *mode1,
990 				 const struct drm_display_mode *mode2)
991 {
992 	return (mode1->flags & ~DRM_MODE_FLAG_3D_MASK) ==
993 		(mode2->flags & ~DRM_MODE_FLAG_3D_MASK);
994 }
995 
drm_mode_match_3d_flags(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)996 static bool drm_mode_match_3d_flags(const struct drm_display_mode *mode1,
997 				    const struct drm_display_mode *mode2)
998 {
999 	return (mode1->flags & DRM_MODE_FLAG_3D_MASK) ==
1000 		(mode2->flags & DRM_MODE_FLAG_3D_MASK);
1001 }
1002 
drm_mode_match_aspect_ratio(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)1003 static bool drm_mode_match_aspect_ratio(const struct drm_display_mode *mode1,
1004 					const struct drm_display_mode *mode2)
1005 {
1006 	return mode1->picture_aspect_ratio == mode2->picture_aspect_ratio;
1007 }
1008 
1009 /**
1010  * drm_mode_match - test modes for (partial) equality
1011  * @mode1: first mode
1012  * @mode2: second mode
1013  * @match_flags: which parts need to match (DRM_MODE_MATCH_*)
1014  *
1015  * Check to see if @mode1 and @mode2 are equivalent.
1016  *
1017  * Returns:
1018  * True if the modes are (partially) equal, false otherwise.
1019  */
drm_mode_match(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2,unsigned int match_flags)1020 bool drm_mode_match(const struct drm_display_mode *mode1,
1021 		    const struct drm_display_mode *mode2,
1022 		    unsigned int match_flags)
1023 {
1024 	if (!mode1 && !mode2)
1025 		return true;
1026 
1027 	if (!mode1 || !mode2)
1028 		return false;
1029 
1030 	if (match_flags & DRM_MODE_MATCH_TIMINGS &&
1031 	    !drm_mode_match_timings(mode1, mode2))
1032 		return false;
1033 
1034 	if (match_flags & DRM_MODE_MATCH_CLOCK &&
1035 	    !drm_mode_match_clock(mode1, mode2))
1036 		return false;
1037 
1038 	if (match_flags & DRM_MODE_MATCH_FLAGS &&
1039 	    !drm_mode_match_flags(mode1, mode2))
1040 		return false;
1041 
1042 	if (match_flags & DRM_MODE_MATCH_3D_FLAGS &&
1043 	    !drm_mode_match_3d_flags(mode1, mode2))
1044 		return false;
1045 
1046 	if (match_flags & DRM_MODE_MATCH_ASPECT_RATIO &&
1047 	    !drm_mode_match_aspect_ratio(mode1, mode2))
1048 		return false;
1049 
1050 	return true;
1051 }
1052 EXPORT_SYMBOL(drm_mode_match);
1053 
1054 /**
1055  * drm_mode_equal - test modes for equality
1056  * @mode1: first mode
1057  * @mode2: second mode
1058  *
1059  * Check to see if @mode1 and @mode2 are equivalent.
1060  *
1061  * Returns:
1062  * True if the modes are equal, false otherwise.
1063  */
drm_mode_equal(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)1064 bool drm_mode_equal(const struct drm_display_mode *mode1,
1065 		    const struct drm_display_mode *mode2)
1066 {
1067 	return drm_mode_match(mode1, mode2,
1068 			      DRM_MODE_MATCH_TIMINGS |
1069 			      DRM_MODE_MATCH_CLOCK |
1070 			      DRM_MODE_MATCH_FLAGS |
1071 			      DRM_MODE_MATCH_3D_FLAGS|
1072 			      DRM_MODE_MATCH_ASPECT_RATIO);
1073 }
1074 EXPORT_SYMBOL(drm_mode_equal);
1075 
1076 /**
1077  * drm_mode_equal_no_clocks - test modes for equality
1078  * @mode1: first mode
1079  * @mode2: second mode
1080  *
1081  * Check to see if @mode1 and @mode2 are equivalent, but
1082  * don't check the pixel clocks.
1083  *
1084  * Returns:
1085  * True if the modes are equal, false otherwise.
1086  */
drm_mode_equal_no_clocks(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)1087 bool drm_mode_equal_no_clocks(const struct drm_display_mode *mode1,
1088 			      const struct drm_display_mode *mode2)
1089 {
1090 	return drm_mode_match(mode1, mode2,
1091 			      DRM_MODE_MATCH_TIMINGS |
1092 			      DRM_MODE_MATCH_FLAGS |
1093 			      DRM_MODE_MATCH_3D_FLAGS);
1094 }
1095 EXPORT_SYMBOL(drm_mode_equal_no_clocks);
1096 
1097 /**
1098  * drm_mode_equal_no_clocks_no_stereo - test modes for equality
1099  * @mode1: first mode
1100  * @mode2: second mode
1101  *
1102  * Check to see if @mode1 and @mode2 are equivalent, but
1103  * don't check the pixel clocks nor the stereo layout.
1104  *
1105  * Returns:
1106  * True if the modes are equal, false otherwise.
1107  */
drm_mode_equal_no_clocks_no_stereo(const struct drm_display_mode * mode1,const struct drm_display_mode * mode2)1108 bool drm_mode_equal_no_clocks_no_stereo(const struct drm_display_mode *mode1,
1109 					const struct drm_display_mode *mode2)
1110 {
1111 	return drm_mode_match(mode1, mode2,
1112 			      DRM_MODE_MATCH_TIMINGS |
1113 			      DRM_MODE_MATCH_FLAGS);
1114 }
1115 EXPORT_SYMBOL(drm_mode_equal_no_clocks_no_stereo);
1116 
1117 static enum drm_mode_status
drm_mode_validate_basic(const struct drm_display_mode * mode)1118 drm_mode_validate_basic(const struct drm_display_mode *mode)
1119 {
1120 	if (mode->type & ~DRM_MODE_TYPE_ALL)
1121 		return MODE_BAD;
1122 
1123 	if (mode->flags & ~DRM_MODE_FLAG_ALL)
1124 		return MODE_BAD;
1125 
1126 	if ((mode->flags & DRM_MODE_FLAG_3D_MASK) > DRM_MODE_FLAG_3D_MAX)
1127 		return MODE_BAD;
1128 
1129 	if (mode->clock == 0)
1130 		return MODE_CLOCK_LOW;
1131 
1132 	if (mode->hdisplay == 0 ||
1133 	    mode->hsync_start < mode->hdisplay ||
1134 	    mode->hsync_end < mode->hsync_start ||
1135 	    mode->htotal < mode->hsync_end)
1136 		return MODE_H_ILLEGAL;
1137 
1138 	if (mode->vdisplay == 0 ||
1139 	    mode->vsync_start < mode->vdisplay ||
1140 	    mode->vsync_end < mode->vsync_start ||
1141 	    mode->vtotal < mode->vsync_end)
1142 		return MODE_V_ILLEGAL;
1143 
1144 	return MODE_OK;
1145 }
1146 
1147 /**
1148  * drm_mode_validate_driver - make sure the mode is somewhat sane
1149  * @dev: drm device
1150  * @mode: mode to check
1151  *
1152  * First do basic validation on the mode, and then allow the driver
1153  * to check for device/driver specific limitations via the optional
1154  * &drm_mode_config_helper_funcs.mode_valid hook.
1155  *
1156  * Returns:
1157  * The mode status
1158  */
1159 enum drm_mode_status
drm_mode_validate_driver(struct drm_device * dev,const struct drm_display_mode * mode)1160 drm_mode_validate_driver(struct drm_device *dev,
1161 			const struct drm_display_mode *mode)
1162 {
1163 	enum drm_mode_status status;
1164 
1165 	status = drm_mode_validate_basic(mode);
1166 	if (status != MODE_OK)
1167 		return status;
1168 
1169 	if (dev->mode_config.funcs->mode_valid)
1170 		return dev->mode_config.funcs->mode_valid(dev, mode);
1171 	else
1172 		return MODE_OK;
1173 }
1174 EXPORT_SYMBOL(drm_mode_validate_driver);
1175 
1176 /**
1177  * drm_mode_validate_size - make sure modes adhere to size constraints
1178  * @mode: mode to check
1179  * @maxX: maximum width
1180  * @maxY: maximum height
1181  *
1182  * This function is a helper which can be used to validate modes against size
1183  * limitations of the DRM device/connector. If a mode is too big its status
1184  * member is updated with the appropriate validation failure code. The list
1185  * itself is not changed.
1186  *
1187  * Returns:
1188  * The mode status
1189  */
1190 enum drm_mode_status
drm_mode_validate_size(const struct drm_display_mode * mode,int maxX,int maxY)1191 drm_mode_validate_size(const struct drm_display_mode *mode,
1192 		       int maxX, int maxY)
1193 {
1194 	if (maxX > 0 && mode->hdisplay > maxX)
1195 		return MODE_VIRTUAL_X;
1196 
1197 #if defined(DRM_MAX_RESOLUTION_HORIZONTAL)
1198 	if (mode->hdisplay > DRM_MAX_RESOLUTION_HORIZONTAL)
1199 		return MODE_VIRTUAL_X;
1200 #endif
1201 
1202 	if (maxY > 0 && mode->vdisplay > maxY)
1203 		return MODE_VIRTUAL_Y;
1204 
1205 #if defined(DRM_MAX_RESOLUTION_VERTICAL)
1206 	if (mode->vdisplay > DRM_MAX_RESOLUTION_VERTICAL)
1207 		return MODE_VIRTUAL_Y;
1208 #endif
1209 
1210 	return MODE_OK;
1211 }
1212 EXPORT_SYMBOL(drm_mode_validate_size);
1213 
1214 /**
1215  * drm_mode_validate_ycbcr420 - add 'ycbcr420-only' modes only when allowed
1216  * @mode: mode to check
1217  * @connector: drm connector under action
1218  *
1219  * This function is a helper which can be used to filter out any YCBCR420
1220  * only mode, when the source doesn't support it.
1221  *
1222  * Returns:
1223  * The mode status
1224  */
1225 enum drm_mode_status
drm_mode_validate_ycbcr420(const struct drm_display_mode * mode,struct drm_connector * connector)1226 drm_mode_validate_ycbcr420(const struct drm_display_mode *mode,
1227 			   struct drm_connector *connector)
1228 {
1229 	u8 vic = drm_match_cea_mode(mode);
1230 	enum drm_mode_status status = MODE_OK;
1231 	struct drm_hdmi_info *hdmi = &connector->display_info.hdmi;
1232 
1233 	if (test_bit(vic, hdmi->y420_vdb_modes)) {
1234 		if (!connector->ycbcr_420_allowed)
1235 			status = MODE_NO_420;
1236 	}
1237 
1238 	return status;
1239 }
1240 EXPORT_SYMBOL(drm_mode_validate_ycbcr420);
1241 
1242 #define MODE_STATUS(status) [MODE_ ## status + 3] = #status
1243 
1244 static const char * const drm_mode_status_names[] = {
1245 	MODE_STATUS(OK),
1246 	MODE_STATUS(HSYNC),
1247 	MODE_STATUS(VSYNC),
1248 	MODE_STATUS(H_ILLEGAL),
1249 	MODE_STATUS(V_ILLEGAL),
1250 	MODE_STATUS(BAD_WIDTH),
1251 	MODE_STATUS(NOMODE),
1252 	MODE_STATUS(NO_INTERLACE),
1253 	MODE_STATUS(NO_DBLESCAN),
1254 	MODE_STATUS(NO_VSCAN),
1255 	MODE_STATUS(MEM),
1256 	MODE_STATUS(VIRTUAL_X),
1257 	MODE_STATUS(VIRTUAL_Y),
1258 	MODE_STATUS(MEM_VIRT),
1259 	MODE_STATUS(NOCLOCK),
1260 	MODE_STATUS(CLOCK_HIGH),
1261 	MODE_STATUS(CLOCK_LOW),
1262 	MODE_STATUS(CLOCK_RANGE),
1263 	MODE_STATUS(BAD_HVALUE),
1264 	MODE_STATUS(BAD_VVALUE),
1265 	MODE_STATUS(BAD_VSCAN),
1266 	MODE_STATUS(HSYNC_NARROW),
1267 	MODE_STATUS(HSYNC_WIDE),
1268 	MODE_STATUS(HBLANK_NARROW),
1269 	MODE_STATUS(HBLANK_WIDE),
1270 	MODE_STATUS(VSYNC_NARROW),
1271 	MODE_STATUS(VSYNC_WIDE),
1272 	MODE_STATUS(VBLANK_NARROW),
1273 	MODE_STATUS(VBLANK_WIDE),
1274 	MODE_STATUS(PANEL),
1275 	MODE_STATUS(INTERLACE_WIDTH),
1276 	MODE_STATUS(ONE_WIDTH),
1277 	MODE_STATUS(ONE_HEIGHT),
1278 	MODE_STATUS(ONE_SIZE),
1279 	MODE_STATUS(NO_REDUCED),
1280 	MODE_STATUS(NO_STEREO),
1281 	MODE_STATUS(NO_420),
1282 	MODE_STATUS(STALE),
1283 	MODE_STATUS(BAD),
1284 	MODE_STATUS(ERROR),
1285 };
1286 
1287 #undef MODE_STATUS
1288 
drm_get_mode_status_name(enum drm_mode_status status)1289 const char *drm_get_mode_status_name(enum drm_mode_status status)
1290 {
1291 	int index = status + 3;
1292 
1293 	if (WARN_ON(index < 0 || index >= ARRAY_SIZE(drm_mode_status_names)))
1294 		return "";
1295 
1296 	return drm_mode_status_names[index];
1297 }
1298 
1299 /**
1300  * drm_mode_prune_invalid - remove invalid modes from mode list
1301  * @dev: DRM device
1302  * @mode_list: list of modes to check
1303  * @verbose: be verbose about it
1304  *
1305  * This helper function can be used to prune a display mode list after
1306  * validation has been completed. All modes whose status is not MODE_OK will be
1307  * removed from the list, and if @verbose the status code and mode name is also
1308  * printed to dmesg.
1309  */
drm_mode_prune_invalid(struct drm_device * dev,struct list_head * mode_list,bool verbose)1310 void drm_mode_prune_invalid(struct drm_device *dev,
1311 			    struct list_head *mode_list, bool verbose)
1312 {
1313 	struct drm_display_mode *mode, *t;
1314 
1315 	list_for_each_entry_safe(mode, t, mode_list, head) {
1316 		if (mode->status != MODE_OK) {
1317 			list_del(&mode->head);
1318 			if (verbose) {
1319 				drm_mode_debug_printmodeline(mode);
1320 				DRM_DEBUG_KMS("Not using %s mode: %s\n",
1321 					      mode->name,
1322 					      drm_get_mode_status_name(mode->status));
1323 			}
1324 			drm_mode_destroy(dev, mode);
1325 		}
1326 	}
1327 }
1328 EXPORT_SYMBOL(drm_mode_prune_invalid);
1329 
1330 /**
1331  * drm_mode_compare - compare modes for favorability
1332  * @priv: unused
1333  * @lh_a: list_head for first mode
1334  * @lh_b: list_head for second mode
1335  *
1336  * Compare two modes, given by @lh_a and @lh_b, returning a value indicating
1337  * which is better.
1338  *
1339  * Returns:
1340  * Negative if @lh_a is better than @lh_b, zero if they're equivalent, or
1341  * positive if @lh_b is better than @lh_a.
1342  */
drm_mode_compare(void * priv,struct list_head * lh_a,struct list_head * lh_b)1343 static int drm_mode_compare(void *priv, struct list_head *lh_a, struct list_head *lh_b)
1344 {
1345 	struct drm_display_mode *a = list_entry(lh_a, struct drm_display_mode, head);
1346 	struct drm_display_mode *b = list_entry(lh_b, struct drm_display_mode, head);
1347 	int diff;
1348 
1349 	diff = ((b->type & DRM_MODE_TYPE_PREFERRED) != 0) -
1350 		((a->type & DRM_MODE_TYPE_PREFERRED) != 0);
1351 	if (diff)
1352 		return diff;
1353 	diff = b->hdisplay * b->vdisplay - a->hdisplay * a->vdisplay;
1354 	if (diff)
1355 		return diff;
1356 
1357 	diff = b->vrefresh - a->vrefresh;
1358 	if (diff)
1359 		return diff;
1360 
1361 	diff = b->clock - a->clock;
1362 	return diff;
1363 }
1364 
1365 /**
1366  * drm_mode_sort - sort mode list
1367  * @mode_list: list of drm_display_mode structures to sort
1368  *
1369  * Sort @mode_list by favorability, moving good modes to the head of the list.
1370  */
drm_mode_sort(struct list_head * mode_list)1371 void drm_mode_sort(struct list_head *mode_list)
1372 {
1373 	list_sort(NULL, mode_list, drm_mode_compare);
1374 }
1375 EXPORT_SYMBOL(drm_mode_sort);
1376 
1377 /**
1378  * drm_connector_list_update - update the mode list for the connector
1379  * @connector: the connector to update
1380  *
1381  * This moves the modes from the @connector probed_modes list
1382  * to the actual mode list. It compares the probed mode against the current
1383  * list and only adds different/new modes.
1384  *
1385  * This is just a helper functions doesn't validate any modes itself and also
1386  * doesn't prune any invalid modes. Callers need to do that themselves.
1387  */
drm_connector_list_update(struct drm_connector * connector)1388 void drm_connector_list_update(struct drm_connector *connector)
1389 {
1390 	struct drm_display_mode *pmode, *pt;
1391 
1392 	WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex));
1393 
1394 	list_for_each_entry_safe(pmode, pt, &connector->probed_modes, head) {
1395 		struct drm_display_mode *mode;
1396 		bool found_it = false;
1397 
1398 		/* go through current modes checking for the new probed mode */
1399 		list_for_each_entry(mode, &connector->modes, head) {
1400 			if (!drm_mode_equal(pmode, mode))
1401 				continue;
1402 
1403 			found_it = true;
1404 
1405 			/*
1406 			 * If the old matching mode is stale (ie. left over
1407 			 * from a previous probe) just replace it outright.
1408 			 * Otherwise just merge the type bits between all
1409 			 * equal probed modes.
1410 			 *
1411 			 * If two probed modes are considered equal, pick the
1412 			 * actual timings from the one that's marked as
1413 			 * preferred (in case the match isn't 100%). If
1414 			 * multiple or zero preferred modes are present, favor
1415 			 * the mode added to the probed_modes list first.
1416 			 */
1417 			if (mode->status == MODE_STALE) {
1418 				drm_mode_copy(mode, pmode);
1419 			} else if ((mode->type & DRM_MODE_TYPE_PREFERRED) == 0 &&
1420 				   (pmode->type & DRM_MODE_TYPE_PREFERRED) != 0) {
1421 				pmode->type |= mode->type;
1422 				drm_mode_copy(mode, pmode);
1423 			} else {
1424 				mode->type |= pmode->type;
1425 			}
1426 
1427 			list_del(&pmode->head);
1428 			drm_mode_destroy(connector->dev, pmode);
1429 			break;
1430 		}
1431 
1432 		if (!found_it) {
1433 			list_move_tail(&pmode->head, &connector->modes);
1434 		}
1435 	}
1436 }
1437 EXPORT_SYMBOL(drm_connector_list_update);
1438 
drm_mode_parse_cmdline_bpp(const char * str,char ** end_ptr,struct drm_cmdline_mode * mode)1439 static int drm_mode_parse_cmdline_bpp(const char *str, char **end_ptr,
1440 				      struct drm_cmdline_mode *mode)
1441 {
1442 	unsigned int bpp;
1443 
1444 	if (str[0] != '-')
1445 		return -EINVAL;
1446 
1447 	str++;
1448 	bpp = simple_strtol(str, end_ptr, 10);
1449 	if (*end_ptr == str)
1450 		return -EINVAL;
1451 
1452 	mode->bpp = bpp;
1453 	mode->bpp_specified = true;
1454 
1455 	return 0;
1456 }
1457 
drm_mode_parse_cmdline_refresh(const char * str,char ** end_ptr,struct drm_cmdline_mode * mode)1458 static int drm_mode_parse_cmdline_refresh(const char *str, char **end_ptr,
1459 					  struct drm_cmdline_mode *mode)
1460 {
1461 	unsigned int refresh;
1462 
1463 	if (str[0] != '@')
1464 		return -EINVAL;
1465 
1466 	str++;
1467 	refresh = simple_strtol(str, end_ptr, 10);
1468 	if (*end_ptr == str)
1469 		return -EINVAL;
1470 
1471 	mode->refresh = refresh;
1472 	mode->refresh_specified = true;
1473 
1474 	return 0;
1475 }
1476 
drm_mode_parse_cmdline_extra(const char * str,int length,bool freestanding,const struct drm_connector * connector,struct drm_cmdline_mode * mode)1477 static int drm_mode_parse_cmdline_extra(const char *str, int length,
1478 					bool freestanding,
1479 					const struct drm_connector *connector,
1480 					struct drm_cmdline_mode *mode)
1481 {
1482 	int i;
1483 
1484 	for (i = 0; i < length; i++) {
1485 		switch (str[i]) {
1486 		case 'i':
1487 			if (freestanding)
1488 				return -EINVAL;
1489 
1490 			mode->interlace = true;
1491 			break;
1492 		case 'm':
1493 			if (freestanding)
1494 				return -EINVAL;
1495 
1496 			mode->margins = true;
1497 			break;
1498 		case 'D':
1499 			if (mode->force != DRM_FORCE_UNSPECIFIED)
1500 				return -EINVAL;
1501 
1502 			if ((connector->connector_type != DRM_MODE_CONNECTOR_DVII) &&
1503 			    (connector->connector_type != DRM_MODE_CONNECTOR_HDMIB))
1504 				mode->force = DRM_FORCE_ON;
1505 			else
1506 				mode->force = DRM_FORCE_ON_DIGITAL;
1507 			break;
1508 		case 'd':
1509 			if (mode->force != DRM_FORCE_UNSPECIFIED)
1510 				return -EINVAL;
1511 
1512 			mode->force = DRM_FORCE_OFF;
1513 			break;
1514 		case 'e':
1515 			if (mode->force != DRM_FORCE_UNSPECIFIED)
1516 				return -EINVAL;
1517 
1518 			mode->force = DRM_FORCE_ON;
1519 			break;
1520 		default:
1521 			return -EINVAL;
1522 		}
1523 	}
1524 
1525 	return 0;
1526 }
1527 
drm_mode_parse_cmdline_res_mode(const char * str,unsigned int length,bool extras,const struct drm_connector * connector,struct drm_cmdline_mode * mode)1528 static int drm_mode_parse_cmdline_res_mode(const char *str, unsigned int length,
1529 					   bool extras,
1530 					   const struct drm_connector *connector,
1531 					   struct drm_cmdline_mode *mode)
1532 {
1533 	const char *str_start = str;
1534 	bool rb = false, cvt = false;
1535 	int xres = 0, yres = 0;
1536 	int remaining, i;
1537 	char *end_ptr;
1538 
1539 	xres = simple_strtol(str, &end_ptr, 10);
1540 	if (end_ptr == str)
1541 		return -EINVAL;
1542 
1543 	if (end_ptr[0] != 'x')
1544 		return -EINVAL;
1545 	end_ptr++;
1546 
1547 	str = end_ptr;
1548 	yres = simple_strtol(str, &end_ptr, 10);
1549 	if (end_ptr == str)
1550 		return -EINVAL;
1551 
1552 	remaining = length - (end_ptr - str_start);
1553 	if (remaining < 0)
1554 		return -EINVAL;
1555 
1556 	for (i = 0; i < remaining; i++) {
1557 		switch (end_ptr[i]) {
1558 		case 'M':
1559 			cvt = true;
1560 			break;
1561 		case 'R':
1562 			rb = true;
1563 			break;
1564 		default:
1565 			/*
1566 			 * Try to pass that to our extras parsing
1567 			 * function to handle the case where the
1568 			 * extras are directly after the resolution
1569 			 */
1570 			if (extras) {
1571 				int ret = drm_mode_parse_cmdline_extra(end_ptr + i,
1572 								       1,
1573 								       false,
1574 								       connector,
1575 								       mode);
1576 				if (ret)
1577 					return ret;
1578 			} else {
1579 				return -EINVAL;
1580 			}
1581 		}
1582 	}
1583 
1584 	mode->xres = xres;
1585 	mode->yres = yres;
1586 	mode->cvt = cvt;
1587 	mode->rb = rb;
1588 
1589 	return 0;
1590 }
1591 
drm_mode_parse_cmdline_int(const char * delim,unsigned int * int_ret)1592 static int drm_mode_parse_cmdline_int(const char *delim, unsigned int *int_ret)
1593 {
1594 	const char *value;
1595 	char *endp;
1596 
1597 	/*
1598 	 * delim must point to the '=', otherwise it is a syntax error and
1599 	 * if delim points to the terminating zero, then delim + 1 wil point
1600 	 * past the end of the string.
1601 	 */
1602 	if (*delim != '=')
1603 		return -EINVAL;
1604 
1605 	value = delim + 1;
1606 	*int_ret = simple_strtol(value, &endp, 10);
1607 
1608 	/* Make sure we have parsed something */
1609 	if (endp == value)
1610 		return -EINVAL;
1611 
1612 	return 0;
1613 }
1614 
drm_mode_parse_panel_orientation(const char * delim,struct drm_cmdline_mode * mode)1615 static int drm_mode_parse_panel_orientation(const char *delim,
1616 					    struct drm_cmdline_mode *mode)
1617 {
1618 	const char *value;
1619 
1620 	if (*delim != '=')
1621 		return -EINVAL;
1622 
1623 	value = delim + 1;
1624 	delim = strchr(value, ',');
1625 	if (!delim)
1626 		delim = value + strlen(value);
1627 
1628 	if (!strncmp(value, "normal", delim - value))
1629 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_NORMAL;
1630 	else if (!strncmp(value, "upside_down", delim - value))
1631 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_BOTTOM_UP;
1632 	else if (!strncmp(value, "left_side_up", delim - value))
1633 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_LEFT_UP;
1634 	else if (!strncmp(value, "right_side_up", delim - value))
1635 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_RIGHT_UP;
1636 	else
1637 		return -EINVAL;
1638 
1639 	return 0;
1640 }
1641 
drm_mode_parse_cmdline_options(const char * str,bool freestanding,const struct drm_connector * connector,struct drm_cmdline_mode * mode)1642 static int drm_mode_parse_cmdline_options(const char *str,
1643 					  bool freestanding,
1644 					  const struct drm_connector *connector,
1645 					  struct drm_cmdline_mode *mode)
1646 {
1647 	unsigned int deg, margin, rotation = 0;
1648 	const char *delim, *option, *sep;
1649 
1650 	option = str;
1651 	do {
1652 		delim = strchr(option, '=');
1653 		if (!delim) {
1654 			delim = strchr(option, ',');
1655 
1656 			if (!delim)
1657 				delim = option + strlen(option);
1658 		}
1659 
1660 		if (!strncmp(option, "rotate", delim - option)) {
1661 			if (drm_mode_parse_cmdline_int(delim, &deg))
1662 				return -EINVAL;
1663 
1664 			switch (deg) {
1665 			case 0:
1666 				rotation |= DRM_MODE_ROTATE_0;
1667 				break;
1668 
1669 			case 90:
1670 				rotation |= DRM_MODE_ROTATE_90;
1671 				break;
1672 
1673 			case 180:
1674 				rotation |= DRM_MODE_ROTATE_180;
1675 				break;
1676 
1677 			case 270:
1678 				rotation |= DRM_MODE_ROTATE_270;
1679 				break;
1680 
1681 			default:
1682 				return -EINVAL;
1683 			}
1684 		} else if (!strncmp(option, "reflect_x", delim - option)) {
1685 			rotation |= DRM_MODE_REFLECT_X;
1686 		} else if (!strncmp(option, "reflect_y", delim - option)) {
1687 			rotation |= DRM_MODE_REFLECT_Y;
1688 		} else if (!strncmp(option, "margin_right", delim - option)) {
1689 			if (drm_mode_parse_cmdline_int(delim, &margin))
1690 				return -EINVAL;
1691 
1692 			mode->tv_margins.right = margin;
1693 		} else if (!strncmp(option, "margin_left", delim - option)) {
1694 			if (drm_mode_parse_cmdline_int(delim, &margin))
1695 				return -EINVAL;
1696 
1697 			mode->tv_margins.left = margin;
1698 		} else if (!strncmp(option, "margin_top", delim - option)) {
1699 			if (drm_mode_parse_cmdline_int(delim, &margin))
1700 				return -EINVAL;
1701 
1702 			mode->tv_margins.top = margin;
1703 		} else if (!strncmp(option, "margin_bottom", delim - option)) {
1704 			if (drm_mode_parse_cmdline_int(delim, &margin))
1705 				return -EINVAL;
1706 
1707 			mode->tv_margins.bottom = margin;
1708 		} else if (!strncmp(option, "panel_orientation", delim - option)) {
1709 			if (drm_mode_parse_panel_orientation(delim, mode))
1710 				return -EINVAL;
1711 		} else {
1712 			return -EINVAL;
1713 		}
1714 		sep = strchr(delim, ',');
1715 		option = sep + 1;
1716 	} while (sep);
1717 
1718 	if (rotation && freestanding)
1719 		return -EINVAL;
1720 
1721 	if (!(rotation & DRM_MODE_ROTATE_MASK))
1722 		rotation |= DRM_MODE_ROTATE_0;
1723 
1724 	/* Make sure there is exactly one rotation defined */
1725 	if (!is_power_of_2(rotation & DRM_MODE_ROTATE_MASK))
1726 		return -EINVAL;
1727 
1728 	mode->rotation_reflection = rotation;
1729 
1730 	return 0;
1731 }
1732 
1733 static const char * const drm_named_modes_whitelist[] = {
1734 	"NTSC",
1735 	"PAL",
1736 };
1737 
1738 /**
1739  * drm_mode_parse_command_line_for_connector - parse command line modeline for connector
1740  * @mode_option: optional per connector mode option
1741  * @connector: connector to parse modeline for
1742  * @mode: preallocated drm_cmdline_mode structure to fill out
1743  *
1744  * This parses @mode_option command line modeline for modes and options to
1745  * configure the connector. If @mode_option is NULL the default command line
1746  * modeline in fb_mode_option will be parsed instead.
1747  *
1748  * This uses the same parameters as the fb modedb.c, except for an extra
1749  * force-enable, force-enable-digital and force-disable bit at the end::
1750  *
1751  *	<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m][eDd]
1752  *
1753  * Additionals options can be provided following the mode, using a comma to
1754  * separate each option. Valid options can be found in
1755  * Documentation/fb/modedb.rst.
1756  *
1757  * The intermediate drm_cmdline_mode structure is required to store additional
1758  * options from the command line modline like the force-enable/disable flag.
1759  *
1760  * Returns:
1761  * True if a valid modeline has been parsed, false otherwise.
1762  */
drm_mode_parse_command_line_for_connector(const char * mode_option,const struct drm_connector * connector,struct drm_cmdline_mode * mode)1763 bool drm_mode_parse_command_line_for_connector(const char *mode_option,
1764 					       const struct drm_connector *connector,
1765 					       struct drm_cmdline_mode *mode)
1766 {
1767 	const char *name;
1768 	bool freestanding = false, parse_extras = false;
1769 	unsigned int bpp_off = 0, refresh_off = 0, options_off = 0;
1770 	unsigned int mode_end = 0;
1771 	const char *bpp_ptr = NULL, *refresh_ptr = NULL, *extra_ptr = NULL;
1772 	const char *options_ptr = NULL;
1773 	char *bpp_end_ptr = NULL, *refresh_end_ptr = NULL;
1774 	int i, len, ret;
1775 
1776 	memset(mode, 0, sizeof(*mode));
1777 	mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_UNKNOWN;
1778 
1779 	if (!mode_option)
1780 		return false;
1781 
1782 	name = mode_option;
1783 
1784 	/* Try to locate the bpp and refresh specifiers, if any */
1785 	bpp_ptr = strchr(name, '-');
1786 	if (bpp_ptr)
1787 		bpp_off = bpp_ptr - name;
1788 
1789 	refresh_ptr = strchr(name, '@');
1790 	if (refresh_ptr)
1791 		refresh_off = refresh_ptr - name;
1792 
1793 	/* Locate the start of named options */
1794 	options_ptr = strchr(name, ',');
1795 	if (options_ptr)
1796 		options_off = options_ptr - name;
1797 
1798 	/* Locate the end of the name / resolution, and parse it */
1799 	if (bpp_ptr) {
1800 		mode_end = bpp_off;
1801 	} else if (refresh_ptr) {
1802 		mode_end = refresh_off;
1803 	} else if (options_ptr) {
1804 		mode_end = options_off;
1805 		parse_extras = true;
1806 	} else {
1807 		mode_end = strlen(name);
1808 		parse_extras = true;
1809 	}
1810 
1811 	/* First check for a named mode */
1812 	for (i = 0; i < ARRAY_SIZE(drm_named_modes_whitelist); i++) {
1813 		ret = str_has_prefix(name, drm_named_modes_whitelist[i]);
1814 		if (ret == mode_end) {
1815 			if (refresh_ptr)
1816 				return false; /* named + refresh is invalid */
1817 
1818 			strcpy(mode->name, drm_named_modes_whitelist[i]);
1819 			mode->specified = true;
1820 			break;
1821 		}
1822 	}
1823 
1824 	/* No named mode? Check for a normal mode argument, e.g. 1024x768 */
1825 	if (!mode->specified && isdigit(name[0])) {
1826 		ret = drm_mode_parse_cmdline_res_mode(name, mode_end,
1827 						      parse_extras,
1828 						      connector,
1829 						      mode);
1830 		if (ret)
1831 			return false;
1832 
1833 		mode->specified = true;
1834 	}
1835 
1836 	/* No mode? Check for freestanding extras and/or options */
1837 	if (!mode->specified) {
1838 		unsigned int len = strlen(mode_option);
1839 
1840 		if (bpp_ptr || refresh_ptr)
1841 			return false; /* syntax error */
1842 
1843 		if (len == 1 || (len >= 2 && mode_option[1] == ','))
1844 			extra_ptr = mode_option;
1845 		else
1846 			options_ptr = mode_option - 1;
1847 
1848 		freestanding = true;
1849 	}
1850 
1851 	if (bpp_ptr) {
1852 		ret = drm_mode_parse_cmdline_bpp(bpp_ptr, &bpp_end_ptr, mode);
1853 		if (ret)
1854 			return false;
1855 
1856 		mode->bpp_specified = true;
1857 	}
1858 
1859 	if (refresh_ptr) {
1860 		ret = drm_mode_parse_cmdline_refresh(refresh_ptr,
1861 						     &refresh_end_ptr, mode);
1862 		if (ret)
1863 			return false;
1864 
1865 		mode->refresh_specified = true;
1866 	}
1867 
1868 	/*
1869 	 * Locate the end of the bpp / refresh, and parse the extras
1870 	 * if relevant
1871 	 */
1872 	if (bpp_ptr && refresh_ptr)
1873 		extra_ptr = max(bpp_end_ptr, refresh_end_ptr);
1874 	else if (bpp_ptr)
1875 		extra_ptr = bpp_end_ptr;
1876 	else if (refresh_ptr)
1877 		extra_ptr = refresh_end_ptr;
1878 
1879 	if (extra_ptr) {
1880 		if (options_ptr)
1881 			len = options_ptr - extra_ptr;
1882 		else
1883 			len = strlen(extra_ptr);
1884 
1885 		ret = drm_mode_parse_cmdline_extra(extra_ptr, len, freestanding,
1886 						   connector, mode);
1887 		if (ret)
1888 			return false;
1889 	}
1890 
1891 	if (options_ptr) {
1892 		ret = drm_mode_parse_cmdline_options(options_ptr + 1,
1893 						     freestanding,
1894 						     connector, mode);
1895 		if (ret)
1896 			return false;
1897 	}
1898 
1899 	return true;
1900 }
1901 EXPORT_SYMBOL(drm_mode_parse_command_line_for_connector);
1902 
1903 /**
1904  * drm_mode_create_from_cmdline_mode - convert a command line modeline into a DRM display mode
1905  * @dev: DRM device to create the new mode for
1906  * @cmd: input command line modeline
1907  *
1908  * Returns:
1909  * Pointer to converted mode on success, NULL on error.
1910  */
1911 struct drm_display_mode *
drm_mode_create_from_cmdline_mode(struct drm_device * dev,struct drm_cmdline_mode * cmd)1912 drm_mode_create_from_cmdline_mode(struct drm_device *dev,
1913 				  struct drm_cmdline_mode *cmd)
1914 {
1915 	struct drm_display_mode *mode;
1916 
1917 	if (cmd->cvt)
1918 		mode = drm_cvt_mode(dev,
1919 				    cmd->xres, cmd->yres,
1920 				    cmd->refresh_specified ? cmd->refresh : 60,
1921 				    cmd->rb, cmd->interlace,
1922 				    cmd->margins);
1923 	else
1924 		mode = drm_gtf_mode(dev,
1925 				    cmd->xres, cmd->yres,
1926 				    cmd->refresh_specified ? cmd->refresh : 60,
1927 				    cmd->interlace,
1928 				    cmd->margins);
1929 	if (!mode)
1930 		return NULL;
1931 
1932 	mode->type |= DRM_MODE_TYPE_USERDEF;
1933 	/* fix up 1368x768: GFT/CVT can't express 1366 width due to alignment */
1934 	if (cmd->xres == 1366)
1935 		drm_mode_fixup_1366x768(mode);
1936 	drm_mode_set_crtcinfo(mode, CRTC_INTERLACE_HALVE_V);
1937 	return mode;
1938 }
1939 EXPORT_SYMBOL(drm_mode_create_from_cmdline_mode);
1940 
1941 /**
1942  * drm_crtc_convert_to_umode - convert a drm_display_mode into a modeinfo
1943  * @out: drm_mode_modeinfo struct to return to the user
1944  * @in: drm_display_mode to use
1945  *
1946  * Convert a drm_display_mode into a drm_mode_modeinfo structure to return to
1947  * the user.
1948  */
drm_mode_convert_to_umode(struct drm_mode_modeinfo * out,const struct drm_display_mode * in)1949 void drm_mode_convert_to_umode(struct drm_mode_modeinfo *out,
1950 			       const struct drm_display_mode *in)
1951 {
1952 	WARN(in->hdisplay > USHRT_MAX || in->hsync_start > USHRT_MAX ||
1953 	     in->hsync_end > USHRT_MAX || in->htotal > USHRT_MAX ||
1954 	     in->hskew > USHRT_MAX || in->vdisplay > USHRT_MAX ||
1955 	     in->vsync_start > USHRT_MAX || in->vsync_end > USHRT_MAX ||
1956 	     in->vtotal > USHRT_MAX || in->vscan > USHRT_MAX,
1957 	     "timing values too large for mode info\n");
1958 
1959 	out->clock = in->clock;
1960 	out->hdisplay = in->hdisplay;
1961 	out->hsync_start = in->hsync_start;
1962 	out->hsync_end = in->hsync_end;
1963 	out->htotal = in->htotal;
1964 	out->hskew = in->hskew;
1965 	out->vdisplay = in->vdisplay;
1966 	out->vsync_start = in->vsync_start;
1967 	out->vsync_end = in->vsync_end;
1968 	out->vtotal = in->vtotal;
1969 	out->vscan = in->vscan;
1970 	out->vrefresh = in->vrefresh;
1971 	out->flags = in->flags;
1972 	out->type = in->type;
1973 
1974 	switch (in->picture_aspect_ratio) {
1975 	case HDMI_PICTURE_ASPECT_4_3:
1976 		out->flags |= DRM_MODE_FLAG_PIC_AR_4_3;
1977 		break;
1978 	case HDMI_PICTURE_ASPECT_16_9:
1979 		out->flags |= DRM_MODE_FLAG_PIC_AR_16_9;
1980 		break;
1981 	case HDMI_PICTURE_ASPECT_64_27:
1982 		out->flags |= DRM_MODE_FLAG_PIC_AR_64_27;
1983 		break;
1984 	case HDMI_PICTURE_ASPECT_256_135:
1985 		out->flags |= DRM_MODE_FLAG_PIC_AR_256_135;
1986 		break;
1987 	default:
1988 		WARN(1, "Invalid aspect ratio (0%x) on mode\n",
1989 		     in->picture_aspect_ratio);
1990 		/* fall through */
1991 	case HDMI_PICTURE_ASPECT_NONE:
1992 		out->flags |= DRM_MODE_FLAG_PIC_AR_NONE;
1993 		break;
1994 	}
1995 
1996 	strncpy(out->name, in->name, DRM_DISPLAY_MODE_LEN);
1997 	out->name[DRM_DISPLAY_MODE_LEN-1] = 0;
1998 }
1999 
2000 /**
2001  * drm_crtc_convert_umode - convert a modeinfo into a drm_display_mode
2002  * @dev: drm device
2003  * @out: drm_display_mode to return to the user
2004  * @in: drm_mode_modeinfo to use
2005  *
2006  * Convert a drm_mode_modeinfo into a drm_display_mode structure to return to
2007  * the caller.
2008  *
2009  * Returns:
2010  * Zero on success, negative errno on failure.
2011  */
drm_mode_convert_umode(struct drm_device * dev,struct drm_display_mode * out,const struct drm_mode_modeinfo * in)2012 int drm_mode_convert_umode(struct drm_device *dev,
2013 			   struct drm_display_mode *out,
2014 			   const struct drm_mode_modeinfo *in)
2015 {
2016 	if (in->clock > INT_MAX || in->vrefresh > INT_MAX)
2017 		return -ERANGE;
2018 
2019 	out->clock = in->clock;
2020 	out->hdisplay = in->hdisplay;
2021 	out->hsync_start = in->hsync_start;
2022 	out->hsync_end = in->hsync_end;
2023 	out->htotal = in->htotal;
2024 	out->hskew = in->hskew;
2025 	out->vdisplay = in->vdisplay;
2026 	out->vsync_start = in->vsync_start;
2027 	out->vsync_end = in->vsync_end;
2028 	out->vtotal = in->vtotal;
2029 	out->vscan = in->vscan;
2030 	out->vrefresh = in->vrefresh;
2031 	out->flags = in->flags;
2032 	/*
2033 	 * Old xf86-video-vmware (possibly others too) used to
2034 	 * leave 'type' unititialized. Just ignore any bits we
2035 	 * don't like. It's a just hint after all, and more
2036 	 * useful for the kernel->userspace direction anyway.
2037 	 */
2038 	out->type = in->type & DRM_MODE_TYPE_ALL;
2039 	strncpy(out->name, in->name, DRM_DISPLAY_MODE_LEN);
2040 	out->name[DRM_DISPLAY_MODE_LEN-1] = 0;
2041 
2042 	/* Clearing picture aspect ratio bits from out flags,
2043 	 * as the aspect-ratio information is not stored in
2044 	 * flags for kernel-mode, but in picture_aspect_ratio.
2045 	 */
2046 	out->flags &= ~DRM_MODE_FLAG_PIC_AR_MASK;
2047 
2048 	switch (in->flags & DRM_MODE_FLAG_PIC_AR_MASK) {
2049 	case DRM_MODE_FLAG_PIC_AR_4_3:
2050 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_4_3;
2051 		break;
2052 	case DRM_MODE_FLAG_PIC_AR_16_9:
2053 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_16_9;
2054 		break;
2055 	case DRM_MODE_FLAG_PIC_AR_64_27:
2056 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_64_27;
2057 		break;
2058 	case DRM_MODE_FLAG_PIC_AR_256_135:
2059 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_256_135;
2060 		break;
2061 	case DRM_MODE_FLAG_PIC_AR_NONE:
2062 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_NONE;
2063 		break;
2064 	default:
2065 		return -EINVAL;
2066 	}
2067 
2068 	out->status = drm_mode_validate_driver(dev, out);
2069 	if (out->status != MODE_OK)
2070 		return -EINVAL;
2071 
2072 	drm_mode_set_crtcinfo(out, CRTC_INTERLACE_HALVE_V);
2073 
2074 	return 0;
2075 }
2076 
2077 /**
2078  * drm_mode_is_420_only - if a given videomode can be only supported in YCBCR420
2079  * output format
2080  *
2081  * @display: display under action
2082  * @mode: video mode to be tested.
2083  *
2084  * Returns:
2085  * true if the mode can be supported in YCBCR420 format
2086  * false if not.
2087  */
drm_mode_is_420_only(const struct drm_display_info * display,const struct drm_display_mode * mode)2088 bool drm_mode_is_420_only(const struct drm_display_info *display,
2089 			  const struct drm_display_mode *mode)
2090 {
2091 	u8 vic = drm_match_cea_mode(mode);
2092 
2093 	return test_bit(vic, display->hdmi.y420_vdb_modes);
2094 }
2095 EXPORT_SYMBOL(drm_mode_is_420_only);
2096 
2097 /**
2098  * drm_mode_is_420_also - if a given videomode can be supported in YCBCR420
2099  * output format also (along with RGB/YCBCR444/422)
2100  *
2101  * @display: display under action.
2102  * @mode: video mode to be tested.
2103  *
2104  * Returns:
2105  * true if the mode can be support YCBCR420 format
2106  * false if not.
2107  */
drm_mode_is_420_also(const struct drm_display_info * display,const struct drm_display_mode * mode)2108 bool drm_mode_is_420_also(const struct drm_display_info *display,
2109 			  const struct drm_display_mode *mode)
2110 {
2111 	u8 vic = drm_match_cea_mode(mode);
2112 
2113 	return test_bit(vic, display->hdmi.y420_cmdb_modes);
2114 }
2115 EXPORT_SYMBOL(drm_mode_is_420_also);
2116 /**
2117  * drm_mode_is_420 - if a given videomode can be supported in YCBCR420
2118  * output format
2119  *
2120  * @display: display under action.
2121  * @mode: video mode to be tested.
2122  *
2123  * Returns:
2124  * true if the mode can be supported in YCBCR420 format
2125  * false if not.
2126  */
drm_mode_is_420(const struct drm_display_info * display,const struct drm_display_mode * mode)2127 bool drm_mode_is_420(const struct drm_display_info *display,
2128 		     const struct drm_display_mode *mode)
2129 {
2130 	return drm_mode_is_420_only(display, mode) ||
2131 		drm_mode_is_420_also(display, mode);
2132 }
2133 EXPORT_SYMBOL(drm_mode_is_420);
2134