xref: /netbsd-src/sys/external/bsd/drm2/dist/drm/drm_modes.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: drm_modes.c,v 1.8 2020/02/14 04:38:36 riastradh Exp $	*/
2 
3 /*
4  * Copyright © 1997-2003 by The XFree86 Project, Inc.
5  * Copyright © 2007 Dave Airlie
6  * Copyright © 2007-2008 Intel Corporation
7  *   Jesse Barnes <jesse.barnes@intel.com>
8  * Copyright 2005-2006 Luc Verhaegen
9  * Copyright (c) 2001, Andy Ritger  aritger@nvidia.com
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included in
19  * all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
24  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
25  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
26  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27  * OTHER DEALINGS IN THE SOFTWARE.
28  *
29  * Except as contained in this notice, the name of the copyright holder(s)
30  * and author(s) shall not be used in advertising or otherwise to promote
31  * the sale, use or other dealings in this Software without prior written
32  * authorization from the copyright holder(s) and author(s).
33  */
34 
35 #include <sys/cdefs.h>
36 __KERNEL_RCSID(0, "$NetBSD: drm_modes.c,v 1.8 2020/02/14 04:38:36 riastradh Exp $");
37 
38 #include <linux/list.h>
39 #include <linux/list_sort.h>
40 #include <linux/export.h>
41 #include <drm/drmP.h>
42 #include <drm/drm_crtc.h>
43 #ifdef CONFIG_VIDEOMODE_HELPERS
44 #ifdef CONFIG_OF
45 #include <video/of_videomode.h>
46 #endif
47 #include <video/videomode.h>
48 #endif
49 #include <drm/drm_modes.h>
50 
51 #include "drm_crtc_internal.h"
52 
53 /**
54  * drm_mode_debug_printmodeline - print a mode to dmesg
55  * @mode: mode to print
56  *
57  * Describe @mode using DRM_DEBUG.
58  */
59 void drm_mode_debug_printmodeline(const struct drm_display_mode *mode)
60 {
61 	DRM_DEBUG_KMS("Modeline %d:\"%s\" %d %d %d %d %d %d %d %d %d %d "
62 			"0x%x 0x%x\n",
63 		mode->base.id, mode->name, mode->vrefresh, mode->clock,
64 		mode->hdisplay, mode->hsync_start,
65 		mode->hsync_end, mode->htotal,
66 		mode->vdisplay, mode->vsync_start,
67 		mode->vsync_end, mode->vtotal, mode->type, mode->flags);
68 }
69 EXPORT_SYMBOL(drm_mode_debug_printmodeline);
70 
71 /**
72  * drm_mode_create - create a new display mode
73  * @dev: DRM device
74  *
75  * Create a new, cleared drm_display_mode with kzalloc, allocate an ID for it
76  * and return it.
77  *
78  * Returns:
79  * Pointer to new mode on success, NULL on error.
80  */
81 struct drm_display_mode *drm_mode_create(struct drm_device *dev)
82 {
83 	struct drm_display_mode *nmode;
84 
85 	nmode = kzalloc(sizeof(struct drm_display_mode), GFP_KERNEL);
86 	if (!nmode)
87 		return NULL;
88 
89 	if (drm_mode_object_get(dev, &nmode->base, DRM_MODE_OBJECT_MODE)) {
90 		kfree(nmode);
91 		return NULL;
92 	}
93 
94 	return nmode;
95 }
96 EXPORT_SYMBOL(drm_mode_create);
97 
98 /**
99  * drm_mode_destroy - remove a mode
100  * @dev: DRM device
101  * @mode: mode to remove
102  *
103  * Release @mode's unique ID, then free it @mode structure itself using kfree.
104  */
105 void drm_mode_destroy(struct drm_device *dev, struct drm_display_mode *mode)
106 {
107 	if (!mode)
108 		return;
109 
110 	drm_mode_object_put(dev, &mode->base);
111 
112 	kfree(mode);
113 }
114 EXPORT_SYMBOL(drm_mode_destroy);
115 
116 /**
117  * drm_mode_probed_add - add a mode to a connector's probed_mode list
118  * @connector: connector the new mode
119  * @mode: mode data
120  *
121  * Add @mode to @connector's probed_mode list for later use. This list should
122  * then in a second step get filtered and all the modes actually supported by
123  * the hardware moved to the @connector's modes list.
124  */
125 void drm_mode_probed_add(struct drm_connector *connector,
126 			 struct drm_display_mode *mode)
127 {
128 	WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex));
129 
130 	list_add_tail(&mode->head, &connector->probed_modes);
131 }
132 EXPORT_SYMBOL(drm_mode_probed_add);
133 
134 /**
135  * drm_cvt_mode -create a modeline based on the CVT algorithm
136  * @dev: drm device
137  * @hdisplay: hdisplay size
138  * @vdisplay: vdisplay size
139  * @vrefresh: vrefresh rate
140  * @reduced: whether to use reduced blanking
141  * @interlaced: whether to compute an interlaced mode
142  * @margins: whether to add margins (borders)
143  *
144  * This function is called to generate the modeline based on CVT algorithm
145  * according to the hdisplay, vdisplay, vrefresh.
146  * It is based from the VESA(TM) Coordinated Video Timing Generator by
147  * Graham Loveridge April 9, 2003 available at
148  * http://www.elo.utfsm.cl/~elo212/docs/CVTd6r1.xls
149  *
150  * And it is copied from xf86CVTmode in xserver/hw/xfree86/modes/xf86cvt.c.
151  * What I have done is to translate it by using integer calculation.
152  *
153  * Returns:
154  * The modeline based on the CVT algorithm stored in a drm_display_mode object.
155  * The display mode object is allocated with drm_mode_create(). Returns NULL
156  * when no mode could be allocated.
157  */
158 struct drm_display_mode *drm_cvt_mode(struct drm_device *dev, int hdisplay,
159 				      int vdisplay, int vrefresh,
160 				      bool reduced, bool interlaced, bool margins)
161 {
162 #define HV_FACTOR			1000
163 	/* 1) top/bottom margin size (% of height) - default: 1.8, */
164 #define	CVT_MARGIN_PERCENTAGE		18
165 	/* 2) character cell horizontal granularity (pixels) - default 8 */
166 #define	CVT_H_GRANULARITY		8
167 	/* 3) Minimum vertical porch (lines) - default 3 */
168 #define	CVT_MIN_V_PORCH			3
169 	/* 4) Minimum number of vertical back porch lines - default 6 */
170 #define	CVT_MIN_V_BPORCH		6
171 	/* Pixel Clock step (kHz) */
172 #define CVT_CLOCK_STEP			250
173 	struct drm_display_mode *drm_mode;
174 	unsigned int vfieldrate, hperiod;
175 	int hdisplay_rnd, hmargin, vdisplay_rnd, vmargin, vsync;
176 	int interlace;
177 
178 	/* allocate the drm_display_mode structure. If failure, we will
179 	 * return directly
180 	 */
181 	drm_mode = drm_mode_create(dev);
182 	if (!drm_mode)
183 		return NULL;
184 
185 	/* the CVT default refresh rate is 60Hz */
186 	if (!vrefresh)
187 		vrefresh = 60;
188 
189 	/* the required field fresh rate */
190 	if (interlaced)
191 		vfieldrate = vrefresh * 2;
192 	else
193 		vfieldrate = vrefresh;
194 
195 	/* horizontal pixels */
196 	hdisplay_rnd = hdisplay - (hdisplay % CVT_H_GRANULARITY);
197 
198 	/* determine the left&right borders */
199 	hmargin = 0;
200 	if (margins) {
201 		hmargin = hdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
202 		hmargin -= hmargin % CVT_H_GRANULARITY;
203 	}
204 	/* find the total active pixels */
205 	drm_mode->hdisplay = hdisplay_rnd + 2 * hmargin;
206 
207 	/* find the number of lines per field */
208 	if (interlaced)
209 		vdisplay_rnd = vdisplay / 2;
210 	else
211 		vdisplay_rnd = vdisplay;
212 
213 	/* find the top & bottom borders */
214 	vmargin = 0;
215 	if (margins)
216 		vmargin = vdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000;
217 
218 	drm_mode->vdisplay = vdisplay + 2 * vmargin;
219 
220 	/* Interlaced */
221 	if (interlaced)
222 		interlace = 1;
223 	else
224 		interlace = 0;
225 
226 	/* Determine VSync Width from aspect ratio */
227 	if (!(vdisplay % 3) && ((vdisplay * 4 / 3) == hdisplay))
228 		vsync = 4;
229 	else if (!(vdisplay % 9) && ((vdisplay * 16 / 9) == hdisplay))
230 		vsync = 5;
231 	else if (!(vdisplay % 10) && ((vdisplay * 16 / 10) == hdisplay))
232 		vsync = 6;
233 	else if (!(vdisplay % 4) && ((vdisplay * 5 / 4) == hdisplay))
234 		vsync = 7;
235 	else if (!(vdisplay % 9) && ((vdisplay * 15 / 9) == hdisplay))
236 		vsync = 7;
237 	else /* custom */
238 		vsync = 10;
239 
240 	if (!reduced) {
241 		/* simplify the GTF calculation */
242 		/* 4) Minimum time of vertical sync + back porch interval (µs)
243 		 * default 550.0
244 		 */
245 		int tmp1, tmp2;
246 #define CVT_MIN_VSYNC_BP	550
247 		/* 3) Nominal HSync width (% of line period) - default 8 */
248 #define CVT_HSYNC_PERCENTAGE	8
249 		unsigned int hblank_percentage;
250 		int vsyncandback_porch, vback_porch __unused, hblank;
251 
252 		/* estimated the horizontal period */
253 		tmp1 = HV_FACTOR * 1000000  -
254 				CVT_MIN_VSYNC_BP * HV_FACTOR * vfieldrate;
255 		tmp2 = (vdisplay_rnd + 2 * vmargin + CVT_MIN_V_PORCH) * 2 +
256 				interlace;
257 		hperiod = tmp1 * 2 / (tmp2 * vfieldrate);
258 
259 		tmp1 = CVT_MIN_VSYNC_BP * HV_FACTOR / hperiod + 1;
260 		/* 9. Find number of lines in sync + backporch */
261 		if (tmp1 < (vsync + CVT_MIN_V_PORCH))
262 			vsyncandback_porch = vsync + CVT_MIN_V_PORCH;
263 		else
264 			vsyncandback_porch = tmp1;
265 		/* 10. Find number of lines in back porch */
266 		vback_porch = vsyncandback_porch - vsync;
267 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin +
268 				vsyncandback_porch + CVT_MIN_V_PORCH;
269 		/* 5) Definition of Horizontal blanking time limitation */
270 		/* Gradient (%/kHz) - default 600 */
271 #define CVT_M_FACTOR	600
272 		/* Offset (%) - default 40 */
273 #define CVT_C_FACTOR	40
274 		/* Blanking time scaling factor - default 128 */
275 #define CVT_K_FACTOR	128
276 		/* Scaling factor weighting - default 20 */
277 #define CVT_J_FACTOR	20
278 #define CVT_M_PRIME	(CVT_M_FACTOR * CVT_K_FACTOR / 256)
279 #define CVT_C_PRIME	((CVT_C_FACTOR - CVT_J_FACTOR) * CVT_K_FACTOR / 256 + \
280 			 CVT_J_FACTOR)
281 		/* 12. Find ideal blanking duty cycle from formula */
282 		hblank_percentage = CVT_C_PRIME * HV_FACTOR - CVT_M_PRIME *
283 					hperiod / 1000;
284 		/* 13. Blanking time */
285 		if (hblank_percentage < 20 * HV_FACTOR)
286 			hblank_percentage = 20 * HV_FACTOR;
287 		hblank = drm_mode->hdisplay * hblank_percentage /
288 			 (100 * HV_FACTOR - hblank_percentage);
289 		hblank -= hblank % (2 * CVT_H_GRANULARITY);
290 		/* 14. find the total pixels per line */
291 		drm_mode->htotal = drm_mode->hdisplay + hblank;
292 		drm_mode->hsync_end = drm_mode->hdisplay + hblank / 2;
293 		drm_mode->hsync_start = drm_mode->hsync_end -
294 			(drm_mode->htotal * CVT_HSYNC_PERCENTAGE) / 100;
295 		drm_mode->hsync_start += CVT_H_GRANULARITY -
296 			drm_mode->hsync_start % CVT_H_GRANULARITY;
297 		/* fill the Vsync values */
298 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_MIN_V_PORCH;
299 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
300 	} else {
301 		/* Reduced blanking */
302 		/* Minimum vertical blanking interval time (µs)- default 460 */
303 #define CVT_RB_MIN_VBLANK	460
304 		/* Fixed number of clocks for horizontal sync */
305 #define CVT_RB_H_SYNC		32
306 		/* Fixed number of clocks for horizontal blanking */
307 #define CVT_RB_H_BLANK		160
308 		/* Fixed number of lines for vertical front porch - default 3*/
309 #define CVT_RB_VFPORCH		3
310 		int vbilines;
311 		int tmp1, tmp2;
312 		/* 8. Estimate Horizontal period. */
313 		tmp1 = HV_FACTOR * 1000000 -
314 			CVT_RB_MIN_VBLANK * HV_FACTOR * vfieldrate;
315 		tmp2 = vdisplay_rnd + 2 * vmargin;
316 		hperiod = tmp1 / (tmp2 * vfieldrate);
317 		/* 9. Find number of lines in vertical blanking */
318 		vbilines = CVT_RB_MIN_VBLANK * HV_FACTOR / hperiod + 1;
319 		/* 10. Check if vertical blanking is sufficient */
320 		if (vbilines < (CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH))
321 			vbilines = CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH;
322 		/* 11. Find total number of lines in vertical field */
323 		drm_mode->vtotal = vdisplay_rnd + 2 * vmargin + vbilines;
324 		/* 12. Find total number of pixels in a line */
325 		drm_mode->htotal = drm_mode->hdisplay + CVT_RB_H_BLANK;
326 		/* Fill in HSync values */
327 		drm_mode->hsync_end = drm_mode->hdisplay + CVT_RB_H_BLANK / 2;
328 		drm_mode->hsync_start = drm_mode->hsync_end - CVT_RB_H_SYNC;
329 		/* Fill in VSync values */
330 		drm_mode->vsync_start = drm_mode->vdisplay + CVT_RB_VFPORCH;
331 		drm_mode->vsync_end = drm_mode->vsync_start + vsync;
332 	}
333 	/* 15/13. Find pixel clock frequency (kHz for xf86) */
334 	drm_mode->clock = drm_mode->htotal * HV_FACTOR * 1000 / hperiod;
335 	drm_mode->clock -= drm_mode->clock % CVT_CLOCK_STEP;
336 	/* 18/16. Find actual vertical frame frequency */
337 	/* ignore - just set the mode flag for interlaced */
338 	if (interlaced) {
339 		drm_mode->vtotal *= 2;
340 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
341 	}
342 	/* Fill the mode line name */
343 	drm_mode_set_name(drm_mode);
344 	if (reduced)
345 		drm_mode->flags |= (DRM_MODE_FLAG_PHSYNC |
346 					DRM_MODE_FLAG_NVSYNC);
347 	else
348 		drm_mode->flags |= (DRM_MODE_FLAG_PVSYNC |
349 					DRM_MODE_FLAG_NHSYNC);
350 
351 	return drm_mode;
352 }
353 EXPORT_SYMBOL(drm_cvt_mode);
354 
355 /**
356  * drm_gtf_mode_complex - create the modeline based on the full GTF algorithm
357  * @dev: drm device
358  * @hdisplay: hdisplay size
359  * @vdisplay: vdisplay size
360  * @vrefresh: vrefresh rate.
361  * @interlaced: whether to compute an interlaced mode
362  * @margins: desired margin (borders) size
363  * @GTF_M: extended GTF formula parameters
364  * @GTF_2C: extended GTF formula parameters
365  * @GTF_K: extended GTF formula parameters
366  * @GTF_2J: extended GTF formula parameters
367  *
368  * GTF feature blocks specify C and J in multiples of 0.5, so we pass them
369  * in here multiplied by two.  For a C of 40, pass in 80.
370  *
371  * Returns:
372  * The modeline based on the full GTF algorithm stored in a drm_display_mode object.
373  * The display mode object is allocated with drm_mode_create(). Returns NULL
374  * when no mode could be allocated.
375  */
376 struct drm_display_mode *
377 drm_gtf_mode_complex(struct drm_device *dev, int hdisplay, int vdisplay,
378 		     int vrefresh, bool interlaced, int margins,
379 		     int GTF_M, int GTF_2C, int GTF_K, int GTF_2J)
380 {	/* 1) top/bottom margin size (% of height) - default: 1.8, */
381 #define	GTF_MARGIN_PERCENTAGE		18
382 	/* 2) character cell horizontal granularity (pixels) - default 8 */
383 #define	GTF_CELL_GRAN			8
384 	/* 3) Minimum vertical porch (lines) - default 3 */
385 #define	GTF_MIN_V_PORCH			1
386 	/* width of vsync in lines */
387 #define V_SYNC_RQD			3
388 	/* width of hsync as % of total line */
389 #define H_SYNC_PERCENT			8
390 	/* min time of vsync + back porch (microsec) */
391 #define MIN_VSYNC_PLUS_BP		550
392 	/* C' and M' are part of the Blanking Duty Cycle computation */
393 #define GTF_C_PRIME	((((GTF_2C - GTF_2J) * GTF_K / 256) + GTF_2J) / 2)
394 #define GTF_M_PRIME	(GTF_K * GTF_M / 256)
395 	struct drm_display_mode *drm_mode;
396 	unsigned int hdisplay_rnd, vdisplay_rnd, vfieldrate_rqd;
397 	int top_margin, bottom_margin;
398 	int interlace;
399 	unsigned int hfreq_est;
400 	int vsync_plus_bp, vback_porch __unused;
401 	unsigned int vtotal_lines, vfieldrate_est __unused, hperiod __unused;
402 	unsigned int vfield_rate, vframe_rate __unused;
403 	int left_margin, right_margin;
404 	unsigned int total_active_pixels, ideal_duty_cycle;
405 	unsigned int hblank, total_pixels, pixel_freq;
406 	int hsync, hfront_porch, vodd_front_porch_lines;
407 	unsigned int tmp1, tmp2;
408 
409 	drm_mode = drm_mode_create(dev);
410 	if (!drm_mode)
411 		return NULL;
412 
413 	/* 1. In order to give correct results, the number of horizontal
414 	 * pixels requested is first processed to ensure that it is divisible
415 	 * by the character size, by rounding it to the nearest character
416 	 * cell boundary:
417 	 */
418 	hdisplay_rnd = (hdisplay + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
419 	hdisplay_rnd = hdisplay_rnd * GTF_CELL_GRAN;
420 
421 	/* 2. If interlace is requested, the number of vertical lines assumed
422 	 * by the calculation must be halved, as the computation calculates
423 	 * the number of vertical lines per field.
424 	 */
425 	if (interlaced)
426 		vdisplay_rnd = vdisplay / 2;
427 	else
428 		vdisplay_rnd = vdisplay;
429 
430 	/* 3. Find the frame rate required: */
431 	if (interlaced)
432 		vfieldrate_rqd = vrefresh * 2;
433 	else
434 		vfieldrate_rqd = vrefresh;
435 
436 	/* 4. Find number of lines in Top margin: */
437 	top_margin = 0;
438 	if (margins)
439 		top_margin = (vdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
440 				1000;
441 	/* 5. Find number of lines in bottom margin: */
442 	bottom_margin = top_margin;
443 
444 	/* 6. If interlace is required, then set variable interlace: */
445 	if (interlaced)
446 		interlace = 1;
447 	else
448 		interlace = 0;
449 
450 	/* 7. Estimate the Horizontal frequency */
451 	{
452 		tmp1 = (1000000  - MIN_VSYNC_PLUS_BP * vfieldrate_rqd) / 500;
453 		tmp2 = (vdisplay_rnd + 2 * top_margin + GTF_MIN_V_PORCH) *
454 				2 + interlace;
455 		hfreq_est = (tmp2 * 1000 * vfieldrate_rqd) / tmp1;
456 	}
457 
458 	/* 8. Find the number of lines in V sync + back porch */
459 	/* [V SYNC+BP] = RINT(([MIN VSYNC+BP] * hfreq_est / 1000000)) */
460 	vsync_plus_bp = MIN_VSYNC_PLUS_BP * hfreq_est / 1000;
461 	vsync_plus_bp = (vsync_plus_bp + 500) / 1000;
462 	/*  9. Find the number of lines in V back porch alone: */
463 	vback_porch = vsync_plus_bp - V_SYNC_RQD;
464 	/*  10. Find the total number of lines in Vertical field period: */
465 	vtotal_lines = vdisplay_rnd + top_margin + bottom_margin +
466 			vsync_plus_bp + GTF_MIN_V_PORCH;
467 	/*  11. Estimate the Vertical field frequency: */
468 	vfieldrate_est = hfreq_est / vtotal_lines;
469 	/*  12. Find the actual horizontal period: */
470 	hperiod = 1000000 / (vfieldrate_rqd * vtotal_lines);
471 
472 	/*  13. Find the actual Vertical field frequency: */
473 	vfield_rate = hfreq_est / vtotal_lines;
474 	/*  14. Find the Vertical frame frequency: */
475 	if (interlaced)
476 		vframe_rate = vfield_rate / 2;
477 	else
478 		vframe_rate = vfield_rate;
479 	/*  15. Find number of pixels in left margin: */
480 	if (margins)
481 		left_margin = (hdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) /
482 				1000;
483 	else
484 		left_margin = 0;
485 
486 	/* 16.Find number of pixels in right margin: */
487 	right_margin = left_margin;
488 	/* 17.Find total number of active pixels in image and left and right */
489 	total_active_pixels = hdisplay_rnd + left_margin + right_margin;
490 	/* 18.Find the ideal blanking duty cycle from blanking duty cycle */
491 	ideal_duty_cycle = GTF_C_PRIME * 1000 -
492 				(GTF_M_PRIME * 1000000 / hfreq_est);
493 	/* 19.Find the number of pixels in the blanking time to the nearest
494 	 * double character cell: */
495 	hblank = total_active_pixels * ideal_duty_cycle /
496 			(100000 - ideal_duty_cycle);
497 	hblank = (hblank + GTF_CELL_GRAN) / (2 * GTF_CELL_GRAN);
498 	hblank = hblank * 2 * GTF_CELL_GRAN;
499 	/* 20.Find total number of pixels: */
500 	total_pixels = total_active_pixels + hblank;
501 	/* 21.Find pixel clock frequency: */
502 	pixel_freq = total_pixels * hfreq_est / 1000;
503 	/* Stage 1 computations are now complete; I should really pass
504 	 * the results to another function and do the Stage 2 computations,
505 	 * but I only need a few more values so I'll just append the
506 	 * computations here for now */
507 	/* 17. Find the number of pixels in the horizontal sync period: */
508 	hsync = H_SYNC_PERCENT * total_pixels / 100;
509 	hsync = (hsync + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN;
510 	hsync = hsync * GTF_CELL_GRAN;
511 	/* 18. Find the number of pixels in horizontal front porch period */
512 	hfront_porch = hblank / 2 - hsync;
513 	/*  36. Find the number of lines in the odd front porch period: */
514 	vodd_front_porch_lines = GTF_MIN_V_PORCH ;
515 
516 	/* finally, pack the results in the mode struct */
517 	drm_mode->hdisplay = hdisplay_rnd;
518 	drm_mode->hsync_start = hdisplay_rnd + hfront_porch;
519 	drm_mode->hsync_end = drm_mode->hsync_start + hsync;
520 	drm_mode->htotal = total_pixels;
521 	drm_mode->vdisplay = vdisplay_rnd;
522 	drm_mode->vsync_start = vdisplay_rnd + vodd_front_porch_lines;
523 	drm_mode->vsync_end = drm_mode->vsync_start + V_SYNC_RQD;
524 	drm_mode->vtotal = vtotal_lines;
525 
526 	drm_mode->clock = pixel_freq;
527 
528 	if (interlaced) {
529 		drm_mode->vtotal *= 2;
530 		drm_mode->flags |= DRM_MODE_FLAG_INTERLACE;
531 	}
532 
533 	drm_mode_set_name(drm_mode);
534 	if (GTF_M == 600 && GTF_2C == 80 && GTF_K == 128 && GTF_2J == 40)
535 		drm_mode->flags = DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC;
536 	else
537 		drm_mode->flags = DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC;
538 
539 	return drm_mode;
540 }
541 EXPORT_SYMBOL(drm_gtf_mode_complex);
542 
543 /**
544  * drm_gtf_mode - create the modeline based on the GTF algorithm
545  * @dev: drm device
546  * @hdisplay: hdisplay size
547  * @vdisplay: vdisplay size
548  * @vrefresh: vrefresh rate.
549  * @interlaced: whether to compute an interlaced mode
550  * @margins: desired margin (borders) size
551  *
552  * return the modeline based on GTF algorithm
553  *
554  * This function is to create the modeline based on the GTF algorithm.
555  * Generalized Timing Formula is derived from:
556  *	GTF Spreadsheet by Andy Morrish (1/5/97)
557  *	available at http://www.vesa.org
558  *
559  * And it is copied from the file of xserver/hw/xfree86/modes/xf86gtf.c.
560  * What I have done is to translate it by using integer calculation.
561  * I also refer to the function of fb_get_mode in the file of
562  * drivers/video/fbmon.c
563  *
564  * Standard GTF parameters:
565  * M = 600
566  * C = 40
567  * K = 128
568  * J = 20
569  *
570  * Returns:
571  * The modeline based on the GTF algorithm stored in a drm_display_mode object.
572  * The display mode object is allocated with drm_mode_create(). Returns NULL
573  * when no mode could be allocated.
574  */
575 struct drm_display_mode *
576 drm_gtf_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh,
577 	     bool interlaced, int margins)
578 {
579 	return drm_gtf_mode_complex(dev, hdisplay, vdisplay, vrefresh,
580 				    interlaced, margins,
581 				    600, 40 * 2, 128, 20 * 2);
582 }
583 EXPORT_SYMBOL(drm_gtf_mode);
584 
585 #ifdef CONFIG_VIDEOMODE_HELPERS
586 /**
587  * drm_display_mode_from_videomode - fill in @dmode using @vm,
588  * @vm: videomode structure to use as source
589  * @dmode: drm_display_mode structure to use as destination
590  *
591  * Fills out @dmode using the display mode specified in @vm.
592  */
593 void drm_display_mode_from_videomode(const struct videomode *vm,
594 				     struct drm_display_mode *dmode)
595 {
596 	dmode->hdisplay = vm->hactive;
597 	dmode->hsync_start = dmode->hdisplay + vm->hfront_porch;
598 	dmode->hsync_end = dmode->hsync_start + vm->hsync_len;
599 	dmode->htotal = dmode->hsync_end + vm->hback_porch;
600 
601 	dmode->vdisplay = vm->vactive;
602 	dmode->vsync_start = dmode->vdisplay + vm->vfront_porch;
603 	dmode->vsync_end = dmode->vsync_start + vm->vsync_len;
604 	dmode->vtotal = dmode->vsync_end + vm->vback_porch;
605 
606 	dmode->clock = vm->pixelclock / 1000;
607 
608 	dmode->flags = 0;
609 	if (vm->flags & DISPLAY_FLAGS_HSYNC_HIGH)
610 		dmode->flags |= DRM_MODE_FLAG_PHSYNC;
611 	else if (vm->flags & DISPLAY_FLAGS_HSYNC_LOW)
612 		dmode->flags |= DRM_MODE_FLAG_NHSYNC;
613 	if (vm->flags & DISPLAY_FLAGS_VSYNC_HIGH)
614 		dmode->flags |= DRM_MODE_FLAG_PVSYNC;
615 	else if (vm->flags & DISPLAY_FLAGS_VSYNC_LOW)
616 		dmode->flags |= DRM_MODE_FLAG_NVSYNC;
617 	if (vm->flags & DISPLAY_FLAGS_INTERLACED)
618 		dmode->flags |= DRM_MODE_FLAG_INTERLACE;
619 	if (vm->flags & DISPLAY_FLAGS_DOUBLESCAN)
620 		dmode->flags |= DRM_MODE_FLAG_DBLSCAN;
621 	if (vm->flags & DISPLAY_FLAGS_DOUBLECLK)
622 		dmode->flags |= DRM_MODE_FLAG_DBLCLK;
623 	drm_mode_set_name(dmode);
624 }
625 EXPORT_SYMBOL_GPL(drm_display_mode_from_videomode);
626 
627 /**
628  * drm_display_mode_to_videomode - fill in @vm using @dmode,
629  * @dmode: drm_display_mode structure to use as source
630  * @vm: videomode structure to use as destination
631  *
632  * Fills out @vm using the display mode specified in @dmode.
633  */
634 void drm_display_mode_to_videomode(const struct drm_display_mode *dmode,
635 				   struct videomode *vm)
636 {
637 	vm->hactive = dmode->hdisplay;
638 	vm->hfront_porch = dmode->hsync_start - dmode->hdisplay;
639 	vm->hsync_len = dmode->hsync_end - dmode->hsync_start;
640 	vm->hback_porch = dmode->htotal - dmode->hsync_end;
641 
642 	vm->vactive = dmode->vdisplay;
643 	vm->vfront_porch = dmode->vsync_start - dmode->vdisplay;
644 	vm->vsync_len = dmode->vsync_end - dmode->vsync_start;
645 	vm->vback_porch = dmode->vtotal - dmode->vsync_end;
646 
647 	vm->pixelclock = dmode->clock * 1000;
648 
649 	vm->flags = 0;
650 	if (dmode->flags & DRM_MODE_FLAG_PHSYNC)
651 		vm->flags |= DISPLAY_FLAGS_HSYNC_HIGH;
652 	else if (dmode->flags & DRM_MODE_FLAG_NHSYNC)
653 		vm->flags |= DISPLAY_FLAGS_HSYNC_LOW;
654 	if (dmode->flags & DRM_MODE_FLAG_PVSYNC)
655 		vm->flags |= DISPLAY_FLAGS_VSYNC_HIGH;
656 	else if (dmode->flags & DRM_MODE_FLAG_NVSYNC)
657 		vm->flags |= DISPLAY_FLAGS_VSYNC_LOW;
658 	if (dmode->flags & DRM_MODE_FLAG_INTERLACE)
659 		vm->flags |= DISPLAY_FLAGS_INTERLACED;
660 	if (dmode->flags & DRM_MODE_FLAG_DBLSCAN)
661 		vm->flags |= DISPLAY_FLAGS_DOUBLESCAN;
662 	if (dmode->flags & DRM_MODE_FLAG_DBLCLK)
663 		vm->flags |= DISPLAY_FLAGS_DOUBLECLK;
664 }
665 EXPORT_SYMBOL_GPL(drm_display_mode_to_videomode);
666 
667 #ifdef CONFIG_OF
668 /**
669  * of_get_drm_display_mode - get a drm_display_mode from devicetree
670  * @np: device_node with the timing specification
671  * @dmode: will be set to the return value
672  * @index: index into the list of display timings in devicetree
673  *
674  * This function is expensive and should only be used, if only one mode is to be
675  * read from DT. To get multiple modes start with of_get_display_timings and
676  * work with that instead.
677  *
678  * Returns:
679  * 0 on success, a negative errno code when no of videomode node was found.
680  */
681 int of_get_drm_display_mode(struct device_node *np,
682 			    struct drm_display_mode *dmode, int index)
683 {
684 	struct videomode vm;
685 	int ret;
686 
687 	ret = of_get_videomode(np, &vm, index);
688 	if (ret)
689 		return ret;
690 
691 	drm_display_mode_from_videomode(&vm, dmode);
692 
693 	pr_debug("%s: got %dx%d display mode from %s\n",
694 		of_node_full_name(np), vm.hactive, vm.vactive, np->name);
695 	drm_mode_debug_printmodeline(dmode);
696 
697 	return 0;
698 }
699 EXPORT_SYMBOL_GPL(of_get_drm_display_mode);
700 #endif /* CONFIG_OF */
701 #endif /* CONFIG_VIDEOMODE_HELPERS */
702 
703 /**
704  * drm_mode_set_name - set the name on a mode
705  * @mode: name will be set in this mode
706  *
707  * Set the name of @mode to a standard format which is <hdisplay>x<vdisplay>
708  * with an optional 'i' suffix for interlaced modes.
709  */
710 void drm_mode_set_name(struct drm_display_mode *mode)
711 {
712 	bool interlaced = !!(mode->flags & DRM_MODE_FLAG_INTERLACE);
713 
714 	snprintf(mode->name, DRM_DISPLAY_MODE_LEN, "%dx%d%s",
715 		 mode->hdisplay, mode->vdisplay,
716 		 interlaced ? "i" : "");
717 }
718 EXPORT_SYMBOL(drm_mode_set_name);
719 
720 /** drm_mode_hsync - get the hsync of a mode
721  * @mode: mode
722  *
723  * Returns:
724  * @modes's hsync rate in kHz, rounded to the nearest integer. Calculates the
725  * value first if it is not yet set.
726  */
727 int drm_mode_hsync(const struct drm_display_mode *mode)
728 {
729 	unsigned int calc_val;
730 
731 	if (mode->hsync)
732 		return mode->hsync;
733 
734 	if (mode->htotal < 0)
735 		return 0;
736 
737 	calc_val = (mode->clock * 1000) / mode->htotal; /* hsync in Hz */
738 	calc_val += 500;				/* round to 1000Hz */
739 	calc_val /= 1000;				/* truncate to kHz */
740 
741 	return calc_val;
742 }
743 EXPORT_SYMBOL(drm_mode_hsync);
744 
745 /**
746  * drm_mode_vrefresh - get the vrefresh of a mode
747  * @mode: mode
748  *
749  * Returns:
750  * @modes's vrefresh rate in Hz, rounded to the nearest integer. Calculates the
751  * value first if it is not yet set.
752  */
753 int drm_mode_vrefresh(const struct drm_display_mode *mode)
754 {
755 	int refresh = 0;
756 	unsigned int calc_val;
757 
758 	if (mode->vrefresh > 0)
759 		refresh = mode->vrefresh;
760 	else if (mode->htotal > 0 && mode->vtotal > 0) {
761 		int vtotal;
762 		vtotal = mode->vtotal;
763 		/* work out vrefresh the value will be x1000 */
764 		calc_val = (mode->clock * 1000);
765 		calc_val /= mode->htotal;
766 		refresh = (calc_val + vtotal / 2) / vtotal;
767 
768 		if (mode->flags & DRM_MODE_FLAG_INTERLACE)
769 			refresh *= 2;
770 		if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
771 			refresh /= 2;
772 		if (mode->vscan > 1)
773 			refresh /= mode->vscan;
774 	}
775 	return refresh;
776 }
777 EXPORT_SYMBOL(drm_mode_vrefresh);
778 
779 /**
780  * drm_mode_set_crtcinfo - set CRTC modesetting timing parameters
781  * @p: mode
782  * @adjust_flags: a combination of adjustment flags
783  *
784  * Setup the CRTC modesetting timing parameters for @p, adjusting if necessary.
785  *
786  * - The CRTC_INTERLACE_HALVE_V flag can be used to halve vertical timings of
787  *   interlaced modes.
788  * - The CRTC_STEREO_DOUBLE flag can be used to compute the timings for
789  *   buffers containing two eyes (only adjust the timings when needed, eg. for
790  *   "frame packing" or "side by side full").
791  * - The CRTC_NO_DBLSCAN and CRTC_NO_VSCAN flags request that adjustment *not*
792  *   be performed for doublescan and vscan > 1 modes respectively.
793  */
794 void drm_mode_set_crtcinfo(struct drm_display_mode *p, int adjust_flags)
795 {
796 	if ((p == NULL) || ((p->type & DRM_MODE_TYPE_CRTC_C) == DRM_MODE_TYPE_BUILTIN))
797 		return;
798 
799 	p->crtc_clock = p->clock;
800 	p->crtc_hdisplay = p->hdisplay;
801 	p->crtc_hsync_start = p->hsync_start;
802 	p->crtc_hsync_end = p->hsync_end;
803 	p->crtc_htotal = p->htotal;
804 	p->crtc_hskew = p->hskew;
805 	p->crtc_vdisplay = p->vdisplay;
806 	p->crtc_vsync_start = p->vsync_start;
807 	p->crtc_vsync_end = p->vsync_end;
808 	p->crtc_vtotal = p->vtotal;
809 
810 	if (p->flags & DRM_MODE_FLAG_INTERLACE) {
811 		if (adjust_flags & CRTC_INTERLACE_HALVE_V) {
812 			p->crtc_vdisplay /= 2;
813 			p->crtc_vsync_start /= 2;
814 			p->crtc_vsync_end /= 2;
815 			p->crtc_vtotal /= 2;
816 		}
817 	}
818 
819 	if (!(adjust_flags & CRTC_NO_DBLSCAN)) {
820 		if (p->flags & DRM_MODE_FLAG_DBLSCAN) {
821 			p->crtc_vdisplay *= 2;
822 			p->crtc_vsync_start *= 2;
823 			p->crtc_vsync_end *= 2;
824 			p->crtc_vtotal *= 2;
825 		}
826 	}
827 
828 	if (!(adjust_flags & CRTC_NO_VSCAN)) {
829 		if (p->vscan > 1) {
830 			p->crtc_vdisplay *= p->vscan;
831 			p->crtc_vsync_start *= p->vscan;
832 			p->crtc_vsync_end *= p->vscan;
833 			p->crtc_vtotal *= p->vscan;
834 		}
835 	}
836 
837 	if (adjust_flags & CRTC_STEREO_DOUBLE) {
838 		unsigned int layout = p->flags & DRM_MODE_FLAG_3D_MASK;
839 
840 		switch (layout) {
841 		case DRM_MODE_FLAG_3D_FRAME_PACKING:
842 			p->crtc_clock *= 2;
843 			p->crtc_vdisplay += p->crtc_vtotal;
844 			p->crtc_vsync_start += p->crtc_vtotal;
845 			p->crtc_vsync_end += p->crtc_vtotal;
846 			p->crtc_vtotal += p->crtc_vtotal;
847 			break;
848 		}
849 	}
850 
851 	p->crtc_vblank_start = min(p->crtc_vsync_start, p->crtc_vdisplay);
852 	p->crtc_vblank_end = max(p->crtc_vsync_end, p->crtc_vtotal);
853 	p->crtc_hblank_start = min(p->crtc_hsync_start, p->crtc_hdisplay);
854 	p->crtc_hblank_end = max(p->crtc_hsync_end, p->crtc_htotal);
855 }
856 EXPORT_SYMBOL(drm_mode_set_crtcinfo);
857 
858 /**
859  * drm_mode_copy - copy the mode
860  * @dst: mode to overwrite
861  * @src: mode to copy
862  *
863  * Copy an existing mode into another mode, preserving the object id and
864  * list head of the destination mode.
865  */
866 void drm_mode_copy(struct drm_display_mode *dst, const struct drm_display_mode *src)
867 {
868 	int id = dst->base.id;
869 	struct list_head head = dst->head;
870 
871 	*dst = *src;
872 	dst->base.id = id;
873 	dst->head = head;
874 }
875 EXPORT_SYMBOL(drm_mode_copy);
876 
877 /**
878  * drm_mode_duplicate - allocate and duplicate an existing mode
879  * @dev: drm_device to allocate the duplicated mode for
880  * @mode: mode to duplicate
881  *
882  * Just allocate a new mode, copy the existing mode into it, and return
883  * a pointer to it.  Used to create new instances of established modes.
884  *
885  * Returns:
886  * Pointer to duplicated mode on success, NULL on error.
887  */
888 struct drm_display_mode *drm_mode_duplicate(struct drm_device *dev,
889 					    const struct drm_display_mode *mode)
890 {
891 	struct drm_display_mode *nmode;
892 
893 	nmode = drm_mode_create(dev);
894 	if (!nmode)
895 		return NULL;
896 
897 	drm_mode_copy(nmode, mode);
898 
899 	return nmode;
900 }
901 EXPORT_SYMBOL(drm_mode_duplicate);
902 
903 /**
904  * drm_mode_equal - test modes for equality
905  * @mode1: first mode
906  * @mode2: second mode
907  *
908  * Check to see if @mode1 and @mode2 are equivalent.
909  *
910  * Returns:
911  * True if the modes are equal, false otherwise.
912  */
913 bool drm_mode_equal(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2)
914 {
915 	if (!mode1 && !mode2)
916 		return true;
917 
918 	if (!mode1 || !mode2)
919 		return false;
920 
921 	/* do clock check convert to PICOS so fb modes get matched
922 	 * the same */
923 	if (mode1->clock && mode2->clock) {
924 		if (KHZ2PICOS(mode1->clock) != KHZ2PICOS(mode2->clock))
925 			return false;
926 	} else if (mode1->clock != mode2->clock)
927 		return false;
928 
929 	if ((mode1->flags & DRM_MODE_FLAG_3D_MASK) !=
930 	    (mode2->flags & DRM_MODE_FLAG_3D_MASK))
931 		return false;
932 
933 	return drm_mode_equal_no_clocks_no_stereo(mode1, mode2);
934 }
935 EXPORT_SYMBOL(drm_mode_equal);
936 
937 /**
938  * drm_mode_equal_no_clocks_no_stereo - test modes for equality
939  * @mode1: first mode
940  * @mode2: second mode
941  *
942  * Check to see if @mode1 and @mode2 are equivalent, but
943  * don't check the pixel clocks nor the stereo layout.
944  *
945  * Returns:
946  * True if the modes are equal, false otherwise.
947  */
948 bool drm_mode_equal_no_clocks_no_stereo(const struct drm_display_mode *mode1,
949 					const struct drm_display_mode *mode2)
950 {
951 	if (mode1->hdisplay == mode2->hdisplay &&
952 	    mode1->hsync_start == mode2->hsync_start &&
953 	    mode1->hsync_end == mode2->hsync_end &&
954 	    mode1->htotal == mode2->htotal &&
955 	    mode1->hskew == mode2->hskew &&
956 	    mode1->vdisplay == mode2->vdisplay &&
957 	    mode1->vsync_start == mode2->vsync_start &&
958 	    mode1->vsync_end == mode2->vsync_end &&
959 	    mode1->vtotal == mode2->vtotal &&
960 	    mode1->vscan == mode2->vscan &&
961 	    (mode1->flags & ~DRM_MODE_FLAG_3D_MASK) ==
962 	     (mode2->flags & ~DRM_MODE_FLAG_3D_MASK))
963 		return true;
964 
965 	return false;
966 }
967 EXPORT_SYMBOL(drm_mode_equal_no_clocks_no_stereo);
968 
969 /**
970  * drm_mode_validate_basic - make sure the mode is somewhat sane
971  * @mode: mode to check
972  *
973  * Check that the mode timings are at least somewhat reasonable.
974  * Any hardware specific limits are left up for each driver to check.
975  *
976  * Returns:
977  * The mode status
978  */
979 enum drm_mode_status
980 drm_mode_validate_basic(const struct drm_display_mode *mode)
981 {
982 	if (mode->clock == 0)
983 		return MODE_CLOCK_LOW;
984 
985 	if (mode->hdisplay == 0 ||
986 	    mode->hsync_start < mode->hdisplay ||
987 	    mode->hsync_end < mode->hsync_start ||
988 	    mode->htotal < mode->hsync_end)
989 		return MODE_H_ILLEGAL;
990 
991 	if (mode->vdisplay == 0 ||
992 	    mode->vsync_start < mode->vdisplay ||
993 	    mode->vsync_end < mode->vsync_start ||
994 	    mode->vtotal < mode->vsync_end)
995 		return MODE_V_ILLEGAL;
996 
997 	return MODE_OK;
998 }
999 EXPORT_SYMBOL(drm_mode_validate_basic);
1000 
1001 /**
1002  * drm_mode_validate_size - make sure modes adhere to size constraints
1003  * @mode: mode to check
1004  * @maxX: maximum width
1005  * @maxY: maximum height
1006  *
1007  * This function is a helper which can be used to validate modes against size
1008  * limitations of the DRM device/connector. If a mode is too big its status
1009  * member is updated with the appropriate validation failure code. The list
1010  * itself is not changed.
1011  *
1012  * Returns:
1013  * The mode status
1014  */
1015 enum drm_mode_status
1016 drm_mode_validate_size(const struct drm_display_mode *mode,
1017 		       int maxX, int maxY)
1018 {
1019 	if (maxX > 0 && mode->hdisplay > maxX)
1020 		return MODE_VIRTUAL_X;
1021 
1022 	if (maxY > 0 && mode->vdisplay > maxY)
1023 		return MODE_VIRTUAL_Y;
1024 
1025 	return MODE_OK;
1026 }
1027 EXPORT_SYMBOL(drm_mode_validate_size);
1028 
1029 #define MODE_STATUS(status) [MODE_ ## status + 3] = #status
1030 
1031 static const char * const drm_mode_status_names[] = {
1032 	MODE_STATUS(OK),
1033 	MODE_STATUS(HSYNC),
1034 	MODE_STATUS(VSYNC),
1035 	MODE_STATUS(H_ILLEGAL),
1036 	MODE_STATUS(V_ILLEGAL),
1037 	MODE_STATUS(BAD_WIDTH),
1038 	MODE_STATUS(NOMODE),
1039 	MODE_STATUS(NO_INTERLACE),
1040 	MODE_STATUS(NO_DBLESCAN),
1041 	MODE_STATUS(NO_VSCAN),
1042 	MODE_STATUS(MEM),
1043 	MODE_STATUS(VIRTUAL_X),
1044 	MODE_STATUS(VIRTUAL_Y),
1045 	MODE_STATUS(MEM_VIRT),
1046 	MODE_STATUS(NOCLOCK),
1047 	MODE_STATUS(CLOCK_HIGH),
1048 	MODE_STATUS(CLOCK_LOW),
1049 	MODE_STATUS(CLOCK_RANGE),
1050 	MODE_STATUS(BAD_HVALUE),
1051 	MODE_STATUS(BAD_VVALUE),
1052 	MODE_STATUS(BAD_VSCAN),
1053 	MODE_STATUS(HSYNC_NARROW),
1054 	MODE_STATUS(HSYNC_WIDE),
1055 	MODE_STATUS(HBLANK_NARROW),
1056 	MODE_STATUS(HBLANK_WIDE),
1057 	MODE_STATUS(VSYNC_NARROW),
1058 	MODE_STATUS(VSYNC_WIDE),
1059 	MODE_STATUS(VBLANK_NARROW),
1060 	MODE_STATUS(VBLANK_WIDE),
1061 	MODE_STATUS(PANEL),
1062 	MODE_STATUS(INTERLACE_WIDTH),
1063 	MODE_STATUS(ONE_WIDTH),
1064 	MODE_STATUS(ONE_HEIGHT),
1065 	MODE_STATUS(ONE_SIZE),
1066 	MODE_STATUS(NO_REDUCED),
1067 	MODE_STATUS(NO_STEREO),
1068 	MODE_STATUS(UNVERIFIED),
1069 	MODE_STATUS(BAD),
1070 	MODE_STATUS(ERROR),
1071 };
1072 
1073 #undef MODE_STATUS
1074 
1075 static const char *drm_get_mode_status_name(enum drm_mode_status status)
1076 {
1077 	int index = status + 3;
1078 
1079 	if (WARN_ON(index < 0 || index >= ARRAY_SIZE(drm_mode_status_names)))
1080 		return "";
1081 
1082 	return drm_mode_status_names[index];
1083 }
1084 
1085 /**
1086  * drm_mode_prune_invalid - remove invalid modes from mode list
1087  * @dev: DRM device
1088  * @mode_list: list of modes to check
1089  * @verbose: be verbose about it
1090  *
1091  * This helper function can be used to prune a display mode list after
1092  * validation has been completed. All modes who's status is not MODE_OK will be
1093  * removed from the list, and if @verbose the status code and mode name is also
1094  * printed to dmesg.
1095  */
1096 void drm_mode_prune_invalid(struct drm_device *dev,
1097 			    struct list_head *mode_list, bool verbose)
1098 {
1099 	struct drm_display_mode *mode, *t;
1100 
1101 	list_for_each_entry_safe(mode, t, mode_list, head) {
1102 		if (mode->status != MODE_OK) {
1103 			list_del(&mode->head);
1104 			if (verbose) {
1105 				drm_mode_debug_printmodeline(mode);
1106 				DRM_DEBUG_KMS("Not using %s mode: %s\n",
1107 					      mode->name,
1108 					      drm_get_mode_status_name(mode->status));
1109 			}
1110 			drm_mode_destroy(dev, mode);
1111 		}
1112 	}
1113 }
1114 EXPORT_SYMBOL(drm_mode_prune_invalid);
1115 
1116 /**
1117  * drm_mode_compare - compare modes for favorability
1118  * @priv: unused
1119  * @lh_a: list_head for first mode
1120  * @lh_b: list_head for second mode
1121  *
1122  * Compare two modes, given by @lh_a and @lh_b, returning a value indicating
1123  * which is better.
1124  *
1125  * Returns:
1126  * Negative if @lh_a is better than @lh_b, zero if they're equivalent, or
1127  * positive if @lh_b is better than @lh_a.
1128  */
1129 static int drm_mode_compare(void *priv, struct list_head *lh_a, struct list_head *lh_b)
1130 {
1131 	struct drm_display_mode *a = list_entry(lh_a, struct drm_display_mode, head);
1132 	struct drm_display_mode *b = list_entry(lh_b, struct drm_display_mode, head);
1133 	int diff;
1134 
1135 	diff = ((b->type & DRM_MODE_TYPE_PREFERRED) != 0) -
1136 		((a->type & DRM_MODE_TYPE_PREFERRED) != 0);
1137 	if (diff)
1138 		return diff;
1139 	diff = b->hdisplay * b->vdisplay - a->hdisplay * a->vdisplay;
1140 	if (diff)
1141 		return diff;
1142 
1143 	diff = b->vrefresh - a->vrefresh;
1144 	if (diff)
1145 		return diff;
1146 
1147 	diff = b->clock - a->clock;
1148 	return diff;
1149 }
1150 
1151 /**
1152  * drm_mode_sort - sort mode list
1153  * @mode_list: list of drm_display_mode structures to sort
1154  *
1155  * Sort @mode_list by favorability, moving good modes to the head of the list.
1156  */
1157 void drm_mode_sort(struct list_head *mode_list)
1158 {
1159 	list_sort(NULL, mode_list, drm_mode_compare);
1160 }
1161 EXPORT_SYMBOL(drm_mode_sort);
1162 
1163 /**
1164  * drm_mode_connector_list_update - update the mode list for the connector
1165  * @connector: the connector to update
1166  * @merge_type_bits: whether to merge or overwrite type bits
1167  *
1168  * This moves the modes from the @connector probed_modes list
1169  * to the actual mode list. It compares the probed mode against the current
1170  * list and only adds different/new modes.
1171  *
1172  * This is just a helper functions doesn't validate any modes itself and also
1173  * doesn't prune any invalid modes. Callers need to do that themselves.
1174  */
1175 void drm_mode_connector_list_update(struct drm_connector *connector,
1176 				    bool merge_type_bits)
1177 {
1178 	struct drm_display_mode *mode;
1179 	struct drm_display_mode *pmode, *pt;
1180 	int found_it;
1181 
1182 	WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex));
1183 
1184 	list_for_each_entry_safe(pmode, pt, &connector->probed_modes,
1185 				 head) {
1186 		found_it = 0;
1187 		/* go through current modes checking for the new probed mode */
1188 		list_for_each_entry(mode, &connector->modes, head) {
1189 			if (drm_mode_equal(pmode, mode)) {
1190 				found_it = 1;
1191 				/* if equal delete the probed mode */
1192 				mode->status = pmode->status;
1193 				/* Merge type bits together */
1194 				if (merge_type_bits)
1195 					mode->type |= pmode->type;
1196 				else
1197 					mode->type = pmode->type;
1198 				list_del(&pmode->head);
1199 				drm_mode_destroy(connector->dev, pmode);
1200 				break;
1201 			}
1202 		}
1203 
1204 		if (!found_it) {
1205 			list_move_tail(&pmode->head, &connector->modes);
1206 		}
1207 	}
1208 }
1209 EXPORT_SYMBOL(drm_mode_connector_list_update);
1210 
1211 /**
1212  * drm_mode_parse_command_line_for_connector - parse command line modeline for connector
1213  * @mode_option: optional per connector mode option
1214  * @connector: connector to parse modeline for
1215  * @mode: preallocated drm_cmdline_mode structure to fill out
1216  *
1217  * This parses @mode_option command line modeline for modes and options to
1218  * configure the connector. If @mode_option is NULL the default command line
1219  * modeline in fb_mode_option will be parsed instead.
1220  *
1221  * This uses the same parameters as the fb modedb.c, except for an extra
1222  * force-enable, force-enable-digital and force-disable bit at the end:
1223  *
1224  *	<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m][eDd]
1225  *
1226  * The intermediate drm_cmdline_mode structure is required to store additional
1227  * options from the command line modline like the force-enable/disable flag.
1228  *
1229  * Returns:
1230  * True if a valid modeline has been parsed, false otherwise.
1231  */
1232 bool drm_mode_parse_command_line_for_connector(const char *mode_option,
1233 					       struct drm_connector *connector,
1234 					       struct drm_cmdline_mode *mode)
1235 {
1236 	const char *name;
1237 	unsigned int namelen;
1238 	bool res_specified = false, bpp_specified = false, refresh_specified = false;
1239 	unsigned int xres = 0, yres = 0, bpp = 32, refresh = 0;
1240 	bool yres_specified = false, cvt = false, rb = false;
1241 	bool interlace = false, margins = false, was_digit = false;
1242 	int i;
1243 	enum drm_connector_force force = DRM_FORCE_UNSPECIFIED;
1244 
1245 #if !defined(__NetBSD__)
1246 #ifdef CONFIG_FB
1247 	if (!mode_option)
1248 		mode_option = fb_mode_option;
1249 #endif
1250 #endif
1251 
1252 	if (!mode_option) {
1253 		mode->specified = false;
1254 		return false;
1255 	}
1256 
1257 	name = mode_option;
1258 	namelen = strlen(name);
1259 	for (i = namelen-1; i >= 0; i--) {
1260 		switch (name[i]) {
1261 		case '@':
1262 			if (!refresh_specified && !bpp_specified &&
1263 			    !yres_specified && !cvt && !rb && was_digit) {
1264 				refresh = simple_strtol(&name[i+1], NULL, 10);
1265 				refresh_specified = true;
1266 				was_digit = false;
1267 			} else
1268 				goto done;
1269 			break;
1270 		case '-':
1271 			if (!bpp_specified && !yres_specified && !cvt &&
1272 			    !rb && was_digit) {
1273 				bpp = simple_strtol(&name[i+1], NULL, 10);
1274 				bpp_specified = true;
1275 				was_digit = false;
1276 			} else
1277 				goto done;
1278 			break;
1279 		case 'x':
1280 			if (!yres_specified && was_digit) {
1281 				yres = simple_strtol(&name[i+1], NULL, 10);
1282 				yres_specified = true;
1283 				was_digit = false;
1284 			} else
1285 				goto done;
1286 			break;
1287 		case '0' ... '9':
1288 			was_digit = true;
1289 			break;
1290 		case 'M':
1291 			if (yres_specified || cvt || was_digit)
1292 				goto done;
1293 			cvt = true;
1294 			break;
1295 		case 'R':
1296 			if (yres_specified || cvt || rb || was_digit)
1297 				goto done;
1298 			rb = true;
1299 			break;
1300 		case 'm':
1301 			if (cvt || yres_specified || was_digit)
1302 				goto done;
1303 			margins = true;
1304 			break;
1305 		case 'i':
1306 			if (cvt || yres_specified || was_digit)
1307 				goto done;
1308 			interlace = true;
1309 			break;
1310 		case 'e':
1311 			if (yres_specified || bpp_specified || refresh_specified ||
1312 			    was_digit || (force != DRM_FORCE_UNSPECIFIED))
1313 				goto done;
1314 
1315 			force = DRM_FORCE_ON;
1316 			break;
1317 		case 'D':
1318 			if (yres_specified || bpp_specified || refresh_specified ||
1319 			    was_digit || (force != DRM_FORCE_UNSPECIFIED))
1320 				goto done;
1321 
1322 			if ((connector->connector_type != DRM_MODE_CONNECTOR_DVII) &&
1323 			    (connector->connector_type != DRM_MODE_CONNECTOR_HDMIB))
1324 				force = DRM_FORCE_ON;
1325 			else
1326 				force = DRM_FORCE_ON_DIGITAL;
1327 			break;
1328 		case 'd':
1329 			if (yres_specified || bpp_specified || refresh_specified ||
1330 			    was_digit || (force != DRM_FORCE_UNSPECIFIED))
1331 				goto done;
1332 
1333 			force = DRM_FORCE_OFF;
1334 			break;
1335 		default:
1336 			goto done;
1337 		}
1338 	}
1339 
1340 	if (i < 0 && yres_specified) {
1341 		char *ch;
1342 		xres = simple_strtol(name, &ch, 10);
1343 		if ((ch != NULL) && (*ch == 'x'))
1344 			res_specified = true;
1345 		else
1346 			i = ch - name;
1347 	} else if (!yres_specified && was_digit) {
1348 		/* catch mode that begins with digits but has no 'x' */
1349 		i = 0;
1350 	}
1351 done:
1352 	if (i >= 0) {
1353 		DRM_ERROR(
1354 			"parse error at position %i in video mode '%s'\n",
1355 			i, name);
1356 		mode->specified = false;
1357 		return false;
1358 	}
1359 
1360 	if (res_specified) {
1361 		mode->specified = true;
1362 		mode->xres = xres;
1363 		mode->yres = yres;
1364 	}
1365 
1366 	if (refresh_specified) {
1367 		mode->refresh_specified = true;
1368 		mode->refresh = refresh;
1369 	}
1370 
1371 	if (bpp_specified) {
1372 		mode->bpp_specified = true;
1373 		mode->bpp = bpp;
1374 	}
1375 	mode->rb = rb;
1376 	mode->cvt = cvt;
1377 	mode->interlace = interlace;
1378 	mode->margins = margins;
1379 	mode->force = force;
1380 
1381 	return true;
1382 }
1383 EXPORT_SYMBOL(drm_mode_parse_command_line_for_connector);
1384 
1385 /**
1386  * drm_mode_create_from_cmdline_mode - convert a command line modeline into a DRM display mode
1387  * @dev: DRM device to create the new mode for
1388  * @cmd: input command line modeline
1389  *
1390  * Returns:
1391  * Pointer to converted mode on success, NULL on error.
1392  */
1393 struct drm_display_mode *
1394 drm_mode_create_from_cmdline_mode(struct drm_device *dev,
1395 				  struct drm_cmdline_mode *cmd)
1396 {
1397 	struct drm_display_mode *mode;
1398 
1399 	if (cmd->cvt)
1400 		mode = drm_cvt_mode(dev,
1401 				    cmd->xres, cmd->yres,
1402 				    cmd->refresh_specified ? cmd->refresh : 60,
1403 				    cmd->rb, cmd->interlace,
1404 				    cmd->margins);
1405 	else
1406 		mode = drm_gtf_mode(dev,
1407 				    cmd->xres, cmd->yres,
1408 				    cmd->refresh_specified ? cmd->refresh : 60,
1409 				    cmd->interlace,
1410 				    cmd->margins);
1411 	if (!mode)
1412 		return NULL;
1413 
1414 	mode->type |= DRM_MODE_TYPE_USERDEF;
1415 	/* fix up 1368x768: GFT/CVT can't express 1366 width due to alignment */
1416 	if (cmd->xres == 1366 && mode->hdisplay == 1368) {
1417 		mode->hdisplay = 1366;
1418 		mode->hsync_start--;
1419 		mode->hsync_end--;
1420 		drm_mode_set_name(mode);
1421 	}
1422 	drm_mode_set_crtcinfo(mode, CRTC_INTERLACE_HALVE_V);
1423 	return mode;
1424 }
1425 EXPORT_SYMBOL(drm_mode_create_from_cmdline_mode);
1426 
1427 /**
1428  * drm_crtc_convert_to_umode - convert a drm_display_mode into a modeinfo
1429  * @out: drm_mode_modeinfo struct to return to the user
1430  * @in: drm_display_mode to use
1431  *
1432  * Convert a drm_display_mode into a drm_mode_modeinfo structure to return to
1433  * the user.
1434  */
1435 void drm_mode_convert_to_umode(struct drm_mode_modeinfo *out,
1436 			       const struct drm_display_mode *in)
1437 {
1438 	WARN(in->hdisplay > USHRT_MAX || in->hsync_start > USHRT_MAX ||
1439 	     in->hsync_end > USHRT_MAX || in->htotal > USHRT_MAX ||
1440 	     in->hskew > USHRT_MAX || in->vdisplay > USHRT_MAX ||
1441 	     in->vsync_start > USHRT_MAX || in->vsync_end > USHRT_MAX ||
1442 	     in->vtotal > USHRT_MAX || in->vscan > USHRT_MAX,
1443 	     "timing values too large for mode info\n");
1444 
1445 	out->clock = in->clock;
1446 	out->hdisplay = in->hdisplay;
1447 	out->hsync_start = in->hsync_start;
1448 	out->hsync_end = in->hsync_end;
1449 	out->htotal = in->htotal;
1450 	out->hskew = in->hskew;
1451 	out->vdisplay = in->vdisplay;
1452 	out->vsync_start = in->vsync_start;
1453 	out->vsync_end = in->vsync_end;
1454 	out->vtotal = in->vtotal;
1455 	out->vscan = in->vscan;
1456 	out->vrefresh = in->vrefresh;
1457 	out->flags = in->flags;
1458 	out->type = in->type;
1459 	strncpy(out->name, in->name, DRM_DISPLAY_MODE_LEN);
1460 	out->name[DRM_DISPLAY_MODE_LEN-1] = 0;
1461 }
1462 
1463 /**
1464  * drm_crtc_convert_umode - convert a modeinfo into a drm_display_mode
1465  * @out: drm_display_mode to return to the user
1466  * @in: drm_mode_modeinfo to use
1467  *
1468  * Convert a drm_mode_modeinfo into a drm_display_mode structure to return to
1469  * the caller.
1470  *
1471  * Returns:
1472  * Zero on success, negative errno on failure.
1473  */
1474 int drm_mode_convert_umode(struct drm_display_mode *out,
1475 			   const struct drm_mode_modeinfo *in)
1476 {
1477 	int ret = -EINVAL;
1478 
1479 	if (in->clock > INT_MAX || in->vrefresh > INT_MAX) {
1480 		ret = -ERANGE;
1481 		goto out;
1482 	}
1483 
1484 	if ((in->flags & DRM_MODE_FLAG_3D_MASK) > DRM_MODE_FLAG_3D_MAX)
1485 		goto out;
1486 
1487 	out->clock = in->clock;
1488 	out->hdisplay = in->hdisplay;
1489 	out->hsync_start = in->hsync_start;
1490 	out->hsync_end = in->hsync_end;
1491 	out->htotal = in->htotal;
1492 	out->hskew = in->hskew;
1493 	out->vdisplay = in->vdisplay;
1494 	out->vsync_start = in->vsync_start;
1495 	out->vsync_end = in->vsync_end;
1496 	out->vtotal = in->vtotal;
1497 	out->vscan = in->vscan;
1498 	out->vrefresh = in->vrefresh;
1499 	out->flags = in->flags;
1500 	out->type = in->type;
1501 	strncpy(out->name, in->name, DRM_DISPLAY_MODE_LEN);
1502 	out->name[DRM_DISPLAY_MODE_LEN-1] = 0;
1503 
1504 	out->status = drm_mode_validate_basic(out);
1505 	if (out->status != MODE_OK)
1506 		goto out;
1507 
1508 	drm_mode_set_crtcinfo(out, CRTC_INTERLACE_HALVE_V);
1509 
1510 	ret = 0;
1511 
1512 out:
1513 	return ret;
1514 }
1515