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