xref: /linux/drivers/gpu/drm/drm_modes.c (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
1 /*
2  * Copyright © 1997-2003 by The XFree86 Project, Inc.
3  * Copyright © 2007 Dave Airlie
4  * Copyright © 2007-2008 Intel Corporation
5  *   Jesse Barnes <jesse.barnes@intel.com>
6  * Copyright 2005-2006 Luc Verhaegen
7  * Copyright (c) 2001, Andy Ritger  aritger@nvidia.com
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a
10  * copy of this software and associated documentation files (the "Software"),
11  * to deal in the Software without restriction, including without limitation
12  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13  * and/or sell copies of the Software, and to permit persons to whom the
14  * Software is furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
22  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
23  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
24  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
25  * OTHER DEALINGS IN THE SOFTWARE.
26  *
27  * Except as contained in this notice, the name of the copyright holder(s)
28  * and author(s) shall not be used in advertising or otherwise to promote
29  * the sale, use or other dealings in this Software without prior written
30  * authorization from the copyright holder(s) and author(s).
31  */
32 
33 #include <linux/ctype.h>
34 #include <linux/export.h>
35 #include <linux/fb.h> /* for KHZ2PICOS() */
36 #include <linux/list.h>
37 #include <linux/list_sort.h>
38 #include <linux/of.h>
39 
40 #include <video/of_display_timing.h>
41 #include <video/of_videomode.h>
42 #include <video/videomode.h>
43 
44 #include <drm/drm_crtc.h>
45 #include <drm/drm_device.h>
46 #include <drm/drm_edid.h>
47 #include <drm/drm_modes.h>
48 #include <drm/drm_print.h>
49 
50 #include "drm_crtc_internal.h"
51 
52 /**
53  * drm_mode_debug_printmodeline - print a mode to dmesg
54  * @mode: mode to print
55  *
56  * Describe @mode using DRM_DEBUG.
57  */
58 void drm_mode_debug_printmodeline(const struct drm_display_mode *mode)
59 {
60 	DRM_DEBUG_KMS("Modeline " DRM_MODE_FMT "\n", DRM_MODE_ARG(mode));
61 }
62 EXPORT_SYMBOL(drm_mode_debug_printmodeline);
63 
64 /**
65  * drm_mode_create - create a new display mode
66  * @dev: DRM device
67  *
68  * Create a new, cleared drm_display_mode with kzalloc, allocate an ID for it
69  * and return it.
70  *
71  * Returns:
72  * Pointer to new mode on success, NULL on error.
73  */
74 struct drm_display_mode *drm_mode_create(struct drm_device *dev)
75 {
76 	struct drm_display_mode *nmode;
77 
78 	nmode = kzalloc_obj(struct drm_display_mode);
79 	if (!nmode)
80 		return NULL;
81 
82 	return nmode;
83 }
84 EXPORT_SYMBOL(drm_mode_create);
85 
86 /**
87  * drm_mode_destroy - remove a mode
88  * @dev: DRM device
89  * @mode: mode to remove
90  *
91  * Release @mode's unique ID, then free it @mode structure itself using kfree.
92  */
93 void drm_mode_destroy(struct drm_device *dev, struct drm_display_mode *mode)
94 {
95 	if (!mode)
96 		return;
97 
98 	kfree(mode);
99 }
100 EXPORT_SYMBOL(drm_mode_destroy);
101 
102 /**
103  * drm_mode_probed_add - add a mode to a connector's probed_mode list
104  * @connector: connector the new mode
105  * @mode: mode data
106  *
107  * Add @mode to @connector's probed_mode list for later use. This list should
108  * then in a second step get filtered and all the modes actually supported by
109  * the hardware moved to the @connector's modes list.
110  */
111 void drm_mode_probed_add(struct drm_connector *connector,
112 			 struct drm_display_mode *mode)
113 {
114 	WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex));
115 
116 	list_add_tail(&mode->head, &connector->probed_modes);
117 }
118 EXPORT_SYMBOL(drm_mode_probed_add);
119 
120 enum drm_mode_analog {
121 	DRM_MODE_ANALOG_NTSC, /* 525 lines, 60Hz */
122 	DRM_MODE_ANALOG_PAL, /* 625 lines, 50Hz */
123 };
124 
125 /*
126  * The timings come from:
127  * - https://web.archive.org/web/20220406232708/http://www.kolumbus.fi/pami1/video/pal_ntsc.html
128  * - https://web.archive.org/web/20220406124914/http://martin.hinner.info/vga/pal.html
129  * - https://web.archive.org/web/20220609202433/http://www.batsocks.co.uk/readme/video_timing.htm
130  */
131 #define NTSC_LINE_DURATION_NS		63556U
132 #define NTSC_LINES_NUMBER		525
133 
134 #define NTSC_HBLK_DURATION_TYP_NS	10900U
135 #define NTSC_HBLK_DURATION_MIN_NS	(NTSC_HBLK_DURATION_TYP_NS - 200)
136 #define NTSC_HBLK_DURATION_MAX_NS	(NTSC_HBLK_DURATION_TYP_NS + 200)
137 
138 #define NTSC_HACT_DURATION_TYP_NS	(NTSC_LINE_DURATION_NS - NTSC_HBLK_DURATION_TYP_NS)
139 #define NTSC_HACT_DURATION_MIN_NS	(NTSC_LINE_DURATION_NS - NTSC_HBLK_DURATION_MAX_NS)
140 #define NTSC_HACT_DURATION_MAX_NS	(NTSC_LINE_DURATION_NS - NTSC_HBLK_DURATION_MIN_NS)
141 
142 #define NTSC_HFP_DURATION_TYP_NS	1500
143 #define NTSC_HFP_DURATION_MIN_NS	1270
144 #define NTSC_HFP_DURATION_MAX_NS	2220
145 
146 #define NTSC_HSLEN_DURATION_TYP_NS	4700
147 #define NTSC_HSLEN_DURATION_MIN_NS	(NTSC_HSLEN_DURATION_TYP_NS - 100)
148 #define NTSC_HSLEN_DURATION_MAX_NS	(NTSC_HSLEN_DURATION_TYP_NS + 100)
149 
150 #define NTSC_HBP_DURATION_TYP_NS	4700
151 
152 /*
153  * I couldn't find the actual tolerance for the back porch, so let's
154  * just reuse the sync length ones.
155  */
156 #define NTSC_HBP_DURATION_MIN_NS	(NTSC_HBP_DURATION_TYP_NS - 100)
157 #define NTSC_HBP_DURATION_MAX_NS	(NTSC_HBP_DURATION_TYP_NS + 100)
158 
159 #define PAL_LINE_DURATION_NS		64000U
160 #define PAL_LINES_NUMBER		625
161 
162 #define PAL_HACT_DURATION_TYP_NS	51950U
163 #define PAL_HACT_DURATION_MIN_NS	(PAL_HACT_DURATION_TYP_NS - 100)
164 #define PAL_HACT_DURATION_MAX_NS	(PAL_HACT_DURATION_TYP_NS + 400)
165 
166 #define PAL_HBLK_DURATION_TYP_NS	(PAL_LINE_DURATION_NS - PAL_HACT_DURATION_TYP_NS)
167 #define PAL_HBLK_DURATION_MIN_NS	(PAL_LINE_DURATION_NS - PAL_HACT_DURATION_MAX_NS)
168 #define PAL_HBLK_DURATION_MAX_NS	(PAL_LINE_DURATION_NS - PAL_HACT_DURATION_MIN_NS)
169 
170 #define PAL_HFP_DURATION_TYP_NS		1650
171 #define PAL_HFP_DURATION_MIN_NS		(PAL_HFP_DURATION_TYP_NS - 100)
172 #define PAL_HFP_DURATION_MAX_NS		(PAL_HFP_DURATION_TYP_NS + 400)
173 
174 #define PAL_HSLEN_DURATION_TYP_NS	4700
175 #define PAL_HSLEN_DURATION_MIN_NS	(PAL_HSLEN_DURATION_TYP_NS - 200)
176 #define PAL_HSLEN_DURATION_MAX_NS	(PAL_HSLEN_DURATION_TYP_NS + 200)
177 
178 #define PAL_HBP_DURATION_TYP_NS		5700
179 #define PAL_HBP_DURATION_MIN_NS		(PAL_HBP_DURATION_TYP_NS - 200)
180 #define PAL_HBP_DURATION_MAX_NS		(PAL_HBP_DURATION_TYP_NS + 200)
181 
182 struct analog_param_field {
183 	unsigned int even, odd;
184 };
185 
186 #define PARAM_FIELD(_odd, _even)		\
187 	{ .even = _even, .odd = _odd }
188 
189 struct analog_param_range {
190 	unsigned int	min, typ, max;
191 };
192 
193 #define PARAM_RANGE(_min, _typ, _max)		\
194 	{ .min = _min, .typ = _typ, .max = _max }
195 
196 struct analog_parameters {
197 	unsigned int			num_lines;
198 	unsigned int			line_duration_ns;
199 
200 	struct analog_param_range	hact_ns;
201 	struct analog_param_range	hfp_ns;
202 	struct analog_param_range	hslen_ns;
203 	struct analog_param_range	hbp_ns;
204 	struct analog_param_range	hblk_ns;
205 
206 	unsigned int			bt601_hfp;
207 
208 	struct analog_param_field	vfp_lines;
209 	struct analog_param_field	vslen_lines;
210 	struct analog_param_field	vbp_lines;
211 };
212 
213 #define TV_MODE_PARAMETER(_mode, _lines, _line_dur, _hact, _hfp,	\
214 			  _hslen, _hbp, _hblk, _bt601_hfp, _vfp,	\
215 			  _vslen, _vbp)					\
216 	[_mode] = {							\
217 		.num_lines = _lines,					\
218 		.line_duration_ns = _line_dur,				\
219 		.hact_ns = _hact,					\
220 		.hfp_ns = _hfp,						\
221 		.hslen_ns = _hslen,					\
222 		.hbp_ns = _hbp,						\
223 		.hblk_ns = _hblk,					\
224 		.bt601_hfp = _bt601_hfp,				\
225 		.vfp_lines = _vfp,					\
226 		.vslen_lines = _vslen,					\
227 		.vbp_lines = _vbp,					\
228 	}
229 
230 static const struct analog_parameters tv_modes_parameters[] = {
231 	TV_MODE_PARAMETER(DRM_MODE_ANALOG_NTSC,
232 			  NTSC_LINES_NUMBER,
233 			  NTSC_LINE_DURATION_NS,
234 			  PARAM_RANGE(NTSC_HACT_DURATION_MIN_NS,
235 				      NTSC_HACT_DURATION_TYP_NS,
236 				      NTSC_HACT_DURATION_MAX_NS),
237 			  PARAM_RANGE(NTSC_HFP_DURATION_MIN_NS,
238 				      NTSC_HFP_DURATION_TYP_NS,
239 				      NTSC_HFP_DURATION_MAX_NS),
240 			  PARAM_RANGE(NTSC_HSLEN_DURATION_MIN_NS,
241 				      NTSC_HSLEN_DURATION_TYP_NS,
242 				      NTSC_HSLEN_DURATION_MAX_NS),
243 			  PARAM_RANGE(NTSC_HBP_DURATION_MIN_NS,
244 				      NTSC_HBP_DURATION_TYP_NS,
245 				      NTSC_HBP_DURATION_MAX_NS),
246 			  PARAM_RANGE(NTSC_HBLK_DURATION_MIN_NS,
247 				      NTSC_HBLK_DURATION_TYP_NS,
248 				      NTSC_HBLK_DURATION_MAX_NS),
249 			  16,
250 			  PARAM_FIELD(3, 3),
251 			  PARAM_FIELD(3, 3),
252 			  PARAM_FIELD(16, 17)),
253 	TV_MODE_PARAMETER(DRM_MODE_ANALOG_PAL,
254 			  PAL_LINES_NUMBER,
255 			  PAL_LINE_DURATION_NS,
256 			  PARAM_RANGE(PAL_HACT_DURATION_MIN_NS,
257 				      PAL_HACT_DURATION_TYP_NS,
258 				      PAL_HACT_DURATION_MAX_NS),
259 			  PARAM_RANGE(PAL_HFP_DURATION_MIN_NS,
260 				      PAL_HFP_DURATION_TYP_NS,
261 				      PAL_HFP_DURATION_MAX_NS),
262 			  PARAM_RANGE(PAL_HSLEN_DURATION_MIN_NS,
263 				      PAL_HSLEN_DURATION_TYP_NS,
264 				      PAL_HSLEN_DURATION_MAX_NS),
265 			  PARAM_RANGE(PAL_HBP_DURATION_MIN_NS,
266 				      PAL_HBP_DURATION_TYP_NS,
267 				      PAL_HBP_DURATION_MAX_NS),
268 			  PARAM_RANGE(PAL_HBLK_DURATION_MIN_NS,
269 				      PAL_HBLK_DURATION_TYP_NS,
270 				      PAL_HBLK_DURATION_MAX_NS),
271 			  12,
272 
273 			  /*
274 			   * The front porch is actually 6 short sync
275 			   * pulses for the even field, and 5 for the
276 			   * odd field. Each sync takes half a life so
277 			   * the odd field front porch is shorter by
278 			   * half a line.
279 			   *
280 			   * In progressive, we're supposed to use 6
281 			   * pulses, so we're fine there
282 			   */
283 			  PARAM_FIELD(3, 2),
284 
285 			  /*
286 			   * The vsync length is 5 long sync pulses,
287 			   * each field taking half a line. We're
288 			   * shorter for both fields by half a line.
289 			   *
290 			   * In progressive, we're supposed to use 5
291 			   * pulses, so we're off by half
292 			   * a line.
293 			   *
294 			   * In interlace, we're now off by half a line
295 			   * for the even field and one line for the odd
296 			   * field.
297 			   */
298 			  PARAM_FIELD(3, 3),
299 
300 			  /*
301 			   * The back porch starts with post-equalizing
302 			   * pulses, consisting in 5 short sync pulses
303 			   * for the even field, 4 for the odd field. In
304 			   * progressive, it's 5 short syncs.
305 			   *
306 			   * In progressive, we thus have 2.5 lines,
307 			   * plus the 0.5 line we were missing
308 			   * previously, so we should use 3 lines.
309 			   *
310 			   * In interlace, the even field is in the
311 			   * exact same case than progressive. For the
312 			   * odd field, we should be using 2 lines but
313 			   * we're one line short, so we'll make up for
314 			   * it here by using 3.
315 			   *
316 			   * The entire blanking area is supposed to
317 			   * take 25 lines, so we also need to account
318 			   * for the rest of the blanking area that
319 			   * can't be in either the front porch or sync
320 			   * period.
321 			   */
322 			  PARAM_FIELD(19, 20)),
323 };
324 
325 static int fill_analog_mode(struct drm_device *dev,
326 			    struct drm_display_mode *mode,
327 			    const struct analog_parameters *params,
328 			    unsigned long pixel_clock_hz,
329 			    unsigned int hactive,
330 			    unsigned int vactive,
331 			    bool interlace)
332 {
333 	unsigned long pixel_duration_ns = NSEC_PER_SEC / pixel_clock_hz;
334 	unsigned int htotal, vtotal;
335 	unsigned int max_hact, hact_duration_ns;
336 	unsigned int hblk, hblk_duration_ns;
337 	unsigned int hfp, hfp_duration_ns;
338 	unsigned int hslen, hslen_duration_ns;
339 	unsigned int hbp, hbp_duration_ns;
340 	unsigned int porches, porches_duration_ns;
341 	unsigned int vfp, vfp_min;
342 	unsigned int vbp, vbp_min;
343 	unsigned int vslen;
344 	bool bt601 = false;
345 	int porches_rem;
346 	u64 result;
347 
348 	drm_dbg_kms(dev,
349 		    "Generating a %ux%u%c, %u-line mode with a %lu kHz clock\n",
350 		    hactive, vactive,
351 		    interlace ? 'i' : 'p',
352 		    params->num_lines,
353 		    pixel_clock_hz / 1000);
354 
355 	max_hact = params->hact_ns.max / pixel_duration_ns;
356 	if (pixel_clock_hz == 13500000 && hactive > max_hact && hactive <= 720) {
357 		drm_dbg_kms(dev, "Trying to generate a BT.601 mode. Disabling checks.\n");
358 		bt601 = true;
359 	}
360 
361 	/*
362 	 * Our pixel duration is going to be round down by the division,
363 	 * so rounding up is probably going to introduce even more
364 	 * deviation.
365 	 */
366 	result = (u64)params->line_duration_ns * pixel_clock_hz;
367 	do_div(result, NSEC_PER_SEC);
368 	htotal = result;
369 
370 	drm_dbg_kms(dev, "Total Horizontal Number of Pixels: %u\n", htotal);
371 
372 	hact_duration_ns = hactive * pixel_duration_ns;
373 	if (!bt601 &&
374 	    (hact_duration_ns < params->hact_ns.min ||
375 	     hact_duration_ns > params->hact_ns.max)) {
376 		drm_err(dev, "Invalid horizontal active area duration: %uns (min: %u, max %u)\n",
377 			hact_duration_ns, params->hact_ns.min, params->hact_ns.max);
378 		return -EINVAL;
379 	}
380 
381 	hblk = htotal - hactive;
382 	drm_dbg_kms(dev, "Horizontal Blanking Period: %u\n", hblk);
383 
384 	hblk_duration_ns = hblk * pixel_duration_ns;
385 	if (!bt601 &&
386 	    (hblk_duration_ns < params->hblk_ns.min ||
387 	     hblk_duration_ns > params->hblk_ns.max)) {
388 		drm_err(dev, "Invalid horizontal blanking duration: %uns (min: %u, max %u)\n",
389 			hblk_duration_ns, params->hblk_ns.min, params->hblk_ns.max);
390 		return -EINVAL;
391 	}
392 
393 	hslen = DIV_ROUND_UP(params->hslen_ns.typ, pixel_duration_ns);
394 	drm_dbg_kms(dev, "Horizontal Sync Period: %u\n", hslen);
395 
396 	hslen_duration_ns = hslen * pixel_duration_ns;
397 	if (!bt601 &&
398 	    (hslen_duration_ns < params->hslen_ns.min ||
399 	     hslen_duration_ns > params->hslen_ns.max)) {
400 		drm_err(dev, "Invalid horizontal sync duration: %uns (min: %u, max %u)\n",
401 			hslen_duration_ns, params->hslen_ns.min, params->hslen_ns.max);
402 		return -EINVAL;
403 	}
404 
405 	porches = hblk - hslen;
406 	drm_dbg_kms(dev, "Remaining horizontal pixels for both porches: %u\n", porches);
407 
408 	porches_duration_ns = porches * pixel_duration_ns;
409 	if (!bt601 &&
410 	    (porches_duration_ns > (params->hfp_ns.max + params->hbp_ns.max) ||
411 	     porches_duration_ns < (params->hfp_ns.min + params->hbp_ns.min))) {
412 		drm_err(dev, "Invalid horizontal porches duration: %uns\n",
413 			porches_duration_ns);
414 		return -EINVAL;
415 	}
416 
417 	if (bt601) {
418 		hfp = params->bt601_hfp;
419 	} else {
420 		unsigned int hfp_min = DIV_ROUND_UP(params->hfp_ns.min,
421 						    pixel_duration_ns);
422 		unsigned int hbp_min = DIV_ROUND_UP(params->hbp_ns.min,
423 						    pixel_duration_ns);
424 		int porches_rem = porches - hfp_min - hbp_min;
425 
426 		hfp = hfp_min + DIV_ROUND_UP(porches_rem, 2);
427 	}
428 
429 	drm_dbg_kms(dev, "Horizontal Front Porch: %u\n", hfp);
430 
431 	hfp_duration_ns = hfp * pixel_duration_ns;
432 	if (!bt601 &&
433 	    (hfp_duration_ns < params->hfp_ns.min ||
434 	     hfp_duration_ns > params->hfp_ns.max)) {
435 		drm_err(dev, "Invalid horizontal front porch duration: %uns (min: %u, max %u)\n",
436 			hfp_duration_ns, params->hfp_ns.min, params->hfp_ns.max);
437 		return -EINVAL;
438 	}
439 
440 	hbp = porches - hfp;
441 	drm_dbg_kms(dev, "Horizontal Back Porch: %u\n", hbp);
442 
443 	hbp_duration_ns = hbp * pixel_duration_ns;
444 	if (!bt601 &&
445 	    (hbp_duration_ns < params->hbp_ns.min ||
446 	     hbp_duration_ns > params->hbp_ns.max)) {
447 		drm_err(dev, "Invalid horizontal back porch duration: %uns (min: %u, max %u)\n",
448 			hbp_duration_ns, params->hbp_ns.min, params->hbp_ns.max);
449 		return -EINVAL;
450 	}
451 
452 	if (htotal != (hactive + hfp + hslen + hbp))
453 		return -EINVAL;
454 
455 	mode->clock = pixel_clock_hz / 1000;
456 	mode->hdisplay = hactive;
457 	mode->hsync_start = mode->hdisplay + hfp;
458 	mode->hsync_end = mode->hsync_start + hslen;
459 	mode->htotal = mode->hsync_end + hbp;
460 
461 	if (interlace) {
462 		vfp_min = params->vfp_lines.even + params->vfp_lines.odd;
463 		vbp_min = params->vbp_lines.even + params->vbp_lines.odd;
464 		vslen = params->vslen_lines.even + params->vslen_lines.odd;
465 	} else {
466 		/*
467 		 * By convention, NTSC (aka 525/60) systems start with
468 		 * the even field, but PAL (aka 625/50) systems start
469 		 * with the odd one.
470 		 *
471 		 * PAL systems also have asymmetric timings between the
472 		 * even and odd field, while NTSC is symmetric.
473 		 *
474 		 * Moreover, if we want to create a progressive mode for
475 		 * PAL, we need to use the odd field timings.
476 		 *
477 		 * Since odd == even for NTSC, we can just use the odd
478 		 * one all the time to simplify the code a bit.
479 		 */
480 		vfp_min = params->vfp_lines.odd;
481 		vbp_min = params->vbp_lines.odd;
482 		vslen = params->vslen_lines.odd;
483 	}
484 
485 	drm_dbg_kms(dev, "Vertical Sync Period: %u\n", vslen);
486 
487 	porches = params->num_lines - vactive - vslen;
488 	drm_dbg_kms(dev, "Remaining vertical pixels for both porches: %u\n", porches);
489 
490 	porches_rem = porches - vfp_min - vbp_min;
491 	vfp = vfp_min + (porches_rem / 2);
492 	drm_dbg_kms(dev, "Vertical Front Porch: %u\n", vfp);
493 
494 	vbp = porches - vfp;
495 	drm_dbg_kms(dev, "Vertical Back Porch: %u\n", vbp);
496 
497 	vtotal = vactive + vfp + vslen + vbp;
498 	if (params->num_lines != vtotal) {
499 		drm_err(dev, "Invalid vertical total: %upx (expected %upx)\n",
500 			vtotal, params->num_lines);
501 		return -EINVAL;
502 	}
503 
504 	mode->vdisplay = vactive;
505 	mode->vsync_start = mode->vdisplay + vfp;
506 	mode->vsync_end = mode->vsync_start + vslen;
507 	mode->vtotal = mode->vsync_end + vbp;
508 
509 	if (mode->vtotal != params->num_lines)
510 		return -EINVAL;
511 
512 	mode->type = DRM_MODE_TYPE_DRIVER;
513 	mode->flags = DRM_MODE_FLAG_NVSYNC | DRM_MODE_FLAG_NHSYNC;
514 	if (interlace)
515 		mode->flags |= DRM_MODE_FLAG_INTERLACE;
516 
517 	drm_mode_set_name(mode);
518 
519 	drm_dbg_kms(dev, "Generated mode " DRM_MODE_FMT "\n", DRM_MODE_ARG(mode));
520 
521 	return 0;
522 }
523 
524 /**
525  * drm_analog_tv_mode - create a display mode for an analog TV
526  * @dev: drm device
527  * @tv_mode: TV Mode standard to create a mode for. See DRM_MODE_TV_MODE_*.
528  * @pixel_clock_hz: Pixel Clock Frequency, in Hertz
529  * @hdisplay: hdisplay size
530  * @vdisplay: vdisplay size
531  * @interlace: whether to compute an interlaced mode
532  *
533  * This function creates a struct drm_display_mode instance suited for
534  * an analog TV output, for one of the usual analog TV modes. Where
535  * this is DRM_MODE_TV_MODE_MONOCHROME, a 625-line mode will be created.
536  *
537  * Note that @hdisplay is larger than the usual constraints for the PAL
538  * and NTSC timings, and we'll choose to ignore most timings constraints
539  * to reach those resolutions.
540  *
541  * Returns:
542  * A pointer to the mode, allocated with drm_mode_create(). Returns NULL
543  * on error.
544  */
545 struct drm_display_mode *drm_analog_tv_mode(struct drm_device *dev,
546 					    enum drm_connector_tv_mode tv_mode,
547 					    unsigned long pixel_clock_hz,
548 					    unsigned int hdisplay,
549 					    unsigned int vdisplay,
550 					    bool interlace)
551 {
552 	struct drm_display_mode *mode;
553 	enum drm_mode_analog analog;
554 	int ret;
555 
556 	switch (tv_mode) {
557 	case DRM_MODE_TV_MODE_NTSC:
558 		fallthrough;
559 	case DRM_MODE_TV_MODE_NTSC_443:
560 		fallthrough;
561 	case DRM_MODE_TV_MODE_NTSC_J:
562 		fallthrough;
563 	case DRM_MODE_TV_MODE_PAL_M:
564 		analog = DRM_MODE_ANALOG_NTSC;
565 		break;
566 
567 	case DRM_MODE_TV_MODE_PAL:
568 		fallthrough;
569 	case DRM_MODE_TV_MODE_PAL_N:
570 		fallthrough;
571 	case DRM_MODE_TV_MODE_SECAM:
572 		fallthrough;
573 	case DRM_MODE_TV_MODE_MONOCHROME:
574 		analog = DRM_MODE_ANALOG_PAL;
575 		break;
576 
577 	default:
578 		return NULL;
579 	}
580 
581 	mode = drm_mode_create(dev);
582 	if (!mode)
583 		return NULL;
584 
585 	ret = fill_analog_mode(dev, mode,
586 			       &tv_modes_parameters[analog],
587 			       pixel_clock_hz, hdisplay, vdisplay, interlace);
588 	if (ret)
589 		goto err_free_mode;
590 
591 	return mode;
592 
593 err_free_mode:
594 	drm_mode_destroy(dev, mode);
595 	return NULL;
596 }
597 EXPORT_SYMBOL(drm_analog_tv_mode);
598 
599 /**
600  * drm_cvt_mode -create a modeline based on the CVT algorithm
601  * @dev: drm device
602  * @hdisplay: hdisplay size
603  * @vdisplay: vdisplay size
604  * @vrefresh: vrefresh rate
605  * @reduced: whether to use reduced blanking
606  * @interlaced: whether to compute an interlaced mode
607  * @margins: whether to add margins (borders)
608  *
609  * This function is called to generate the modeline based on CVT algorithm
610  * according to the hdisplay, vdisplay, vrefresh.
611  * It is based from the VESA(TM) Coordinated Video Timing Generator by
612  * Graham Loveridge April 9, 2003 available at
613  * http://www.elo.utfsm.cl/~elo212/docs/CVTd6r1.xls
614  *
615  * And it is copied from xf86CVTmode in xserver/hw/xfree86/modes/xf86cvt.c.
616  * What I have done is to translate it by using integer calculation.
617  *
618  * Returns:
619  * The modeline based on the CVT algorithm stored in a drm_display_mode object.
620  * The display mode object is allocated with drm_mode_create(). Returns NULL
621  * when no mode could be allocated.
622  */
623 struct drm_display_mode *drm_cvt_mode(struct drm_device *dev, int hdisplay,
624 				      int vdisplay, int vrefresh,
625 				      bool reduced, bool interlaced, bool margins)
626 {
627 #define HV_FACTOR			1000
628 	/* 1) top/bottom margin size (% of height) - default: 1.8, */
629 #define	CVT_MARGIN_PERCENTAGE		18
630 	/* 2) character cell horizontal granularity (pixels) - default 8 */
631 #define	CVT_H_GRANULARITY		8
632 	/* 3) Minimum vertical porch (lines) - default 3 */
633 #define	CVT_MIN_V_PORCH			3
634 	/* 4) Minimum number of vertical back porch lines - default 6 */
635 #define	CVT_MIN_V_BPORCH		6
636 	/* Pixel Clock step (kHz) */
637 #define CVT_CLOCK_STEP			250
638 	struct drm_display_mode *drm_mode;
639 	unsigned int vfieldrate, hperiod;
640 	int hdisplay_rnd, hmargin, vdisplay_rnd, vmargin, vsync;
641 	int interlace;
642 	u64 tmp;
643 
644 	if (!hdisplay || !vdisplay)
645 		return NULL;
646 
647 	/* allocate the drm_display_mode structure. If failure, we will
648 	 * return directly
649 	 */
650 	drm_mode = drm_mode_create(dev);
651 	if (!drm_mode)
652 		return NULL;
653 
654 	/* the CVT default refresh rate is 60Hz */
655 	if (!vrefresh)
656 		vrefresh = 60;
657 
658 	/* the required field fresh rate */
659 	if (interlaced)
660 		vfieldrate = vrefresh * 2;
661 	else
662 		vfieldrate = vrefresh;
663 
664 	/* horizontal pixels */
665 	hdisplay_rnd = hdisplay - (hdisplay % CVT_H_GRANULARITY);
666 
667 	/* determine the left&right borders */
668 	hmargin = 0;
669 	if (margins) {
670 		hmargin = hdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
671 		hmargin -= hmargin % CVT_H_GRANULARITY;
672 	}
673 	/* find the total active pixels */
674 	drm_mode->hdisplay = hdisplay_rnd + 2 * hmargin;
675 
676 	/* find the number of lines per field */
677 	if (interlaced)
678 		vdisplay_rnd = vdisplay / 2;
679 	else
680 		vdisplay_rnd = vdisplay;
681 
682 	/* find the top & bottom borders */
683 	vmargin = 0;
684 	if (margins)
685 		vmargin = vdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
686 
687 	drm_mode->vdisplay = vdisplay + 2 * vmargin;
688 
689 	/* Interlaced */
690 	if (interlaced)
691 		interlace = 1;
692 	else
693 		interlace = 0;
694 
695 	/* Determine VSync Width from aspect ratio */
696 	if (!(vdisplay % 3) && ((vdisplay * 4 / 3) == hdisplay))
697 		vsync = 4;
698 	else if (!(vdisplay % 9) && ((vdisplay * 16 / 9) == hdisplay))
699 		vsync = 5;
700 	else if (!(vdisplay % 10) && ((vdisplay * 16 / 10) == hdisplay))
701 		vsync = 6;
702 	else if (!(vdisplay % 4) && ((vdisplay * 5 / 4) == hdisplay))
703 		vsync = 7;
704 	else if (!(vdisplay % 9) && ((vdisplay * 15 / 9) == hdisplay))
705 		vsync = 7;
706 	else /* custom */
707 		vsync = 10;
708 
709 	if (!reduced) {
710 		/* simplify the GTF calculation */
711 		/* 4) Minimum time of vertical sync + back porch interval (µs)
712 		 * default 550.0
713 		 */
714 		int tmp1, tmp2;
715 #define CVT_MIN_VSYNC_BP	550
716 		/* 3) Nominal HSync width (% of line period) - default 8 */
717 #define CVT_HSYNC_PERCENTAGE	8
718 		unsigned int hblank_percentage;
719 		int vsyncandback_porch, __maybe_unused vback_porch, hblank;
720 
721 		/* estimated the horizontal period */
722 		tmp1 = HV_FACTOR * 1000000  -
723 				CVT_MIN_VSYNC_BP * HV_FACTOR * vfieldrate;
724 		tmp2 = (vdisplay_rnd + 2 * vmargin + CVT_MIN_V_PORCH) * 2 +
725 				interlace;
726 		hperiod = tmp1 * 2 / (tmp2 * vfieldrate);
727 
728 		tmp1 = CVT_MIN_VSYNC_BP * HV_FACTOR / hperiod + 1;
729 		/* 9. Find number of lines in sync + backporch */
730 		if (tmp1 < (vsync + CVT_MIN_V_PORCH))
731 			vsyncandback_porch = vsync + CVT_MIN_V_PORCH;
732 		else
733 			vsyncandback_porch = tmp1;
734 		/* 10. Find number of lines in back porch */
735 		vback_porch = vsyncandback_porch - vsync;
736 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin +
737 				vsyncandback_porch + CVT_MIN_V_PORCH;
738 		/* 5) Definition of Horizontal blanking time limitation */
739 		/* Gradient (%/kHz) - default 600 */
740 #define CVT_M_FACTOR	600
741 		/* Offset (%) - default 40 */
742 #define CVT_C_FACTOR	40
743 		/* Blanking time scaling factor - default 128 */
744 #define CVT_K_FACTOR	128
745 		/* Scaling factor weighting - default 20 */
746 #define CVT_J_FACTOR	20
747 #define CVT_M_PRIME	(CVT_M_FACTOR * CVT_K_FACTOR / 256)
748 #define CVT_C_PRIME	((CVT_C_FACTOR - CVT_J_FACTOR) * CVT_K_FACTOR / 256 + \
749 			 CVT_J_FACTOR)
750 		/* 12. Find ideal blanking duty cycle from formula */
751 		hblank_percentage = CVT_C_PRIME * HV_FACTOR - CVT_M_PRIME *
752 					hperiod / 1000;
753 		/* 13. Blanking time */
754 		if (hblank_percentage < 20 * HV_FACTOR)
755 			hblank_percentage = 20 * HV_FACTOR;
756 		hblank = drm_mode->hdisplay * hblank_percentage /
757 			 (100 * HV_FACTOR - hblank_percentage);
758 		hblank -= hblank % (2 * CVT_H_GRANULARITY);
759 		/* 14. find the total pixels per line */
760 		drm_mode->htotal = drm_mode->hdisplay + hblank;
761 		drm_mode->hsync_end = drm_mode->hdisplay + hblank / 2;
762 		drm_mode->hsync_start = drm_mode->hsync_end -
763 			(drm_mode->htotal * CVT_HSYNC_PERCENTAGE) / 100;
764 		drm_mode->hsync_start += CVT_H_GRANULARITY -
765 			drm_mode->hsync_start % CVT_H_GRANULARITY;
766 		/* fill the Vsync values */
767 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_MIN_V_PORCH;
768 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
769 	} else {
770 		/* Reduced blanking */
771 		/* Minimum vertical blanking interval time (µs)- default 460 */
772 #define CVT_RB_MIN_VBLANK	460
773 		/* Fixed number of clocks for horizontal sync */
774 #define CVT_RB_H_SYNC		32
775 		/* Fixed number of clocks for horizontal blanking */
776 #define CVT_RB_H_BLANK		160
777 		/* Fixed number of lines for vertical front porch - default 3*/
778 #define CVT_RB_VFPORCH		3
779 		int vbilines;
780 		int tmp1, tmp2;
781 		/* 8. Estimate Horizontal period. */
782 		tmp1 = HV_FACTOR * 1000000 -
783 			CVT_RB_MIN_VBLANK * HV_FACTOR * vfieldrate;
784 		tmp2 = vdisplay_rnd + 2 * vmargin;
785 		hperiod = tmp1 / (tmp2 * vfieldrate);
786 		/* 9. Find number of lines in vertical blanking */
787 		vbilines = CVT_RB_MIN_VBLANK * HV_FACTOR / hperiod + 1;
788 		/* 10. Check if vertical blanking is sufficient */
789 		if (vbilines < (CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH))
790 			vbilines = CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH;
791 		/* 11. Find total number of lines in vertical field */
792 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin + vbilines;
793 		/* 12. Find total number of pixels in a line */
794 		drm_mode->htotal = drm_mode->hdisplay + CVT_RB_H_BLANK;
795 		/* Fill in HSync values */
796 		drm_mode->hsync_end = drm_mode->hdisplay + CVT_RB_H_BLANK / 2;
797 		drm_mode->hsync_start = drm_mode->hsync_end - CVT_RB_H_SYNC;
798 		/* Fill in VSync values */
799 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_RB_VFPORCH;
800 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
801 	}
802 	/* 15/13. Find pixel clock frequency (kHz for xf86) */
803 	tmp = drm_mode->htotal; /* perform intermediate calcs in u64 */
804 	tmp *= HV_FACTOR * 1000;
805 	do_div(tmp, hperiod);
806 	tmp -= drm_mode->clock % CVT_CLOCK_STEP;
807 	drm_mode->clock = tmp;
808 	/* 18/16. Find actual vertical frame frequency */
809 	/* ignore - just set the mode flag for interlaced */
810 	if (interlaced) {
811 		drm_mode->vtotal *= 2;
812 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
813 	}
814 	/* Fill the mode line name */
815 	drm_mode_set_name(drm_mode);
816 	if (reduced)
817 		drm_mode->flags |= (DRM_MODE_FLAG_PHSYNC |
818 					DRM_MODE_FLAG_NVSYNC);
819 	else
820 		drm_mode->flags |= (DRM_MODE_FLAG_PVSYNC |
821 					DRM_MODE_FLAG_NHSYNC);
822 
823 	return drm_mode;
824 }
825 EXPORT_SYMBOL(drm_cvt_mode);
826 
827 /**
828  * drm_gtf_mode_complex - create the modeline based on the full GTF algorithm
829  * @dev: drm device
830  * @hdisplay: hdisplay size
831  * @vdisplay: vdisplay size
832  * @vrefresh: vrefresh rate.
833  * @interlaced: whether to compute an interlaced mode
834  * @margins: desired margin (borders) size
835  * @GTF_M: extended GTF formula parameters
836  * @GTF_2C: extended GTF formula parameters
837  * @GTF_K: extended GTF formula parameters
838  * @GTF_2J: extended GTF formula parameters
839  *
840  * GTF feature blocks specify C and J in multiples of 0.5, so we pass them
841  * in here multiplied by two.  For a C of 40, pass in 80.
842  *
843  * Returns:
844  * The modeline based on the full GTF algorithm stored in a drm_display_mode object.
845  * The display mode object is allocated with drm_mode_create(). Returns NULL
846  * when no mode could be allocated.
847  */
848 struct drm_display_mode *
849 drm_gtf_mode_complex(struct drm_device *dev, int hdisplay, int vdisplay,
850 		     int vrefresh, bool interlaced, int margins,
851 		     int GTF_M, int GTF_2C, int GTF_K, int GTF_2J)
852 {	/* 1) top/bottom margin size (% of height) - default: 1.8, */
853 #define	GTF_MARGIN_PERCENTAGE		18
854 	/* 2) character cell horizontal granularity (pixels) - default 8 */
855 #define	GTF_CELL_GRAN			8
856 	/* 3) Minimum vertical porch (lines) - default 3 */
857 #define	GTF_MIN_V_PORCH			1
858 	/* width of vsync in lines */
859 #define V_SYNC_RQD			3
860 	/* width of hsync as % of total line */
861 #define H_SYNC_PERCENT			8
862 	/* min time of vsync + back porch (microsec) */
863 #define MIN_VSYNC_PLUS_BP		550
864 	/* C' and M' are part of the Blanking Duty Cycle computation */
865 #define GTF_C_PRIME	((((GTF_2C - GTF_2J) * GTF_K / 256) + GTF_2J) / 2)
866 #define GTF_M_PRIME	(GTF_K * GTF_M / 256)
867 	struct drm_display_mode *drm_mode;
868 	unsigned int hdisplay_rnd, vdisplay_rnd, vfieldrate_rqd;
869 	int top_margin, bottom_margin;
870 	int interlace;
871 	unsigned int hfreq_est;
872 	int vsync_plus_bp, __maybe_unused vback_porch;
873 	unsigned int vtotal_lines, __maybe_unused vfieldrate_est;
874 	unsigned int __maybe_unused hperiod;
875 	unsigned int vfield_rate, __maybe_unused vframe_rate;
876 	int left_margin, right_margin;
877 	unsigned int total_active_pixels, ideal_duty_cycle;
878 	unsigned int hblank, total_pixels, pixel_freq;
879 	int hsync, hfront_porch, vodd_front_porch_lines;
880 	unsigned int tmp1, tmp2;
881 
882 	if (!hdisplay || !vdisplay)
883 		return NULL;
884 
885 	drm_mode = drm_mode_create(dev);
886 	if (!drm_mode)
887 		return NULL;
888 
889 	/* 1. In order to give correct results, the number of horizontal
890 	 * pixels requested is first processed to ensure that it is divisible
891 	 * by the character size, by rounding it to the nearest character
892 	 * cell boundary:
893 	 */
894 	hdisplay_rnd = (hdisplay + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
895 	hdisplay_rnd = hdisplay_rnd * GTF_CELL_GRAN;
896 
897 	/* 2. If interlace is requested, the number of vertical lines assumed
898 	 * by the calculation must be halved, as the computation calculates
899 	 * the number of vertical lines per field.
900 	 */
901 	if (interlaced)
902 		vdisplay_rnd = vdisplay / 2;
903 	else
904 		vdisplay_rnd = vdisplay;
905 
906 	/* 3. Find the frame rate required: */
907 	if (interlaced)
908 		vfieldrate_rqd = vrefresh * 2;
909 	else
910 		vfieldrate_rqd = vrefresh;
911 
912 	/* 4. Find number of lines in Top margin: */
913 	top_margin = 0;
914 	if (margins)
915 		top_margin = (vdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
916 				1000;
917 	/* 5. Find number of lines in bottom margin: */
918 	bottom_margin = top_margin;
919 
920 	/* 6. If interlace is required, then set variable interlace: */
921 	if (interlaced)
922 		interlace = 1;
923 	else
924 		interlace = 0;
925 
926 	/* 7. Estimate the Horizontal frequency */
927 	{
928 		tmp1 = (1000000  - MIN_VSYNC_PLUS_BP * vfieldrate_rqd) / 500;
929 		tmp2 = (vdisplay_rnd + 2 * top_margin + GTF_MIN_V_PORCH) *
930 				2 + interlace;
931 		hfreq_est = (tmp2 * 1000 * vfieldrate_rqd) / tmp1;
932 	}
933 
934 	/* 8. Find the number of lines in V sync + back porch */
935 	/* [V SYNC+BP] = RINT(([MIN VSYNC+BP] * hfreq_est / 1000000)) */
936 	vsync_plus_bp = MIN_VSYNC_PLUS_BP * hfreq_est / 1000;
937 	vsync_plus_bp = (vsync_plus_bp + 500) / 1000;
938 	/*  9. Find the number of lines in V back porch alone: */
939 	vback_porch = vsync_plus_bp - V_SYNC_RQD;
940 	/*  10. Find the total number of lines in Vertical field period: */
941 	vtotal_lines = vdisplay_rnd + top_margin + bottom_margin +
942 			vsync_plus_bp + GTF_MIN_V_PORCH;
943 	/*  11. Estimate the Vertical field frequency: */
944 	vfieldrate_est = hfreq_est / vtotal_lines;
945 	/*  12. Find the actual horizontal period: */
946 	hperiod = 1000000 / (vfieldrate_rqd * vtotal_lines);
947 
948 	/*  13. Find the actual Vertical field frequency: */
949 	vfield_rate = hfreq_est / vtotal_lines;
950 	/*  14. Find the Vertical frame frequency: */
951 	if (interlaced)
952 		vframe_rate = vfield_rate / 2;
953 	else
954 		vframe_rate = vfield_rate;
955 	/*  15. Find number of pixels in left margin: */
956 	if (margins)
957 		left_margin = (hdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
958 				1000;
959 	else
960 		left_margin = 0;
961 
962 	/* 16.Find number of pixels in right margin: */
963 	right_margin = left_margin;
964 	/* 17.Find total number of active pixels in image and left and right */
965 	total_active_pixels = hdisplay_rnd + left_margin + right_margin;
966 	/* 18.Find the ideal blanking duty cycle from blanking duty cycle */
967 	ideal_duty_cycle = GTF_C_PRIME * 1000 -
968 				(GTF_M_PRIME * 1000000 / hfreq_est);
969 	/* 19.Find the number of pixels in the blanking time to the nearest
970 	 * double character cell: */
971 	hblank = total_active_pixels * ideal_duty_cycle /
972 			(100000 - ideal_duty_cycle);
973 	hblank = (hblank + GTF_CELL_GRAN) / (2 * GTF_CELL_GRAN);
974 	hblank = hblank * 2 * GTF_CELL_GRAN;
975 	/* 20.Find total number of pixels: */
976 	total_pixels = total_active_pixels + hblank;
977 	/* 21.Find pixel clock frequency: */
978 	pixel_freq = total_pixels * hfreq_est / 1000;
979 	/* Stage 1 computations are now complete; I should really pass
980 	 * the results to another function and do the Stage 2 computations,
981 	 * but I only need a few more values so I'll just append the
982 	 * computations here for now */
983 	/* 17. Find the number of pixels in the horizontal sync period: */
984 	hsync = H_SYNC_PERCENT * total_pixels / 100;
985 	hsync = (hsync + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
986 	hsync = hsync * GTF_CELL_GRAN;
987 	/* 18. Find the number of pixels in horizontal front porch period */
988 	hfront_porch = hblank / 2 - hsync;
989 	/*  36. Find the number of lines in the odd front porch period: */
990 	vodd_front_porch_lines = GTF_MIN_V_PORCH ;
991 
992 	/* finally, pack the results in the mode struct */
993 	drm_mode->hdisplay = hdisplay_rnd;
994 	drm_mode->hsync_start = hdisplay_rnd + hfront_porch;
995 	drm_mode->hsync_end = drm_mode->hsync_start + hsync;
996 	drm_mode->htotal = total_pixels;
997 	drm_mode->vdisplay = vdisplay_rnd;
998 	drm_mode->vsync_start = vdisplay_rnd + vodd_front_porch_lines;
999 	drm_mode->vsync_end = drm_mode->vsync_start + V_SYNC_RQD;
1000 	drm_mode->vtotal = vtotal_lines;
1001 
1002 	drm_mode->clock = pixel_freq;
1003 
1004 	if (interlaced) {
1005 		drm_mode->vtotal *= 2;
1006 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
1007 	}
1008 
1009 	drm_mode_set_name(drm_mode);
1010 	if (GTF_M == 600 && GTF_2C == 80 && GTF_K == 128 && GTF_2J == 40)
1011 		drm_mode->flags = DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC;
1012 	else
1013 		drm_mode->flags = DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC;
1014 
1015 	return drm_mode;
1016 }
1017 EXPORT_SYMBOL(drm_gtf_mode_complex);
1018 
1019 /**
1020  * drm_gtf_mode - create the modeline based on the GTF algorithm
1021  * @dev: drm device
1022  * @hdisplay: hdisplay size
1023  * @vdisplay: vdisplay size
1024  * @vrefresh: vrefresh rate.
1025  * @interlaced: whether to compute an interlaced mode
1026  * @margins: desired margin (borders) size
1027  *
1028  * return the modeline based on GTF algorithm
1029  *
1030  * This function is to create the modeline based on the GTF algorithm.
1031  * Generalized Timing Formula is derived from:
1032  *
1033  *	GTF Spreadsheet by Andy Morrish (1/5/97)
1034  *	available at https://www.vesa.org
1035  *
1036  * And it is copied from the file of xserver/hw/xfree86/modes/xf86gtf.c.
1037  * What I have done is to translate it by using integer calculation.
1038  * I also refer to the function of fb_get_mode in the file of
1039  * drivers/video/fbmon.c
1040  *
1041  * Standard GTF parameters::
1042  *
1043  *     M = 600
1044  *     C = 40
1045  *     K = 128
1046  *     J = 20
1047  *
1048  * Returns:
1049  * The modeline based on the GTF algorithm stored in a drm_display_mode object.
1050  * The display mode object is allocated with drm_mode_create(). Returns NULL
1051  * when no mode could be allocated.
1052  */
1053 struct drm_display_mode *
1054 drm_gtf_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh,
1055 	     bool interlaced, int margins)
1056 {
1057 	return drm_gtf_mode_complex(dev, hdisplay, vdisplay, vrefresh,
1058 				    interlaced, margins,
1059 				    600, 40 * 2, 128, 20 * 2);
1060 }
1061 EXPORT_SYMBOL(drm_gtf_mode);
1062 
1063 #ifdef CONFIG_VIDEOMODE_HELPERS
1064 /**
1065  * drm_display_mode_from_videomode - fill in @dmode using @vm,
1066  * @vm: videomode structure to use as source
1067  * @dmode: drm_display_mode structure to use as destination
1068  *
1069  * Fills out @dmode using the display mode specified in @vm.
1070  */
1071 void drm_display_mode_from_videomode(const struct videomode *vm,
1072 				     struct drm_display_mode *dmode)
1073 {
1074 	dmode->hdisplay = vm->hactive;
1075 	dmode->hsync_start = dmode->hdisplay + vm->hfront_porch;
1076 	dmode->hsync_end = dmode->hsync_start + vm->hsync_len;
1077 	dmode->htotal = dmode->hsync_end + vm->hback_porch;
1078 
1079 	dmode->vdisplay = vm->vactive;
1080 	dmode->vsync_start = dmode->vdisplay + vm->vfront_porch;
1081 	dmode->vsync_end = dmode->vsync_start + vm->vsync_len;
1082 	dmode->vtotal = dmode->vsync_end + vm->vback_porch;
1083 
1084 	dmode->clock = vm->pixelclock / 1000;
1085 
1086 	dmode->flags = 0;
1087 	if (vm->flags & DISPLAY_FLAGS_HSYNC_HIGH)
1088 		dmode->flags |= DRM_MODE_FLAG_PHSYNC;
1089 	else if (vm->flags & DISPLAY_FLAGS_HSYNC_LOW)
1090 		dmode->flags |= DRM_MODE_FLAG_NHSYNC;
1091 	if (vm->flags & DISPLAY_FLAGS_VSYNC_HIGH)
1092 		dmode->flags |= DRM_MODE_FLAG_PVSYNC;
1093 	else if (vm->flags & DISPLAY_FLAGS_VSYNC_LOW)
1094 		dmode->flags |= DRM_MODE_FLAG_NVSYNC;
1095 	if (vm->flags & DISPLAY_FLAGS_INTERLACED)
1096 		dmode->flags |= DRM_MODE_FLAG_INTERLACE;
1097 	if (vm->flags & DISPLAY_FLAGS_DOUBLESCAN)
1098 		dmode->flags |= DRM_MODE_FLAG_DBLSCAN;
1099 	if (vm->flags & DISPLAY_FLAGS_DOUBLECLK)
1100 		dmode->flags |= DRM_MODE_FLAG_DBLCLK;
1101 	drm_mode_set_name(dmode);
1102 }
1103 EXPORT_SYMBOL_GPL(drm_display_mode_from_videomode);
1104 
1105 /**
1106  * drm_display_mode_to_videomode - fill in @vm using @dmode,
1107  * @dmode: drm_display_mode structure to use as source
1108  * @vm: videomode structure to use as destination
1109  *
1110  * Fills out @vm using the display mode specified in @dmode.
1111  */
1112 void drm_display_mode_to_videomode(const struct drm_display_mode *dmode,
1113 				   struct videomode *vm)
1114 {
1115 	vm->hactive = dmode->hdisplay;
1116 	vm->hfront_porch = dmode->hsync_start - dmode->hdisplay;
1117 	vm->hsync_len = dmode->hsync_end - dmode->hsync_start;
1118 	vm->hback_porch = dmode->htotal - dmode->hsync_end;
1119 
1120 	vm->vactive = dmode->vdisplay;
1121 	vm->vfront_porch = dmode->vsync_start - dmode->vdisplay;
1122 	vm->vsync_len = dmode->vsync_end - dmode->vsync_start;
1123 	vm->vback_porch = dmode->vtotal - dmode->vsync_end;
1124 
1125 	vm->pixelclock = dmode->clock * 1000;
1126 
1127 	vm->flags = 0;
1128 	if (dmode->flags & DRM_MODE_FLAG_PHSYNC)
1129 		vm->flags |= DISPLAY_FLAGS_HSYNC_HIGH;
1130 	else if (dmode->flags & DRM_MODE_FLAG_NHSYNC)
1131 		vm->flags |= DISPLAY_FLAGS_HSYNC_LOW;
1132 	if (dmode->flags & DRM_MODE_FLAG_PVSYNC)
1133 		vm->flags |= DISPLAY_FLAGS_VSYNC_HIGH;
1134 	else if (dmode->flags & DRM_MODE_FLAG_NVSYNC)
1135 		vm->flags |= DISPLAY_FLAGS_VSYNC_LOW;
1136 	if (dmode->flags & DRM_MODE_FLAG_INTERLACE)
1137 		vm->flags |= DISPLAY_FLAGS_INTERLACED;
1138 	if (dmode->flags & DRM_MODE_FLAG_DBLSCAN)
1139 		vm->flags |= DISPLAY_FLAGS_DOUBLESCAN;
1140 	if (dmode->flags & DRM_MODE_FLAG_DBLCLK)
1141 		vm->flags |= DISPLAY_FLAGS_DOUBLECLK;
1142 }
1143 EXPORT_SYMBOL_GPL(drm_display_mode_to_videomode);
1144 
1145 /**
1146  * drm_bus_flags_from_videomode - extract information about pixelclk and
1147  * DE polarity from videomode and store it in a separate variable
1148  * @vm: videomode structure to use
1149  * @bus_flags: information about pixelclk, sync and DE polarity will be stored
1150  * here
1151  *
1152  * Sets DRM_BUS_FLAG_DE_(LOW|HIGH),  DRM_BUS_FLAG_PIXDATA_DRIVE_(POS|NEG)EDGE
1153  * and DISPLAY_FLAGS_SYNC_(POS|NEG)EDGE in @bus_flags according to DISPLAY_FLAGS
1154  * found in @vm
1155  */
1156 void drm_bus_flags_from_videomode(const struct videomode *vm, u32 *bus_flags)
1157 {
1158 	*bus_flags = 0;
1159 	if (vm->flags & DISPLAY_FLAGS_PIXDATA_POSEDGE)
1160 		*bus_flags |= DRM_BUS_FLAG_PIXDATA_DRIVE_POSEDGE;
1161 	if (vm->flags & DISPLAY_FLAGS_PIXDATA_NEGEDGE)
1162 		*bus_flags |= DRM_BUS_FLAG_PIXDATA_DRIVE_NEGEDGE;
1163 
1164 	if (vm->flags & DISPLAY_FLAGS_SYNC_POSEDGE)
1165 		*bus_flags |= DRM_BUS_FLAG_SYNC_DRIVE_POSEDGE;
1166 	if (vm->flags & DISPLAY_FLAGS_SYNC_NEGEDGE)
1167 		*bus_flags |= DRM_BUS_FLAG_SYNC_DRIVE_NEGEDGE;
1168 
1169 	if (vm->flags & DISPLAY_FLAGS_DE_LOW)
1170 		*bus_flags |= DRM_BUS_FLAG_DE_LOW;
1171 	if (vm->flags & DISPLAY_FLAGS_DE_HIGH)
1172 		*bus_flags |= DRM_BUS_FLAG_DE_HIGH;
1173 }
1174 EXPORT_SYMBOL_GPL(drm_bus_flags_from_videomode);
1175 
1176 #ifdef CONFIG_OF
1177 /**
1178  * of_get_drm_display_mode - get a drm_display_mode from devicetree
1179  * @np: device_node with the timing specification
1180  * @dmode: will be set to the return value
1181  * @bus_flags: information about pixelclk, sync and DE polarity
1182  * @index: index into the list of display timings in devicetree
1183  *
1184  * This function is expensive and should only be used, if only one mode is to be
1185  * read from DT. To get multiple modes start with of_get_display_timings and
1186  * work with that instead.
1187  *
1188  * Returns:
1189  * 0 on success, a negative errno code when no of videomode node was found.
1190  */
1191 int of_get_drm_display_mode(struct device_node *np,
1192 			    struct drm_display_mode *dmode, u32 *bus_flags,
1193 			    int index)
1194 {
1195 	struct videomode vm;
1196 	int ret;
1197 
1198 	ret = of_get_videomode(np, &vm, index);
1199 	if (ret)
1200 		return ret;
1201 
1202 	drm_display_mode_from_videomode(&vm, dmode);
1203 	if (bus_flags)
1204 		drm_bus_flags_from_videomode(&vm, bus_flags);
1205 
1206 	pr_debug("%pOF: got %dx%d display mode: " DRM_MODE_FMT "\n",
1207 		 np, vm.hactive, vm.vactive, DRM_MODE_ARG(dmode));
1208 
1209 	return 0;
1210 }
1211 EXPORT_SYMBOL_GPL(of_get_drm_display_mode);
1212 
1213 /**
1214  * of_get_drm_panel_display_mode - get a panel-timing drm_display_mode from devicetree
1215  * @np: device_node with the panel-timing specification
1216  * @dmode: will be set to the return value
1217  * @bus_flags: information about pixelclk, sync and DE polarity
1218  *
1219  * The mandatory Device Tree properties width-mm and height-mm
1220  * are read and set on the display mode.
1221  *
1222  * Returns:
1223  * Zero on success, negative error code on failure.
1224  */
1225 int of_get_drm_panel_display_mode(struct device_node *np,
1226 				  struct drm_display_mode *dmode, u32 *bus_flags)
1227 {
1228 	u32 width_mm = 0, height_mm = 0;
1229 	struct display_timing timing;
1230 	struct videomode vm;
1231 	int ret;
1232 
1233 	ret = of_get_display_timing(np, "panel-timing", &timing);
1234 	if (ret)
1235 		return ret;
1236 
1237 	videomode_from_timing(&timing, &vm);
1238 
1239 	memset(dmode, 0, sizeof(*dmode));
1240 	drm_display_mode_from_videomode(&vm, dmode);
1241 	if (bus_flags)
1242 		drm_bus_flags_from_videomode(&vm, bus_flags);
1243 
1244 	ret = of_property_read_u32(np, "width-mm", &width_mm);
1245 	if (ret)
1246 		return ret;
1247 
1248 	ret = of_property_read_u32(np, "height-mm", &height_mm);
1249 	if (ret)
1250 		return ret;
1251 
1252 	dmode->width_mm = width_mm;
1253 	dmode->height_mm = height_mm;
1254 
1255 	pr_debug(DRM_MODE_FMT "\n", DRM_MODE_ARG(dmode));
1256 
1257 	return 0;
1258 }
1259 EXPORT_SYMBOL_GPL(of_get_drm_panel_display_mode);
1260 #endif /* CONFIG_OF */
1261 #endif /* CONFIG_VIDEOMODE_HELPERS */
1262 
1263 /**
1264  * drm_mode_set_name - set the name on a mode
1265  * @mode: name will be set in this mode
1266  *
1267  * Set the name of @mode to a standard format which is <hdisplay>x<vdisplay>
1268  * with an optional 'i' suffix for interlaced modes.
1269  */
1270 void drm_mode_set_name(struct drm_display_mode *mode)
1271 {
1272 	bool interlaced = !!(mode->flags & DRM_MODE_FLAG_INTERLACE);
1273 
1274 	snprintf(mode->name, DRM_DISPLAY_MODE_LEN, "%dx%d%s",
1275 		 mode->hdisplay, mode->vdisplay,
1276 		 interlaced ? "i" : "");
1277 }
1278 EXPORT_SYMBOL(drm_mode_set_name);
1279 
1280 /**
1281  * drm_mode_vrefresh - get the vrefresh of a mode
1282  * @mode: mode
1283  *
1284  * Returns:
1285  * @modes's vrefresh rate in Hz, rounded to the nearest integer.
1286  */
1287 int drm_mode_vrefresh(const struct drm_display_mode *mode)
1288 {
1289 	unsigned int num = 1, den = 1;
1290 
1291 	if (mode->htotal == 0 || mode->vtotal == 0)
1292 		return 0;
1293 
1294 	if (mode->flags & DRM_MODE_FLAG_INTERLACE)
1295 		num *= 2;
1296 	if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
1297 		den *= 2;
1298 	if (mode->vscan > 1)
1299 		den *= mode->vscan;
1300 
1301 	if (check_mul_overflow(mode->clock, num, &num))
1302 		return 0;
1303 
1304 	if (check_mul_overflow(mode->htotal * mode->vtotal, den, &den))
1305 		return 0;
1306 
1307 	return DIV_ROUND_CLOSEST_ULL(mul_u32_u32(num, 1000), den);
1308 }
1309 EXPORT_SYMBOL(drm_mode_vrefresh);
1310 
1311 /**
1312  * drm_mode_get_hv_timing - Fetches hdisplay/vdisplay for given mode
1313  * @mode: mode to query
1314  * @hdisplay: hdisplay value to fill in
1315  * @vdisplay: vdisplay value to fill in
1316  *
1317  * The vdisplay value will be doubled if the specified mode is a stereo mode of
1318  * the appropriate layout.
1319  */
1320 void drm_mode_get_hv_timing(const struct drm_display_mode *mode,
1321 			    int *hdisplay, int *vdisplay)
1322 {
1323 	struct drm_display_mode adjusted;
1324 
1325 	drm_mode_init(&adjusted, mode);
1326 
1327 	drm_mode_set_crtcinfo(&adjusted, CRTC_STEREO_DOUBLE_ONLY);
1328 	*hdisplay = adjusted.crtc_hdisplay;
1329 	*vdisplay = adjusted.crtc_vdisplay;
1330 }
1331 EXPORT_SYMBOL(drm_mode_get_hv_timing);
1332 
1333 /**
1334  * drm_mode_set_crtcinfo - set CRTC modesetting timing parameters
1335  * @p: mode
1336  * @adjust_flags: a combination of adjustment flags
1337  *
1338  * Setup the CRTC modesetting timing parameters for @p, adjusting if necessary.
1339  *
1340  * - The CRTC_INTERLACE_HALVE_V flag can be used to halve vertical timings of
1341  *   interlaced modes.
1342  * - The CRTC_STEREO_DOUBLE flag can be used to compute the timings for
1343  *   buffers containing two eyes (only adjust the timings when needed, eg. for
1344  *   "frame packing" or "side by side full").
1345  * - The CRTC_NO_DBLSCAN and CRTC_NO_VSCAN flags request that adjustment *not*
1346  *   be performed for doublescan and vscan > 1 modes respectively.
1347  */
1348 void drm_mode_set_crtcinfo(struct drm_display_mode *p, int adjust_flags)
1349 {
1350 	if (!p)
1351 		return;
1352 
1353 	p->crtc_clock = p->clock;
1354 	p->crtc_hdisplay = p->hdisplay;
1355 	p->crtc_hsync_start = p->hsync_start;
1356 	p->crtc_hsync_end = p->hsync_end;
1357 	p->crtc_htotal = p->htotal;
1358 	p->crtc_hskew = p->hskew;
1359 	p->crtc_vdisplay = p->vdisplay;
1360 	p->crtc_vsync_start = p->vsync_start;
1361 	p->crtc_vsync_end = p->vsync_end;
1362 	p->crtc_vtotal = p->vtotal;
1363 
1364 	if (p->flags & DRM_MODE_FLAG_INTERLACE) {
1365 		if (adjust_flags & CRTC_INTERLACE_HALVE_V) {
1366 			p->crtc_vdisplay /= 2;
1367 			p->crtc_vsync_start /= 2;
1368 			p->crtc_vsync_end /= 2;
1369 			p->crtc_vtotal /= 2;
1370 		}
1371 	}
1372 
1373 	if (!(adjust_flags & CRTC_NO_DBLSCAN)) {
1374 		if (p->flags & DRM_MODE_FLAG_DBLSCAN) {
1375 			p->crtc_vdisplay *= 2;
1376 			p->crtc_vsync_start *= 2;
1377 			p->crtc_vsync_end *= 2;
1378 			p->crtc_vtotal *= 2;
1379 		}
1380 	}
1381 
1382 	if (!(adjust_flags & CRTC_NO_VSCAN)) {
1383 		if (p->vscan > 1) {
1384 			p->crtc_vdisplay *= p->vscan;
1385 			p->crtc_vsync_start *= p->vscan;
1386 			p->crtc_vsync_end *= p->vscan;
1387 			p->crtc_vtotal *= p->vscan;
1388 		}
1389 	}
1390 
1391 	if (adjust_flags & CRTC_STEREO_DOUBLE) {
1392 		unsigned int layout = p->flags & DRM_MODE_FLAG_3D_MASK;
1393 
1394 		switch (layout) {
1395 		case DRM_MODE_FLAG_3D_FRAME_PACKING:
1396 			p->crtc_clock *= 2;
1397 			p->crtc_vdisplay += p->crtc_vtotal;
1398 			p->crtc_vsync_start += p->crtc_vtotal;
1399 			p->crtc_vsync_end += p->crtc_vtotal;
1400 			p->crtc_vtotal += p->crtc_vtotal;
1401 			break;
1402 		}
1403 	}
1404 
1405 	p->crtc_vblank_start = min(p->crtc_vsync_start, p->crtc_vdisplay);
1406 	p->crtc_vblank_end = max(p->crtc_vsync_end, p->crtc_vtotal);
1407 	p->crtc_hblank_start = min(p->crtc_hsync_start, p->crtc_hdisplay);
1408 	p->crtc_hblank_end = max(p->crtc_hsync_end, p->crtc_htotal);
1409 }
1410 EXPORT_SYMBOL(drm_mode_set_crtcinfo);
1411 
1412 /**
1413  * drm_mode_copy - copy the mode
1414  * @dst: mode to overwrite
1415  * @src: mode to copy
1416  *
1417  * Copy an existing mode into another mode, preserving the
1418  * list head of the destination mode.
1419  */
1420 void drm_mode_copy(struct drm_display_mode *dst, const struct drm_display_mode *src)
1421 {
1422 	struct list_head head = dst->head;
1423 
1424 	*dst = *src;
1425 	dst->head = head;
1426 }
1427 EXPORT_SYMBOL(drm_mode_copy);
1428 
1429 /**
1430  * drm_mode_init - initialize the mode from another mode
1431  * @dst: mode to overwrite
1432  * @src: mode to copy
1433  *
1434  * Copy an existing mode into another mode, zeroing the
1435  * list head of the destination mode. Typically used
1436  * to guarantee the list head is not left with stack
1437  * garbage in on-stack modes.
1438  */
1439 void drm_mode_init(struct drm_display_mode *dst, const struct drm_display_mode *src)
1440 {
1441 	memset(dst, 0, sizeof(*dst));
1442 	drm_mode_copy(dst, src);
1443 }
1444 EXPORT_SYMBOL(drm_mode_init);
1445 
1446 /**
1447  * drm_mode_duplicate - allocate and duplicate an existing mode
1448  * @dev: drm_device to allocate the duplicated mode for
1449  * @mode: mode to duplicate
1450  *
1451  * Just allocate a new mode, copy the existing mode into it, and return
1452  * a pointer to it.  Used to create new instances of established modes.
1453  *
1454  * Returns:
1455  * Pointer to duplicated mode on success, NULL on error.
1456  */
1457 struct drm_display_mode *drm_mode_duplicate(struct drm_device *dev,
1458 					    const struct drm_display_mode *mode)
1459 {
1460 	struct drm_display_mode *nmode;
1461 
1462 	nmode = drm_mode_create(dev);
1463 	if (!nmode)
1464 		return NULL;
1465 
1466 	drm_mode_copy(nmode, mode);
1467 
1468 	return nmode;
1469 }
1470 EXPORT_SYMBOL(drm_mode_duplicate);
1471 
1472 static bool drm_mode_match_timings_vrr(const struct drm_display_mode *mode1,
1473 				       const struct drm_display_mode *mode2)
1474 {
1475 	int mode1_vsync_start_offset = mode1->vtotal - mode1->vsync_start;
1476 	int mode1_vsync_end_offset = mode1->vtotal - mode1->vsync_end;
1477 	int mode2_vsync_start_offset = mode2->vtotal - mode2->vsync_start;
1478 	int mode2_vsync_end_offset = mode2->vtotal - mode2->vsync_end;
1479 
1480 	return mode1->hdisplay == mode2->hdisplay &&
1481 		mode1->hsync_start == mode2->hsync_start &&
1482 		mode1->hsync_end == mode2->hsync_end &&
1483 		mode1->htotal == mode2->htotal &&
1484 		mode1->hskew == mode2->hskew &&
1485 		mode1->vdisplay == mode2->vdisplay &&
1486 		mode1_vsync_start_offset == mode2_vsync_start_offset &&
1487 		mode1_vsync_end_offset == mode2_vsync_end_offset &&
1488 		mode1->vscan == mode2->vscan;
1489 }
1490 
1491 static bool drm_mode_match_timings(const struct drm_display_mode *mode1,
1492 				   const struct drm_display_mode *mode2)
1493 {
1494 	return mode1->hdisplay == mode2->hdisplay &&
1495 		mode1->hsync_start == mode2->hsync_start &&
1496 		mode1->hsync_end == mode2->hsync_end &&
1497 		mode1->htotal == mode2->htotal &&
1498 		mode1->hskew == mode2->hskew &&
1499 		mode1->vdisplay == mode2->vdisplay &&
1500 		mode1->vsync_start == mode2->vsync_start &&
1501 		mode1->vsync_end == mode2->vsync_end &&
1502 		mode1->vtotal == mode2->vtotal &&
1503 		mode1->vscan == mode2->vscan;
1504 }
1505 
1506 static bool drm_mode_match_clock(const struct drm_display_mode *mode1,
1507 				  const struct drm_display_mode *mode2)
1508 {
1509 	/*
1510 	 * do clock check convert to PICOS
1511 	 * so fb modes get matched the same
1512 	 */
1513 	if (mode1->clock && mode2->clock)
1514 		return KHZ2PICOS(mode1->clock) == KHZ2PICOS(mode2->clock);
1515 	else
1516 		return mode1->clock == mode2->clock;
1517 }
1518 
1519 static bool drm_mode_match_flags(const struct drm_display_mode *mode1,
1520 				 const struct drm_display_mode *mode2)
1521 {
1522 	return (mode1->flags & ~DRM_MODE_FLAG_3D_MASK) ==
1523 		(mode2->flags & ~DRM_MODE_FLAG_3D_MASK);
1524 }
1525 
1526 static bool drm_mode_match_3d_flags(const struct drm_display_mode *mode1,
1527 				    const struct drm_display_mode *mode2)
1528 {
1529 	return (mode1->flags & DRM_MODE_FLAG_3D_MASK) ==
1530 		(mode2->flags & DRM_MODE_FLAG_3D_MASK);
1531 }
1532 
1533 static bool drm_mode_match_aspect_ratio(const struct drm_display_mode *mode1,
1534 					const struct drm_display_mode *mode2)
1535 {
1536 	return mode1->picture_aspect_ratio == mode2->picture_aspect_ratio;
1537 }
1538 
1539 /**
1540  * drm_mode_match - test modes for (partial) equality
1541  * @mode1: first mode
1542  * @mode2: second mode
1543  * @match_flags: which parts need to match (DRM_MODE_MATCH_*)
1544  *
1545  * Check to see if @mode1 and @mode2 are equivalent.
1546  *
1547  * Returns:
1548  * True if the modes are (partially) equal, false otherwise.
1549  */
1550 bool drm_mode_match(const struct drm_display_mode *mode1,
1551 		    const struct drm_display_mode *mode2,
1552 		    unsigned int match_flags)
1553 {
1554 	if (!mode1 && !mode2)
1555 		return true;
1556 
1557 	if (!mode1 || !mode2)
1558 		return false;
1559 
1560 	if (match_flags & DRM_MODE_MATCH_TIMINGS_VRR &&
1561 	    !drm_mode_match_timings_vrr(mode1, mode2))
1562 		return false;
1563 
1564 	if (match_flags & DRM_MODE_MATCH_TIMINGS &&
1565 	    !drm_mode_match_timings(mode1, mode2))
1566 		return false;
1567 
1568 	if (match_flags & DRM_MODE_MATCH_CLOCK &&
1569 	    !drm_mode_match_clock(mode1, mode2))
1570 		return false;
1571 
1572 	if (match_flags & DRM_MODE_MATCH_FLAGS &&
1573 	    !drm_mode_match_flags(mode1, mode2))
1574 		return false;
1575 
1576 	if (match_flags & DRM_MODE_MATCH_3D_FLAGS &&
1577 	    !drm_mode_match_3d_flags(mode1, mode2))
1578 		return false;
1579 
1580 	if (match_flags & DRM_MODE_MATCH_ASPECT_RATIO &&
1581 	    !drm_mode_match_aspect_ratio(mode1, mode2))
1582 		return false;
1583 
1584 	return true;
1585 }
1586 EXPORT_SYMBOL(drm_mode_match);
1587 
1588 /**
1589  * drm_mode_equal - test modes for equality
1590  * @mode1: first mode
1591  * @mode2: second mode
1592  *
1593  * Check to see if @mode1 and @mode2 are equivalent.
1594  *
1595  * Returns:
1596  * True if the modes are equal, false otherwise.
1597  */
1598 bool drm_mode_equal(const struct drm_display_mode *mode1,
1599 		    const struct drm_display_mode *mode2)
1600 {
1601 	return drm_mode_match(mode1, mode2,
1602 			      DRM_MODE_MATCH_TIMINGS |
1603 			      DRM_MODE_MATCH_CLOCK |
1604 			      DRM_MODE_MATCH_FLAGS |
1605 			      DRM_MODE_MATCH_3D_FLAGS|
1606 			      DRM_MODE_MATCH_ASPECT_RATIO);
1607 }
1608 EXPORT_SYMBOL(drm_mode_equal);
1609 
1610 /**
1611  * drm_mode_equal_no_clocks - test modes for equality
1612  * @mode1: first mode
1613  * @mode2: second mode
1614  *
1615  * Check to see if @mode1 and @mode2 are equivalent, but
1616  * don't check the pixel clocks.
1617  *
1618  * Returns:
1619  * True if the modes are equal, false otherwise.
1620  */
1621 bool drm_mode_equal_no_clocks(const struct drm_display_mode *mode1,
1622 			      const struct drm_display_mode *mode2)
1623 {
1624 	return drm_mode_match(mode1, mode2,
1625 			      DRM_MODE_MATCH_TIMINGS |
1626 			      DRM_MODE_MATCH_FLAGS |
1627 			      DRM_MODE_MATCH_3D_FLAGS);
1628 }
1629 EXPORT_SYMBOL(drm_mode_equal_no_clocks);
1630 
1631 /**
1632  * drm_mode_equal_no_clocks_no_stereo - test modes for equality
1633  * @mode1: first mode
1634  * @mode2: second mode
1635  *
1636  * Check to see if @mode1 and @mode2 are equivalent, but
1637  * don't check the pixel clocks nor the stereo layout.
1638  *
1639  * Returns:
1640  * True if the modes are equal, false otherwise.
1641  */
1642 bool drm_mode_equal_no_clocks_no_stereo(const struct drm_display_mode *mode1,
1643 					const struct drm_display_mode *mode2)
1644 {
1645 	return drm_mode_match(mode1, mode2,
1646 			      DRM_MODE_MATCH_TIMINGS |
1647 			      DRM_MODE_MATCH_FLAGS);
1648 }
1649 EXPORT_SYMBOL(drm_mode_equal_no_clocks_no_stereo);
1650 
1651 static enum drm_mode_status
1652 drm_mode_validate_basic(const struct drm_display_mode *mode)
1653 {
1654 	if (mode->type & ~DRM_MODE_TYPE_ALL)
1655 		return MODE_BAD;
1656 
1657 	if (mode->flags & ~DRM_MODE_FLAG_ALL)
1658 		return MODE_BAD;
1659 
1660 	if ((mode->flags & DRM_MODE_FLAG_3D_MASK) > DRM_MODE_FLAG_3D_MAX)
1661 		return MODE_BAD;
1662 
1663 	if (mode->clock == 0)
1664 		return MODE_CLOCK_LOW;
1665 
1666 	if (mode->hdisplay == 0 ||
1667 	    mode->hsync_start < mode->hdisplay ||
1668 	    mode->hsync_end < mode->hsync_start ||
1669 	    mode->htotal < mode->hsync_end)
1670 		return MODE_H_ILLEGAL;
1671 
1672 	if (mode->vdisplay == 0 ||
1673 	    mode->vsync_start < mode->vdisplay ||
1674 	    mode->vsync_end < mode->vsync_start ||
1675 	    mode->vtotal < mode->vsync_end)
1676 		return MODE_V_ILLEGAL;
1677 
1678 	return MODE_OK;
1679 }
1680 
1681 /**
1682  * drm_mode_validate_driver - make sure the mode is somewhat sane
1683  * @dev: drm device
1684  * @mode: mode to check
1685  *
1686  * First do basic validation on the mode, and then allow the driver
1687  * to check for device/driver specific limitations via the optional
1688  * &drm_mode_config_helper_funcs.mode_valid hook.
1689  *
1690  * Returns:
1691  * The mode status
1692  */
1693 enum drm_mode_status
1694 drm_mode_validate_driver(struct drm_device *dev,
1695 			const struct drm_display_mode *mode)
1696 {
1697 	enum drm_mode_status status;
1698 
1699 	status = drm_mode_validate_basic(mode);
1700 	if (status != MODE_OK)
1701 		return status;
1702 
1703 	if (dev->mode_config.funcs->mode_valid)
1704 		return dev->mode_config.funcs->mode_valid(dev, mode);
1705 	else
1706 		return MODE_OK;
1707 }
1708 EXPORT_SYMBOL(drm_mode_validate_driver);
1709 
1710 /**
1711  * drm_mode_validate_size - make sure modes adhere to size constraints
1712  * @mode: mode to check
1713  * @maxX: maximum width
1714  * @maxY: maximum height
1715  *
1716  * This function is a helper which can be used to validate modes against size
1717  * limitations of the DRM device/connector. If a mode is too big its status
1718  * member is updated with the appropriate validation failure code. The list
1719  * itself is not changed.
1720  *
1721  * Returns:
1722  * The mode status
1723  */
1724 enum drm_mode_status
1725 drm_mode_validate_size(const struct drm_display_mode *mode,
1726 		       int maxX, int maxY)
1727 {
1728 	if (maxX > 0 && mode->hdisplay > maxX)
1729 		return MODE_VIRTUAL_X;
1730 
1731 	if (maxY > 0 && mode->vdisplay > maxY)
1732 		return MODE_VIRTUAL_Y;
1733 
1734 	return MODE_OK;
1735 }
1736 EXPORT_SYMBOL(drm_mode_validate_size);
1737 
1738 /**
1739  * drm_mode_validate_ycbcr420 - add 'ycbcr420-only' modes only when allowed
1740  * @mode: mode to check
1741  * @connector: drm connector under action
1742  *
1743  * This function is a helper which can be used to filter out any YCBCR420
1744  * only mode, when the source doesn't support it.
1745  *
1746  * Returns:
1747  * The mode status
1748  */
1749 enum drm_mode_status
1750 drm_mode_validate_ycbcr420(const struct drm_display_mode *mode,
1751 			   struct drm_connector *connector)
1752 {
1753 	if (!connector->ycbcr_420_allowed &&
1754 	    drm_mode_is_420_only(&connector->display_info, mode))
1755 		return MODE_NO_420;
1756 
1757 	return MODE_OK;
1758 }
1759 EXPORT_SYMBOL(drm_mode_validate_ycbcr420);
1760 
1761 #define MODE_STATUS(status) [MODE_ ## status + 3] = #status
1762 
1763 static const char * const drm_mode_status_names[] = {
1764 	MODE_STATUS(OK),
1765 	MODE_STATUS(HSYNC),
1766 	MODE_STATUS(VSYNC),
1767 	MODE_STATUS(H_ILLEGAL),
1768 	MODE_STATUS(V_ILLEGAL),
1769 	MODE_STATUS(BAD_WIDTH),
1770 	MODE_STATUS(NOMODE),
1771 	MODE_STATUS(NO_INTERLACE),
1772 	MODE_STATUS(NO_DBLESCAN),
1773 	MODE_STATUS(NO_VSCAN),
1774 	MODE_STATUS(MEM),
1775 	MODE_STATUS(VIRTUAL_X),
1776 	MODE_STATUS(VIRTUAL_Y),
1777 	MODE_STATUS(MEM_VIRT),
1778 	MODE_STATUS(NOCLOCK),
1779 	MODE_STATUS(CLOCK_HIGH),
1780 	MODE_STATUS(CLOCK_LOW),
1781 	MODE_STATUS(CLOCK_RANGE),
1782 	MODE_STATUS(BAD_HVALUE),
1783 	MODE_STATUS(BAD_VVALUE),
1784 	MODE_STATUS(BAD_VSCAN),
1785 	MODE_STATUS(HSYNC_NARROW),
1786 	MODE_STATUS(HSYNC_WIDE),
1787 	MODE_STATUS(HBLANK_NARROW),
1788 	MODE_STATUS(HBLANK_WIDE),
1789 	MODE_STATUS(VSYNC_NARROW),
1790 	MODE_STATUS(VSYNC_WIDE),
1791 	MODE_STATUS(VBLANK_NARROW),
1792 	MODE_STATUS(VBLANK_WIDE),
1793 	MODE_STATUS(PANEL),
1794 	MODE_STATUS(INTERLACE_WIDTH),
1795 	MODE_STATUS(ONE_WIDTH),
1796 	MODE_STATUS(ONE_HEIGHT),
1797 	MODE_STATUS(ONE_SIZE),
1798 	MODE_STATUS(NO_REDUCED),
1799 	MODE_STATUS(NO_STEREO),
1800 	MODE_STATUS(NO_420),
1801 	MODE_STATUS(STALE),
1802 	MODE_STATUS(BAD),
1803 	MODE_STATUS(ERROR),
1804 };
1805 
1806 #undef MODE_STATUS
1807 
1808 const char *drm_get_mode_status_name(enum drm_mode_status status)
1809 {
1810 	int index = status + 3;
1811 
1812 	if (WARN_ON(index < 0 || index >= ARRAY_SIZE(drm_mode_status_names)))
1813 		return "";
1814 
1815 	return drm_mode_status_names[index];
1816 }
1817 
1818 /**
1819  * drm_mode_prune_invalid - remove invalid modes from mode list
1820  * @dev: DRM device
1821  * @mode_list: list of modes to check
1822  * @verbose: be verbose about it
1823  *
1824  * This helper function can be used to prune a display mode list after
1825  * validation has been completed. All modes whose status is not MODE_OK will be
1826  * removed from the list, and if @verbose the status code and mode name is also
1827  * printed to dmesg.
1828  */
1829 void drm_mode_prune_invalid(struct drm_device *dev,
1830 			    struct list_head *mode_list, bool verbose)
1831 {
1832 	struct drm_display_mode *mode, *t;
1833 
1834 	list_for_each_entry_safe(mode, t, mode_list, head) {
1835 		if (mode->status != MODE_OK) {
1836 			list_del(&mode->head);
1837 			if (mode->type & DRM_MODE_TYPE_USERDEF) {
1838 				drm_warn(dev, "User-defined mode not supported: "
1839 					 DRM_MODE_FMT "\n", DRM_MODE_ARG(mode));
1840 			}
1841 			if (verbose) {
1842 				drm_dbg_kms(dev, "Rejected mode: " DRM_MODE_FMT " (%s)\n",
1843 					    DRM_MODE_ARG(mode), drm_get_mode_status_name(mode->status));
1844 			}
1845 			drm_mode_destroy(dev, mode);
1846 		}
1847 	}
1848 }
1849 EXPORT_SYMBOL(drm_mode_prune_invalid);
1850 
1851 /**
1852  * drm_mode_compare - compare modes for favorability
1853  * @priv: unused
1854  * @lh_a: list_head for first mode
1855  * @lh_b: list_head for second mode
1856  *
1857  * Compare two modes, given by @lh_a and @lh_b, returning a value indicating
1858  * which is better.
1859  *
1860  * Returns:
1861  * Negative if @lh_a is better than @lh_b, zero if they're equivalent, or
1862  * positive if @lh_b is better than @lh_a.
1863  */
1864 static int drm_mode_compare(void *priv, const struct list_head *lh_a,
1865 			    const struct list_head *lh_b)
1866 {
1867 	struct drm_display_mode *a = list_entry(lh_a, struct drm_display_mode, head);
1868 	struct drm_display_mode *b = list_entry(lh_b, struct drm_display_mode, head);
1869 	int diff;
1870 
1871 	diff = ((b->type & DRM_MODE_TYPE_PREFERRED) != 0) -
1872 		((a->type & DRM_MODE_TYPE_PREFERRED) != 0);
1873 	if (diff)
1874 		return diff;
1875 	diff = b->hdisplay * b->vdisplay - a->hdisplay * a->vdisplay;
1876 	if (diff)
1877 		return diff;
1878 
1879 	diff = drm_mode_vrefresh(b) - drm_mode_vrefresh(a);
1880 	if (diff)
1881 		return diff;
1882 
1883 	diff = b->clock - a->clock;
1884 	return diff;
1885 }
1886 
1887 /**
1888  * drm_mode_sort - sort mode list
1889  * @mode_list: list of drm_display_mode structures to sort
1890  *
1891  * Sort @mode_list by favorability, moving good modes to the head of the list.
1892  */
1893 void drm_mode_sort(struct list_head *mode_list)
1894 {
1895 	list_sort(NULL, mode_list, drm_mode_compare);
1896 }
1897 EXPORT_SYMBOL(drm_mode_sort);
1898 
1899 /**
1900  * drm_connector_list_update - update the mode list for the connector
1901  * @connector: the connector to update
1902  *
1903  * This moves the modes from the @connector probed_modes list
1904  * to the actual mode list. It compares the probed mode against the current
1905  * list and only adds different/new modes.
1906  *
1907  * This is just a helper functions doesn't validate any modes itself and also
1908  * doesn't prune any invalid modes. Callers need to do that themselves.
1909  */
1910 void drm_connector_list_update(struct drm_connector *connector)
1911 {
1912 	struct drm_display_mode *pmode, *pt;
1913 
1914 	WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex));
1915 
1916 	list_for_each_entry_safe(pmode, pt, &connector->probed_modes, head) {
1917 		struct drm_display_mode *mode;
1918 		bool found_it = false;
1919 
1920 		/* go through current modes checking for the new probed mode */
1921 		list_for_each_entry(mode, &connector->modes, head) {
1922 			if (!drm_mode_equal(pmode, mode))
1923 				continue;
1924 
1925 			found_it = true;
1926 
1927 			/*
1928 			 * If the old matching mode is stale (ie. left over
1929 			 * from a previous probe) just replace it outright.
1930 			 * Otherwise just merge the type bits between all
1931 			 * equal probed modes.
1932 			 *
1933 			 * If two probed modes are considered equal, pick the
1934 			 * actual timings from the one that's marked as
1935 			 * preferred (in case the match isn't 100%). If
1936 			 * multiple or zero preferred modes are present, favor
1937 			 * the mode added to the probed_modes list first.
1938 			 */
1939 			if (mode->status == MODE_STALE) {
1940 				drm_mode_copy(mode, pmode);
1941 			} else if ((mode->type & DRM_MODE_TYPE_PREFERRED) == 0 &&
1942 				   (pmode->type & DRM_MODE_TYPE_PREFERRED) != 0) {
1943 				pmode->type |= mode->type;
1944 				drm_mode_copy(mode, pmode);
1945 			} else {
1946 				mode->type |= pmode->type;
1947 			}
1948 
1949 			list_del(&pmode->head);
1950 			drm_mode_destroy(connector->dev, pmode);
1951 			break;
1952 		}
1953 
1954 		if (!found_it) {
1955 			list_move_tail(&pmode->head, &connector->modes);
1956 		}
1957 	}
1958 }
1959 EXPORT_SYMBOL(drm_connector_list_update);
1960 
1961 static int drm_mode_parse_cmdline_bpp(const char *str, char **end_ptr,
1962 				      struct drm_cmdline_mode *mode)
1963 {
1964 	unsigned int bpp;
1965 
1966 	if (str[0] != '-')
1967 		return -EINVAL;
1968 
1969 	str++;
1970 	bpp = simple_strtol(str, end_ptr, 10);
1971 	if (*end_ptr == str)
1972 		return -EINVAL;
1973 
1974 	mode->bpp = bpp;
1975 	mode->bpp_specified = true;
1976 
1977 	return 0;
1978 }
1979 
1980 static int drm_mode_parse_cmdline_refresh(const char *str, char **end_ptr,
1981 					  struct drm_cmdline_mode *mode)
1982 {
1983 	unsigned int refresh;
1984 
1985 	if (str[0] != '@')
1986 		return -EINVAL;
1987 
1988 	str++;
1989 	refresh = simple_strtol(str, end_ptr, 10);
1990 	if (*end_ptr == str)
1991 		return -EINVAL;
1992 
1993 	mode->refresh = refresh;
1994 	mode->refresh_specified = true;
1995 
1996 	return 0;
1997 }
1998 
1999 static int drm_mode_parse_cmdline_extra(const char *str, int length,
2000 					bool freestanding,
2001 					const struct drm_connector *connector,
2002 					struct drm_cmdline_mode *mode)
2003 {
2004 	int i;
2005 
2006 	for (i = 0; i < length; i++) {
2007 		switch (str[i]) {
2008 		case 'i':
2009 			if (freestanding)
2010 				return -EINVAL;
2011 
2012 			mode->interlace = true;
2013 			break;
2014 		case 'm':
2015 			if (freestanding)
2016 				return -EINVAL;
2017 
2018 			mode->margins = true;
2019 			break;
2020 		case 'D':
2021 			if (mode->force != DRM_FORCE_UNSPECIFIED)
2022 				return -EINVAL;
2023 
2024 			if ((connector->connector_type != DRM_MODE_CONNECTOR_DVII) &&
2025 			    (connector->connector_type != DRM_MODE_CONNECTOR_HDMIB))
2026 				mode->force = DRM_FORCE_ON;
2027 			else
2028 				mode->force = DRM_FORCE_ON_DIGITAL;
2029 			break;
2030 		case 'd':
2031 			if (mode->force != DRM_FORCE_UNSPECIFIED)
2032 				return -EINVAL;
2033 
2034 			mode->force = DRM_FORCE_OFF;
2035 			break;
2036 		case 'e':
2037 			if (mode->force != DRM_FORCE_UNSPECIFIED)
2038 				return -EINVAL;
2039 
2040 			mode->force = DRM_FORCE_ON;
2041 			break;
2042 		default:
2043 			return -EINVAL;
2044 		}
2045 	}
2046 
2047 	return 0;
2048 }
2049 
2050 static int drm_mode_parse_cmdline_res_mode(const char *str, unsigned int length,
2051 					   bool extras,
2052 					   const struct drm_connector *connector,
2053 					   struct drm_cmdline_mode *mode)
2054 {
2055 	const char *str_start = str;
2056 	bool rb = false, cvt = false;
2057 	int xres = 0, yres = 0;
2058 	int remaining, i;
2059 	char *end_ptr;
2060 
2061 	xres = simple_strtol(str, &end_ptr, 10);
2062 	if (end_ptr == str)
2063 		return -EINVAL;
2064 
2065 	if (end_ptr[0] != 'x')
2066 		return -EINVAL;
2067 	end_ptr++;
2068 
2069 	str = end_ptr;
2070 	yres = simple_strtol(str, &end_ptr, 10);
2071 	if (end_ptr == str)
2072 		return -EINVAL;
2073 
2074 	remaining = length - (end_ptr - str_start);
2075 	if (remaining < 0)
2076 		return -EINVAL;
2077 
2078 	for (i = 0; i < remaining; i++) {
2079 		switch (end_ptr[i]) {
2080 		case 'M':
2081 			cvt = true;
2082 			break;
2083 		case 'R':
2084 			rb = true;
2085 			break;
2086 		default:
2087 			/*
2088 			 * Try to pass that to our extras parsing
2089 			 * function to handle the case where the
2090 			 * extras are directly after the resolution
2091 			 */
2092 			if (extras) {
2093 				int ret = drm_mode_parse_cmdline_extra(end_ptr + i,
2094 								       1,
2095 								       false,
2096 								       connector,
2097 								       mode);
2098 				if (ret)
2099 					return ret;
2100 			} else {
2101 				return -EINVAL;
2102 			}
2103 		}
2104 	}
2105 
2106 	mode->xres = xres;
2107 	mode->yres = yres;
2108 	mode->cvt = cvt;
2109 	mode->rb = rb;
2110 
2111 	return 0;
2112 }
2113 
2114 static int drm_mode_parse_cmdline_int(const char *delim, unsigned int *int_ret)
2115 {
2116 	const char *value;
2117 	char *endp;
2118 
2119 	/*
2120 	 * delim must point to the '=', otherwise it is a syntax error and
2121 	 * if delim points to the terminating zero, then delim + 1 will point
2122 	 * past the end of the string.
2123 	 */
2124 	if (*delim != '=')
2125 		return -EINVAL;
2126 
2127 	value = delim + 1;
2128 	*int_ret = simple_strtol(value, &endp, 10);
2129 
2130 	/* Make sure we have parsed something */
2131 	if (endp == value)
2132 		return -EINVAL;
2133 
2134 	return 0;
2135 }
2136 
2137 static int drm_mode_parse_panel_orientation(const char *delim,
2138 					    struct drm_cmdline_mode *mode)
2139 {
2140 	const char *value;
2141 
2142 	if (*delim != '=')
2143 		return -EINVAL;
2144 
2145 	value = delim + 1;
2146 	delim = strchr(value, ',');
2147 	if (!delim)
2148 		delim = value + strlen(value);
2149 
2150 	if (!strncmp(value, "normal", delim - value))
2151 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_NORMAL;
2152 	else if (!strncmp(value, "upside_down", delim - value))
2153 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_BOTTOM_UP;
2154 	else if (!strncmp(value, "left_side_up", delim - value))
2155 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_LEFT_UP;
2156 	else if (!strncmp(value, "right_side_up", delim - value))
2157 		mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_RIGHT_UP;
2158 	else
2159 		return -EINVAL;
2160 
2161 	return 0;
2162 }
2163 
2164 static int drm_mode_parse_tv_mode(const char *delim,
2165 				  struct drm_cmdline_mode *mode)
2166 {
2167 	const char *value;
2168 	int ret;
2169 
2170 	if (*delim != '=')
2171 		return -EINVAL;
2172 
2173 	value = delim + 1;
2174 	delim = strchr(value, ',');
2175 	if (!delim)
2176 		delim = value + strlen(value);
2177 
2178 	ret = drm_get_tv_mode_from_name(value, delim - value);
2179 	if (ret < 0)
2180 		return ret;
2181 
2182 	mode->tv_mode_specified = true;
2183 	mode->tv_mode = ret;
2184 
2185 	return 0;
2186 }
2187 
2188 static int drm_mode_parse_cmdline_options(const char *str,
2189 					  bool freestanding,
2190 					  const struct drm_connector *connector,
2191 					  struct drm_cmdline_mode *mode)
2192 {
2193 	unsigned int deg, margin, rotation = 0;
2194 	const char *delim, *option, *sep;
2195 
2196 	option = str;
2197 	do {
2198 		delim = strchr(option, '=');
2199 		if (!delim) {
2200 			delim = strchr(option, ',');
2201 
2202 			if (!delim)
2203 				delim = option + strlen(option);
2204 		}
2205 
2206 		if (!strncmp(option, "rotate", delim - option)) {
2207 			if (drm_mode_parse_cmdline_int(delim, &deg))
2208 				return -EINVAL;
2209 
2210 			switch (deg) {
2211 			case 0:
2212 				rotation |= DRM_MODE_ROTATE_0;
2213 				break;
2214 
2215 			case 90:
2216 				rotation |= DRM_MODE_ROTATE_90;
2217 				break;
2218 
2219 			case 180:
2220 				rotation |= DRM_MODE_ROTATE_180;
2221 				break;
2222 
2223 			case 270:
2224 				rotation |= DRM_MODE_ROTATE_270;
2225 				break;
2226 
2227 			default:
2228 				return -EINVAL;
2229 			}
2230 		} else if (!strncmp(option, "reflect_x", delim - option)) {
2231 			rotation |= DRM_MODE_REFLECT_X;
2232 		} else if (!strncmp(option, "reflect_y", delim - option)) {
2233 			rotation |= DRM_MODE_REFLECT_Y;
2234 		} else if (!strncmp(option, "margin_right", delim - option)) {
2235 			if (drm_mode_parse_cmdline_int(delim, &margin))
2236 				return -EINVAL;
2237 
2238 			mode->tv_margins.right = margin;
2239 		} else if (!strncmp(option, "margin_left", delim - option)) {
2240 			if (drm_mode_parse_cmdline_int(delim, &margin))
2241 				return -EINVAL;
2242 
2243 			mode->tv_margins.left = margin;
2244 		} else if (!strncmp(option, "margin_top", delim - option)) {
2245 			if (drm_mode_parse_cmdline_int(delim, &margin))
2246 				return -EINVAL;
2247 
2248 			mode->tv_margins.top = margin;
2249 		} else if (!strncmp(option, "margin_bottom", delim - option)) {
2250 			if (drm_mode_parse_cmdline_int(delim, &margin))
2251 				return -EINVAL;
2252 
2253 			mode->tv_margins.bottom = margin;
2254 		} else if (!strncmp(option, "panel_orientation", delim - option)) {
2255 			if (drm_mode_parse_panel_orientation(delim, mode))
2256 				return -EINVAL;
2257 		} else if (!strncmp(option, "tv_mode", delim - option)) {
2258 			if (drm_mode_parse_tv_mode(delim, mode))
2259 				return -EINVAL;
2260 		} else {
2261 			return -EINVAL;
2262 		}
2263 		sep = strchr(delim, ',');
2264 		option = sep + 1;
2265 	} while (sep);
2266 
2267 	if (rotation && freestanding)
2268 		return -EINVAL;
2269 
2270 	if (!(rotation & DRM_MODE_ROTATE_MASK))
2271 		rotation |= DRM_MODE_ROTATE_0;
2272 
2273 	/* Make sure there is exactly one rotation defined */
2274 	if (!is_power_of_2(rotation & DRM_MODE_ROTATE_MASK))
2275 		return -EINVAL;
2276 
2277 	mode->rotation_reflection = rotation;
2278 
2279 	return 0;
2280 }
2281 
2282 struct drm_named_mode {
2283 	const char *name;
2284 	unsigned int pixel_clock_khz;
2285 	unsigned int xres;
2286 	unsigned int yres;
2287 	unsigned int flags;
2288 	unsigned int tv_mode;
2289 };
2290 
2291 #define NAMED_MODE(_name, _pclk, _x, _y, _flags, _mode)	\
2292 	{						\
2293 		.name = _name,				\
2294 		.pixel_clock_khz = _pclk,		\
2295 		.xres = _x,				\
2296 		.yres = _y,				\
2297 		.flags = _flags,			\
2298 		.tv_mode = _mode,			\
2299 	}
2300 
2301 static const struct drm_named_mode drm_named_modes[] = {
2302 	NAMED_MODE("NTSC", 13500, 720, 480, DRM_MODE_FLAG_INTERLACE, DRM_MODE_TV_MODE_NTSC),
2303 	NAMED_MODE("NTSC-J", 13500, 720, 480, DRM_MODE_FLAG_INTERLACE, DRM_MODE_TV_MODE_NTSC_J),
2304 	NAMED_MODE("PAL", 13500, 720, 576, DRM_MODE_FLAG_INTERLACE, DRM_MODE_TV_MODE_PAL),
2305 	NAMED_MODE("PAL-M", 13500, 720, 480, DRM_MODE_FLAG_INTERLACE, DRM_MODE_TV_MODE_PAL_M),
2306 };
2307 
2308 static int drm_mode_parse_cmdline_named_mode(const char *name,
2309 					     unsigned int name_end,
2310 					     struct drm_cmdline_mode *cmdline_mode)
2311 {
2312 	unsigned int i;
2313 
2314 	if (!name_end)
2315 		return 0;
2316 
2317 	/* If the name starts with a digit, it's not a named mode */
2318 	if (isdigit(name[0]))
2319 		return 0;
2320 
2321 	/*
2322 	 * If there's an equal sign in the name, the command-line
2323 	 * contains only an option and no mode.
2324 	 */
2325 	if (strnchr(name, name_end, '='))
2326 		return 0;
2327 
2328 	/* The connection status extras can be set without a mode. */
2329 	if (name_end == 1 &&
2330 	    (name[0] == 'd' || name[0] == 'D' || name[0] == 'e'))
2331 		return 0;
2332 
2333 	/*
2334 	 * We're sure we're a named mode at this point, iterate over the
2335 	 * list of modes we're aware of.
2336 	 */
2337 	for (i = 0; i < ARRAY_SIZE(drm_named_modes); i++) {
2338 		const struct drm_named_mode *mode = &drm_named_modes[i];
2339 		int ret;
2340 
2341 		ret = str_has_prefix(name, mode->name);
2342 		if (ret != name_end)
2343 			continue;
2344 
2345 		strscpy(cmdline_mode->name, mode->name, sizeof(cmdline_mode->name));
2346 		cmdline_mode->pixel_clock = mode->pixel_clock_khz;
2347 		cmdline_mode->xres = mode->xres;
2348 		cmdline_mode->yres = mode->yres;
2349 		cmdline_mode->interlace = !!(mode->flags & DRM_MODE_FLAG_INTERLACE);
2350 		cmdline_mode->tv_mode = mode->tv_mode;
2351 		cmdline_mode->tv_mode_specified = true;
2352 		cmdline_mode->specified = true;
2353 
2354 		return 1;
2355 	}
2356 
2357 	return -EINVAL;
2358 }
2359 
2360 /**
2361  * drm_mode_parse_command_line_for_connector - parse command line modeline for connector
2362  * @mode_option: optional per connector mode option
2363  * @connector: connector to parse modeline for
2364  * @mode: preallocated drm_cmdline_mode structure to fill out
2365  *
2366  * This parses @mode_option command line modeline for modes and options to
2367  * configure the connector.
2368  *
2369  * This uses the same parameters as the fb modedb.c, except for an extra
2370  * force-enable, force-enable-digital and force-disable bit at the end::
2371  *
2372  *	<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m][eDd]
2373  *
2374  * Additionals options can be provided following the mode, using a comma to
2375  * separate each option. Valid options can be found in
2376  * Documentation/fb/modedb.rst.
2377  *
2378  * The intermediate drm_cmdline_mode structure is required to store additional
2379  * options from the command line modline like the force-enable/disable flag.
2380  *
2381  * Returns:
2382  * True if a valid modeline has been parsed, false otherwise.
2383  */
2384 bool drm_mode_parse_command_line_for_connector(const char *mode_option,
2385 					       const struct drm_connector *connector,
2386 					       struct drm_cmdline_mode *mode)
2387 {
2388 	const char *name;
2389 	bool freestanding = false, parse_extras = false;
2390 	unsigned int bpp_off = 0, refresh_off = 0, options_off = 0;
2391 	unsigned int mode_end = 0;
2392 	const char *bpp_ptr = NULL, *refresh_ptr = NULL, *extra_ptr = NULL;
2393 	const char *options_ptr = NULL;
2394 	char *bpp_end_ptr = NULL, *refresh_end_ptr = NULL;
2395 	int len, ret;
2396 
2397 	memset(mode, 0, sizeof(*mode));
2398 	mode->panel_orientation = DRM_MODE_PANEL_ORIENTATION_UNKNOWN;
2399 
2400 	if (!mode_option)
2401 		return false;
2402 
2403 	name = mode_option;
2404 
2405 	/* Locate the start of named options */
2406 	options_ptr = strchr(name, ',');
2407 	if (options_ptr)
2408 		options_off = options_ptr - name;
2409 	else
2410 		options_off = strlen(name);
2411 
2412 	/* Try to locate the bpp and refresh specifiers, if any */
2413 	bpp_ptr = strnchr(name, options_off, '-');
2414 	while (bpp_ptr && !isdigit(bpp_ptr[1]))
2415 		bpp_ptr = strnchr(bpp_ptr + 1, options_off, '-');
2416 	if (bpp_ptr)
2417 		bpp_off = bpp_ptr - name;
2418 
2419 	refresh_ptr = strnchr(name, options_off, '@');
2420 	if (refresh_ptr)
2421 		refresh_off = refresh_ptr - name;
2422 
2423 	/* Locate the end of the name / resolution, and parse it */
2424 	if (bpp_ptr) {
2425 		mode_end = bpp_off;
2426 	} else if (refresh_ptr) {
2427 		mode_end = refresh_off;
2428 	} else if (options_ptr) {
2429 		mode_end = options_off;
2430 		parse_extras = true;
2431 	} else {
2432 		mode_end = strlen(name);
2433 		parse_extras = true;
2434 	}
2435 
2436 	if (!mode_end)
2437 		return false;
2438 
2439 	ret = drm_mode_parse_cmdline_named_mode(name, mode_end, mode);
2440 	if (ret < 0)
2441 		return false;
2442 
2443 	/*
2444 	 * Having a mode that starts by a letter (and thus is named) and
2445 	 * an at-sign (used to specify a refresh rate) is disallowed.
2446 	 */
2447 	if (ret && refresh_ptr)
2448 		return false;
2449 
2450 	/* No named mode? Check for a normal mode argument, e.g. 1024x768 */
2451 	if (!mode->specified && isdigit(name[0])) {
2452 		ret = drm_mode_parse_cmdline_res_mode(name, mode_end,
2453 						      parse_extras,
2454 						      connector,
2455 						      mode);
2456 		if (ret)
2457 			return false;
2458 
2459 		mode->specified = true;
2460 	}
2461 
2462 	/* No mode? Check for freestanding extras and/or options */
2463 	if (!mode->specified) {
2464 		unsigned int len = strlen(mode_option);
2465 
2466 		if (bpp_ptr || refresh_ptr)
2467 			return false; /* syntax error */
2468 
2469 		if (len == 1 || (len >= 2 && mode_option[1] == ','))
2470 			extra_ptr = mode_option;
2471 		else
2472 			options_ptr = mode_option - 1;
2473 
2474 		freestanding = true;
2475 	}
2476 
2477 	if (bpp_ptr) {
2478 		ret = drm_mode_parse_cmdline_bpp(bpp_ptr, &bpp_end_ptr, mode);
2479 		if (ret)
2480 			return false;
2481 
2482 		mode->bpp_specified = true;
2483 	}
2484 
2485 	if (refresh_ptr) {
2486 		ret = drm_mode_parse_cmdline_refresh(refresh_ptr,
2487 						     &refresh_end_ptr, mode);
2488 		if (ret)
2489 			return false;
2490 
2491 		mode->refresh_specified = true;
2492 	}
2493 
2494 	/*
2495 	 * Locate the end of the bpp / refresh, and parse the extras
2496 	 * if relevant
2497 	 */
2498 	if (bpp_ptr && refresh_ptr)
2499 		extra_ptr = max(bpp_end_ptr, refresh_end_ptr);
2500 	else if (bpp_ptr)
2501 		extra_ptr = bpp_end_ptr;
2502 	else if (refresh_ptr)
2503 		extra_ptr = refresh_end_ptr;
2504 
2505 	if (extra_ptr) {
2506 		if (options_ptr)
2507 			len = options_ptr - extra_ptr;
2508 		else
2509 			len = strlen(extra_ptr);
2510 
2511 		ret = drm_mode_parse_cmdline_extra(extra_ptr, len, freestanding,
2512 						   connector, mode);
2513 		if (ret)
2514 			return false;
2515 	}
2516 
2517 	if (options_ptr) {
2518 		ret = drm_mode_parse_cmdline_options(options_ptr + 1,
2519 						     freestanding,
2520 						     connector, mode);
2521 		if (ret)
2522 			return false;
2523 	}
2524 
2525 	return true;
2526 }
2527 EXPORT_SYMBOL(drm_mode_parse_command_line_for_connector);
2528 
2529 static struct drm_display_mode *drm_named_mode(struct drm_device *dev,
2530 					       struct drm_cmdline_mode *cmd)
2531 {
2532 	unsigned int i;
2533 
2534 	for (i = 0; i < ARRAY_SIZE(drm_named_modes); i++) {
2535 		const struct drm_named_mode *named_mode = &drm_named_modes[i];
2536 
2537 		if (strcmp(cmd->name, named_mode->name))
2538 			continue;
2539 
2540 		if (!cmd->tv_mode_specified)
2541 			continue;
2542 
2543 		return drm_analog_tv_mode(dev,
2544 					  named_mode->tv_mode,
2545 					  named_mode->pixel_clock_khz * 1000,
2546 					  named_mode->xres,
2547 					  named_mode->yres,
2548 					  named_mode->flags & DRM_MODE_FLAG_INTERLACE);
2549 	}
2550 
2551 	return NULL;
2552 }
2553 
2554 /**
2555  * drm_mode_create_from_cmdline_mode - convert a command line modeline into a DRM display mode
2556  * @dev: DRM device to create the new mode for
2557  * @cmd: input command line modeline
2558  *
2559  * Returns:
2560  * Pointer to converted mode on success, NULL on error.
2561  */
2562 struct drm_display_mode *
2563 drm_mode_create_from_cmdline_mode(struct drm_device *dev,
2564 				  struct drm_cmdline_mode *cmd)
2565 {
2566 	struct drm_display_mode *mode;
2567 
2568 	if (cmd->xres == 0 || cmd->yres == 0)
2569 		return NULL;
2570 
2571 	if (strlen(cmd->name))
2572 		mode = drm_named_mode(dev, cmd);
2573 	else if (cmd->cvt)
2574 		mode = drm_cvt_mode(dev,
2575 				    cmd->xres, cmd->yres,
2576 				    cmd->refresh_specified ? cmd->refresh : 60,
2577 				    cmd->rb, cmd->interlace,
2578 				    cmd->margins);
2579 	else
2580 		mode = drm_gtf_mode(dev,
2581 				    cmd->xres, cmd->yres,
2582 				    cmd->refresh_specified ? cmd->refresh : 60,
2583 				    cmd->interlace,
2584 				    cmd->margins);
2585 	if (!mode)
2586 		return NULL;
2587 
2588 	mode->type |= DRM_MODE_TYPE_USERDEF;
2589 	/* fix up 1368x768: GFT/CVT can't express 1366 width due to alignment */
2590 	if (cmd->xres == 1366)
2591 		drm_mode_fixup_1366x768(mode);
2592 	drm_mode_set_crtcinfo(mode, CRTC_INTERLACE_HALVE_V);
2593 	return mode;
2594 }
2595 EXPORT_SYMBOL(drm_mode_create_from_cmdline_mode);
2596 
2597 /**
2598  * drm_mode_convert_to_umode - convert a drm_display_mode into a modeinfo
2599  * @out: drm_mode_modeinfo struct to return to the user
2600  * @in: drm_display_mode to use
2601  *
2602  * Convert a drm_display_mode into a drm_mode_modeinfo structure to return to
2603  * the user.
2604  */
2605 void drm_mode_convert_to_umode(struct drm_mode_modeinfo *out,
2606 			       const struct drm_display_mode *in)
2607 {
2608 	out->clock = in->clock;
2609 	out->hdisplay = in->hdisplay;
2610 	out->hsync_start = in->hsync_start;
2611 	out->hsync_end = in->hsync_end;
2612 	out->htotal = in->htotal;
2613 	out->hskew = in->hskew;
2614 	out->vdisplay = in->vdisplay;
2615 	out->vsync_start = in->vsync_start;
2616 	out->vsync_end = in->vsync_end;
2617 	out->vtotal = in->vtotal;
2618 	out->vscan = in->vscan;
2619 	out->vrefresh = drm_mode_vrefresh(in);
2620 	out->flags = in->flags;
2621 	out->type = in->type;
2622 
2623 	switch (in->picture_aspect_ratio) {
2624 	case HDMI_PICTURE_ASPECT_4_3:
2625 		out->flags |= DRM_MODE_FLAG_PIC_AR_4_3;
2626 		break;
2627 	case HDMI_PICTURE_ASPECT_16_9:
2628 		out->flags |= DRM_MODE_FLAG_PIC_AR_16_9;
2629 		break;
2630 	case HDMI_PICTURE_ASPECT_64_27:
2631 		out->flags |= DRM_MODE_FLAG_PIC_AR_64_27;
2632 		break;
2633 	case HDMI_PICTURE_ASPECT_256_135:
2634 		out->flags |= DRM_MODE_FLAG_PIC_AR_256_135;
2635 		break;
2636 	default:
2637 		WARN(1, "Invalid aspect ratio (0%x) on mode\n",
2638 		     in->picture_aspect_ratio);
2639 		fallthrough;
2640 	case HDMI_PICTURE_ASPECT_NONE:
2641 		out->flags |= DRM_MODE_FLAG_PIC_AR_NONE;
2642 		break;
2643 	}
2644 
2645 	strscpy_pad(out->name, in->name, sizeof(out->name));
2646 }
2647 
2648 /**
2649  * drm_mode_convert_umode - convert a modeinfo into a drm_display_mode
2650  * @dev: drm device
2651  * @out: drm_display_mode to return to the user
2652  * @in: drm_mode_modeinfo to use
2653  *
2654  * Convert a drm_mode_modeinfo into a drm_display_mode structure to return to
2655  * the caller.
2656  *
2657  * Returns:
2658  * Zero on success, negative errno on failure.
2659  */
2660 int drm_mode_convert_umode(struct drm_device *dev,
2661 			   struct drm_display_mode *out,
2662 			   const struct drm_mode_modeinfo *in)
2663 {
2664 	if (in->clock > INT_MAX || in->vrefresh > INT_MAX)
2665 		return -ERANGE;
2666 
2667 	out->clock = in->clock;
2668 	out->hdisplay = in->hdisplay;
2669 	out->hsync_start = in->hsync_start;
2670 	out->hsync_end = in->hsync_end;
2671 	out->htotal = in->htotal;
2672 	out->hskew = in->hskew;
2673 	out->vdisplay = in->vdisplay;
2674 	out->vsync_start = in->vsync_start;
2675 	out->vsync_end = in->vsync_end;
2676 	out->vtotal = in->vtotal;
2677 	out->vscan = in->vscan;
2678 	out->flags = in->flags;
2679 	/*
2680 	 * Old xf86-video-vmware (possibly others too) used to
2681 	 * leave 'type' uninitialized. Just ignore any bits we
2682 	 * don't like. It's a just hint after all, and more
2683 	 * useful for the kernel->userspace direction anyway.
2684 	 */
2685 	out->type = in->type & DRM_MODE_TYPE_ALL;
2686 	strscpy_pad(out->name, in->name, sizeof(out->name));
2687 
2688 	/* Clearing picture aspect ratio bits from out flags,
2689 	 * as the aspect-ratio information is not stored in
2690 	 * flags for kernel-mode, but in picture_aspect_ratio.
2691 	 */
2692 	out->flags &= ~DRM_MODE_FLAG_PIC_AR_MASK;
2693 
2694 	switch (in->flags & DRM_MODE_FLAG_PIC_AR_MASK) {
2695 	case DRM_MODE_FLAG_PIC_AR_4_3:
2696 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_4_3;
2697 		break;
2698 	case DRM_MODE_FLAG_PIC_AR_16_9:
2699 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_16_9;
2700 		break;
2701 	case DRM_MODE_FLAG_PIC_AR_64_27:
2702 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_64_27;
2703 		break;
2704 	case DRM_MODE_FLAG_PIC_AR_256_135:
2705 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_256_135;
2706 		break;
2707 	case DRM_MODE_FLAG_PIC_AR_NONE:
2708 		out->picture_aspect_ratio = HDMI_PICTURE_ASPECT_NONE;
2709 		break;
2710 	default:
2711 		return -EINVAL;
2712 	}
2713 
2714 	out->status = drm_mode_validate_driver(dev, out);
2715 	if (out->status != MODE_OK)
2716 		return -EINVAL;
2717 
2718 	drm_mode_set_crtcinfo(out, CRTC_INTERLACE_HALVE_V);
2719 
2720 	return 0;
2721 }
2722 
2723 /**
2724  * drm_mode_is_420_only - if a given videomode can be only supported in YCBCR420
2725  * output format
2726  *
2727  * @display: display under action
2728  * @mode: video mode to be tested.
2729  *
2730  * Returns:
2731  * true if the mode can be supported in YCBCR420 format
2732  * false if not.
2733  */
2734 bool drm_mode_is_420_only(const struct drm_display_info *display,
2735 			  const struct drm_display_mode *mode)
2736 {
2737 	u8 vic = drm_match_cea_mode(mode);
2738 
2739 	return test_bit(vic, display->hdmi.y420_vdb_modes);
2740 }
2741 EXPORT_SYMBOL(drm_mode_is_420_only);
2742 
2743 /**
2744  * drm_mode_is_420_also - if a given videomode can be supported in YCBCR420
2745  * output format also (along with RGB/YCBCR444/422)
2746  *
2747  * @display: display under action.
2748  * @mode: video mode to be tested.
2749  *
2750  * Returns:
2751  * true if the mode can be support YCBCR420 format
2752  * false if not.
2753  */
2754 bool drm_mode_is_420_also(const struct drm_display_info *display,
2755 			  const struct drm_display_mode *mode)
2756 {
2757 	u8 vic = drm_match_cea_mode(mode);
2758 
2759 	return test_bit(vic, display->hdmi.y420_cmdb_modes);
2760 }
2761 EXPORT_SYMBOL(drm_mode_is_420_also);
2762 /**
2763  * drm_mode_is_420 - if a given videomode can be supported in YCBCR420
2764  * output format
2765  *
2766  * @display: display under action.
2767  * @mode: video mode to be tested.
2768  *
2769  * Returns:
2770  * true if the mode can be supported in YCBCR420 format
2771  * false if not.
2772  */
2773 bool drm_mode_is_420(const struct drm_display_info *display,
2774 		     const struct drm_display_mode *mode)
2775 {
2776 	return drm_mode_is_420_only(display, mode) ||
2777 		drm_mode_is_420_also(display, mode);
2778 }
2779 EXPORT_SYMBOL(drm_mode_is_420);
2780 
2781 /**
2782  * drm_set_preferred_mode - Sets the preferred mode of a connector
2783  * @connector: connector whose mode list should be processed
2784  * @hpref: horizontal resolution of preferred mode
2785  * @vpref: vertical resolution of preferred mode
2786  *
2787  * Marks a mode as preferred if it matches the resolution specified by @hpref
2788  * and @vpref.
2789  */
2790 void drm_set_preferred_mode(struct drm_connector *connector,
2791 			    int hpref, int vpref)
2792 {
2793 	struct drm_display_mode *mode;
2794 
2795 	list_for_each_entry(mode, &connector->probed_modes, head) {
2796 		if (mode->hdisplay == hpref &&
2797 		    mode->vdisplay == vpref)
2798 			mode->type |= DRM_MODE_TYPE_PREFERRED;
2799 	}
2800 }
2801 EXPORT_SYMBOL(drm_set_preferred_mode);
2802