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