drm: Reduce differences with Linux 3.8
[dragonfly.git] / sys / dev / drm / drm_edid.c
1 /*
2  * Copyright (c) 2006 Luc Verhaegen (quirks list)
3  * Copyright (c) 2007-2008 Intel Corporation
4  *   Jesse Barnes <jesse.barnes@intel.com>
5  * Copyright 2010 Red Hat, Inc.
6  *
7  * DDC probing routines (drm_ddc_read & drm_do_probe_ddc_edid) originally from
8  * FB layer.
9  *   Copyright (C) 2006 Dennis Munsie <dmunsie@cecropia.com>
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sub license,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice (including the
19  * next paragraph) shall be included in all copies or substantial portions
20  * of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
25  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28  * DEALINGS IN THE SOFTWARE.
29  *
30  * $FreeBSD: head/sys/dev/drm2/drm_edid.c 249041 2013-04-03 08:27:35Z dumbbell $
31  */
32
33 #include <drm/drmP.h>
34 #include <drm/drm_edid.h>
35 #include "drm_edid_modes.h"
36 #include <bus/iicbus/iic.h>
37 #include <bus/iicbus/iiconf.h>
38 #include "iicbus_if.h"
39
40 #define version_greater(edid, maj, min) \
41         (((edid)->version > (maj)) || \
42          ((edid)->version == (maj) && (edid)->revision > (min)))
43
44 #define EDID_EST_TIMINGS 16
45 #define EDID_STD_TIMINGS 8
46 #define EDID_DETAILED_TIMINGS 4
47
48 /*
49  * EDID blocks out in the wild have a variety of bugs, try to collect
50  * them here (note that userspace may work around broken monitors first,
51  * but fixes should make their way here so that the kernel "just works"
52  * on as many displays as possible).
53  */
54
55 /* First detailed mode wrong, use largest 60Hz mode */
56 #define EDID_QUIRK_PREFER_LARGE_60              (1 << 0)
57 /* Reported 135MHz pixel clock is too high, needs adjustment */
58 #define EDID_QUIRK_135_CLOCK_TOO_HIGH           (1 << 1)
59 /* Prefer the largest mode at 75 Hz */
60 #define EDID_QUIRK_PREFER_LARGE_75              (1 << 2)
61 /* Detail timing is in cm not mm */
62 #define EDID_QUIRK_DETAILED_IN_CM               (1 << 3)
63 /* Detailed timing descriptors have bogus size values, so just take the
64  * maximum size and use that.
65  */
66 #define EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE    (1 << 4)
67 /* Monitor forgot to set the first detailed is preferred bit. */
68 #define EDID_QUIRK_FIRST_DETAILED_PREFERRED     (1 << 5)
69 /* use +hsync +vsync for detailed mode */
70 #define EDID_QUIRK_DETAILED_SYNC_PP             (1 << 6)
71
72 struct detailed_mode_closure {
73         struct drm_connector *connector;
74         struct edid *edid;
75         bool preferred;
76         u32 quirks;
77         int modes;
78 };
79
80 #define LEVEL_DMT       0
81 #define LEVEL_GTF       1
82 #define LEVEL_GTF2      2
83 #define LEVEL_CVT       3
84
85 static struct edid_quirk {
86         char *vendor;
87         int product_id;
88         u32 quirks;
89 } edid_quirk_list[] = {
90         /* Acer AL1706 */
91         { "ACR", 44358, EDID_QUIRK_PREFER_LARGE_60 },
92         /* Acer F51 */
93         { "API", 0x7602, EDID_QUIRK_PREFER_LARGE_60 },
94         /* Unknown Acer */
95         { "ACR", 2423, EDID_QUIRK_FIRST_DETAILED_PREFERRED },
96
97         /* Belinea 10 15 55 */
98         { "MAX", 1516, EDID_QUIRK_PREFER_LARGE_60 },
99         { "MAX", 0x77e, EDID_QUIRK_PREFER_LARGE_60 },
100
101         /* Envision Peripherals, Inc. EN-7100e */
102         { "EPI", 59264, EDID_QUIRK_135_CLOCK_TOO_HIGH },
103         /* Envision EN2028 */
104         { "EPI", 8232, EDID_QUIRK_PREFER_LARGE_60 },
105
106         /* Funai Electronics PM36B */
107         { "FCM", 13600, EDID_QUIRK_PREFER_LARGE_75 |
108           EDID_QUIRK_DETAILED_IN_CM },
109
110         /* LG Philips LCD LP154W01-A5 */
111         { "LPL", 0, EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE },
112         { "LPL", 0x2a00, EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE },
113
114         /* Philips 107p5 CRT */
115         { "PHL", 57364, EDID_QUIRK_FIRST_DETAILED_PREFERRED },
116
117         /* Proview AY765C */
118         { "PTS", 765, EDID_QUIRK_FIRST_DETAILED_PREFERRED },
119
120         /* Samsung SyncMaster 205BW.  Note: irony */
121         { "SAM", 541, EDID_QUIRK_DETAILED_SYNC_PP },
122         /* Samsung SyncMaster 22[5-6]BW */
123         { "SAM", 596, EDID_QUIRK_PREFER_LARGE_60 },
124         { "SAM", 638, EDID_QUIRK_PREFER_LARGE_60 },
125 };
126
127 /*** DDC fetch and block validation ***/
128
129 static const u8 edid_header[] = {
130         0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00
131 };
132
133  /*
134  * Sanity check the header of the base EDID block.  Return 8 if the header
135  * is perfect, down to 0 if it's totally wrong.
136  */
137 int drm_edid_header_is_valid(const u8 *raw_edid)
138 {
139         int i, score = 0;
140
141         for (i = 0; i < sizeof(edid_header); i++)
142                 if (raw_edid[i] == edid_header[i])
143                         score++;
144
145         return score;
146 }
147
148 /*
149  * Sanity check the EDID block (base or extension).  Return 0 if the block
150  * doesn't check out, or 1 if it's valid.
151  */
152 static bool
153 drm_edid_block_valid(u8 *raw_edid)
154 {
155         int i;
156         u8 csum = 0;
157         struct edid *edid = (struct edid *)raw_edid;
158
159         if (raw_edid[0] == 0x00) {
160                 int score = drm_edid_header_is_valid(raw_edid);
161                 if (score == 8) ;
162                 else if (score >= 6) {
163                         DRM_DEBUG("Fixing EDID header, your hardware may be failing\n");
164                         memcpy(raw_edid, edid_header, sizeof(edid_header));
165                 } else {
166                         goto bad;
167                 }
168         }
169
170         for (i = 0; i < EDID_LENGTH; i++)
171                 csum += raw_edid[i];
172         if (csum) {
173                 DRM_ERROR("EDID checksum is invalid, remainder is %d\n", csum);
174
175                 /* allow CEA to slide through, switches mangle this */
176                 if (raw_edid[0] != 0x02)
177                         goto bad;
178         }
179
180         /* per-block-type checks */
181         switch (raw_edid[0]) {
182         case 0: /* base */
183                 if (edid->version != 1) {
184                         DRM_ERROR("EDID has major version %d, instead of 1\n", edid->version);
185                         goto bad;
186                 }
187
188                 if (edid->revision > 4)
189                         DRM_DEBUG("EDID minor > 4, assuming backward compatibility\n");
190                 break;
191
192         default:
193                 break;
194         }
195
196         return 1;
197
198 bad:
199         if (raw_edid) {
200                 DRM_DEBUG_KMS("Raw EDID:\n");
201                 if ((drm_debug & DRM_DEBUGBITS_KMS) != 0) {
202                         for (i = 0; i < EDID_LENGTH; ) {
203                                 kprintf("%02x", raw_edid[i]);
204                                 i++;
205                                 if (i % 16 == 0 || i == EDID_LENGTH)
206                                         kprintf("\n");
207                                 else if (i % 8 == 0)
208                                         kprintf("  ");
209                                 else
210                                         kprintf(" ");
211                         }
212                 }
213         }
214         return 0;
215 }
216
217 /**
218  * drm_edid_is_valid - sanity check EDID data
219  * @edid: EDID data
220  *
221  * Sanity-check an entire EDID record (including extensions)
222  */
223 bool drm_edid_is_valid(struct edid *edid)
224 {
225         int i;
226         u8 *raw = (u8 *)edid;
227
228         if (!edid)
229                 return false;
230
231         for (i = 0; i <= edid->extensions; i++)
232                 if (!drm_edid_block_valid(raw + i * EDID_LENGTH))
233                         return false;
234
235         return true;
236 }
237
238 #define DDC_ADDR 0x50
239 #define DDC_SEGMENT_ADDR 0x30
240 /**
241  * Get EDID information via I2C.
242  *
243  * \param adapter : i2c device adaptor
244  * \param buf     : EDID data buffer to be filled
245  * \param len     : EDID data buffer length
246  * \return 0 on success or -1 on failure.
247  *
248  * Try to fetch EDID information by calling i2c driver function.
249  */
250 static int
251 drm_do_probe_ddc_edid(device_t adapter, unsigned char *buf,
252                       int block, int len)
253 {
254         unsigned char start = block * EDID_LENGTH;
255         unsigned char segment = block >> 1;
256         unsigned char xfers = segment ? 3 : 2;
257         int ret, retries = 5;
258
259         /* The core i2c driver will automatically retry the transfer if the
260          * adapter reports EAGAIN. However, we find that bit-banging transfers
261          * are susceptible to errors under a heavily loaded machine and
262          * generate spurious NAKs and timeouts. Retrying the transfer
263          * of the individual block a few times seems to overcome this.
264          */
265         do {
266                 struct iic_msg msgs[] = {
267                         {
268                                 .slave  = DDC_SEGMENT_ADDR << 1,
269                                 .flags  = 0,
270                                 .len    = 1,
271                                 .buf    = &segment,
272                         }, {
273                                 .slave  = DDC_ADDR << 1,
274                                 .flags  = IIC_M_WR,
275                                 .len    = 1,
276                                 .buf    = &start,
277                         }, {
278                                 .slave  = DDC_ADDR << 1,
279                                 .flags  = IIC_M_RD,
280                                 .len    = len,
281                                 .buf    = buf,
282                         }
283                 };
284
285         /*
286          * Avoid sending the segment addr to not upset non-compliant ddc
287          * monitors.
288          */
289                 ret = iicbus_transfer(adapter, &msgs[3 - xfers], xfers);
290
291                 if (ret != 0)
292                         DRM_DEBUG_KMS("iicbus_transfer countdown %d error %d\n",
293                             retries, ret);
294         } while (ret != 0 && --retries);
295
296         return (ret == 0 ? 0 : -1);
297 }
298
299 static bool drm_edid_is_zero(u8 *in_edid, int length)
300 {
301         int i;
302         u32 *raw_edid = (u32 *)in_edid;
303
304         for (i = 0; i < length / 4; i++)
305                 if (*(raw_edid + i) != 0)
306                         return false;
307         return true;
308 }
309
310 static u8 *
311 drm_do_get_edid(struct drm_connector *connector, device_t adapter)
312 {
313         int i, j = 0, valid_extensions = 0;
314         u8 *block, *new;
315
316         block = kmalloc(EDID_LENGTH, DRM_MEM_KMS, M_WAITOK | M_ZERO);
317
318         /* base block fetch */
319         for (i = 0; i < 4; i++) {
320                 if (drm_do_probe_ddc_edid(adapter, block, 0, EDID_LENGTH))
321                         goto out;
322                 if (drm_edid_block_valid(block))
323                         break;
324                 if (i == 0 && drm_edid_is_zero(block, EDID_LENGTH)) {
325                         connector->null_edid_counter++;
326                         goto carp;
327                 }
328         }
329         if (i == 4)
330                 goto carp;
331
332         /* if there's no extensions, we're done */
333         if (block[0x7e] == 0)
334                 return block;
335
336         new = krealloc(block, (block[0x7e] + 1) * EDID_LENGTH, DRM_MEM_KMS,
337             M_WAITOK);
338         block = new;
339
340         for (j = 1; j <= block[0x7e]; j++) {
341                 for (i = 0; i < 4; i++) {
342                         if (drm_do_probe_ddc_edid(adapter,
343                                   block + (valid_extensions + 1) * EDID_LENGTH,
344                                   j, EDID_LENGTH))
345                                 goto out;
346                         if (drm_edid_block_valid(block + (valid_extensions + 1) * EDID_LENGTH)) {
347                                 valid_extensions++;
348                                 break;
349                         }
350                 }
351                 if (i == 4)
352                         DRM_DEBUG_KMS("%s: Ignoring invalid EDID block %d.\n",
353                              drm_get_connector_name(connector), j);
354         }
355
356         if (valid_extensions != block[0x7e]) {
357                 block[EDID_LENGTH-1] += block[0x7e] - valid_extensions;
358                 block[0x7e] = valid_extensions;
359                 new = krealloc(block, (valid_extensions + 1) * EDID_LENGTH,
360                     DRM_MEM_KMS, M_WAITOK);
361                 block = new;
362         }
363
364         DRM_DEBUG_KMS("got EDID from %s\n", drm_get_connector_name(connector));
365         return block;
366
367 carp:
368         DRM_ERROR("%s: EDID block %d invalid.\n",
369             drm_get_connector_name(connector), j);
370
371 out:
372         drm_free(block, DRM_MEM_KMS);
373         return NULL;
374 }
375
376 /**
377  * Probe DDC presence.
378  *
379  * \param adapter : i2c device adaptor
380  * \return 1 on success
381  */
382 static bool
383 drm_probe_ddc(device_t adapter)
384 {
385         unsigned char out;
386
387         return (drm_do_probe_ddc_edid(adapter, &out, 0, 1) == 0);
388 }
389
390 /**
391  * drm_get_edid - get EDID data, if available
392  * @connector: connector we're probing
393  * @adapter: i2c adapter to use for DDC
394  *
395  * Poke the given i2c channel to grab EDID data if possible.  If found,
396  * attach it to the connector.
397  *
398  * Return edid data or NULL if we couldn't find any.
399  */
400 struct edid *drm_get_edid(struct drm_connector *connector,
401                           device_t adapter)
402 {
403         struct edid *edid = NULL;
404
405         if (drm_probe_ddc(adapter))
406                 edid = (struct edid *)drm_do_get_edid(connector, adapter);
407
408         return edid;
409 }
410 EXPORT_SYMBOL(drm_get_edid);
411
412 /*** EDID parsing ***/
413
414 /**
415  * edid_vendor - match a string against EDID's obfuscated vendor field
416  * @edid: EDID to match
417  * @vendor: vendor string
418  *
419  * Returns true if @vendor is in @edid, false otherwise
420  */
421 static bool edid_vendor(struct edid *edid, char *vendor)
422 {
423         char edid_vendor[3];
424
425         edid_vendor[0] = ((edid->mfg_id[0] & 0x7c) >> 2) + '@';
426         edid_vendor[1] = (((edid->mfg_id[0] & 0x3) << 3) |
427                           ((edid->mfg_id[1] & 0xe0) >> 5)) + '@';
428         edid_vendor[2] = (edid->mfg_id[1] & 0x1f) + '@';
429
430         return !strncmp(edid_vendor, vendor, 3);
431 }
432
433 /**
434  * edid_get_quirks - return quirk flags for a given EDID
435  * @edid: EDID to process
436  *
437  * This tells subsequent routines what fixes they need to apply.
438  */
439 static u32 edid_get_quirks(struct edid *edid)
440 {
441         struct edid_quirk *quirk;
442         int i;
443
444         for (i = 0; i < DRM_ARRAY_SIZE(edid_quirk_list); i++) {
445                 quirk = &edid_quirk_list[i];
446
447                 if (edid_vendor(edid, quirk->vendor) &&
448                     (EDID_PRODUCT_ID(edid) == quirk->product_id))
449                         return quirk->quirks;
450         }
451
452         return 0;
453 }
454
455 #define MODE_SIZE(m) ((m)->hdisplay * (m)->vdisplay)
456 #define MODE_REFRESH_DIFF(m,r) (abs((m)->vrefresh - target_refresh))
457
458 /**
459  * edid_fixup_preferred - set preferred modes based on quirk list
460  * @connector: has mode list to fix up
461  * @quirks: quirks list
462  *
463  * Walk the mode list for @connector, clearing the preferred status
464  * on existing modes and setting it anew for the right mode ala @quirks.
465  */
466 static void edid_fixup_preferred(struct drm_connector *connector,
467                                  u32 quirks)
468 {
469         struct drm_display_mode *t, *cur_mode, *preferred_mode;
470         int target_refresh = 0;
471
472         if (list_empty(&connector->probed_modes))
473                 return;
474
475         if (quirks & EDID_QUIRK_PREFER_LARGE_60)
476                 target_refresh = 60;
477         if (quirks & EDID_QUIRK_PREFER_LARGE_75)
478                 target_refresh = 75;
479
480         preferred_mode = list_first_entry(&connector->probed_modes,
481                                           struct drm_display_mode, head);
482
483         list_for_each_entry_safe(cur_mode, t, &connector->probed_modes, head) {
484                 cur_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
485
486                 if (cur_mode == preferred_mode)
487                         continue;
488
489                 /* Largest mode is preferred */
490                 if (MODE_SIZE(cur_mode) > MODE_SIZE(preferred_mode))
491                         preferred_mode = cur_mode;
492
493                 /* At a given size, try to get closest to target refresh */
494                 if ((MODE_SIZE(cur_mode) == MODE_SIZE(preferred_mode)) &&
495                     MODE_REFRESH_DIFF(cur_mode, target_refresh) <
496                     MODE_REFRESH_DIFF(preferred_mode, target_refresh)) {
497                         preferred_mode = cur_mode;
498                 }
499         }
500
501         preferred_mode->type |= DRM_MODE_TYPE_PREFERRED;
502 }
503
504 /*
505  * drm_mode_find_dmt - Create a copy of a mode if present in DMT
506  * @dev: Device to duplicate against
507  * @hsize: Mode width
508  * @vsize: Mode height
509  * @fresh: Mode refresh rate
510  * @rb: Mode reduced-blanking-ness
511  *
512  * Walk the DMT mode list looking for a match for the given parameters.
513  * Return a newly allocated copy of the mode, or NULL if not found.
514  */
515 struct drm_display_mode *drm_mode_find_dmt(struct drm_device *dev,
516                                            int hsize, int vsize, int fresh)
517 {
518         struct drm_display_mode *mode = NULL;
519         int i;
520
521         for (i = 0; i < drm_num_dmt_modes; i++) {
522                 struct drm_display_mode *ptr = &drm_dmt_modes[i];
523                 if (hsize == ptr->hdisplay &&
524                         vsize == ptr->vdisplay &&
525                         fresh == drm_mode_vrefresh(ptr)) {
526                         /* get the expected default mode */
527                         mode = drm_mode_duplicate(dev, ptr);
528                         break;
529                 }
530         }
531         return mode;
532 }
533 EXPORT_SYMBOL(drm_mode_find_dmt);
534
535 typedef void detailed_cb(struct detailed_timing *timing, void *closure);
536
537 static void
538 cea_for_each_detailed_block(u8 *ext, detailed_cb *cb, void *closure)
539 {
540         int i, n = 0;
541         u8 d = ext[0x02];
542         u8 *det_base = ext + d;
543
544         n = (127 - d) / 18;
545         for (i = 0; i < n; i++)
546                 cb((struct detailed_timing *)(det_base + 18 * i), closure);
547 }
548
549 static void
550 vtb_for_each_detailed_block(u8 *ext, detailed_cb *cb, void *closure)
551 {
552         unsigned int i, n = min((int)ext[0x02], 6);
553         u8 *det_base = ext + 5;
554
555         if (ext[0x01] != 1)
556                 return; /* unknown version */
557
558         for (i = 0; i < n; i++)
559                 cb((struct detailed_timing *)(det_base + 18 * i), closure);
560 }
561
562 static void
563 drm_for_each_detailed_block(u8 *raw_edid, detailed_cb *cb, void *closure)
564 {
565         int i;
566         struct edid *edid = (struct edid *)raw_edid;
567
568         if (edid == NULL)
569                 return;
570
571         for (i = 0; i < EDID_DETAILED_TIMINGS; i++)
572                 cb(&(edid->detailed_timings[i]), closure);
573
574         for (i = 1; i <= raw_edid[0x7e]; i++) {
575                 u8 *ext = raw_edid + (i * EDID_LENGTH);
576                 switch (*ext) {
577                 case CEA_EXT:
578                         cea_for_each_detailed_block(ext, cb, closure);
579                         break;
580                 case VTB_EXT:
581                         vtb_for_each_detailed_block(ext, cb, closure);
582                         break;
583                 default:
584                         break;
585                 }
586         }
587 }
588
589 static void
590 is_rb(struct detailed_timing *t, void *data)
591 {
592         u8 *r = (u8 *)t;
593         if (r[3] == EDID_DETAIL_MONITOR_RANGE)
594                 if (r[15] & 0x10)
595                         *(bool *)data = true;
596 }
597
598 /* EDID 1.4 defines this explicitly.  For EDID 1.3, we guess, badly. */
599 static bool
600 drm_monitor_supports_rb(struct edid *edid)
601 {
602         if (edid->revision >= 4) {
603                 bool ret;
604                 drm_for_each_detailed_block((u8 *)edid, is_rb, &ret);
605                 return ret;
606         }
607
608         return ((edid->input & DRM_EDID_INPUT_DIGITAL) != 0);
609 }
610
611 static void
612 find_gtf2(struct detailed_timing *t, void *data)
613 {
614         u8 *r = (u8 *)t;
615         if (r[3] == EDID_DETAIL_MONITOR_RANGE && r[10] == 0x02)
616                 *(u8 **)data = r;
617 }
618
619 /* Secondary GTF curve kicks in above some break frequency */
620 static int
621 drm_gtf2_hbreak(struct edid *edid)
622 {
623         u8 *r = NULL;
624         drm_for_each_detailed_block((u8 *)edid, find_gtf2, &r);
625         return r ? (r[12] * 2) : 0;
626 }
627
628 static int
629 drm_gtf2_2c(struct edid *edid)
630 {
631         u8 *r = NULL;
632         drm_for_each_detailed_block((u8 *)edid, find_gtf2, &r);
633         return r ? r[13] : 0;
634 }
635
636 static int
637 drm_gtf2_m(struct edid *edid)
638 {
639         u8 *r = NULL;
640         drm_for_each_detailed_block((u8 *)edid, find_gtf2, &r);
641         return r ? (r[15] << 8) + r[14] : 0;
642 }
643
644 static int
645 drm_gtf2_k(struct edid *edid)
646 {
647         u8 *r = NULL;
648         drm_for_each_detailed_block((u8 *)edid, find_gtf2, &r);
649         return r ? r[16] : 0;
650 }
651
652 static int
653 drm_gtf2_2j(struct edid *edid)
654 {
655         u8 *r = NULL;
656         drm_for_each_detailed_block((u8 *)edid, find_gtf2, &r);
657         return r ? r[17] : 0;
658 }
659
660 /**
661  * standard_timing_level - get std. timing level(CVT/GTF/DMT)
662  * @edid: EDID block to scan
663  */
664 static int standard_timing_level(struct edid *edid)
665 {
666         if (edid->revision >= 2) {
667                 if (edid->revision >= 4 && (edid->features & DRM_EDID_FEATURE_DEFAULT_GTF))
668                         return LEVEL_CVT;
669                 if (drm_gtf2_hbreak(edid))
670                         return LEVEL_GTF2;
671                 return LEVEL_GTF;
672         }
673         return LEVEL_DMT;
674 }
675
676 /*
677  * 0 is reserved.  The spec says 0x01 fill for unused timings.  Some old
678  * monitors fill with ascii space (0x20) instead.
679  */
680 static int
681 bad_std_timing(u8 a, u8 b)
682 {
683         return (a == 0x00 && b == 0x00) ||
684                (a == 0x01 && b == 0x01) ||
685                (a == 0x20 && b == 0x20);
686 }
687
688 /**
689  * drm_mode_std - convert standard mode info (width, height, refresh) into mode
690  * @t: standard timing params
691  * @timing_level: standard timing level
692  *
693  * Take the standard timing params (in this case width, aspect, and refresh)
694  * and convert them into a real mode using CVT/GTF/DMT.
695  */
696 static struct drm_display_mode *
697 drm_mode_std(struct drm_connector *connector, struct edid *edid,
698              struct std_timing *t, int revision)
699 {
700         struct drm_device *dev = connector->dev;
701         struct drm_display_mode *m, *mode = NULL;
702         int hsize, vsize;
703         int vrefresh_rate;
704         unsigned aspect_ratio = (t->vfreq_aspect & EDID_TIMING_ASPECT_MASK)
705                 >> EDID_TIMING_ASPECT_SHIFT;
706         unsigned vfreq = (t->vfreq_aspect & EDID_TIMING_VFREQ_MASK)
707                 >> EDID_TIMING_VFREQ_SHIFT;
708         int timing_level = standard_timing_level(edid);
709
710         if (bad_std_timing(t->hsize, t->vfreq_aspect))
711                 return NULL;
712
713         /* According to the EDID spec, the hdisplay = hsize * 8 + 248 */
714         hsize = t->hsize * 8 + 248;
715         /* vrefresh_rate = vfreq + 60 */
716         vrefresh_rate = vfreq + 60;
717         /* the vdisplay is calculated based on the aspect ratio */
718         if (aspect_ratio == 0) {
719                 if (revision < 3)
720                         vsize = hsize;
721                 else
722                         vsize = (hsize * 10) / 16;
723         } else if (aspect_ratio == 1)
724                 vsize = (hsize * 3) / 4;
725         else if (aspect_ratio == 2)
726                 vsize = (hsize * 4) / 5;
727         else
728                 vsize = (hsize * 9) / 16;
729
730         /* HDTV hack, part 1 */
731         if (vrefresh_rate == 60 &&
732             ((hsize == 1360 && vsize == 765) ||
733              (hsize == 1368 && vsize == 769))) {
734                 hsize = 1366;
735                 vsize = 768;
736         }
737
738         /*
739          * If this connector already has a mode for this size and refresh
740          * rate (because it came from detailed or CVT info), use that
741          * instead.  This way we don't have to guess at interlace or
742          * reduced blanking.
743          */
744         list_for_each_entry(m, &connector->probed_modes, head)
745                 if (m->hdisplay == hsize && m->vdisplay == vsize &&
746                     drm_mode_vrefresh(m) == vrefresh_rate)
747                         return NULL;
748
749         /* HDTV hack, part 2 */
750         if (hsize == 1366 && vsize == 768 && vrefresh_rate == 60) {
751                 mode = drm_cvt_mode(dev, 1366, 768, vrefresh_rate, 0, 0,
752                                     false);
753                 mode->hdisplay = 1366;
754                 mode->hsync_start = mode->hsync_start - 1;
755                 mode->hsync_end = mode->hsync_end - 1;
756                 return mode;
757         }
758
759         /* check whether it can be found in default mode table */
760         mode = drm_mode_find_dmt(dev, hsize, vsize, vrefresh_rate);
761         if (mode)
762                 return mode;
763
764         switch (timing_level) {
765         case LEVEL_DMT:
766                 break;
767         case LEVEL_GTF:
768                 mode = drm_gtf_mode(dev, hsize, vsize, vrefresh_rate, 0, 0);
769                 break;
770         case LEVEL_GTF2:
771                 /*
772                  * This is potentially wrong if there's ever a monitor with
773                  * more than one ranges section, each claiming a different
774                  * secondary GTF curve.  Please don't do that.
775                  */
776                 mode = drm_gtf_mode(dev, hsize, vsize, vrefresh_rate, 0, 0);
777                 if (drm_mode_hsync(mode) > drm_gtf2_hbreak(edid)) {
778                         drm_free(mode, DRM_MEM_KMS);
779                         mode = drm_gtf_mode_complex(dev, hsize, vsize,
780                                                     vrefresh_rate, 0, 0,
781                                                     drm_gtf2_m(edid),
782                                                     drm_gtf2_2c(edid),
783                                                     drm_gtf2_k(edid),
784                                                     drm_gtf2_2j(edid));
785                 }
786                 break;
787         case LEVEL_CVT:
788                 mode = drm_cvt_mode(dev, hsize, vsize, vrefresh_rate, 0, 0,
789                                     false);
790                 break;
791         }
792         return mode;
793 }
794
795 /*
796  * EDID is delightfully ambiguous about how interlaced modes are to be
797  * encoded.  Our internal representation is of frame height, but some
798  * HDTV detailed timings are encoded as field height.
799  *
800  * The format list here is from CEA, in frame size.  Technically we
801  * should be checking refresh rate too.  Whatever.
802  */
803 static void
804 drm_mode_do_interlace_quirk(struct drm_display_mode *mode,
805                             struct detailed_pixel_timing *pt)
806 {
807         int i;
808         static const struct {
809                 int w, h;
810         } cea_interlaced[] = {
811                 { 1920, 1080 },
812                 {  720,  480 },
813                 { 1440,  480 },
814                 { 2880,  480 },
815                 {  720,  576 },
816                 { 1440,  576 },
817                 { 2880,  576 },
818         };
819
820         if (!(pt->misc & DRM_EDID_PT_INTERLACED))
821                 return;
822
823         for (i = 0; i < DRM_ARRAY_SIZE(cea_interlaced); i++) {
824                 if ((mode->hdisplay == cea_interlaced[i].w) &&
825                     (mode->vdisplay == cea_interlaced[i].h / 2)) {
826                         mode->vdisplay *= 2;
827                         mode->vsync_start *= 2;
828                         mode->vsync_end *= 2;
829                         mode->vtotal *= 2;
830                         mode->vtotal |= 1;
831                 }
832         }
833
834         mode->flags |= DRM_MODE_FLAG_INTERLACE;
835 }
836
837 /**
838  * drm_mode_detailed - create a new mode from an EDID detailed timing section
839  * @dev: DRM device (needed to create new mode)
840  * @edid: EDID block
841  * @timing: EDID detailed timing info
842  * @quirks: quirks to apply
843  *
844  * An EDID detailed timing block contains enough info for us to create and
845  * return a new struct drm_display_mode.
846  */
847 static struct drm_display_mode *drm_mode_detailed(struct drm_device *dev,
848                                                   struct edid *edid,
849                                                   struct detailed_timing *timing,
850                                                   u32 quirks)
851 {
852         struct drm_display_mode *mode;
853         struct detailed_pixel_timing *pt = &timing->data.pixel_data;
854         unsigned hactive = (pt->hactive_hblank_hi & 0xf0) << 4 | pt->hactive_lo;
855         unsigned vactive = (pt->vactive_vblank_hi & 0xf0) << 4 | pt->vactive_lo;
856         unsigned hblank = (pt->hactive_hblank_hi & 0xf) << 8 | pt->hblank_lo;
857         unsigned vblank = (pt->vactive_vblank_hi & 0xf) << 8 | pt->vblank_lo;
858         unsigned hsync_offset = (pt->hsync_vsync_offset_pulse_width_hi & 0xc0) << 2 | pt->hsync_offset_lo;
859         unsigned hsync_pulse_width = (pt->hsync_vsync_offset_pulse_width_hi & 0x30) << 4 | pt->hsync_pulse_width_lo;
860         unsigned vsync_offset = (pt->hsync_vsync_offset_pulse_width_hi & 0xc) >> 2 | pt->vsync_offset_pulse_width_lo >> 4;
861         unsigned vsync_pulse_width = (pt->hsync_vsync_offset_pulse_width_hi & 0x3) << 4 | (pt->vsync_offset_pulse_width_lo & 0xf);
862
863         /* ignore tiny modes */
864         if (hactive < 64 || vactive < 64)
865                 return NULL;
866
867         if (pt->misc & DRM_EDID_PT_STEREO) {
868                 kprintf("stereo mode not supported\n");
869                 return NULL;
870         }
871         if (!(pt->misc & DRM_EDID_PT_SEPARATE_SYNC)) {
872                 kprintf("composite sync not supported\n");
873         }
874
875         /* it is incorrect if hsync/vsync width is zero */
876         if (!hsync_pulse_width || !vsync_pulse_width) {
877                 DRM_DEBUG_KMS("Incorrect Detailed timing. "
878                                 "Wrong Hsync/Vsync pulse width\n");
879                 return NULL;
880         }
881         mode = drm_mode_create(dev);
882         if (!mode)
883                 return NULL;
884
885         mode->type = DRM_MODE_TYPE_DRIVER;
886
887         if (quirks & EDID_QUIRK_135_CLOCK_TOO_HIGH)
888                 timing->pixel_clock = htole16(1088);
889
890         mode->clock = le16toh(timing->pixel_clock) * 10;
891
892         mode->hdisplay = hactive;
893         mode->hsync_start = mode->hdisplay + hsync_offset;
894         mode->hsync_end = mode->hsync_start + hsync_pulse_width;
895         mode->htotal = mode->hdisplay + hblank;
896
897         mode->vdisplay = vactive;
898         mode->vsync_start = mode->vdisplay + vsync_offset;
899         mode->vsync_end = mode->vsync_start + vsync_pulse_width;
900         mode->vtotal = mode->vdisplay + vblank;
901
902         /* Some EDIDs have bogus h/vtotal values */
903         if (mode->hsync_end > mode->htotal)
904                 mode->htotal = mode->hsync_end + 1;
905         if (mode->vsync_end > mode->vtotal)
906                 mode->vtotal = mode->vsync_end + 1;
907
908         drm_mode_do_interlace_quirk(mode, pt);
909
910         drm_mode_set_name(mode);
911
912         if (quirks & EDID_QUIRK_DETAILED_SYNC_PP) {
913                 pt->misc |= DRM_EDID_PT_HSYNC_POSITIVE | DRM_EDID_PT_VSYNC_POSITIVE;
914         }
915
916         mode->flags |= (pt->misc & DRM_EDID_PT_HSYNC_POSITIVE) ?
917                 DRM_MODE_FLAG_PHSYNC : DRM_MODE_FLAG_NHSYNC;
918         mode->flags |= (pt->misc & DRM_EDID_PT_VSYNC_POSITIVE) ?
919                 DRM_MODE_FLAG_PVSYNC : DRM_MODE_FLAG_NVSYNC;
920
921         mode->width_mm = pt->width_mm_lo | (pt->width_height_mm_hi & 0xf0) << 4;
922         mode->height_mm = pt->height_mm_lo | (pt->width_height_mm_hi & 0xf) << 8;
923
924         if (quirks & EDID_QUIRK_DETAILED_IN_CM) {
925                 mode->width_mm *= 10;
926                 mode->height_mm *= 10;
927         }
928
929         if (quirks & EDID_QUIRK_DETAILED_USE_MAXIMUM_SIZE) {
930                 mode->width_mm = edid->width_cm * 10;
931                 mode->height_mm = edid->height_cm * 10;
932         }
933
934         return mode;
935 }
936
937 static bool
938 mode_is_rb(const struct drm_display_mode *mode)
939 {
940         return (mode->htotal - mode->hdisplay == 160) &&
941                (mode->hsync_end - mode->hdisplay == 80) &&
942                (mode->hsync_end - mode->hsync_start == 32) &&
943                (mode->vsync_start - mode->vdisplay == 3);
944 }
945
946 static bool
947 mode_in_hsync_range(struct drm_display_mode *mode,
948                     struct edid *edid, u8 *t)
949 {
950         int hsync, hmin, hmax;
951
952         hmin = t[7];
953         if (edid->revision >= 4)
954             hmin += ((t[4] & 0x04) ? 255 : 0);
955         hmax = t[8];
956         if (edid->revision >= 4)
957             hmax += ((t[4] & 0x08) ? 255 : 0);
958         hsync = drm_mode_hsync(mode);
959
960         return (hsync <= hmax && hsync >= hmin);
961 }
962
963 static bool
964 mode_in_vsync_range(struct drm_display_mode *mode,
965                     struct edid *edid, u8 *t)
966 {
967         int vsync, vmin, vmax;
968
969         vmin = t[5];
970         if (edid->revision >= 4)
971             vmin += ((t[4] & 0x01) ? 255 : 0);
972         vmax = t[6];
973         if (edid->revision >= 4)
974             vmax += ((t[4] & 0x02) ? 255 : 0);
975         vsync = drm_mode_vrefresh(mode);
976
977         return (vsync <= vmax && vsync >= vmin);
978 }
979
980 static u32
981 range_pixel_clock(struct edid *edid, u8 *t)
982 {
983         /* unspecified */
984         if (t[9] == 0 || t[9] == 255)
985                 return 0;
986
987         /* 1.4 with CVT support gives us real precision, yay */
988         if (edid->revision >= 4 && t[10] == 0x04)
989                 return (t[9] * 10000) - ((t[12] >> 2) * 250);
990
991         /* 1.3 is pathetic, so fuzz up a bit */
992         return t[9] * 10000 + 5001;
993 }
994
995 static bool
996 mode_in_range(struct drm_display_mode *mode, struct edid *edid,
997               struct detailed_timing *timing)
998 {
999         u32 max_clock;
1000         u8 *t = (u8 *)timing;
1001
1002         if (!mode_in_hsync_range(mode, edid, t))
1003                 return false;
1004
1005         if (!mode_in_vsync_range(mode, edid, t))
1006                 return false;
1007
1008         if ((max_clock = range_pixel_clock(edid, t)))
1009                 if (mode->clock > max_clock)
1010                         return false;
1011
1012         /* 1.4 max horizontal check */
1013         if (edid->revision >= 4 && t[10] == 0x04)
1014                 if (t[13] && mode->hdisplay > 8 * (t[13] + (256 * (t[12]&0x3))))
1015                         return false;
1016
1017         if (mode_is_rb(mode) && !drm_monitor_supports_rb(edid))
1018                 return false;
1019
1020         return true;
1021 }
1022
1023 /*
1024  * XXX If drm_dmt_modes ever regrows the CVT-R modes (and it will) this will
1025  * need to account for them.
1026  */
1027 static int
1028 drm_gtf_modes_for_range(struct drm_connector *connector, struct edid *edid,
1029                         struct detailed_timing *timing)
1030 {
1031         int i, modes = 0;
1032         struct drm_display_mode *newmode;
1033         struct drm_device *dev = connector->dev;
1034
1035         for (i = 0; i < drm_num_dmt_modes; i++) {
1036                 if (mode_in_range(drm_dmt_modes + i, edid, timing)) {
1037                         newmode = drm_mode_duplicate(dev, &drm_dmt_modes[i]);
1038                         if (newmode) {
1039                                 drm_mode_probed_add(connector, newmode);
1040                                 modes++;
1041                         }
1042                 }
1043         }
1044
1045         return modes;
1046 }
1047
1048 static void
1049 do_inferred_modes(struct detailed_timing *timing, void *c)
1050 {
1051         struct detailed_mode_closure *closure = c;
1052         struct detailed_non_pixel *data = &timing->data.other_data;
1053         int gtf = (closure->edid->features & DRM_EDID_FEATURE_DEFAULT_GTF);
1054
1055         if (gtf && data->type == EDID_DETAIL_MONITOR_RANGE)
1056                 closure->modes += drm_gtf_modes_for_range(closure->connector,
1057                                                           closure->edid,
1058                                                           timing);
1059 }
1060
1061 static int
1062 add_inferred_modes(struct drm_connector *connector, struct edid *edid)
1063 {
1064         struct detailed_mode_closure closure = {
1065                 connector, edid, 0, 0, 0
1066         };
1067
1068         if (version_greater(edid, 1, 0))
1069                 drm_for_each_detailed_block((u8 *)edid, do_inferred_modes,
1070                                             &closure);
1071
1072         return closure.modes;
1073 }
1074
1075 static int
1076 drm_est3_modes(struct drm_connector *connector, struct detailed_timing *timing)
1077 {
1078         int i, j, m, modes = 0;
1079         struct drm_display_mode *mode;
1080         u8 *est = ((u8 *)timing) + 5;
1081
1082         for (i = 0; i < 6; i++) {
1083                 for (j = 7; j > 0; j--) {
1084                         m = (i * 8) + (7 - j);
1085                         if (m >= DRM_ARRAY_SIZE(est3_modes))
1086                                 break;
1087                         if (est[i] & (1 << j)) {
1088                                 mode = drm_mode_find_dmt(connector->dev,
1089                                                          est3_modes[m].w,
1090                                                          est3_modes[m].h,
1091                                                          est3_modes[m].r
1092                                                          /*, est3_modes[m].rb */);
1093                                 if (mode) {
1094                                         drm_mode_probed_add(connector, mode);
1095                                         modes++;
1096                                 }
1097                         }
1098                 }
1099         }
1100
1101         return modes;
1102 }
1103
1104 static void
1105 do_established_modes(struct detailed_timing *timing, void *c)
1106 {
1107         struct detailed_mode_closure *closure = c;
1108         struct detailed_non_pixel *data = &timing->data.other_data;
1109
1110         if (data->type == EDID_DETAIL_EST_TIMINGS)
1111                 closure->modes += drm_est3_modes(closure->connector, timing);
1112 }
1113
1114 /**
1115  * add_established_modes - get est. modes from EDID and add them
1116  * @edid: EDID block to scan
1117  *
1118  * Each EDID block contains a bitmap of the supported "established modes" list
1119  * (defined above).  Tease them out and add them to the global modes list.
1120  */
1121 static int
1122 add_established_modes(struct drm_connector *connector, struct edid *edid)
1123 {
1124         struct drm_device *dev = connector->dev;
1125         unsigned long est_bits = edid->established_timings.t1 |
1126                 (edid->established_timings.t2 << 8) |
1127                 ((edid->established_timings.mfg_rsvd & 0x80) << 9);
1128         int i, modes = 0;
1129         struct detailed_mode_closure closure = {
1130                 connector, edid, 0, 0, 0
1131         };
1132
1133         for (i = 0; i <= EDID_EST_TIMINGS; i++) {
1134                 if (est_bits & (1<<i)) {
1135                         struct drm_display_mode *newmode;
1136                         newmode = drm_mode_duplicate(dev, &edid_est_modes[i]);
1137                         if (newmode) {
1138                                 drm_mode_probed_add(connector, newmode);
1139                                 modes++;
1140                         }
1141                 }
1142         }
1143
1144         if (version_greater(edid, 1, 0))
1145                     drm_for_each_detailed_block((u8 *)edid,
1146                                                 do_established_modes, &closure);
1147
1148         return modes + closure.modes;
1149 }
1150
1151 static void
1152 do_standard_modes(struct detailed_timing *timing, void *c)
1153 {
1154         struct detailed_mode_closure *closure = c;
1155         struct detailed_non_pixel *data = &timing->data.other_data;
1156         struct drm_connector *connector = closure->connector;
1157         struct edid *edid = closure->edid;
1158
1159         if (data->type == EDID_DETAIL_STD_MODES) {
1160                 int i;
1161                 for (i = 0; i < 6; i++) {
1162                         struct std_timing *std;
1163                         struct drm_display_mode *newmode;
1164
1165                         std = &data->data.timings[i];
1166                         newmode = drm_mode_std(connector, edid, std,
1167                                                edid->revision);
1168                         if (newmode) {
1169                                 drm_mode_probed_add(connector, newmode);
1170                                 closure->modes++;
1171                         }
1172                 }
1173         }
1174 }
1175
1176 /**
1177  * add_standard_modes - get std. modes from EDID and add them
1178  * @edid: EDID block to scan
1179  *
1180  * Standard modes can be calculated using the appropriate standard (DMT,
1181  * GTF or CVT. Grab them from @edid and add them to the list.
1182  */
1183 static int
1184 add_standard_modes(struct drm_connector *connector, struct edid *edid)
1185 {
1186         int i, modes = 0;
1187         struct detailed_mode_closure closure = {
1188                 connector, edid, 0, 0, 0
1189         };
1190
1191         for (i = 0; i < EDID_STD_TIMINGS; i++) {
1192                 struct drm_display_mode *newmode;
1193
1194                 newmode = drm_mode_std(connector, edid,
1195                                        &edid->standard_timings[i],
1196                                        edid->revision);
1197                 if (newmode) {
1198                         drm_mode_probed_add(connector, newmode);
1199                         modes++;
1200                 }
1201         }
1202
1203         if (version_greater(edid, 1, 0))
1204                 drm_for_each_detailed_block((u8 *)edid, do_standard_modes,
1205                                             &closure);
1206
1207         /* XXX should also look for standard codes in VTB blocks */
1208
1209         return modes + closure.modes;
1210 }
1211
1212 static int drm_cvt_modes(struct drm_connector *connector,
1213                          struct detailed_timing *timing)
1214 {
1215         int i, j, modes = 0;
1216         struct drm_display_mode *newmode;
1217         struct drm_device *dev = connector->dev;
1218         struct cvt_timing *cvt;
1219         const int rates[] = { 60, 85, 75, 60, 50 };
1220         const u8 empty[3] = { 0, 0, 0 };
1221
1222         for (i = 0; i < 4; i++) {
1223                 int width = 0, height;
1224                 cvt = &(timing->data.other_data.data.cvt[i]);
1225
1226                 if (!memcmp(cvt->code, empty, 3))
1227                         continue;
1228
1229                 height = (cvt->code[0] + ((cvt->code[1] & 0xf0) << 4) + 1) * 2;
1230                 switch (cvt->code[1] & 0x0c) {
1231                 case 0x00:
1232                         width = height * 4 / 3;
1233                         break;
1234                 case 0x04:
1235                         width = height * 16 / 9;
1236                         break;
1237                 case 0x08:
1238                         width = height * 16 / 10;
1239                         break;
1240                 case 0x0c:
1241                         width = height * 15 / 9;
1242                         break;
1243                 }
1244
1245                 for (j = 1; j < 5; j++) {
1246                         if (cvt->code[2] & (1 << j)) {
1247                                 newmode = drm_cvt_mode(dev, width, height,
1248                                                        rates[j], j == 0,
1249                                                        false, false);
1250                                 if (newmode) {
1251                                         drm_mode_probed_add(connector, newmode);
1252                                         modes++;
1253                                 }
1254                         }
1255                 }
1256         }
1257
1258         return modes;
1259 }
1260
1261 static void
1262 do_cvt_mode(struct detailed_timing *timing, void *c)
1263 {
1264         struct detailed_mode_closure *closure = c;
1265         struct detailed_non_pixel *data = &timing->data.other_data;
1266
1267         if (data->type == EDID_DETAIL_CVT_3BYTE)
1268                 closure->modes += drm_cvt_modes(closure->connector, timing);
1269 }
1270
1271 static int
1272 add_cvt_modes(struct drm_connector *connector, struct edid *edid)
1273 {       
1274         struct detailed_mode_closure closure = {
1275                 connector, edid, 0, 0, 0
1276         };
1277
1278         if (version_greater(edid, 1, 2))
1279                 drm_for_each_detailed_block((u8 *)edid, do_cvt_mode, &closure);
1280
1281         /* XXX should also look for CVT codes in VTB blocks */
1282
1283         return closure.modes;
1284 }
1285
1286 static void
1287 do_detailed_mode(struct detailed_timing *timing, void *c)
1288 {
1289         struct detailed_mode_closure *closure = c;
1290         struct drm_display_mode *newmode;
1291
1292         if (timing->pixel_clock) {
1293                 newmode = drm_mode_detailed(closure->connector->dev,
1294                                             closure->edid, timing,
1295                                             closure->quirks);
1296                 if (!newmode)
1297                         return;
1298
1299                 if (closure->preferred)
1300                         newmode->type |= DRM_MODE_TYPE_PREFERRED;
1301
1302                 drm_mode_probed_add(closure->connector, newmode);
1303                 closure->modes++;
1304                 closure->preferred = 0;
1305         }
1306 }
1307
1308 /*
1309  * add_detailed_modes - Add modes from detailed timings
1310  * @connector: attached connector
1311  * @edid: EDID block to scan
1312  * @quirks: quirks to apply
1313  */
1314 static int
1315 add_detailed_modes(struct drm_connector *connector, struct edid *edid,
1316                    u32 quirks)
1317 {
1318         struct detailed_mode_closure closure = {
1319                 connector,
1320                 edid,
1321                 1,
1322                 quirks,
1323                 0
1324         };
1325
1326         if (closure.preferred && !version_greater(edid, 1, 3))
1327                 closure.preferred =
1328                     (edid->features & DRM_EDID_FEATURE_PREFERRED_TIMING);
1329
1330         drm_for_each_detailed_block((u8 *)edid, do_detailed_mode, &closure);
1331
1332         return closure.modes;
1333 }
1334
1335 #define HDMI_IDENTIFIER 0x000C03
1336 #define AUDIO_BLOCK     0x01
1337 #define VENDOR_BLOCK    0x03
1338 #define SPEAKER_BLOCK   0x04
1339 #define EDID_BASIC_AUDIO        (1 << 6)
1340
1341 /**
1342  * Search EDID for CEA extension block.
1343  */
1344 u8 *drm_find_cea_extension(struct edid *edid)
1345 {
1346         u8 *edid_ext = NULL;
1347         int i;
1348
1349         /* No EDID or EDID extensions */
1350         if (edid == NULL || edid->extensions == 0)
1351                 return NULL;
1352
1353         /* Find CEA extension */
1354         for (i = 0; i < edid->extensions; i++) {
1355                 edid_ext = (u8 *)edid + EDID_LENGTH * (i + 1);
1356                 if (edid_ext[0] == CEA_EXT)
1357                         break;
1358         }
1359
1360         if (i == edid->extensions)
1361                 return NULL;
1362
1363         return edid_ext;
1364 }
1365
1366 static void
1367 parse_hdmi_vsdb(struct drm_connector *connector, uint8_t *db)
1368 {
1369         connector->eld[5] |= (db[6] >> 7) << 1;  /* Supports_AI */
1370
1371         connector->dvi_dual = db[6] & 1;
1372         connector->max_tmds_clock = db[7] * 5;
1373
1374         connector->latency_present[0] = db[8] >> 7;
1375         connector->latency_present[1] = (db[8] >> 6) & 1;
1376         connector->video_latency[0] = db[9];
1377         connector->audio_latency[0] = db[10];
1378         connector->video_latency[1] = db[11];
1379         connector->audio_latency[1] = db[12];
1380
1381         DRM_DEBUG_KMS("HDMI: DVI dual %d, "
1382                     "max TMDS clock %d, "
1383                     "latency present %d %d, "
1384                     "video latency %d %d, "
1385                     "audio latency %d %d\n",
1386                     connector->dvi_dual,
1387                     connector->max_tmds_clock,
1388               (int) connector->latency_present[0],
1389               (int) connector->latency_present[1],
1390                     connector->video_latency[0],
1391                     connector->video_latency[1],
1392                     connector->audio_latency[0],
1393                     connector->audio_latency[1]);
1394 }
1395
1396 static void
1397 monitor_name(struct detailed_timing *t, void *data)
1398 {
1399         if (t->data.other_data.type == EDID_DETAIL_MONITOR_NAME)
1400                 *(u8 **)data = t->data.other_data.data.str.str;
1401 }
1402
1403 /**
1404  * drm_edid_to_eld - build ELD from EDID
1405  * @connector: connector corresponding to the HDMI/DP sink
1406  * @edid: EDID to parse
1407  *
1408  * Fill the ELD (EDID-Like Data) buffer for passing to the audio driver.
1409  * Some ELD fields are left to the graphics driver caller:
1410  * - Conn_Type
1411  * - HDCP
1412  * - Port_ID
1413  */
1414 void drm_edid_to_eld(struct drm_connector *connector, struct edid *edid)
1415 {
1416         uint8_t *eld = connector->eld;
1417         u8 *cea;
1418         u8 *name;
1419         u8 *db;
1420         int sad_count = 0;
1421         int mnl;
1422         int dbl;
1423
1424         memset(eld, 0, sizeof(connector->eld));
1425
1426         cea = drm_find_cea_extension(edid);
1427         if (!cea) {
1428                 DRM_DEBUG_KMS("ELD: no CEA Extension found\n");
1429                 return;
1430         }
1431
1432         name = NULL;
1433         drm_for_each_detailed_block((u8 *)edid, monitor_name, &name);
1434         for (mnl = 0; name && mnl < 13; mnl++) {
1435                 if (name[mnl] == 0x0a)
1436                         break;
1437                 eld[20 + mnl] = name[mnl];
1438         }
1439         eld[4] = (cea[1] << 5) | mnl;
1440         DRM_DEBUG_KMS("ELD monitor %s\n", eld + 20);
1441
1442         eld[0] = 2 << 3;                /* ELD version: 2 */
1443
1444         eld[16] = edid->mfg_id[0];
1445         eld[17] = edid->mfg_id[1];
1446         eld[18] = edid->prod_code[0];
1447         eld[19] = edid->prod_code[1];
1448
1449         for (db = cea + 4; db < cea + cea[2]; db += dbl + 1) {
1450                 dbl = db[0] & 0x1f;
1451
1452                 switch ((db[0] & 0xe0) >> 5) {
1453                 case AUDIO_BLOCK:       /* Audio Data Block, contains SADs */
1454                         sad_count = dbl / 3;
1455                         memcpy(eld + 20 + mnl, &db[1], dbl);
1456                         break;
1457                 case SPEAKER_BLOCK:     /* Speaker Allocation Data Block */
1458                         eld[7] = db[1];
1459                         break;
1460                 case VENDOR_BLOCK:
1461                         /* HDMI Vendor-Specific Data Block */
1462                         if (db[1] == 0x03 && db[2] == 0x0c && db[3] == 0)
1463                                 parse_hdmi_vsdb(connector, db);
1464                         break;
1465                 default:
1466                         break;
1467                 }
1468         }
1469         eld[5] |= sad_count << 4;
1470         eld[2] = (20 + mnl + sad_count * 3 + 3) / 4;
1471
1472         DRM_DEBUG_KMS("ELD size %d, SAD count %d\n", (int)eld[2], sad_count);
1473 }
1474
1475 /**
1476  * drm_av_sync_delay - HDMI/DP sink audio-video sync delay in millisecond
1477  * @connector: connector associated with the HDMI/DP sink
1478  * @mode: the display mode
1479  */
1480 int drm_av_sync_delay(struct drm_connector *connector,
1481                       struct drm_display_mode *mode)
1482 {
1483         int i = !!(mode->flags & DRM_MODE_FLAG_INTERLACE);
1484         int a, v;
1485
1486         if (!connector->latency_present[0])
1487                 return 0;
1488         if (!connector->latency_present[1])
1489                 i = 0;
1490
1491         a = connector->audio_latency[i];
1492         v = connector->video_latency[i];
1493
1494         /*
1495          * HDMI/DP sink doesn't support audio or video?
1496          */
1497         if (a == 255 || v == 255)
1498                 return 0;
1499
1500         /*
1501          * Convert raw EDID values to millisecond.
1502          * Treat unknown latency as 0ms.
1503          */
1504         if (a)
1505                 a = min(2 * (a - 1), 500);
1506         if (v)
1507                 v = min(2 * (v - 1), 500);
1508
1509         return max(v - a, 0);
1510 }
1511
1512 /**
1513  * drm_select_eld - select one ELD from multiple HDMI/DP sinks
1514  * @encoder: the encoder just changed display mode
1515  * @mode: the adjusted display mode
1516  *
1517  * It's possible for one encoder to be associated with multiple HDMI/DP sinks.
1518  * The policy is now hard coded to simply use the first HDMI/DP sink's ELD.
1519  */
1520 struct drm_connector *drm_select_eld(struct drm_encoder *encoder,
1521                                      struct drm_display_mode *mode)
1522 {
1523         struct drm_connector *connector;
1524         struct drm_device *dev = encoder->dev;
1525
1526         list_for_each_entry(connector, &dev->mode_config.connector_list, head)
1527                 if (connector->encoder == encoder && connector->eld[0])
1528                         return connector;
1529
1530         return NULL;
1531 }
1532
1533 /**
1534  * drm_detect_hdmi_monitor - detect whether monitor is hdmi.
1535  * @edid: monitor EDID information
1536  *
1537  * Parse the CEA extension according to CEA-861-B.
1538  * Return true if HDMI, false if not or unknown.
1539  */
1540 bool drm_detect_hdmi_monitor(struct edid *edid)
1541 {
1542         u8 *edid_ext;
1543         int i, hdmi_id;
1544         int start_offset, end_offset;
1545         bool is_hdmi = false;
1546
1547         edid_ext = drm_find_cea_extension(edid);
1548         if (!edid_ext)
1549                 goto end;
1550
1551         /* Data block offset in CEA extension block */
1552         start_offset = 4;
1553         end_offset = edid_ext[2];
1554
1555         /*
1556          * Because HDMI identifier is in Vendor Specific Block,
1557          * search it from all data blocks of CEA extension.
1558          */
1559         for (i = start_offset; i < end_offset;
1560                 /* Increased by data block len */
1561                 i += ((edid_ext[i] & 0x1f) + 1)) {
1562                 /* Find vendor specific block */
1563                 if ((edid_ext[i] >> 5) == VENDOR_BLOCK) {
1564                         hdmi_id = edid_ext[i + 1] | (edid_ext[i + 2] << 8) |
1565                                   edid_ext[i + 3] << 16;
1566                         /* Find HDMI identifier */
1567                         if (hdmi_id == HDMI_IDENTIFIER)
1568                                 is_hdmi = true;
1569                         break;
1570                 }
1571         }
1572
1573 end:
1574         return is_hdmi;
1575 }
1576
1577 /**
1578  * drm_detect_monitor_audio - check monitor audio capability
1579  *
1580  * Monitor should have CEA extension block.
1581  * If monitor has 'basic audio', but no CEA audio blocks, it's 'basic
1582  * audio' only. If there is any audio extension block and supported
1583  * audio format, assume at least 'basic audio' support, even if 'basic
1584  * audio' is not defined in EDID.
1585  *
1586  */
1587 bool drm_detect_monitor_audio(struct edid *edid)
1588 {
1589         u8 *edid_ext;
1590         int i, j;
1591         bool has_audio = false;
1592         int start_offset, end_offset;
1593
1594         edid_ext = drm_find_cea_extension(edid);
1595         if (!edid_ext)
1596                 goto end;
1597
1598         has_audio = ((edid_ext[3] & EDID_BASIC_AUDIO) != 0);
1599
1600         if (has_audio) {
1601                 DRM_DEBUG_KMS("Monitor has basic audio support\n");
1602                 goto end;
1603         }
1604
1605         /* Data block offset in CEA extension block */
1606         start_offset = 4;
1607         end_offset = edid_ext[2];
1608
1609         for (i = start_offset; i < end_offset;
1610                         i += ((edid_ext[i] & 0x1f) + 1)) {
1611                 if ((edid_ext[i] >> 5) == AUDIO_BLOCK) {
1612                         has_audio = true;
1613                         for (j = 1; j < (edid_ext[i] & 0x1f); j += 3)
1614                                 DRM_DEBUG_KMS("CEA audio format %d\n",
1615                                               (edid_ext[i + j] >> 3) & 0xf);
1616                         goto end;
1617                 }
1618         }
1619 end:
1620         return has_audio;
1621 }
1622
1623 /**
1624  * drm_add_display_info - pull display info out if present
1625  * @edid: EDID data
1626  * @info: display info (attached to connector)
1627  *
1628  * Grab any available display info and stuff it into the drm_display_info
1629  * structure that's part of the connector.  Useful for tracking bpp and
1630  * color spaces.
1631  */
1632 static void drm_add_display_info(struct edid *edid,
1633                                  struct drm_display_info *info)
1634 {
1635         u8 *edid_ext;
1636
1637         info->width_mm = edid->width_cm * 10;
1638         info->height_mm = edid->height_cm * 10;
1639
1640         /* driver figures it out in this case */
1641         info->bpc = 0;
1642         info->color_formats = 0;
1643
1644         /* Only defined for 1.4 with digital displays */
1645         if (edid->revision < 4)
1646                 return;
1647
1648         if (!(edid->input & DRM_EDID_INPUT_DIGITAL))
1649                 return;
1650
1651         switch (edid->input & DRM_EDID_DIGITAL_DEPTH_MASK) {
1652         case DRM_EDID_DIGITAL_DEPTH_6:
1653                 info->bpc = 6;
1654                 break;
1655         case DRM_EDID_DIGITAL_DEPTH_8:
1656                 info->bpc = 8;
1657                 break;
1658         case DRM_EDID_DIGITAL_DEPTH_10:
1659                 info->bpc = 10;
1660                 break;
1661         case DRM_EDID_DIGITAL_DEPTH_12:
1662                 info->bpc = 12;
1663                 break;
1664         case DRM_EDID_DIGITAL_DEPTH_14:
1665                 info->bpc = 14;
1666                 break;
1667         case DRM_EDID_DIGITAL_DEPTH_16:
1668                 info->bpc = 16;
1669                 break;
1670         case DRM_EDID_DIGITAL_DEPTH_UNDEF:
1671         default:
1672                 info->bpc = 0;
1673                 break;
1674         }
1675
1676         info->color_formats = DRM_COLOR_FORMAT_RGB444;
1677         if (info->color_formats & DRM_EDID_FEATURE_RGB_YCRCB444)
1678                 info->color_formats = DRM_COLOR_FORMAT_YCRCB444;
1679         if (info->color_formats & DRM_EDID_FEATURE_RGB_YCRCB422)
1680                 info->color_formats = DRM_COLOR_FORMAT_YCRCB422;
1681
1682         /* Get data from CEA blocks if present */
1683         edid_ext = drm_find_cea_extension(edid);
1684         if (!edid_ext)
1685                 return;
1686
1687         info->cea_rev = edid_ext[1];
1688 }
1689
1690 /**
1691  * drm_add_edid_modes - add modes from EDID data, if available
1692  * @connector: connector we're probing
1693  * @edid: edid data
1694  *
1695  * Add the specified modes to the connector's mode list.
1696  *
1697  * Return number of modes added or 0 if we couldn't find any.
1698  */
1699 int drm_add_edid_modes(struct drm_connector *connector, struct edid *edid)
1700 {
1701         int num_modes = 0;
1702         u32 quirks;
1703
1704         if (edid == NULL) {
1705                 return 0;
1706         }
1707         if (!drm_edid_is_valid(edid)) {
1708                 device_printf(connector->dev->device, "%s: EDID invalid.\n",
1709                          drm_get_connector_name(connector));
1710                 return 0;
1711         }
1712
1713         quirks = edid_get_quirks(edid);
1714
1715         /*
1716          * EDID spec says modes should be preferred in this order:
1717          * - preferred detailed mode
1718          * - other detailed modes from base block
1719          * - detailed modes from extension blocks
1720          * - CVT 3-byte code modes
1721          * - standard timing codes
1722          * - established timing codes
1723          * - modes inferred from GTF or CVT range information
1724          *
1725          * We get this pretty much right.
1726          *
1727          * XXX order for additional mode types in extension blocks?
1728          */
1729         num_modes += add_detailed_modes(connector, edid, quirks);
1730         num_modes += add_cvt_modes(connector, edid);
1731         num_modes += add_standard_modes(connector, edid);
1732         num_modes += add_established_modes(connector, edid);
1733         num_modes += add_inferred_modes(connector, edid);
1734
1735         if (quirks & (EDID_QUIRK_PREFER_LARGE_60 | EDID_QUIRK_PREFER_LARGE_75))
1736                 edid_fixup_preferred(connector, quirks);
1737
1738         drm_add_display_info(edid, &connector->display_info);
1739
1740         return num_modes;
1741 }
1742
1743 /**
1744  * drm_add_modes_noedid - add modes for the connectors without EDID
1745  * @connector: connector we're probing
1746  * @hdisplay: the horizontal display limit
1747  * @vdisplay: the vertical display limit
1748  *
1749  * Add the specified modes to the connector's mode list. Only when the
1750  * hdisplay/vdisplay is not beyond the given limit, it will be added.
1751  *
1752  * Return number of modes added or 0 if we couldn't find any.
1753  */
1754 int drm_add_modes_noedid(struct drm_connector *connector,
1755                         int hdisplay, int vdisplay)
1756 {
1757         int i, count, num_modes = 0;
1758         struct drm_display_mode *mode;
1759         struct drm_device *dev = connector->dev;
1760
1761         count = sizeof(drm_dmt_modes) / sizeof(struct drm_display_mode);
1762         if (hdisplay < 0)
1763                 hdisplay = 0;
1764         if (vdisplay < 0)
1765                 vdisplay = 0;
1766
1767         for (i = 0; i < count; i++) {
1768                 struct drm_display_mode *ptr = &drm_dmt_modes[i];
1769                 if (hdisplay && vdisplay) {
1770                         /*
1771                          * Only when two are valid, they will be used to check
1772                          * whether the mode should be added to the mode list of
1773                          * the connector.
1774                          */
1775                         if (ptr->hdisplay > hdisplay ||
1776                                         ptr->vdisplay > vdisplay)
1777                                 continue;
1778                 }
1779                 if (drm_mode_vrefresh(ptr) > 61)
1780                         continue;
1781                 mode = drm_mode_duplicate(dev, ptr);
1782                 if (mode) {
1783                         drm_mode_probed_add(connector, mode);
1784                         num_modes++;
1785                 }
1786         }
1787         return num_modes;
1788 }