Add a function to lock/unlock all crtcs, use it in nv_bios code
[nouveau] / src / nv_bios.c
1 /*
2  * Copyright 2005-2006 Erik Waling
3  * Copyright 2006 Stephane Marchesin
4  * Copyright 2007-2008 Stuart Bennett
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
21  * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24
25 #include "nv_include.h"
26
27
28 #if defined(__FreeBSD__) || defined(__NetBSD__)
29 #define bswap_16 bswap16
30 #define bswap_32 bswap32
31 #else
32 #include <byteswap.h>
33 #endif
34
35
36 /* these defines are made up */
37 #define NV_CIO_CRE_44_HEADA 0x0
38 #define NV_CIO_CRE_44_HEADB 0x3
39 #define FEATURE_MOBILE 0x10
40
41 //#define BIOSLOG(sip, fmt, arg...) xf86DrvMsg(sip->scrnIndex, X_INFO, fmt, ##arg)
42 //#define LOG_OLD_VALUE(x) x
43 #define BIOSLOG(sip, fmt, arg...)
44 #define LOG_OLD_VALUE(x)
45
46 #define BIOS_USLEEP(n) usleep(n)
47
48 static int crtchead = 0;
49
50 /* this will need remembering across a suspend */
51 static uint32_t saved_nv_pfb_cfg0;
52
53 typedef struct {
54         bool execute;
55         bool repeat;
56 } init_exec_t;
57
58 static uint16_t le16_to_cpu(const uint16_t x)
59 {
60 #if X_BYTE_ORDER == X_BIG_ENDIAN
61         return bswap_16(x);
62 #else
63         return x;
64 #endif
65 }
66
67 static uint32_t le32_to_cpu(const uint32_t x)
68 {
69 #if X_BYTE_ORDER == X_BIG_ENDIAN
70         return bswap_32(x);
71 #else
72         return x;
73 #endif
74 }
75
76 static bool nv_cksum(const uint8_t *data, unsigned int length)
77 {
78         /* there's a few checksums in the BIOS, so here's a generic checking function */
79         int i;
80         uint8_t sum = 0;
81
82         for (i = 0; i < length; i++)
83                 sum += data[i];
84
85         if (sum)
86                 return true;
87
88         return false;
89 }
90
91 static int score_vbios(ScrnInfoPtr pScrn, const uint8_t *data)
92 {
93         if (!(data[0] == 0x55 && data[1] == 0xAA)) {
94                 xf86DrvMsg(pScrn->scrnIndex, X_NOTICE, "... BIOS signature not found\n");
95                 return 0;
96         }
97
98         if (nv_cksum(data, data[2] * 512)) {
99                 xf86DrvMsg(pScrn->scrnIndex, X_NOTICE, "... BIOS checksum invalid\n");
100                 return 1;
101         } else
102                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "... appears to be valid\n");
103
104         return 2;
105 }
106
107 static void load_vbios_prom(NVPtr pNv, uint8_t *data)
108 {
109         int i;
110
111         /* enable ROM access */
112         nvWriteMC(pNv, NV_PBUS_PCI_NV_20, NV_PBUS_PCI_NV_20_ROM_SHADOW_DISABLED);
113         for (i = 0; i < NV_PROM_SIZE; i++) {
114                 /* according to nvclock, we need that to work around a 6600GT/6800LE bug */
115                 data[i] = NV_RD08(pNv->REGS, NV_PROM_OFFSET + i);
116                 data[i] = NV_RD08(pNv->REGS, NV_PROM_OFFSET + i);
117                 data[i] = NV_RD08(pNv->REGS, NV_PROM_OFFSET + i);
118                 data[i] = NV_RD08(pNv->REGS, NV_PROM_OFFSET + i);
119                 data[i] = NV_RD08(pNv->REGS, NV_PROM_OFFSET + i);
120         }
121         /* disable ROM access */
122         nvWriteMC(pNv, NV_PBUS_PCI_NV_20, NV_PBUS_PCI_NV_20_ROM_SHADOW_ENABLED);
123 }
124
125 static void load_vbios_pramin(NVPtr pNv, uint8_t *data)
126 {
127         uint32_t old_bar0_pramin = 0;
128         int i;
129
130         if (pNv->Architecture >= NV_ARCH_50) {
131                 uint32_t vbios_vram = (NV_RD32(pNv->REGS, 0x619f04) & ~0xff) << 8;
132
133                 if (!vbios_vram)
134                         vbios_vram = (NV_RD32(pNv->REGS, 0x1700) << 16) + 0xf0000;
135
136                 old_bar0_pramin = NV_RD32(pNv->REGS, 0x1700);
137                 NV_WR32(pNv->REGS, 0x1700, vbios_vram >> 16);
138         }
139
140         for (i = 0; i < NV_PROM_SIZE; i++)
141                 data[i] = NV_RD08(pNv->REGS, NV_PRAMIN_OFFSET + i);
142
143         if (pNv->Architecture >= NV_ARCH_50)
144                 NV_WR32(pNv->REGS, 0x1700, old_bar0_pramin);
145 }
146
147 static void load_vbios_pci(NVPtr pNv, uint8_t *data)
148 {
149 #if XSERVER_LIBPCIACCESS
150         pci_device_read_rom(pNv->PciInfo, data);
151 #else
152         xf86ReadPciBIOS(0, pNv->PciTag, 0, data, NV_PROM_SIZE);
153 #endif
154 }
155
156 static bool NVShadowVBIOS(ScrnInfoPtr pScrn, uint8_t *data)
157 {
158         NVPtr pNv = NVPTR(pScrn);
159         struct methods {
160                 const char desc[8];
161                 void (*loadbios)(NVPtr, uint8_t *);
162                 int score;
163         } method[] = {
164 #ifndef __powerpc__
165                 { "PROM", load_vbios_prom },
166 #endif
167                 { "PRAMIN", load_vbios_pramin },
168 #ifndef __powerpc__
169                 { "PCI ROM", load_vbios_pci }
170 #endif
171         };
172         int i;
173
174         for (i = 0; i < sizeof(method) / sizeof(struct methods); i++) {
175                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
176                            "Attempting to load BIOS image from %s\n", method[i].desc);
177                 method[i].loadbios(pNv, data);
178                 if ((method[i].score = score_vbios(pScrn, data)) == 2)
179                         return true;
180         }
181
182         for (i = 0; i < sizeof(method) / sizeof(struct methods); i++)
183                 if (method[i].score == 1) {
184                         xf86DrvMsg(pScrn->scrnIndex, X_INFO,
185                                    "Using BIOS image from %s\n", method[i].desc);
186                         method[i].loadbios(pNv, data);
187                         return true;
188                 }
189
190         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "No valid BIOS image found\n");
191
192         return false;
193 }
194
195 typedef struct {
196         char* name;
197         uint8_t id;
198         int length;
199         int length_offset;
200         int length_multiplier;
201         bool (*handler)(ScrnInfoPtr pScrn, bios_t *, uint16_t, init_exec_t *);
202 } init_tbl_entry_t;
203
204 typedef struct {
205         uint8_t id[2];
206         uint16_t length;
207         uint16_t offset;
208 } bit_entry_t;
209
210 static void parse_init_table(ScrnInfoPtr pScrn, bios_t *bios, unsigned int offset, init_exec_t *iexec);
211
212 #define MACRO_INDEX_SIZE        2
213 #define MACRO_SIZE              8
214 #define CONDITION_SIZE          12
215 #define IO_FLAG_CONDITION_SIZE  9
216 #define MEM_INIT_SIZE           66
217
218 static void still_alive(void)
219 {
220 //      sync();
221 //      BIOS_USLEEP(2000);
222 }
223
224 static int nv_valid_reg(ScrnInfoPtr pScrn, uint32_t reg)
225 {
226         NVPtr pNv = NVPTR(pScrn);
227
228         /* C51 has misaligned regs on purpose. Marvellous */
229         if ((reg & 0x3 && pNv->VBIOS.chip_version != 0x51) ||
230                         (reg & 0x2 && pNv->VBIOS.chip_version == 0x51)) {
231                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
232                            "========== misaligned reg 0x%08X ==========\n", reg);
233                 return 0;
234         }
235
236         #define WITHIN(x,y,z) ((x>=y)&&(x<=y+z))
237         if (WITHIN(reg,NV_PMC_OFFSET,NV_PMC_SIZE))
238                 return 1;
239         if (WITHIN(reg,NV_PBUS_OFFSET,NV_PBUS_SIZE))
240                 return 1;
241         if (WITHIN(reg,NV_PFIFO_OFFSET,NV_PFIFO_SIZE))
242                 return 1;
243         /* maybe a little large, but it will do for the moment. */
244         if (pNv->VBIOS.chip_version >= 0x80 && WITHIN(reg, 0x1000, 0xEFFF))
245                 return 1;
246         if (pNv->VBIOS.chip_version >= 0x30 && WITHIN(reg,0x4000,0x600))
247                 return 1;
248         if (pNv->VBIOS.chip_version >= 0x40 && WITHIN(reg,0xc000,0x48))
249                 return 1;
250         if (pNv->VBIOS.chip_version >= 0x17 && reg == 0x0000d204)
251                 return 1;
252         if (pNv->VBIOS.chip_version >= 0x40) {
253                 if (reg == 0x00011014 || reg == 0x00020328)
254                         return 1;
255                 if (WITHIN(reg,0x88000,NV_PBUS_SIZE)) /* new PBUS */
256                         return 1;
257         }
258         if (WITHIN(reg,NV_PFB_OFFSET,NV_PFB_SIZE))
259                 return 1;
260         if (WITHIN(reg,NV_PEXTDEV_OFFSET,NV_PEXTDEV_SIZE))
261                 return 1;
262         if (WITHIN(reg,NV_PCRTC0_OFFSET,NV_PCRTC0_SIZE * 2))
263                 return 1;
264         if (pNv->VBIOS.chip_version >= 0x80 && WITHIN(reg, NV50_DISPLAY_OFFSET, NV50_DISPLAY_SIZE))
265                 return 1;
266         if (WITHIN(reg,NV_PRAMDAC0_OFFSET,NV_PRAMDAC0_SIZE * 2))
267                 return 1;
268         if (pNv->VBIOS.chip_version >= 0x17 && reg == 0x0070fff0)
269                 return 1;
270         if (pNv->VBIOS.chip_version == 0x51 && WITHIN(reg,NV_PRAMIN_OFFSET,NV_PRAMIN_SIZE))
271                 return 1;
272         #undef WITHIN
273
274         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
275                    "========== unknown reg 0x%08X ==========\n", reg);
276
277         return 0;
278 }
279
280 static bool nv_valid_idx_port(ScrnInfoPtr pScrn, uint16_t port)
281 {
282         /* if adding more ports here, the read/write functions below will need
283          * updating so that the correct mmio range (PRMCIO, PRMDIO, PRMVIO) is
284          * used for the port in question
285          */
286         if (port == NV_CIO_CRX__COLOR)
287                 return true;
288         if (port == NV_VIO_SRX)
289                 return true;
290
291         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
292                    "========== unknown indexed io port 0x%04X ==========\n", port);
293
294         return false;
295 }
296
297 static bool nv_valid_port(ScrnInfoPtr pScrn, uint16_t port)
298 {
299         /* if adding more ports here, the read/write functions below will need
300          * updating so that the correct mmio range (PRMCIO, PRMDIO, PRMVIO) is
301          * used for the port in question
302          */
303         if (port == NV_VIO_VSE2)
304                 return true;
305
306         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
307                    "========== unknown io port 0x%04X ==========\n", port);
308
309         return false;
310 }
311
312 static uint32_t nv32_rd(ScrnInfoPtr pScrn, uint32_t reg)
313 {
314         NVPtr pNv = NVPTR(pScrn);
315         uint32_t data;
316
317         if (!nv_valid_reg(pScrn, reg))
318                 return 0;
319
320         /* C51 sometimes uses regs with bit0 set in the address. For these
321          * cases there should exist a translation in a BIOS table to an IO
322          * port address which the BIOS uses for accessing the reg
323          *
324          * These only seem to appear for the power control regs to a flat panel
325          * and in C51 mmio traces the normal regs for 0x1308 and 0x1310 are
326          * used - hence the mask below. An S3 suspend-resume mmio trace from a
327          * C51 will be required to see if this is true for the power microcode
328          * in 0x14.., or whether the direct IO port access method is needed
329          */
330         if (reg & 0x1)
331                 reg &= ~0x1;
332
333         data = NV_RD32(pNv->REGS, reg);
334
335         BIOSLOG(pScrn, "        Read:  Reg: 0x%08X, Data: 0x%08X\n", reg, data);
336
337         return data;
338 }
339
340 static void nv32_wr(ScrnInfoPtr pScrn, uint32_t reg, uint32_t data)
341 {
342         NVPtr pNv = NVPTR(pScrn);
343
344         if (!nv_valid_reg(pScrn, reg))
345                 return;
346
347         /* see note in nv32_rd */
348         if (reg & 0x1)
349                 reg &= 0xfffffffe;
350
351         LOG_OLD_VALUE(nv32_rd(pScrn, reg));
352         BIOSLOG(pScrn, "        Write: Reg: 0x%08X, Data: 0x%08X\n", reg, data);
353
354         if (pNv->VBIOS.execute) {
355                 still_alive();
356                 NV_WR32(pNv->REGS, reg, data);
357         }
358 }
359
360 static uint8_t nv_idx_port_rd(ScrnInfoPtr pScrn, uint16_t port, uint8_t index)
361 {
362         NVPtr pNv = NVPTR(pScrn);
363         uint8_t data;
364
365         if (!nv_valid_idx_port(pScrn, port))
366                 return 0;
367
368         if (port == NV_VIO_SRX)
369                 data = NVReadVgaSeq(pNv, crtchead, index);
370         else    /* assume NV_CIO_CRX__COLOR */
371                 data = NVReadVgaCrtc(pNv, crtchead, index);
372
373         BIOSLOG(pScrn, "        Indexed IO read:  Port: 0x%04X, Index: 0x%02X, Head: 0x%02X, Data: 0x%02X\n",
374                 port, index, crtchead, data);
375
376         return data;
377 }
378
379 static void nv_idx_port_wr(ScrnInfoPtr pScrn, uint16_t port, uint8_t index, uint8_t data)
380 {
381         NVPtr pNv = NVPTR(pScrn);
382
383         if (!nv_valid_idx_port(pScrn, port))
384                 return;
385
386         /* The current head is maintained in a file scope variable crtchead.
387          * We trap changes to CR44 and update the head variable and hence the
388          * register set written.
389          * As CR44 only exists on CRTC0, we update crtchead to head0 in advance
390          * of the write, and to head1 after the write
391          */
392         if (port == NV_CIO_CRX__COLOR && index == NV_CIO_CRE_44 && data != NV_CIO_CRE_44_HEADB)
393                 crtchead = 0;
394
395         LOG_OLD_VALUE(nv_idx_port_rd(pScrn, port, index));
396         BIOSLOG(pScrn, "        Indexed IO write: Port: 0x%04X, Index: 0x%02X, Head: 0x%02X, Data: 0x%02X\n",
397                 port, index, crtchead, data);
398
399         if (pNv->VBIOS.execute) {
400                 still_alive();
401                 if (port == NV_VIO_SRX)
402                         NVWriteVgaSeq(pNv, crtchead, index, data);
403                 else    /* assume NV_CIO_CRX__COLOR */
404                         NVWriteVgaCrtc(pNv, crtchead, index, data);
405         }
406
407         if (port == NV_CIO_CRX__COLOR && index == NV_CIO_CRE_44 && data == NV_CIO_CRE_44_HEADB)
408                 crtchead = 1;
409 }
410
411 static uint8_t nv_port_rd(ScrnInfoPtr pScrn, uint16_t port)
412 {
413         NVPtr pNv = NVPTR(pScrn);
414         uint8_t data;
415
416         if (!nv_valid_port(pScrn, port))
417                 return 0;
418
419         data = NVReadPRMVIO(pNv, crtchead, NV_PRMVIO0_OFFSET + port);
420
421         BIOSLOG(pScrn, "        IO read:  Port: 0x%04X, Head: 0x%02X, Data: 0x%02X\n",
422                 port, crtchead, data);
423
424         return data;
425 }
426
427 static void nv_port_wr(ScrnInfoPtr pScrn, uint16_t port, uint8_t data)
428 {
429         NVPtr pNv = NVPTR(pScrn);
430
431         if (!nv_valid_port(pScrn, port))
432                 return;
433
434         LOG_OLD_VALUE(nv_port_rd(pScrn, port));
435         BIOSLOG(pScrn, "        IO write: Port: 0x%04X, Head: 0x%02X, Data: 0x%02X\n",
436                 port, crtchead, data);
437
438         if (pNv->VBIOS.execute) {
439                 still_alive();
440                 NVWritePRMVIO(pNv, crtchead, NV_PRMVIO0_OFFSET + port, data);
441         }
442 }
443
444 static bool io_flag_condition(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, uint8_t cond)
445 {
446         /* The IO flag condition entry has 2 bytes for the CRTC port; 1 byte
447          * for the CRTC index; 1 byte for the mask to apply to the value
448          * retrieved from the CRTC; 1 byte for the shift right to apply to the
449          * masked CRTC value; 2 bytes for the offset to the flag array, to
450          * which the shifted value is added; 1 byte for the mask applied to the
451          * value read from the flag array; and 1 byte for the value to compare
452          * against the masked byte from the flag table.
453          */
454
455         uint16_t condptr = bios->io_flag_condition_tbl_ptr + cond * IO_FLAG_CONDITION_SIZE;
456         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[condptr])));
457         uint8_t crtcindex = bios->data[condptr + 2];
458         uint8_t mask = bios->data[condptr + 3];
459         uint8_t shift = bios->data[condptr + 4];
460         uint16_t flagarray = le16_to_cpu(*((uint16_t *)(&bios->data[condptr + 5])));
461         uint8_t flagarraymask = bios->data[condptr + 7];
462         uint8_t cmpval = bios->data[condptr + 8];
463         uint8_t data;
464
465         BIOSLOG(pScrn, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, Shift: 0x%02X, FlagArray: 0x%04X, FAMask: 0x%02X, Cmpval: 0x%02X\n",
466                 offset, crtcport, crtcindex, mask, shift, flagarray, flagarraymask, cmpval);
467
468         data = nv_idx_port_rd(pScrn, crtcport, crtcindex);
469
470         data = bios->data[flagarray + ((data & mask) >> shift)];
471         data &= flagarraymask;
472
473         BIOSLOG(pScrn, "0x%04X: Checking if 0x%02X equals 0x%02X\n", offset, data, cmpval);
474
475         if (data == cmpval)
476                 return true;
477
478         return false;
479 }
480
481 int getMNP_single(ScrnInfoPtr pScrn, struct pll_lims *pll_lim, int clk, int *bestNM, int *bestlog2P)
482 {
483         /* Find M, N and P for a single stage PLL
484          *
485          * Note that some bioses (NV3x) have lookup tables of precomputed MNP
486          * values, but we're too lazy to use those atm
487          *
488          * "clk" parameter in kHz
489          * returns calculated clock
490          */
491
492         bios_t *bios = &NVPTR(pScrn)->VBIOS;
493         int minvco = pll_lim->vco1.minfreq, maxvco = pll_lim->vco1.maxfreq;
494         int minM = pll_lim->vco1.min_m, maxM = pll_lim->vco1.max_m;
495         int minN = pll_lim->vco1.min_n, maxN = pll_lim->vco1.max_n;
496         int minU = pll_lim->vco1.min_inputfreq, maxU = pll_lim->vco1.max_inputfreq;
497         int maxlog2P;
498         int crystal = pll_lim->refclk;
499         int M, N, log2P, P;
500         int clkP, calcclk;
501         int delta, bestdelta = INT_MAX;
502         int bestclk = 0;
503
504         /* this division verified for nv20, nv18, nv28 (Haiku), and nv34 */
505         /* possibly correlated with introduction of 27MHz crystal */
506         if (bios->chip_version <= 0x16 || bios->chip_version == 0x20) {
507                 if (clk > 250000)
508                         maxM = 6;
509                 if (clk > 340000)
510                         maxM = 2;
511                 maxlog2P = 4;
512         } else if (bios->chip_version < 0x40) {
513                 if (clk > 150000)
514                         maxM = 6;
515                 if (clk > 200000)
516                         maxM = 4;
517                 if (clk > 340000)
518                         maxM = 2;
519                 maxlog2P = 5;
520         } else /* nv4x may be subject to the nv17+ limits, but assume not for now */
521                 maxlog2P = 6;
522
523         if ((clk << maxlog2P) < minvco) {
524                 minvco = clk << maxlog2P;
525                 maxvco = minvco * 2;
526         }
527         if (clk + clk/200 > maxvco)     /* +0.5% */
528                 maxvco = clk + clk/200;
529
530         /* NV34 goes maxlog2P->0, NV20 goes 0->maxlog2P */
531         for (log2P = 0; log2P <= maxlog2P; log2P++) {
532                 P = 1 << log2P;
533                 clkP = clk * P;
534
535                 if (clkP < minvco)
536                         continue;
537                 if (clkP > maxvco)
538                         return bestclk;
539
540                 for (M = minM; M <= maxM; M++) {
541                         if (crystal/M < minU)
542                                 return bestclk;
543                         if (crystal/M > maxU)
544                                 continue;
545
546                         /* add crystal/2 to round better */
547                         N = (clkP * M + crystal/2) / crystal;
548
549                         if (N < minN)
550                                 continue;
551                         if (N > maxN)
552                                 break;
553
554                         /* more rounding additions */
555                         calcclk = ((N * crystal + P/2) / P + M/2) / M;
556                         delta = abs(calcclk - clk);
557                         /* we do an exhaustive search rather than terminating
558                          * on an optimality condition...
559                          */
560                         if (delta < bestdelta) {
561                                 bestdelta = delta;
562                                 bestclk = calcclk;
563                                 *bestNM = N << 8 | M;
564                                 *bestlog2P = log2P;
565                                 if (delta == 0) /* except this one */
566                                         return bestclk;
567                         }
568                 }
569         }
570
571         return bestclk;
572 }
573
574 int getMNP_double(ScrnInfoPtr pScrn, struct pll_lims *pll_lim, int clk, int *bestNM1, int *bestNM2, int *bestlog2P)
575 {
576         /* Find M, N and P for a two stage PLL
577          *
578          * Note that some bioses (NV30+) have lookup tables of precomputed MNP
579          * values, but we're too lazy to use those atm
580          *
581          * "clk" parameter in kHz
582          * returns calculated clock
583          */
584
585         int minvco1 = pll_lim->vco1.minfreq, maxvco1 = pll_lim->vco1.maxfreq;
586         int minvco2 = pll_lim->vco2.minfreq, maxvco2 = pll_lim->vco2.maxfreq;
587         int minU1 = pll_lim->vco1.min_inputfreq, minU2 = pll_lim->vco2.min_inputfreq;
588         int maxU1 = pll_lim->vco1.max_inputfreq, maxU2 = pll_lim->vco2.max_inputfreq;
589         int minM1 = pll_lim->vco1.min_m, maxM1 = pll_lim->vco1.max_m;
590         int minN1 = pll_lim->vco1.min_n, maxN1 = pll_lim->vco1.max_n;
591         int minM2 = pll_lim->vco2.min_m, maxM2 = pll_lim->vco2.max_m;
592         int minN2 = pll_lim->vco2.min_n, maxN2 = pll_lim->vco2.max_n;
593         int crystal = pll_lim->refclk;
594         bool fixedgain2 = (minM2 == maxM2 && minN2 == maxN2);
595         int M1, N1, M2, N2, log2P;
596         int clkP, calcclk1, calcclk2, calcclkout;
597         int delta, bestdelta = INT_MAX;
598         int bestclk = 0;
599
600         int vco2 = (maxvco2 - maxvco2/200) / 2;
601         for (log2P = 0; clk && log2P < 6 && clk <= (vco2 >> log2P); log2P++) /* log2P is maximum of 6 */
602                 ;
603         clkP = clk << log2P;
604
605         if (maxvco2 < clk + clk/200)    /* +0.5% */
606                 maxvco2 = clk + clk/200;
607
608         for (M1 = minM1; M1 <= maxM1; M1++) {
609                 if (crystal/M1 < minU1)
610                         return bestclk;
611                 if (crystal/M1 > maxU1)
612                         continue;
613
614                 for (N1 = minN1; N1 <= maxN1; N1++) {
615                         calcclk1 = crystal * N1 / M1;
616                         if (calcclk1 < minvco1)
617                                 continue;
618                         if (calcclk1 > maxvco1)
619                                 break;
620
621                         for (M2 = minM2; M2 <= maxM2; M2++) {
622                                 if (calcclk1/M2 < minU2)
623                                         break;
624                                 if (calcclk1/M2 > maxU2)
625                                         continue;
626
627                                 /* add calcclk1/2 to round better */
628                                 N2 = (clkP * M2 + calcclk1/2) / calcclk1;
629                                 if (N2 < minN2)
630                                         continue;
631                                 if (N2 > maxN2)
632                                         break;
633
634                                 if (!fixedgain2) {
635                                         if (NVPTR(pScrn)->VBIOS.chip_version < 0x60)
636                                                 if (N2/M2 < 4 || N2/M2 > 10)
637                                                         continue;
638
639                                         calcclk2 = calcclk1 * N2 / M2;
640                                         if (calcclk2 < minvco2)
641                                                 break;
642                                         if (calcclk2 > maxvco2)
643                                                 continue;
644                                 } else
645                                         calcclk2 = calcclk1;
646
647                                 calcclkout = calcclk2 >> log2P;
648                                 delta = abs(calcclkout - clk);
649                                 /* we do an exhaustive search rather than terminating
650                                  * on an optimality condition...
651                                  */
652                                 if (delta < bestdelta) {
653                                         bestdelta = delta;
654                                         bestclk = calcclkout;
655                                         *bestNM1 = N1 << 8 | M1;
656                                         *bestNM2 = N2 << 8 | M2;
657                                         *bestlog2P = log2P;
658                                         if (delta == 0) /* except this one */
659                                                 return bestclk;
660                                 }
661                         }
662                 }
663         }
664
665         return bestclk;
666 }
667
668 static void setPLL_single(ScrnInfoPtr pScrn, uint32_t reg, int NM, int log2P)
669 {
670         bios_t *bios = &NVPTR(pScrn)->VBIOS;
671         uint32_t oldpll = nv32_rd(pScrn, reg);
672         uint32_t pll = (oldpll & 0xfff80000) | log2P << 16 | NM;
673         uint32_t saved_powerctrl_1 = 0;
674         int shift_powerctrl_1 = -4;
675
676         if (oldpll == pll)
677                 return; /* already set */
678
679         /* nv18 doesn't change POWERCTRL_1 for VPLL*; does gf4 need special-casing? */
680         if (bios->chip_version >= 0x17 && bios->chip_version != 0x20) {
681                 switch (reg) {
682                 case NV_RAMDAC_VPLL2:
683                         shift_powerctrl_1 += 4;
684                 case NV_RAMDAC_VPLL:
685                         shift_powerctrl_1 += 4;
686                 case NV_RAMDAC_MPLL:
687                         shift_powerctrl_1 += 4;
688                 case NV_RAMDAC_NVPLL:
689                         shift_powerctrl_1 += 4;
690                 }
691
692                 if (shift_powerctrl_1 >= 0) {
693                         saved_powerctrl_1 = nv32_rd(pScrn, NV_PBUS_POWERCTRL_1);
694                         nv32_wr(pScrn, NV_PBUS_POWERCTRL_1, (saved_powerctrl_1 & ~(0xf << shift_powerctrl_1)) | 1 << shift_powerctrl_1);
695                 }
696         }
697
698         /* write NM first */
699         nv32_wr(pScrn, reg, (oldpll & 0xffff0000) | NM);
700
701         /* wait a bit */
702         BIOS_USLEEP(64000);
703         nv32_rd(pScrn, reg);
704
705         /* then write P as well */
706         nv32_wr(pScrn, reg, pll);
707
708         if (shift_powerctrl_1 >= 0)
709                 nv32_wr(pScrn, NV_PBUS_POWERCTRL_1, saved_powerctrl_1);
710 }
711
712 static void setPLL_double_highregs(ScrnInfoPtr pScrn, uint32_t reg1, int NM1, int NM2, int log2P)
713 {
714         bios_t *bios = &NVPTR(pScrn)->VBIOS;
715         bool nv3035 = bios->chip_version == 0x30 || bios->chip_version == 0x35;
716         uint32_t reg2 = reg1 + ((reg1 == NV_RAMDAC_VPLL2) ? 0x5c : 0x70);
717         uint32_t oldpll1 = nv32_rd(pScrn, reg1), oldpll2 = !nv3035 ? nv32_rd(pScrn, reg2) : 0;
718         uint32_t pll1 = (oldpll1 & 0xfff80000) | log2P << 16 | NM1;
719         uint32_t pll2 = !nv3035 ? (oldpll2 & 0x7fff0000) | 1 << 31 | NM2 : 0;
720         uint32_t saved_powerctrl_1 = 0, savedc040 = 0, maskc040 = ~0;
721         int shift_powerctrl_1 = -1;
722         bool single_stage = !NM2 || (((NM2 >> 8) & 0xff) == (NM2 & 0xff));
723
724         if (nv3035)
725                 pll1 = (pll1 & 0xfcc7ffff) | (NM2 & (0x18 << 8)) << 13 | (NM2 & (0x7 << 8)) << 11 | 8 << 4 | (NM2 & 7) << 4;
726         
727         if (oldpll1 == pll1 && oldpll2 == pll2)
728                 return; /* already set */
729
730         if (reg1 == NV_RAMDAC_NVPLL) {
731                 shift_powerctrl_1 = 0;
732                 maskc040 = ~(3 << 20);
733         }
734         if (reg1 == NV_RAMDAC_MPLL) {
735                 shift_powerctrl_1 = 4;
736                 maskc040 = ~(3 << 22);
737         }
738         if (shift_powerctrl_1 >= 0) {
739                 saved_powerctrl_1 = nv32_rd(pScrn, NV_PBUS_POWERCTRL_1);
740                 nv32_wr(pScrn, NV_PBUS_POWERCTRL_1, (saved_powerctrl_1 & ~(0xf << shift_powerctrl_1)) | 1 << shift_powerctrl_1);
741         }
742
743         if (bios->chip_version >= 0x40) {
744                 savedc040 = nv32_rd(pScrn, 0xc040);
745                 nv32_wr(pScrn, 0xc040, savedc040 & maskc040);
746
747                 if (!single_stage) {
748                         if (reg1 == NV_RAMDAC_VPLL)
749                                 nv32_wr(pScrn, NV_RAMDAC_580, nv32_rd(pScrn, NV_RAMDAC_580) & ~NV_RAMDAC_580_VPLL1_ACTIVE);
750                         if (reg1 == NV_RAMDAC_VPLL2)
751                                 nv32_wr(pScrn, NV_RAMDAC_580, nv32_rd(pScrn, NV_RAMDAC_580) & ~NV_RAMDAC_580_VPLL2_ACTIVE);
752                 } else {
753                         if (reg1 == NV_RAMDAC_VPLL)
754                                 nv32_wr(pScrn, NV_RAMDAC_580, nv32_rd(pScrn, NV_RAMDAC_580) | NV_RAMDAC_580_VPLL1_ACTIVE);
755                         if (reg1 == NV_RAMDAC_VPLL2)
756                                 nv32_wr(pScrn, NV_RAMDAC_580, nv32_rd(pScrn, NV_RAMDAC_580) | NV_RAMDAC_580_VPLL2_ACTIVE);
757                         pll2 |= 0x011f;
758                 }
759         }
760
761         if (!nv3035)
762                 nv32_wr(pScrn, reg2, pll2);
763         nv32_wr(pScrn, reg1, pll1);
764
765         if (shift_powerctrl_1 >= 0) {
766                 nv32_wr(pScrn, NV_PBUS_POWERCTRL_1, saved_powerctrl_1);
767                 if (bios->chip_version >= 0x40)
768                         nv32_wr(pScrn, 0xc040, savedc040);
769         }
770 }
771
772 static void setPLL_double_lowregs(ScrnInfoPtr pScrn, uint32_t NMNMreg, int NM1, int NM2, int log2P)
773 {
774         /* When setting PLLs, there is a merry game of disabling and enabling
775          * various bits of hardware during the process. This function is a
776          * synthesis of six nv40 traces, nearly each card doing a subtly
777          * different thing. With luck all the necessary bits for each card are
778          * combined herein. Without luck it deviates from each card's formula
779          * so as to not work on any :)
780          */
781
782         uint32_t Preg = NMNMreg - 4;
783         uint32_t oldPval = nv32_rd(pScrn, Preg);
784         uint32_t NMNM = NM2 << 16 | NM1;
785         uint32_t Pval = (oldPval & ((Preg == 0x4020) ? ~(0x11 << 16) : ~(1 << 16))) | 0xc << 28 | log2P << 16;
786         uint32_t saved4600 = 0;
787         /* some cards have different maskc040s */
788         uint32_t maskc040 = ~(3 << 14), savedc040;
789         bool single_stage = !NM2 || (((NM2 >> 8) & 0xff) == (NM2 & 0xff));
790
791         if (nv32_rd(pScrn, NMNMreg) == NMNM && (oldPval & 0xc0070000) == Pval)
792                 return;
793
794         if (Preg == 0x4000)
795                 maskc040 = ~0x333;
796         if (Preg == 0x4058)
797                 maskc040 = ~(0xc << 24);
798
799         if (Preg == 0x4020) {
800                 struct pll_lims pll_lim;
801                 uint8_t Pval2;
802
803                 if (!get_pll_limits(pScrn, Preg, &pll_lim))
804                         return;
805
806                 Pval2 = log2P + pll_lim.log2p_bias;
807                 if (Pval2 > pll_lim.max_log2p_bias)
808                         Pval2 = pll_lim.max_log2p_bias;
809                 Pval |= 1 << 28 | Pval2 << 20;
810
811                 saved4600 = nv32_rd(pScrn, 0x4600);
812                 nv32_wr(pScrn, 0x4600, saved4600 | 8 << 28);
813         }
814         if (single_stage)
815                 Pval |= (Preg == 0x4020) ? 1 << 12 : 1 << 8;
816
817         nv32_wr(pScrn, Preg, oldPval | 1 << 28);
818         nv32_wr(pScrn, Preg, Pval & ~(4 << 28));
819         if (Preg == 0x4020) {
820                 Pval |= 8 << 20;
821                 nv32_wr(pScrn, 0x4020, Pval & ~(0xc << 28));
822                 nv32_wr(pScrn, 0x4038, Pval & ~(0xc << 28));
823         }
824
825         savedc040 = nv32_rd(pScrn, 0xc040);
826         nv32_wr(pScrn, 0xc040, savedc040 & maskc040);
827
828         nv32_wr(pScrn, NMNMreg, NMNM);
829         if (NMNMreg == 0x4024)
830                 nv32_wr(pScrn, 0x403c, NMNM);
831
832         nv32_wr(pScrn, Preg, Pval);
833         if (Preg == 0x4020) {
834                 Pval &= ~(8 << 20);
835                 nv32_wr(pScrn, 0x4020, Pval);
836                 nv32_wr(pScrn, 0x4038, Pval);
837                 nv32_wr(pScrn, 0x4600, saved4600);
838         }
839
840         nv32_wr(pScrn, 0xc040, savedc040);
841
842         if (Preg == 0x4020) {
843                 nv32_wr(pScrn, 0x4020, Pval & ~(1 << 28));
844                 nv32_wr(pScrn, 0x4038, Pval & ~(1 << 28));
845         }
846 }
847
848 static void setPLL(ScrnInfoPtr pScrn, bios_t *bios, uint32_t reg, uint32_t clk)
849 {
850         /* clk in kHz */
851         struct pll_lims pll_lim;
852         int NM1 = 0xbeef, NM2 = 0xdead, log2P;
853
854         /* high regs (such as in the mac g5 table) are not -= 4 */
855         if (!get_pll_limits(pScrn, reg > 0x405c ? reg : reg - 4, &pll_lim))
856                 return;
857
858         if (bios->chip_version >= 0x40 || bios->chip_version == 0x30 ||
859             bios->chip_version == 0x31 || bios->chip_version == 0x35 ||
860             bios->chip_version == 0x36) {
861                 getMNP_double(pScrn, &pll_lim, clk, &NM1, &NM2, &log2P);
862                 if (NM2 == 0xdead) {
863                         xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
864                                    "Could not find a suitable set of PLL coefficients, giving up\n");
865                         return;
866                 }
867                 if (reg > 0x405c)
868                         setPLL_double_highregs(pScrn, reg, NM1, NM2, log2P);
869                 else
870                         setPLL_double_lowregs(pScrn, reg, NM1, NM2, log2P);
871         } else {
872                 getMNP_single(pScrn, &pll_lim, clk, &NM1, &log2P);
873                 setPLL_single(pScrn, reg, NM1, log2P);
874         }
875 }
876
877 #if 0
878 static bool init_prog(ScrnInfoPtr pScrn, bios_t *bios, CARD16 offset, init_exec_t *iexec)
879 {
880         /* INIT_PROG   opcode: 0x31
881          * 
882          * offset      (8  bit): opcode
883          * offset + 1  (32 bit): reg
884          * offset + 5  (32 bit): and mask
885          * offset + 9  (8  bit): shift right
886          * offset + 10 (8  bit): number of configurations
887          * offset + 11 (32 bit): register
888          * offset + 15 (32 bit): configuration 1
889          * ...
890          * 
891          * Starting at offset + 15 there are "number of configurations"
892          * 32 bit values. To find out which configuration value to use
893          * read "CRTC reg" on the CRTC controller with index "CRTC index"
894          * and bitwise AND this value with "and mask" and then bit shift the
895          * result "shift right" bits to the right.
896          * Assign "register" with appropriate configuration value.
897          */
898
899         CARD32 reg = *((CARD32 *) (&bios->data[offset + 1]));
900         CARD32 and = *((CARD32 *) (&bios->data[offset + 5]));
901         CARD8 shiftr = *((CARD8 *) (&bios->data[offset + 9]));
902         CARD8 nr = *((CARD8 *) (&bios->data[offset + 10]));
903         CARD32 reg2 = *((CARD32 *) (&bios->data[offset + 11]));
904         CARD8 configuration;
905         CARD32 configval, tmp;
906
907         if (iexec->execute) {
908                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,  "0x%04X: REG: 0x%04X\n", offset, 
909                                 reg);
910
911                 tmp = nv32_rd(pScrn, reg);
912                 configuration = (tmp & and) >> shiftr;
913
914                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,  "0x%04X: CONFIGURATION TO USE: 0x%02X\n", 
915                                 offset, configuration);
916
917                 if (configuration <= nr) {
918
919                         configval = 
920                                 *((CARD32 *) (&bios->data[offset + 15 + configuration * 4]));
921
922                         xf86DrvMsg(pScrn->scrnIndex, X_INFO,  "0x%04X: REG: 0x%08X, VALUE: 0x%08X\n", offset, 
923                                         reg2, configval);
924                         
925                         tmp = nv32_rd(pScrn, reg2);
926                         xf86DrvMsg(pScrn->scrnIndex, X_INFO,  "0x%04X: CURRENT VALUE IS: 0x%08X\n",
927                                 offset, tmp);
928                         nv32_wr(pScrn, reg2, configval);
929                 }
930         }
931         return true;
932 }
933 #endif
934
935 static bool init_io_restrict_prog(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
936 {
937         /* INIT_IO_RESTRICT_PROG   opcode: 0x32 ('2')
938          *
939          * offset      (8  bit): opcode
940          * offset + 1  (16 bit): CRTC port
941          * offset + 3  (8  bit): CRTC index
942          * offset + 4  (8  bit): mask
943          * offset + 5  (8  bit): shift
944          * offset + 6  (8  bit): count
945          * offset + 7  (32 bit): register
946          * offset + 11 (32 bit): configuration 1
947          * ...
948          *
949          * Starting at offset + 11 there are "count" 32 bit values.
950          * To find out which value to use read index "CRTC index" on "CRTC port",
951          * AND this value with "mask" and then bit shift right "shift" bits.
952          * Read the appropriate value using this index and write to "register"
953          */
954
955         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
956         uint8_t crtcindex = bios->data[offset + 3];
957         uint8_t mask = bios->data[offset + 4];
958         uint8_t shift = bios->data[offset + 5];
959         uint8_t count = bios->data[offset + 6];
960         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 7])));
961         uint8_t config;
962         uint32_t configval;
963
964         if (!iexec->execute)
965                 return true;
966
967         BIOSLOG(pScrn, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, Shift: 0x%02X, Count: 0x%02X, Reg: 0x%08X\n",
968                 offset, crtcport, crtcindex, mask, shift, count, reg);
969
970         config = (nv_idx_port_rd(pScrn, crtcport, crtcindex) & mask) >> shift;
971         if (config > count) {
972                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
973                            "0x%04X: Config 0x%02X exceeds maximal bound 0x%02X\n",
974                            offset, config, count);
975                 return false;
976         }
977
978         configval = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 11 + config * 4])));
979
980         BIOSLOG(pScrn, "0x%04X: Writing config %02X\n", offset, config);
981
982         nv32_wr(pScrn, reg, configval);
983
984         return true;
985 }
986
987 static bool init_repeat(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
988 {
989         /* INIT_REPEAT   opcode: 0x33 ('3')
990          *
991          * offset      (8 bit): opcode
992          * offset + 1  (8 bit): count
993          *
994          * Execute script following this opcode up to INIT_REPEAT_END
995          * "count" times
996          */
997
998         uint8_t count = bios->data[offset + 1];
999         uint8_t i;
1000
1001         /* no iexec->execute check by design */
1002
1003         BIOSLOG(pScrn, "0x%04X: Repeating following segment %d times\n", offset, count);
1004
1005         iexec->repeat = true;
1006
1007         /* count - 1, as the script block will execute once when we leave this
1008          * opcode -- this is compatible with bios behaviour as:
1009          * a) the block is always executed at least once, even if count == 0
1010          * b) the bios interpreter skips to the op following INIT_END_REPEAT,
1011          * while we don't
1012          */
1013         for (i = 0; i < count - 1; i++)
1014                 parse_init_table(pScrn, bios, offset + 2, iexec);
1015
1016         iexec->repeat = false;
1017
1018         return true;
1019 }
1020
1021 static bool init_io_restrict_pll(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1022 {
1023         /* INIT_IO_RESTRICT_PLL   opcode: 0x34 ('4')
1024          *
1025          * offset      (8  bit): opcode
1026          * offset + 1  (16 bit): CRTC port
1027          * offset + 3  (8  bit): CRTC index
1028          * offset + 4  (8  bit): mask
1029          * offset + 5  (8  bit): shift
1030          * offset + 6  (8  bit): IO flag condition index
1031          * offset + 7  (8  bit): count
1032          * offset + 8  (32 bit): register
1033          * offset + 12 (16 bit): frequency 1
1034          * ...
1035          *
1036          * Starting at offset + 12 there are "count" 16 bit frequencies (10kHz).
1037          * Set PLL register "register" to coefficients for frequency n,
1038          * selected by reading index "CRTC index" of "CRTC port" ANDed with
1039          * "mask" and shifted right by "shift". If "IO flag condition index" > 0,
1040          * and condition met, double frequency before setting it.
1041          */
1042
1043         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
1044         uint8_t crtcindex = bios->data[offset + 3];
1045         uint8_t mask = bios->data[offset + 4];
1046         uint8_t shift = bios->data[offset + 5];
1047         int8_t io_flag_condition_idx = bios->data[offset + 6];
1048         uint8_t count = bios->data[offset + 7];
1049         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 8])));
1050         uint8_t config;
1051         uint16_t freq;
1052
1053         if (!iexec->execute)
1054                 return true;
1055
1056         BIOSLOG(pScrn, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, Shift: 0x%02X, IO Flag Condition: 0x%02X, Count: 0x%02X, Reg: 0x%08X\n",
1057                 offset, crtcport, crtcindex, mask, shift, io_flag_condition_idx, count, reg);
1058
1059         config = (nv_idx_port_rd(pScrn, crtcport, crtcindex) & mask) >> shift;
1060         if (config > count) {
1061                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1062                            "0x%04X: Config 0x%02X exceeds maximal bound 0x%02X\n",
1063                            offset, config, count);
1064                 return false;
1065         }
1066
1067         freq = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 12 + config * 2])));
1068
1069         if (io_flag_condition_idx > 0) {
1070                 if (io_flag_condition(pScrn, bios, offset, io_flag_condition_idx)) {
1071                         BIOSLOG(pScrn, "0x%04X: Condition fulfilled -- frequency doubled\n", offset);
1072                         freq *= 2;
1073                 } else
1074                         BIOSLOG(pScrn, "0x%04X: Condition not fulfilled -- frequency unchanged\n", offset);
1075         }
1076
1077         BIOSLOG(pScrn, "0x%04X: Reg: 0x%08X, Config: 0x%02X, Freq: %d0kHz\n",
1078                 offset, reg, config, freq);
1079
1080         setPLL(pScrn, bios, reg, freq * 10);
1081
1082         return true;
1083 }
1084
1085 static bool init_end_repeat(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1086 {
1087         /* INIT_END_REPEAT   opcode: 0x36 ('6')
1088          *
1089          * offset      (8 bit): opcode
1090          *
1091          * Marks the end of the block for INIT_REPEAT to repeat
1092          */
1093
1094         /* no iexec->execute check by design */
1095
1096         /* iexec->repeat flag necessary to go past INIT_END_REPEAT opcode when
1097          * we're not in repeat mode
1098          */
1099         if (iexec->repeat)
1100                 return false;
1101
1102         return true;
1103 }
1104
1105 static bool init_copy(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1106 {
1107         /* INIT_COPY   opcode: 0x37 ('7')
1108          *
1109          * offset      (8  bit): opcode
1110          * offset + 1  (32 bit): register
1111          * offset + 5  (8  bit): shift
1112          * offset + 6  (8  bit): srcmask
1113          * offset + 7  (16 bit): CRTC port
1114          * offset + 9  (8 bit): CRTC index
1115          * offset + 10  (8 bit): mask
1116          *
1117          * Read index "CRTC index" on "CRTC port", AND with "mask", OR with
1118          * (REGVAL("register") >> "shift" & "srcmask") and write-back to CRTC port
1119          */
1120
1121         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
1122         uint8_t shift = bios->data[offset + 5];
1123         uint8_t srcmask = bios->data[offset + 6];
1124         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 7])));
1125         uint8_t crtcindex = bios->data[offset + 9];
1126         uint8_t mask = bios->data[offset + 10];
1127         uint32_t data;
1128         uint8_t crtcdata;
1129
1130         if (!iexec->execute)
1131                 return true;
1132
1133         BIOSLOG(pScrn, "0x%04X: Reg: 0x%08X, Shift: 0x%02X, SrcMask: 0x%02X, Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X\n",
1134                 offset, reg, shift, srcmask, crtcport, crtcindex, mask);
1135
1136         data = nv32_rd(pScrn, reg);
1137
1138         if (shift < 0x80)
1139                 data >>= shift;
1140         else
1141                 data <<= (0x100 - shift);
1142
1143         data &= srcmask;
1144
1145         crtcdata = (nv_idx_port_rd(pScrn, crtcport, crtcindex) & mask) | (uint8_t)data;
1146         nv_idx_port_wr(pScrn, crtcport, crtcindex, crtcdata);
1147
1148         return true;
1149 }
1150
1151 static bool init_not(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1152 {
1153         /* INIT_NOT   opcode: 0x38 ('8')
1154          *
1155          * offset      (8  bit): opcode
1156          *
1157          * Invert the current execute / no-execute condition (i.e. "else")
1158          */
1159         if (iexec->execute)
1160                 BIOSLOG(pScrn, "0x%04X: ------ Skipping following commands  ------\n", offset);
1161         else
1162                 BIOSLOG(pScrn, "0x%04X: ------ Executing following commands ------\n", offset);
1163
1164         iexec->execute = !iexec->execute;
1165         return true;
1166 }
1167
1168 static bool init_io_flag_condition(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1169 {
1170         /* INIT_IO_FLAG_CONDITION   opcode: 0x39 ('9')
1171          *
1172          * offset      (8 bit): opcode
1173          * offset + 1  (8 bit): condition number
1174          *
1175          * Check condition "condition number" in the IO flag condition table.
1176          * If condition not met skip subsequent opcodes until condition is
1177          * inverted (INIT_NOT), or we hit INIT_RESUME
1178          */
1179
1180         uint8_t cond = bios->data[offset + 1];
1181
1182         if (!iexec->execute)
1183                 return true;
1184
1185         if (io_flag_condition(pScrn, bios, offset, cond))
1186                 BIOSLOG(pScrn, "0x%04X: Condition fulfilled -- continuing to execute\n", offset);
1187         else {
1188                 BIOSLOG(pScrn, "0x%04X: Condition not fulfilled -- skipping following commands\n", offset);
1189                 iexec->execute = false;
1190         }
1191
1192         return true;
1193 }
1194
1195 static bool init_idx_addr_latched(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1196 {
1197         /* INIT_INDEX_ADDRESS_LATCHED   opcode: 0x49 ('I')
1198          *
1199          * offset      (8  bit): opcode
1200          * offset + 1  (32 bit): control register
1201          * offset + 5  (32 bit): data register
1202          * offset + 9  (32 bit): mask
1203          * offset + 13 (32 bit): data
1204          * offset + 17 (8  bit): count
1205          * offset + 18 (8  bit): address 1
1206          * offset + 19 (8  bit): data 1
1207          * ...
1208          *
1209          * For each of "count" address and data pairs, write "data n" to "data register",
1210          * read the current value of "control register", and write it back once ANDed
1211          * with "mask", ORed with "data", and ORed with "address n"
1212          */
1213
1214         uint32_t controlreg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
1215         uint32_t datareg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 5])));
1216         uint32_t mask = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 9])));
1217         uint32_t data = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 13])));
1218         uint8_t count = bios->data[offset + 17];
1219         uint32_t value;
1220         int i;
1221
1222         if (!iexec->execute)
1223                 return true;
1224
1225         BIOSLOG(pScrn, "0x%04X: ControlReg: 0x%08X, DataReg: 0x%08X, Mask: 0x%08X, Data: 0x%08X, Count: 0x%02X\n",
1226                 offset, controlreg, datareg, mask, data, count);
1227
1228         for (i = 0; i < count; i++) {
1229                 uint8_t instaddress = bios->data[offset + 18 + i * 2];
1230                 uint8_t instdata = bios->data[offset + 19 + i * 2];
1231
1232                 BIOSLOG(pScrn, "0x%04X: Address: 0x%02X, Data: 0x%02X\n", offset, instaddress, instdata);
1233
1234                 nv32_wr(pScrn, datareg, instdata);
1235                 value = (nv32_rd(pScrn, controlreg) & mask) | data | instaddress;
1236                 nv32_wr(pScrn, controlreg, value);
1237         }
1238
1239         return true;
1240 }
1241
1242 static bool init_io_restrict_pll2(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1243 {
1244         /* INIT_IO_RESTRICT_PLL2   opcode: 0x4A ('J')
1245          *
1246          * offset      (8  bit): opcode
1247          * offset + 1  (16 bit): CRTC port
1248          * offset + 3  (8  bit): CRTC index
1249          * offset + 4  (8  bit): mask
1250          * offset + 5  (8  bit): shift
1251          * offset + 6  (8  bit): count
1252          * offset + 7  (32 bit): register
1253          * offset + 11 (32 bit): frequency 1
1254          * ...
1255          *
1256          * Starting at offset + 11 there are "count" 32 bit frequencies (kHz).
1257          * Set PLL register "register" to coefficients for frequency n,
1258          * selected by reading index "CRTC index" of "CRTC port" ANDed with
1259          * "mask" and shifted right by "shift".
1260          */
1261
1262         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
1263         uint8_t crtcindex = bios->data[offset + 3];
1264         uint8_t mask = bios->data[offset + 4];
1265         uint8_t shift = bios->data[offset + 5];
1266         uint8_t count = bios->data[offset + 6];
1267         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 7])));
1268         uint8_t config;
1269         uint32_t freq;
1270
1271         if (!iexec->execute)
1272                 return true;
1273
1274         BIOSLOG(pScrn, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, Shift: 0x%02X, Count: 0x%02X, Reg: 0x%08X\n",
1275                 offset, crtcport, crtcindex, mask, shift, count, reg);
1276
1277         if (!reg)
1278                 return true;
1279
1280         config = (nv_idx_port_rd(pScrn, crtcport, crtcindex) & mask) >> shift;
1281         if (config > count) {
1282                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1283                            "0x%04X: Config 0x%02X exceeds maximal bound 0x%02X\n",
1284                            offset, config, count);
1285                 return false;
1286         }
1287
1288         freq = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 11 + config * 4])));
1289
1290         BIOSLOG(pScrn, "0x%04X: Reg: 0x%08X, Config: 0x%02X, Freq: %dkHz\n",
1291                 offset, reg, config, freq);
1292
1293         setPLL(pScrn, bios, reg, freq);
1294
1295         return true;
1296 }
1297
1298 static bool init_pll2(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1299 {
1300         /* INIT_PLL2   opcode: 0x4B ('K')
1301          *
1302          * offset      (8  bit): opcode
1303          * offset + 1  (32 bit): register
1304          * offset + 5  (32 bit): freq
1305          *
1306          * Set PLL register "register" to coefficients for frequency "freq"
1307          */
1308
1309         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
1310         uint32_t freq = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 5])));
1311
1312         if (!iexec->execute)
1313                 return true;
1314
1315         BIOSLOG(pScrn, "0x%04X: Reg: 0x%04X, Freq: %dkHz\n",
1316                 offset, reg, freq);
1317
1318         setPLL(pScrn, bios, reg, freq);
1319
1320         return true;
1321 }
1322
1323 static uint32_t get_tmds_index_reg(ScrnInfoPtr pScrn, uint8_t mlv)
1324 {
1325         /* For mlv < 0x80, it is an index into a table of TMDS base addresses
1326          * For mlv == 0x80 use the "or" value of the dcb_entry indexed by CR58 for CR57 = 0
1327          * to index a table of offsets to the basic 0x6808b0 address
1328          * For mlv == 0x81 use the "or" value of the dcb_entry indexed by CR58 for CR57 = 0
1329          * to index a table of offsets to the basic 0x6808b0 address, and then flip the offset by 8
1330          */
1331
1332         NVPtr pNv = NVPTR(pScrn);
1333         const int pramdac_offset[13] = {0, 0, 0x8, 0, 0x2000, 0, 0, 0, 0x2008, 0, 0, 0, 0x2000};
1334         const uint32_t pramdac_table[4] = {0x6808b0, 0x6808b8, 0x6828b0, 0x6828b8};
1335
1336         if (mlv >= 0x80) {
1337                 /* here we assume that the DCB table has already been parsed */
1338                 uint8_t dcb_entry = NVReadVgaCrtc5758(NVPTR(pScrn), crtchead, 0);
1339                 int dacoffset;
1340
1341                 if (dcb_entry > pNv->dcb_table.entries) {
1342                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1343                                    "CR58 doesn't have a valid DCB entry currently (%02X)\n", dcb_entry);
1344                         return 0;
1345                 }
1346                 dacoffset = pramdac_offset[pNv->dcb_table.entry[dcb_entry].or];
1347                 if (mlv == 0x81)
1348                         dacoffset ^= 8;
1349                 return (0x6808b0 + dacoffset);
1350         } else {
1351                 if (mlv > (sizeof(pramdac_table) / sizeof(uint32_t))) {
1352                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
1353                                    "Magic Lookup Value too big (%02X)\n", mlv);
1354                         return 0;
1355                 }
1356                 return pramdac_table[mlv];
1357         }
1358 }
1359
1360 static bool init_tmds(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1361 {
1362         /* INIT_TMDS   opcode: 0x4F ('O')       (non-canon name)
1363          *
1364          * offset      (8 bit): opcode
1365          * offset + 1  (8 bit): magic lookup value
1366          * offset + 2  (8 bit): TMDS address
1367          * offset + 3  (8 bit): mask
1368          * offset + 4  (8 bit): data
1369          *
1370          * Read the data reg for TMDS address "TMDS address", AND it with mask
1371          * and OR it with data, then write it back
1372          * "magic lookup value" determines which TMDS base address register is used --
1373          * see get_tmds_index_reg()
1374          */
1375
1376         uint8_t mlv = bios->data[offset + 1];
1377         uint32_t tmdsaddr = bios->data[offset + 2];
1378         uint8_t mask = bios->data[offset + 3];
1379         uint8_t data = bios->data[offset + 4];
1380         uint32_t reg, value;
1381
1382         if (!iexec->execute)
1383                 return true;
1384
1385         BIOSLOG(pScrn, "0x%04X: MagicLookupValue: 0x%02X, TMDSAddr: 0x%02X, Mask: 0x%02X, Data: 0x%02X\n",
1386                 offset, mlv, tmdsaddr, mask, data);
1387
1388         if (!(reg = get_tmds_index_reg(pScrn, mlv)))
1389                 return false;
1390
1391         nv32_wr(pScrn, reg, tmdsaddr | NV_RAMDAC_FP_TMDS_CONTROL_WRITE_DISABLE);
1392         value = (nv32_rd(pScrn, reg + 4) & mask) | data;
1393         nv32_wr(pScrn, reg + 4, value);
1394         nv32_wr(pScrn, reg, tmdsaddr);
1395
1396         return true;
1397 }
1398
1399 static bool init_zm_tmds_group(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1400 {
1401         /* INIT_ZM_TMDS_GROUP   opcode: 0x50 ('P')      (non-canon name)
1402          *
1403          * offset      (8 bit): opcode
1404          * offset + 1  (8 bit): magic lookup value
1405          * offset + 2  (8 bit): count
1406          * offset + 3  (8 bit): addr 1
1407          * offset + 4  (8 bit): data 1
1408          * ...
1409          *
1410          * For each of "count" TMDS address and data pairs write "data n" to "addr n"
1411          * "magic lookup value" determines which TMDS base address register is used --
1412          * see get_tmds_index_reg()
1413          */
1414
1415         uint8_t mlv = bios->data[offset + 1];
1416         uint8_t count = bios->data[offset + 2];
1417         uint32_t reg;
1418         int i;
1419
1420         if (!iexec->execute)
1421                 return true;
1422
1423         BIOSLOG(pScrn, "0x%04X: MagicLookupValue: 0x%02X, Count: 0x%02X\n",
1424                 offset, mlv, count);
1425
1426         if (!(reg = get_tmds_index_reg(pScrn, mlv)))
1427                 return false;
1428
1429         for (i = 0; i < count; i++) {
1430                 uint8_t tmdsaddr = bios->data[offset + 3 + i * 2];
1431                 uint8_t tmdsdata = bios->data[offset + 4 + i * 2];
1432
1433                 nv32_wr(pScrn, reg + 4, tmdsdata);
1434                 nv32_wr(pScrn, reg, tmdsaddr);
1435         }
1436
1437         return true;
1438 }
1439
1440 static bool init_cr_idx_adr_latch(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1441 {
1442         /* INIT_CR_INDEX_ADDRESS_LATCHED   opcode: 0x51 ('Q')
1443          *
1444          * offset      (8 bit): opcode
1445          * offset + 1  (8 bit): CRTC index1
1446          * offset + 2  (8 bit): CRTC index2
1447          * offset + 3  (8 bit): baseaddr
1448          * offset + 4  (8 bit): count
1449          * offset + 5  (8 bit): data 1
1450          * ...
1451          *
1452          * For each of "count" address and data pairs, write "baseaddr + n" to
1453          * "CRTC index1" and "data n" to "CRTC index2"
1454          * Once complete, restore initial value read from "CRTC index1"
1455          */
1456         uint8_t crtcindex1 = bios->data[offset + 1];
1457         uint8_t crtcindex2 = bios->data[offset + 2];
1458         uint8_t baseaddr = bios->data[offset + 3];
1459         uint8_t count = bios->data[offset + 4];
1460         uint8_t oldaddr, data;
1461         int i;
1462
1463         if (!iexec->execute)
1464                 return true;
1465
1466         BIOSLOG(pScrn, "0x%04X: Index1: 0x%02X, Index2: 0x%02X, BaseAddr: 0x%02X, Count: 0x%02X\n",
1467                 offset, crtcindex1, crtcindex2, baseaddr, count);
1468
1469         oldaddr = nv_idx_port_rd(pScrn, NV_CIO_CRX__COLOR, crtcindex1);
1470
1471         for (i = 0; i < count; i++) {
1472                 nv_idx_port_wr(pScrn, NV_CIO_CRX__COLOR, crtcindex1, baseaddr + i);
1473
1474                 data = bios->data[offset + 5 + i];
1475                 nv_idx_port_wr(pScrn, NV_CIO_CRX__COLOR, crtcindex2, data);
1476         }
1477
1478         nv_idx_port_wr(pScrn, NV_CIO_CRX__COLOR, crtcindex1, oldaddr);
1479
1480         return true;
1481 }
1482
1483 static bool init_cr(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1484 {
1485         /* INIT_CR   opcode: 0x52 ('R')
1486          *
1487          * offset      (8  bit): opcode
1488          * offset + 1  (8  bit): CRTC index
1489          * offset + 2  (8  bit): mask
1490          * offset + 3  (8  bit): data
1491          *
1492          * Assign the value of at "CRTC index" ANDed with mask and ORed with data
1493          * back to "CRTC index"
1494          */
1495
1496         uint8_t crtcindex = bios->data[offset + 1];
1497         uint8_t mask = bios->data[offset + 2];
1498         uint8_t data = bios->data[offset + 3];
1499         uint8_t value;
1500
1501         if (!iexec->execute)
1502                 return true;
1503
1504         BIOSLOG(pScrn, "0x%04X: Index: 0x%02X, Mask: 0x%02X, Data: 0x%02X\n",
1505                 offset, crtcindex, mask, data);
1506
1507         value = (nv_idx_port_rd(pScrn, NV_CIO_CRX__COLOR, crtcindex) & mask) | data;
1508         nv_idx_port_wr(pScrn, NV_CIO_CRX__COLOR, crtcindex, value);
1509
1510         return true;
1511 }
1512
1513 static bool init_zm_cr(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1514 {
1515         /* INIT_ZM_CR   opcode: 0x53 ('S')
1516          *
1517          * offset      (8 bit): opcode
1518          * offset + 1  (8 bit): CRTC index
1519          * offset + 2  (8 bit): value
1520          *
1521          * Assign "value" to CRTC register with index "CRTC index".
1522          */
1523
1524         uint8_t crtcindex = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
1525         uint8_t data = bios->data[offset + 2];
1526
1527         if (!iexec->execute)
1528                 return true;
1529
1530         nv_idx_port_wr(pScrn, NV_CIO_CRX__COLOR, crtcindex, data);
1531
1532         return true;
1533 }
1534
1535 static bool init_zm_cr_group(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1536 {
1537         /* INIT_ZM_CR_GROUP   opcode: 0x54 ('T')
1538          *
1539          * offset      (8 bit): opcode
1540          * offset + 1  (8 bit): count
1541          * offset + 2  (8 bit): CRTC index 1
1542          * offset + 3  (8 bit): value 1
1543          * ...
1544          *
1545          * For "count", assign "value n" to CRTC register with index "CRTC index n".
1546          */
1547     
1548         uint8_t count = bios->data[offset + 1];
1549         int i;
1550
1551         if (!iexec->execute)
1552                 return true;
1553
1554         for (i = 0; i < count; i++)
1555                 init_zm_cr(pScrn, bios, offset + 2 + 2 * i - 1, iexec);
1556
1557         return true;
1558 }
1559
1560 static bool init_condition_time(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1561 {
1562         /* INIT_CONDITION_TIME   opcode: 0x56 ('V')
1563          *
1564          * offset      (8 bit): opcode
1565          * offset + 1  (8 bit): condition number
1566          * offset + 2  (8 bit): retries / 50
1567          *
1568          * Check condition "condition number" in the condition table.
1569          * The condition table entry has 4 bytes for the address of the
1570          * register to check, 4 bytes for a mask and 4 for a test value.
1571          * If condition not met sleep for 2ms, and repeat upto "retries" times.
1572          * If still not met after retries, clear execution flag for this table.
1573          */
1574
1575         uint8_t cond = bios->data[offset + 1];
1576         uint16_t retries = bios->data[offset + 2];
1577         uint16_t condptr = bios->condition_tbl_ptr + cond * CONDITION_SIZE;
1578         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[condptr])));
1579         uint32_t mask = le32_to_cpu(*((uint32_t *)(&bios->data[condptr + 4])));
1580         uint32_t cmpval = le32_to_cpu(*((uint32_t *)(&bios->data[condptr + 8])));
1581         uint32_t data = 0;
1582
1583         if (!iexec->execute)
1584                 return true;
1585
1586         retries *= 50;
1587
1588         BIOSLOG(pScrn, "0x%04X: Cond: 0x%02X, Retries: 0x%02X\n", offset, cond, retries);
1589
1590         for (; retries > 0; retries--) {
1591                 data = nv32_rd(pScrn, reg) & mask;
1592
1593                 BIOSLOG(pScrn, "0x%04X: Checking if 0x%08X equals 0x%08X\n", offset, data, cmpval);
1594
1595                 if (data != cmpval) {
1596                         BIOSLOG(pScrn, "0x%04X: Condition not met, sleeping for 2ms\n", offset);
1597                         BIOS_USLEEP(2000);
1598                 } else {
1599                         BIOSLOG(pScrn, "0x%04X: Condition met, continuing\n", offset);
1600                         break;
1601                 }
1602         }
1603
1604         if (data != cmpval) {
1605                 BIOSLOG(pScrn, "0x%04X: Condition still not met, skiping following opcodes\n", offset);
1606                 iexec->execute = false;
1607         }
1608
1609         return true;
1610 }
1611
1612 static bool init_zm_reg_sequence(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1613 {
1614         /* INIT_ZM_REG_SEQUENCE   opcode: 0x58 ('X')
1615          *
1616          * offset      (8  bit): opcode
1617          * offset + 1  (32 bit): base register
1618          * offset + 5  (8  bit): count
1619          * offset + 6  (32 bit): value 1
1620          * ...
1621          *
1622          * Starting at offset + 6 there are "count" 32 bit values.
1623          * For "count" iterations set "base register" + 4 * current_iteration
1624          * to "value current_iteration"
1625          */
1626
1627         uint32_t basereg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
1628         uint32_t count = bios->data[offset + 5];
1629         int i;
1630
1631         if (!iexec->execute)
1632                 return true;
1633
1634         BIOSLOG(pScrn, "0x%04X: BaseReg: 0x%08X, Count: 0x%02X\n", offset, basereg, count);
1635
1636         for (i = 0; i < count; i++) {
1637                 uint32_t reg = basereg + i * 4;
1638                 uint32_t data = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 6 + i * 4])));
1639
1640                 nv32_wr(pScrn, reg, data);
1641         }
1642
1643         return true;
1644 }
1645
1646 #if 0
1647 static bool init_indirect_reg(ScrnInfoPtr pScrn, bios_t *bios, CARD16 offset, init_exec_t *iexec)
1648 {
1649         /* INIT_INDIRECT_REG opcode: 0x5A
1650          *
1651          * offset      (8  bit): opcode
1652          * offset + 1  (32 bit): register
1653          * offset + 5  (16 bit): adress offset (in bios)
1654          *
1655          * Lookup value at offset data in the bios and write it to reg
1656          */
1657         CARD32 reg = *((CARD32 *) (&bios->data[offset + 1]));
1658         CARD16 data = le16_to_cpu(*((CARD16 *) (&bios->data[offset + 5])));
1659         CARD32 data2 = bios->data[data];
1660
1661         if (iexec->execute) {
1662                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,  
1663                                 "0x%04X: REG: 0x%04X, DATA AT: 0x%04X, VALUE IS: 0x%08X\n", 
1664                                 offset, reg, data, data2);
1665
1666                 if (DEBUGLEVEL >= 6) {
1667                         CARD32 tmpval;
1668                         tmpval = nv32_rd(pScrn, reg);
1669                         xf86DrvMsg(pScrn->scrnIndex, X_INFO,  "0x%04X: CURRENT VALUE IS: 0x%08X\n", offset, tmpval);
1670                 }
1671
1672                 nv32_wr(pScrn, reg, data2);
1673         }
1674         return true;
1675 }
1676 #endif
1677
1678 static bool init_sub_direct(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1679 {
1680         /* INIT_SUB_DIRECT   opcode: 0x5B ('[')
1681          *
1682          * offset      (8  bit): opcode
1683          * offset + 1  (16 bit): subroutine offset (in bios)
1684          *
1685          * Calls a subroutine that will execute commands until INIT_DONE
1686          * is found. 
1687          */
1688
1689         uint16_t sub_offset = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
1690
1691         if (!iexec->execute)
1692                 return true;
1693
1694         BIOSLOG(pScrn, "0x%04X: Executing subroutine at 0x%04X\n", offset, sub_offset);
1695
1696         parse_init_table(pScrn, bios, sub_offset, iexec);
1697
1698         BIOSLOG(pScrn, "0x%04X: End of 0x%04X subroutine\n", offset, sub_offset);
1699
1700         return true;
1701 }
1702
1703 static bool init_copy_nv_reg(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1704 {
1705         /* INIT_COPY_NV_REG   opcode: 0x5F ('_')
1706          *
1707          * offset      (8  bit): opcode
1708          * offset + 1  (32 bit): src reg
1709          * offset + 5  (8  bit): shift
1710          * offset + 6  (32 bit): src mask
1711          * offset + 10 (32 bit): xor
1712          * offset + 14 (32 bit): dst reg
1713          * offset + 18 (32 bit): dst mask
1714          *
1715          * Shift REGVAL("src reg") right by (signed) "shift", AND result with
1716          * "src mask", then XOR with "xor". Write this OR'd with
1717          * (REGVAL("dst reg") AND'd with "dst mask") to "dst reg"
1718          */
1719
1720         uint32_t srcreg = *((uint32_t *)(&bios->data[offset + 1]));
1721         uint8_t shift = bios->data[offset + 5];
1722         uint32_t srcmask = *((uint32_t *)(&bios->data[offset + 6]));
1723         uint32_t xor = *((uint32_t *)(&bios->data[offset + 10]));
1724         uint32_t dstreg = *((uint32_t *)(&bios->data[offset + 14]));
1725         uint32_t dstmask = *((uint32_t *)(&bios->data[offset + 18]));
1726         uint32_t srcvalue, dstvalue;
1727
1728         if (!iexec->execute)
1729                 return true;
1730
1731         BIOSLOG(pScrn, "0x%04X: SrcReg: 0x%08X, Shift: 0x%02X, SrcMask: 0x%08X, Xor: 0x%08X, DstReg: 0x%08X, DstMask: 0x%08X\n",
1732                 offset, srcreg, shift, srcmask, xor, dstreg, dstmask);
1733
1734         srcvalue = nv32_rd(pScrn, srcreg);
1735
1736         if (shift < 0x80)
1737                 srcvalue >>= shift;
1738         else
1739                 srcvalue <<= (0x100 - shift);
1740
1741         srcvalue = (srcvalue & srcmask) ^ xor;
1742
1743         dstvalue = nv32_rd(pScrn, dstreg) & dstmask;
1744
1745         nv32_wr(pScrn, dstreg, dstvalue | srcvalue);
1746
1747         return true;
1748 }
1749
1750 static bool init_zm_index_io(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1751 {
1752         /* INIT_ZM_INDEX_IO   opcode: 0x62 ('b')
1753          *
1754          * offset      (8  bit): opcode
1755          * offset + 1  (16 bit): CRTC port
1756          * offset + 3  (8  bit): CRTC index
1757          * offset + 4  (8  bit): data
1758          *
1759          * Write "data" to index "CRTC index" of "CRTC port"
1760          */
1761         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
1762         uint8_t crtcindex = bios->data[offset + 3];
1763         uint8_t data = bios->data[offset + 4];
1764
1765         if (!iexec->execute)
1766                 return true;
1767
1768         nv_idx_port_wr(pScrn, crtcport, crtcindex, data);
1769
1770         return true;
1771 }
1772
1773 static bool init_compute_mem(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1774 {
1775         /* INIT_COMPUTE_MEM   opcode: 0x63 ('c')
1776          *
1777          * offset      (8 bit): opcode
1778          *
1779          * This opcode is meant to set NV_PFB_CFG0 (0x100200) appropriately so
1780          * that the hardware can correctly calculate how much VRAM it has
1781          * (and subsequently report that value in 0x10020C)
1782          *
1783          * The implementation of this opcode in general consists of two parts:
1784          * 1) determination of the memory bus width
1785          * 2) determination of how many of the card's RAM pads have ICs attached
1786          *
1787          * 1) is done by a cunning combination of writes to offsets 0x1c and
1788          * 0x3c in the framebuffer, and seeing whether the written values are
1789          * read back correctly. This then affects bits 4-7 of NV_PFB_CFG0
1790          *
1791          * 2) is done by a cunning combination of writes to an offset slightly
1792          * less than the maximum memory reported by 0x10020C, then seeing if
1793          * the test pattern can be read back. This then affects bits 12-15 of
1794          * NV_PFB_CFG0
1795          *
1796          * In this context a "cunning combination" may include multiple reads
1797          * and writes to varying locations, often alternating the test pattern
1798          * and 0, doubtless to make sure buffers are filled, residual charges
1799          * on tracks are removed etc.
1800          *
1801          * Unfortunately, the "cunning combination"s mentioned above, and the
1802          * changes to the bits in NV_PFB_CFG0 differ with nearly every bios
1803          * trace I have.
1804          *
1805          * Therefore, we cheat and assume the value of NV_PFB_CFG0 with which
1806          * we started was correct, and use that instead
1807          */
1808
1809         /* no iexec->execute check by design */
1810
1811         /* on every card I've seen, this step gets done for us earlier in the init scripts
1812         uint8_t crdata = nv_idx_port_rd(pScrn, NV_VIO_SRX, 0x01);
1813         nv_idx_port_wr(pScrn, NV_VIO_SRX, 0x01, crdata | 0x20);
1814         */
1815
1816         /* this also has probably been done in the scripts, but an mmio trace of
1817          * s3 resume shows nvidia doing it anyway (unlike the NV_VIO_SRX write)
1818          */
1819         nv32_wr(pScrn, NV_PFB_REFCTRL, NV_PFB_REFCTRL_VALID_1);
1820
1821         /* write back the saved configuration value */
1822         nv32_wr(pScrn, NV_PFB_CFG0, saved_nv_pfb_cfg0);
1823
1824         return true;
1825 }
1826
1827 static bool init_reset(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1828 {
1829         /* INIT_RESET   opcode: 0x65 ('e')
1830          *
1831          * offset      (8  bit): opcode
1832          * offset + 1  (32 bit): register
1833          * offset + 5  (32 bit): value1
1834          * offset + 9  (32 bit): value2
1835          *
1836          * Assign "value1" to "register", then assign "value2" to "register"
1837          */
1838
1839         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
1840         uint32_t value1 = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 5])));
1841         uint32_t value2 = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 9])));
1842         uint32_t pci_nv_19, pci_nv_20;
1843
1844         /* no iexec->execute check by design */
1845
1846         pci_nv_19 = nv32_rd(pScrn, NV_PBUS_PCI_NV_19);
1847         nv32_wr(pScrn, NV_PBUS_PCI_NV_19, 0);
1848         nv32_wr(pScrn, reg, value1);
1849
1850         BIOS_USLEEP(10);
1851
1852         nv32_wr(pScrn, reg, value2);
1853         nv32_wr(pScrn, NV_PBUS_PCI_NV_19, pci_nv_19);
1854
1855         pci_nv_20 = nv32_rd(pScrn, NV_PBUS_PCI_NV_20);
1856         pci_nv_20 &= ~NV_PBUS_PCI_NV_20_ROM_SHADOW_ENABLED;     /* 0xfffffffe */
1857         nv32_wr(pScrn, NV_PBUS_PCI_NV_20, pci_nv_20);
1858
1859         return true;
1860 }
1861
1862 static bool init_configure_mem(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1863 {
1864         /* INIT_CONFIGURE_MEM   opcode: 0x66 ('f')
1865          *
1866          * offset      (8 bit): opcode
1867          *
1868          * Equivalent to INIT_DONE on bios version 3 or greater.
1869          * For early bios versions, sets up the memory registers, using values
1870          * taken from the memory init table
1871          */
1872
1873         /* no iexec->execute check by design */
1874
1875         uint16_t meminitoffs = bios->legacy.mem_init_tbl_ptr + MEM_INIT_SIZE * (nv_idx_port_rd(pScrn, NV_CIO_CRX__COLOR, NV_CIO_CRE_SCRATCH4__INDEX) >> 4);
1876         uint16_t seqtbloffs = bios->legacy.sdr_seq_tbl_ptr, meminitdata = meminitoffs + 6;
1877         uint32_t reg, data;
1878
1879         if (bios->major_version > 2)
1880                 return false;
1881
1882         nv_idx_port_wr(pScrn, NV_VIO_SRX, NV_VIO_SR_CLOCK_INDEX,
1883                        nv_idx_port_rd(pScrn, NV_VIO_SRX, NV_VIO_SR_CLOCK_INDEX) | 0x20);
1884
1885         if (bios->data[meminitoffs] & 1)
1886                 seqtbloffs = bios->legacy.ddr_seq_tbl_ptr;
1887
1888         for (reg = le32_to_cpu(*(uint32_t *)&bios->data[seqtbloffs]);
1889              reg != 0xffffffff;
1890              reg = le32_to_cpu(*(uint32_t *)&bios->data[seqtbloffs += 4])) {
1891
1892                 switch (reg) {
1893                 case NV_PFB_PRE:
1894                         data = NV_PFB_PRE_CMD_PRECHARGE;
1895                         break;
1896                 case NV_PFB_PAD:
1897                         data = NV_PFB_PAD_CKE_NORMAL;
1898                         break;
1899                 case NV_PFB_REF:
1900                         data = NV_PFB_REF_CMD_REFRESH;
1901                         break;
1902                 default:
1903                         data = le32_to_cpu(*(uint32_t *)&bios->data[meminitdata]);
1904                         meminitdata += 4;
1905                         if (data == 0xffffffff)
1906                                 continue;
1907                 }
1908
1909                 nv32_wr(pScrn, reg, data);
1910         }
1911
1912         return true;
1913 }
1914
1915 static bool init_configure_clk(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1916 {
1917         /* INIT_CONFIGURE_CLK   opcode: 0x67 ('g')
1918          *
1919          * offset      (8 bit): opcode
1920          *
1921          * Equivalent to INIT_DONE on bios version 3 or greater.
1922          * For early bios versions, sets up the NVClk and MClk PLLs, using
1923          * values taken from the memory init table
1924          */
1925
1926         /* no iexec->execute check by design */
1927
1928         uint16_t meminitoffs = bios->legacy.mem_init_tbl_ptr + MEM_INIT_SIZE * (nv_idx_port_rd(pScrn, NV_CIO_CRX__COLOR, NV_CIO_CRE_SCRATCH4__INDEX) >> 4);
1929         int clock;
1930
1931         if (bios->major_version > 2)
1932                 return false;
1933
1934         clock = le16_to_cpu(*(uint16_t *)&bios->data[meminitoffs + 4]) * 10;
1935         setPLL(pScrn, bios, NV_RAMDAC_NVPLL, clock);
1936
1937         clock = le16_to_cpu(*(uint16_t *)&bios->data[meminitoffs + 2]) * 10;
1938         if (bios->data[meminitoffs] & 1) /* DDR */
1939                 clock *= 2;
1940         setPLL(pScrn, bios, NV_RAMDAC_MPLL, clock);
1941
1942         return true;
1943 }
1944
1945 static bool init_configure_preinit(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1946 {
1947         /* INIT_CONFIGURE_PREINIT   opcode: 0x68 ('h')
1948          *
1949          * offset      (8 bit): opcode
1950          *
1951          * Equivalent to INIT_DONE on bios version 3 or greater.
1952          * For early bios versions, does early init, loading ram and crystal
1953          * configuration from straps into CR3C
1954          */
1955
1956         /* no iexec->execute check by design */
1957
1958         uint32_t straps = nv32_rd(pScrn, NV_PEXTDEV_BOOT_0);
1959         uint8_t cr3c = ((straps << 2) & 0xf0) | (straps & (1 << 6));
1960
1961         if (bios->major_version > 2)
1962                 return false;
1963
1964         nv_idx_port_wr(pScrn, NV_CIO_CRX__COLOR, NV_CIO_CRE_SCRATCH4__INDEX, cr3c);
1965
1966         return true;
1967 }
1968
1969 static bool init_io(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1970 {
1971         /* INIT_IO   opcode: 0x69 ('i')
1972          *
1973          * offset      (8  bit): opcode
1974          * offset + 1  (16 bit): CRTC port
1975          * offset + 3  (8  bit): mask
1976          * offset + 4  (8  bit): data
1977          *
1978          * Assign ((IOVAL("crtc port") & "mask") | "data") to "crtc port"
1979          */
1980
1981         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
1982         uint8_t mask = bios->data[offset + 3];
1983         uint8_t data = bios->data[offset + 4];
1984
1985         if (!iexec->execute)
1986                 return true;
1987
1988         BIOSLOG(pScrn, "0x%04X: Port: 0x%04X, Mask: 0x%02X, Data: 0x%02X\n",
1989                 offset, crtcport, mask, data);
1990
1991         nv_port_wr(pScrn, crtcport, (nv_port_rd(pScrn, crtcport) & mask) | data);
1992
1993         return true;
1994 }
1995
1996 static bool init_sub(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
1997 {
1998         /* INIT_SUB   opcode: 0x6B ('k')
1999          *
2000          * offset      (8 bit): opcode
2001          * offset + 1  (8 bit): script number
2002          *
2003          * Execute script number "script number", as a subroutine
2004          */
2005
2006         uint8_t sub = bios->data[offset + 1];
2007
2008         if (!iexec->execute)
2009                 return true;
2010
2011         BIOSLOG(pScrn, "0x%04X: Calling script %d\n", offset, sub);
2012
2013         parse_init_table(pScrn, bios,
2014                          le16_to_cpu(*((uint16_t *)(&bios->data[bios->init_script_tbls_ptr + sub * 2]))),
2015                          iexec);
2016
2017         BIOSLOG(pScrn, "0x%04X: End of script %d\n", offset, sub);
2018
2019         return true;
2020 }
2021
2022 static bool init_ram_condition(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2023 {
2024         /* INIT_RAM_CONDITION   opcode: 0x6D ('m')
2025          *
2026          * offset      (8 bit): opcode
2027          * offset + 1  (8 bit): mask
2028          * offset + 2  (8 bit): cmpval
2029          *
2030          * Test if (NV_PFB_BOOT_0 & "mask") equals "cmpval".
2031          * If condition not met skip subsequent opcodes until condition is
2032          * inverted (INIT_NOT), or we hit INIT_RESUME
2033          */
2034
2035         uint8_t mask = bios->data[offset + 1];
2036         uint8_t cmpval = bios->data[offset + 2];
2037         uint8_t data;
2038
2039         if (!iexec->execute)
2040                 return true;
2041
2042         data = nv32_rd(pScrn, NV_PFB_BOOT_0) & mask;
2043
2044         BIOSLOG(pScrn, "0x%04X: Checking if 0x%08X equals 0x%08X\n", offset, data, cmpval);
2045
2046         if (data == cmpval)
2047                 BIOSLOG(pScrn, "0x%04X: Condition fulfilled -- continuing to execute\n", offset);
2048         else {
2049                 BIOSLOG(pScrn, "0x%04X: Condition not fulfilled -- skipping following commands\n", offset);
2050                 iexec->execute = false;
2051         }
2052
2053         return true;
2054 }
2055
2056 static bool init_nv_reg(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2057 {
2058         /* INIT_NV_REG   opcode: 0x6E ('n')
2059          *
2060          * offset      (8  bit): opcode
2061          * offset + 1  (32 bit): register
2062          * offset + 5  (32 bit): mask
2063          * offset + 9  (32 bit): data
2064          *
2065          * Assign ((REGVAL("register") & "mask") | "data") to "register"
2066          */
2067
2068         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
2069         uint32_t mask = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 5])));
2070         uint32_t data = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 9])));
2071
2072         if (!iexec->execute)
2073                 return true;
2074
2075         BIOSLOG(pScrn, "0x%04X: Reg: 0x%08X, Mask: 0x%08X, Data: 0x%08X\n", offset, reg, mask, data);
2076
2077         nv32_wr(pScrn, reg, (nv32_rd(pScrn, reg) & mask) | data);
2078
2079         return true;
2080 }
2081
2082 static bool init_macro(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2083 {
2084         /* INIT_MACRO   opcode: 0x6F ('o')
2085          *
2086          * offset      (8 bit): opcode
2087          * offset + 1  (8 bit): macro number
2088          *
2089          * Look up macro index "macro number" in the macro index table.
2090          * The macro index table entry has 1 byte for the index in the macro table,
2091          * and 1 byte for the number of times to repeat the macro.
2092          * The macro table entry has 4 bytes for the register address and
2093          * 4 bytes for the value to write to that register
2094          */
2095
2096         uint8_t macro_index_tbl_idx = bios->data[offset + 1];
2097         uint16_t tmp = bios->macro_index_tbl_ptr + (macro_index_tbl_idx * MACRO_INDEX_SIZE);
2098         uint8_t macro_tbl_idx = bios->data[tmp];
2099         uint8_t count = bios->data[tmp + 1];
2100         uint32_t reg, data;
2101         int i;
2102
2103         if (!iexec->execute)
2104                 return true;
2105
2106         BIOSLOG(pScrn, "0x%04X: Macro: 0x%02X, MacroTableIndex: 0x%02X, Count: 0x%02X\n",
2107                 offset, macro_index_tbl_idx, macro_tbl_idx, count);
2108
2109         for (i = 0; i < count; i++) {
2110                 uint16_t macroentryptr = bios->macro_tbl_ptr + (macro_tbl_idx + i) * MACRO_SIZE;
2111
2112                 reg = le32_to_cpu(*((uint32_t *)(&bios->data[macroentryptr])));
2113                 data = le32_to_cpu(*((uint32_t *)(&bios->data[macroentryptr + 4])));
2114
2115                 nv32_wr(pScrn, reg, data);
2116         }
2117
2118         return true;
2119 }
2120
2121 static bool init_done(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2122 {
2123         /* INIT_DONE   opcode: 0x71 ('q')
2124          *
2125          * offset      (8  bit): opcode
2126          *
2127          * End the current script
2128          */
2129
2130         /* mild retval abuse to stop parsing this table */
2131         return false;
2132 }
2133
2134 static bool init_resume(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2135 {
2136         /* INIT_RESUME   opcode: 0x72 ('r')
2137          *
2138          * offset      (8  bit): opcode
2139          *
2140          * End the current execute / no-execute condition
2141          */
2142
2143         if (iexec->execute)
2144                 return true;
2145
2146         iexec->execute = true;
2147         BIOSLOG(pScrn, "0x%04X: ---- Executing following commands ----\n", offset);
2148
2149         return true;
2150 }
2151
2152 #if 0
2153 static bool init_ram_condition2(ScrnInfoPtr pScrn, bios_t *bios, CARD16 offset, init_exec_t *iexec)
2154 {
2155         /* INIT_RAM_CONDITION2   opcode: 0x73
2156          * 
2157          * offset      (8  bit): opcode
2158          * offset + 1  (8  bit): and mask
2159          * offset + 2  (8  bit): cmpval
2160          *
2161          * Test if (NV_EXTDEV_BOOT & and mask) matches cmpval
2162          */
2163         NVPtr pNv = NVPTR(pScrn);
2164         CARD32 and = *((CARD32 *) (&bios->data[offset + 1]));
2165         CARD32 cmpval = *((CARD32 *) (&bios->data[offset + 5]));
2166         CARD32 data;
2167
2168         if (iexec->execute) {
2169                 data=(nvReadEXTDEV(pNv, NV_PEXTDEV_BOOT))&and;
2170                 
2171                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,  
2172                                 "0x%04X: CHECKING IF REGVAL: 0x%08X equals COND: 0x%08X\n",
2173                                 offset, data, cmpval);
2174
2175                 if (data == cmpval) {
2176                         xf86DrvMsg(pScrn->scrnIndex, X_INFO,  
2177                                         "0x%04X: CONDITION FULFILLED - CONTINUING TO EXECUTE\n",
2178                                         offset);
2179                 } else {
2180                         xf86DrvMsg(pScrn->scrnIndex, X_INFO,  "0x%04X: CONDITION IS NOT FULFILLED\n", offset);
2181                         xf86DrvMsg(pScrn->scrnIndex, X_INFO,  
2182                                         "0x%04X: ------ SKIPPING FOLLOWING COMMANDS  ------\n", offset);
2183                         iexec->execute = false;
2184                 }
2185         }
2186         return true;
2187 }
2188 #endif
2189
2190 static bool init_time(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2191 {
2192         /* INIT_TIME   opcode: 0x74 ('t')
2193          *
2194          * offset      (8  bit): opcode
2195          * offset + 1  (16 bit): time
2196          *
2197          * Sleep for "time" microseconds.
2198          */
2199
2200         uint16_t time = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
2201
2202         if (!iexec->execute)
2203                 return true;
2204
2205         BIOSLOG(pScrn, "0x%04X: Sleeping for 0x%04X microseconds\n", offset, time);
2206
2207         BIOS_USLEEP(time);
2208
2209         return true;
2210 }
2211
2212 static bool init_condition(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2213 {
2214         /* INIT_CONDITION   opcode: 0x75 ('u')
2215          *
2216          * offset      (8 bit): opcode
2217          * offset + 1  (8 bit): condition number
2218          *
2219          * Check condition "condition number" in the condition table.
2220          * The condition table entry has 4 bytes for the address of the
2221          * register to check, 4 bytes for a mask and 4 for a test value.
2222          * If condition not met skip subsequent opcodes until condition is
2223          * inverted (INIT_NOT), or we hit INIT_RESUME
2224          */
2225
2226         uint8_t cond = bios->data[offset + 1];
2227         uint16_t condptr = bios->condition_tbl_ptr + cond * CONDITION_SIZE;
2228         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[condptr])));
2229         uint32_t mask = le32_to_cpu(*((uint32_t *)(&bios->data[condptr + 4])));
2230         uint32_t cmpval = le32_to_cpu(*((uint32_t *)(&bios->data[condptr + 8])));
2231         uint32_t data;
2232
2233         if (!iexec->execute)
2234                 return true;
2235
2236         BIOSLOG(pScrn, "0x%04X: Cond: 0x%02X, Reg: 0x%08X, Mask: 0x%08X, Cmpval: 0x%08X\n",
2237                 offset, cond, reg, mask, cmpval);
2238
2239         data = nv32_rd(pScrn, reg) & mask;
2240
2241         BIOSLOG(pScrn, "0x%04X: Checking if 0x%08X equals 0x%08X\n", offset, data, cmpval);
2242
2243         if (data == cmpval)
2244                 BIOSLOG(pScrn, "0x%04X: Condition fulfilled -- continuing to execute\n", offset);
2245         else {
2246                 BIOSLOG(pScrn, "0x%04X: Condition not fulfilled -- skipping following commands\n", offset);
2247                 iexec->execute = false;
2248         }
2249
2250         return true;
2251 }
2252
2253 static bool init_index_io(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2254 {
2255         /* INIT_INDEX_IO   opcode: 0x78 ('x')
2256          *
2257          * offset      (8  bit): opcode
2258          * offset + 1  (16 bit): CRTC port
2259          * offset + 3  (8  bit): CRTC index
2260          * offset + 4  (8  bit): mask
2261          * offset + 5  (8  bit): data
2262          *
2263          * Read value at index "CRTC index" on "CRTC port", AND with "mask", OR with "data", write-back
2264          */
2265
2266         uint16_t crtcport = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 1])));
2267         uint8_t crtcindex = bios->data[offset + 3];
2268         uint8_t mask = bios->data[offset + 4];
2269         uint8_t data = bios->data[offset + 5];
2270         uint8_t value;
2271
2272         if (!iexec->execute)
2273                 return true;
2274
2275         BIOSLOG(pScrn, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, Data: 0x%02X\n",
2276                 offset, crtcport, crtcindex, mask, data);
2277
2278         value = (nv_idx_port_rd(pScrn, crtcport, crtcindex) & mask) | data;
2279         nv_idx_port_wr(pScrn, crtcport, crtcindex, value);
2280
2281         return true;
2282 }
2283
2284 static bool init_pll(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2285 {
2286         /* INIT_PLL   opcode: 0x79 ('y')
2287          *
2288          * offset      (8  bit): opcode
2289          * offset + 1  (32 bit): register
2290          * offset + 5  (16 bit): freq
2291          *
2292          * Set PLL register "register" to coefficients for frequency (10kHz) "freq"
2293          */
2294
2295         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
2296         uint16_t freq = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 5])));
2297
2298         if (!iexec->execute)
2299                 return true;
2300
2301         BIOSLOG(pScrn, "0x%04X: Reg: 0x%08X, Freq: %d0kHz\n", offset, reg, freq);
2302
2303         setPLL(pScrn, bios, reg, freq * 10);
2304
2305         return true;
2306 }
2307
2308 static bool init_zm_reg(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2309 {
2310         /* INIT_ZM_REG   opcode: 0x7A ('z')
2311          *
2312          * offset      (8  bit): opcode
2313          * offset + 1  (32 bit): register
2314          * offset + 5  (32 bit): value
2315          *
2316          * Assign "value" to "register"
2317          */
2318
2319         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
2320         uint32_t value = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 5])));
2321
2322         if (!iexec->execute)
2323                 return true;
2324
2325         nv32_wr(pScrn, reg, value);
2326
2327         return true;
2328 }
2329
2330 static bool init_8e(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2331 {
2332         /* INIT_8E   opcode: 0x8E ('')
2333          *
2334          * offset      (8 bit): opcode
2335          *
2336          * The purpose of this opcode is unclear (being for nv50 cards), and
2337          * the literal functionality can be seen in the code below.
2338          *
2339          * A brief synopsis is that for each entry in a table pointed to by the
2340          * DCB table header, depending on the settings of various bits, various
2341          * other bits in registers 0xe100, 0xe104, and 0xe108, are set or
2342          * cleared.
2343          */
2344
2345         uint16_t dcbptr = le16_to_cpu(*(uint16_t *)&bios->data[0x36]);
2346         uint16_t init8etblptr = le16_to_cpu(*(uint16_t *)&bios->data[dcbptr + 10]);
2347         uint8_t headerlen = bios->data[init8etblptr + 1];
2348         uint8_t entries = bios->data[init8etblptr + 2];
2349         uint8_t recordlen = bios->data[init8etblptr + 3];
2350         int i;
2351
2352         if (!dcbptr) {
2353                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2354                            "No Display Configuration Block pointer found\n");
2355                 return false;
2356         }
2357         if (bios->data[dcbptr] != 0x40) {
2358                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2359                            "DCB table not version 4.0\n");
2360                 return false;
2361         }
2362         if (!init8etblptr) {
2363                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
2364                            "Invalid pointer to INIT_8E table\n");
2365                 return false;
2366         }
2367
2368         for (i = 0; i < entries; i++) {
2369                 uint32_t entry = le32_to_cpu(*(uint32_t *)&bios->data[init8etblptr + headerlen + recordlen * i]);
2370                 int shift = (entry & 0x1f) * 4;
2371                 uint32_t mask;
2372                 uint32_t reg = 0xe104;
2373                 uint32_t data;
2374
2375                 if ((entry & 0xff00) == 0xff00)
2376                         continue;
2377
2378                 if (shift >= 32) {
2379                         reg += 4;
2380                         shift -= 32;
2381                 }
2382                 shift %= 32;
2383
2384                 mask = ~(3 << shift);
2385                 if (entry & (1 << 24))
2386                         data = (entry >> 21);
2387                 else
2388                         data = (entry >> 19);
2389                 data = ((data & 3) ^ 2) << shift;
2390
2391                 BIOSLOG(pScrn, "0x%04X: Entry: 0x%08X, Reg: 0x%08X, Shift: 0x%02X, Mask: 0x%08X, Data: 0x%08X\n",
2392                         offset, entry, reg, shift, mask, data);
2393
2394                 nv32_wr(pScrn, reg, (nv32_rd(pScrn, reg) & mask) | data);
2395
2396                 reg = 0xe100;
2397                 shift = entry & 0x1f;
2398
2399                 mask = ~(1 << 16 | 1);
2400                 mask = mask << shift | mask >> (32 - shift);
2401                 data = 0;
2402                 if ((entry & (3 << 25)) == (1 << 25))
2403                         data |= 1;
2404                 if ((entry & (3 << 25)) == (2 << 25))
2405                         data |= 0x10000;
2406                 data <<= shift;
2407
2408                 BIOSLOG(pScrn, "0x%04X: Entry: 0x%08X, Reg: 0x%08X, Shift: 0x%02X, Mask: 0x%08X, Data: 0x%08X\n",
2409                         offset, entry, reg, shift, mask, data);
2410
2411                 nv32_wr(pScrn, reg, (nv32_rd(pScrn, reg) & mask) | data);
2412         }
2413
2414         return true;
2415 }
2416
2417 /* hack to avoid moving the itbl_entry array before this function */
2418 int init_ram_restrict_zm_reg_group_blocklen = 0;
2419
2420 static bool init_ram_restrict_zm_reg_group(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2421 {
2422         /* INIT_RAM_RESTRICT_ZM_REG_GROUP   opcode: 0x8F ('')
2423          *
2424          * offset      (8  bit): opcode
2425          * offset + 1  (32 bit): reg
2426          * offset + 5  (8  bit): regincrement
2427          * offset + 6  (8  bit): count
2428          * offset + 7  (32 bit): value 1,1
2429          * ...
2430          *
2431          * Use the RAMCFG strap of PEXTDEV_BOOT as an index into the table at
2432          * ram_restrict_table_ptr. The value read from here is 'n', and
2433          * "value 1,n" gets written to "reg". This repeats "count" times and on
2434          * each iteration 'm', "reg" increases by "regincrement" and
2435          * "value m,n" is used. The extent of n is limited by a number read
2436          * from the 'M' BIT table, herein called "blocklen"
2437          */
2438
2439         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
2440         uint8_t regincrement = bios->data[offset + 5];
2441         uint8_t count = bios->data[offset + 6];
2442         uint32_t strap_ramcfg, data;
2443         uint16_t blocklen;
2444         uint8_t index;
2445         int i;
2446
2447         /* previously set by 'M' BIT table */
2448         blocklen = init_ram_restrict_zm_reg_group_blocklen;
2449
2450         if (!iexec->execute)
2451                 return true;
2452
2453         if (!blocklen) {
2454                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2455                            "0x%04X: Zero block length - has the M table been parsed?\n", offset);
2456                 return false;
2457         }
2458
2459         strap_ramcfg = (nv32_rd(pScrn, NV_PEXTDEV_BOOT_0) >> 2) & 0xf;
2460         index = bios->data[bios->ram_restrict_tbl_ptr + strap_ramcfg];
2461
2462         BIOSLOG(pScrn, "0x%04X: Reg: 0x%08X, RegIncrement: 0x%02X, Count: 0x%02X, StrapRamCfg: 0x%02X, Index: 0x%02X\n",
2463                 offset, reg, regincrement, count, strap_ramcfg, index);
2464
2465         for (i = 0; i < count; i++) {
2466                 data = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 7 + index * 4 + blocklen * i])));
2467
2468                 nv32_wr(pScrn, reg, data);
2469
2470                 reg += regincrement;
2471         }
2472
2473         return true;
2474 }
2475
2476 static bool init_copy_zm_reg(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2477 {
2478         /* INIT_COPY_ZM_REG   opcode: 0x90 ('')
2479          *
2480          * offset      (8  bit): opcode
2481          * offset + 1  (32 bit): src reg
2482          * offset + 5  (32 bit): dst reg
2483          *
2484          * Put contents of "src reg" into "dst reg"
2485          */
2486
2487         uint32_t srcreg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
2488         uint32_t dstreg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 5])));
2489
2490         if (!iexec->execute)
2491                 return true;
2492
2493         nv32_wr(pScrn, dstreg, nv32_rd(pScrn, srcreg));
2494
2495         return true;
2496 }
2497
2498 static bool init_zm_reg_group_addr_latched(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2499 {
2500         /* INIT_ZM_REG_GROUP_ADDRESS_LATCHED   opcode: 0x91 ('')
2501          *
2502          * offset      (8  bit): opcode
2503          * offset + 1  (32 bit): dst reg
2504          * offset + 5  (8  bit): count
2505          * offset + 6  (32 bit): data 1
2506          * ...
2507          *
2508          * For each of "count" values write "data n" to "dst reg"
2509          */
2510
2511         uint32_t reg = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 1])));
2512         uint8_t count = bios->data[offset + 5];
2513         int i;
2514
2515         if (!iexec->execute)
2516                 return true;
2517
2518         for (i = 0; i < count; i++) {
2519                 uint32_t data = le32_to_cpu(*((uint32_t *)(&bios->data[offset + 6 + 4 * i])));
2520                 nv32_wr(pScrn, reg, data);
2521         }
2522
2523         return true;
2524 }
2525
2526 static bool init_reserved(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset, init_exec_t *iexec)
2527 {
2528         /* INIT_RESERVED   opcode: 0x92 ('')
2529          *
2530          * offset      (8 bit): opcode
2531          *
2532          * Seemingly does nothing
2533          */
2534
2535         return true;
2536 }
2537
2538 static init_tbl_entry_t itbl_entry[] = {
2539         /* command name                       , id  , length  , offset  , mult    , command handler                 */
2540 //      { "INIT_PROG"                         , 0x31, 15      , 10      , 4       , init_prog                       },
2541         { "INIT_IO_RESTRICT_PROG"             , 0x32, 11      , 6       , 4       , init_io_restrict_prog           },
2542         { "INIT_REPEAT"                       , 0x33, 2       , 0       , 0       , init_repeat                     },
2543         { "INIT_IO_RESTRICT_PLL"              , 0x34, 12      , 7       , 2       , init_io_restrict_pll            },
2544         { "INIT_END_REPEAT"                   , 0x36, 1       , 0       , 0       , init_end_repeat                 },
2545         { "INIT_COPY"                         , 0x37, 11      , 0       , 0       , init_copy                       },
2546         { "INIT_NOT"                          , 0x38, 1       , 0       , 0       , init_not                        },
2547         { "INIT_IO_FLAG_CONDITION"            , 0x39, 2       , 0       , 0       , init_io_flag_condition          },
2548         { "INIT_INDEX_ADDRESS_LATCHED"        , 0x49, 18      , 17      , 2       , init_idx_addr_latched           },
2549         { "INIT_IO_RESTRICT_PLL2"             , 0x4A, 11      , 6       , 4       , init_io_restrict_pll2           },
2550         { "INIT_PLL2"                         , 0x4B, 9       , 0       , 0       , init_pll2                       },
2551 /*      { "INIT_I2C_BYTE"                     , 0x4C, x       , x       , x       , init_i2c_byte                   }, */
2552 /*      { "INIT_ZM_I2C_BYTE"                  , 0x4D, x       , x       , x       , init_zm_i2c_byte                }, */
2553 /*      { "INIT_ZM_I2C"                       , 0x4E, x       , x       , x       , init_zm_i2c                     }, */
2554         { "INIT_TMDS"                         , 0x4F, 5       , 0       , 0       , init_tmds                       },
2555         { "INIT_ZM_TMDS_GROUP"                , 0x50, 3       , 2       , 2       , init_zm_tmds_group              },
2556         { "INIT_CR_INDEX_ADDRESS_LATCHED"     , 0x51, 5       , 4       , 1       , init_cr_idx_adr_latch           },
2557         { "INIT_CR"                           , 0x52, 4       , 0       , 0       , init_cr                         },
2558         { "INIT_ZM_CR"                        , 0x53, 3       , 0       , 0       , init_zm_cr                      },
2559         { "INIT_ZM_CR_GROUP"                  , 0x54, 2       , 1       , 2       , init_zm_cr_group                },
2560         { "INIT_CONDITION_TIME"               , 0x56, 3       , 0       , 0       , init_condition_time             },
2561         { "INIT_ZM_REG_SEQUENCE"              , 0x58, 6       , 5       , 4       , init_zm_reg_sequence            },
2562 //      { "INIT_INDIRECT_REG"                 , 0x5A, 7       , 0       , 0       , init_indirect_reg               },
2563         { "INIT_SUB_DIRECT"                   , 0x5B, 3       , 0       , 0       , init_sub_direct                 },
2564         { "INIT_COPY_NV_REG"                  , 0x5F, 22      , 0       , 0       , init_copy_nv_reg                },
2565         { "INIT_ZM_INDEX_IO"                  , 0x62, 5       , 0       , 0       , init_zm_index_io                },
2566         { "INIT_COMPUTE_MEM"                  , 0x63, 1       , 0       , 0       , init_compute_mem                },
2567         { "INIT_RESET"                        , 0x65, 13      , 0       , 0       , init_reset                      },
2568         { "INIT_CONFIGURE_MEM"                , 0x66, 1       , 0       , 0       , init_configure_mem              },
2569         { "INIT_CONFIGURE_CLK"                , 0x67, 1       , 0       , 0       , init_configure_clk              },
2570         { "INIT_CONFIGURE_PREINIT"            , 0x68, 1       , 0       , 0       , init_configure_preinit          },
2571         { "INIT_IO"                           , 0x69, 5       , 0       , 0       , init_io                         },
2572         { "INIT_SUB"                          , 0x6B, 2       , 0       , 0       , init_sub                        },
2573         { "INIT_RAM_CONDITION"                , 0x6D, 3       , 0       , 0       , init_ram_condition              },
2574         { "INIT_NV_REG"                       , 0x6E, 13      , 0       , 0       , init_nv_reg                     },
2575         { "INIT_MACRO"                        , 0x6F, 2       , 0       , 0       , init_macro                      },
2576         { "INIT_DONE"                         , 0x71, 1       , 0       , 0       , init_done                       },
2577         { "INIT_RESUME"                       , 0x72, 1       , 0       , 0       , init_resume                     },
2578 //      { "INIT_RAM_CONDITION2"               , 0x73, 9       , 0       , 0       , init_ram_condition2             },
2579         { "INIT_TIME"                         , 0x74, 3       , 0       , 0       , init_time                       },
2580         { "INIT_CONDITION"                    , 0x75, 2       , 0       , 0       , init_condition                  },
2581 /*      { "INIT_IO_CONDITION"                 , 0x76, x       , x       , x       , init_io_condition               }, */
2582         { "INIT_INDEX_IO"                     , 0x78, 6       , 0       , 0       , init_index_io                   },
2583         { "INIT_PLL"                          , 0x79, 7       , 0       , 0       , init_pll                        },
2584         { "INIT_ZM_REG"                       , 0x7A, 9       , 0       , 0       , init_zm_reg                     },
2585         { "INIT_8E"                           , 0x8E, 1       , 0       , 0       , init_8e                         },
2586         /* INIT_RAM_RESTRICT_ZM_REG_GROUP's mult is loaded by M table in BIT */
2587         { "INIT_RAM_RESTRICT_ZM_REG_GROUP"    , 0x8F, 7       , 6       , 0       , init_ram_restrict_zm_reg_group  },
2588         { "INIT_COPY_ZM_REG"                  , 0x90, 9       , 0       , 0       , init_copy_zm_reg                },
2589         { "INIT_ZM_REG_GROUP_ADDRESS_LATCHED" , 0x91, 6       , 5       , 4       , init_zm_reg_group_addr_latched  },
2590         { "INIT_RESERVED"                     , 0x92, 1       , 0       , 0       , init_reserved                   },
2591         { 0                                   , 0   , 0       , 0       , 0       , 0                               }
2592 };
2593
2594 static unsigned int get_init_table_entry_length(bios_t *bios, unsigned int offset, int i)
2595 {
2596         /* Calculates the length of a given init table entry. */
2597         return itbl_entry[i].length + bios->data[offset + itbl_entry[i].length_offset]*itbl_entry[i].length_multiplier;
2598 }
2599
2600 static void parse_init_table(ScrnInfoPtr pScrn, bios_t *bios, unsigned int offset, init_exec_t *iexec)
2601 {
2602         /* Parses all commands in a init table. */
2603
2604         /* We start out executing all commands found in the
2605          * init table. Some op codes may change the status
2606          * of this variable to SKIP, which will cause
2607          * the following op codes to perform no operation until
2608          * the value is changed back to EXECUTE.
2609          */
2610         unsigned char id;
2611         int i;
2612
2613         int count=0;
2614         /* Loop until INIT_DONE causes us to break out of the loop
2615          * (or until offset > bios length just in case... )
2616          * (and no more than 10000 iterations just in case... ) */
2617         while ((offset < bios->length) && (count++ < 10000)) {
2618                 id = bios->data[offset];
2619
2620                 /* Find matching id in itbl_entry */
2621                 for (i = 0; itbl_entry[i].name && (itbl_entry[i].id != id); i++)
2622                         ;
2623
2624                 if (itbl_entry[i].name) {
2625                         BIOSLOG(pScrn, "0x%04X: [ (0x%02X) - %s ]\n",
2626                                 offset, itbl_entry[i].id, itbl_entry[i].name);
2627
2628                         /* execute eventual command handler */
2629                         if (itbl_entry[i].handler)
2630                                 if (!(*itbl_entry[i].handler)(pScrn, bios, offset, iexec))
2631                                         break;
2632                 } else {
2633                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2634                                    "0x%04X: Init table command not found: 0x%02X\n", offset, id);
2635                         break;
2636                 }
2637
2638                 /* Add the offset of the current command including all data
2639                  * of that command. The offset will then be pointing on the
2640                  * next op code.
2641                  */
2642                 offset += get_init_table_entry_length(bios, offset, i);
2643         }
2644 }
2645
2646 static void parse_init_tables(ScrnInfoPtr pScrn, bios_t *bios)
2647 {
2648         /* Loops and calls parse_init_table() for each present table. */
2649
2650         int i = 0;
2651         uint16_t table;
2652         init_exec_t iexec = {true, false};
2653
2654         while ((table = le16_to_cpu(*((uint16_t *)(&bios->data[bios->init_script_tbls_ptr + i]))))) {
2655                 xf86DrvMsg(pScrn->scrnIndex, X_PROBED,
2656                            "Parsing VBIOS init table %d at offset 0x%04X\n", i / 2, table);
2657                 BIOSLOG(pScrn, "0x%04X: ------ Executing following commands ------\n", table);
2658
2659                 parse_init_table(pScrn, bios, table, &iexec);
2660                 i += 2;
2661         }
2662 }
2663
2664 static void link_head_and_output(ScrnInfoPtr pScrn, struct dcb_entry *dcbent, int head)
2665 {
2666         /* The BIOS scripts don't do this for us, sadly
2667          * Luckily we do know the values ;-)
2668          *
2669          * head < 0 indicates we wish to force a setting with the overrideval
2670          * (for VT restore etc.)
2671          */
2672
2673         NVPtr pNv = NVPTR(pScrn);
2674         int ramdac = (dcbent->or & OUTPUT_C) >> 2;
2675         uint8_t tmds04 = 0x80;
2676
2677         if (head != ramdac)
2678                 tmds04 = 0x88;
2679
2680         if (dcbent->type == OUTPUT_LVDS)
2681                 tmds04 |= 0x01;
2682
2683         nv_write_tmds(pNv, dcbent->or, 0, 0x04, tmds04);
2684
2685         if (dcbent->type == OUTPUT_LVDS && pNv->VBIOS.fp.dual_link)
2686                 nv_write_tmds(pNv, dcbent->or, 1, 0x04, tmds04 ^ 0x08);
2687 }
2688
2689 static uint16_t clkcmptable(bios_t *bios, uint16_t clktable, int pxclk)
2690 {
2691         int compare_record_len, i = 0;
2692         uint16_t compareclk, scriptptr = 0;
2693
2694         if (bios->major_version < 5) /* pre BIT */
2695                 compare_record_len = 3;
2696         else
2697                 compare_record_len = 4;
2698
2699         do {
2700                 compareclk = le16_to_cpu(*((uint16_t *)&bios->data[clktable + compare_record_len * i]));
2701                 if (pxclk >= compareclk * 10) {
2702                         if (bios->major_version < 5) {
2703                                 uint8_t tmdssub = bios->data[clktable + 2 + compare_record_len * i];
2704                                 scriptptr = le16_to_cpu(*((uint16_t *)(&bios->data[bios->init_script_tbls_ptr + tmdssub * 2])));
2705                         } else
2706                                 scriptptr = le16_to_cpu(*((uint16_t *)&bios->data[clktable + 2 + compare_record_len * i]));
2707                         break;
2708                 }
2709                 i++;
2710         } while (compareclk);
2711
2712         return scriptptr;
2713 }
2714
2715 static void rundigitaloutscript(ScrnInfoPtr pScrn, uint16_t scriptptr, struct dcb_entry *dcbent, int head)
2716 {
2717         bios_t *bios = &NVPTR(pScrn)->VBIOS;
2718         init_exec_t iexec = {true, false};
2719
2720         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "0x%04X: Parsing digital output script table\n", scriptptr);
2721         nv_idx_port_wr(pScrn, NV_CIO_CRX__COLOR, NV_CIO_CRE_44,
2722                        head ? NV_CIO_CRE_44_HEADB : NV_CIO_CRE_44_HEADA);
2723         NVWriteVgaCrtc5758(NVPTR(pScrn), head, 0, dcbent->index);
2724         parse_init_table(pScrn, bios, scriptptr, &iexec);
2725
2726         link_head_and_output(pScrn, dcbent, head);
2727 }
2728
2729 static void call_lvds_manufacturer_script(ScrnInfoPtr pScrn, struct dcb_entry *dcbent, int head, enum LVDS_script script)
2730 {
2731         NVPtr pNv = NVPTR(pScrn);
2732         bios_t *bios = &pNv->VBIOS;
2733         uint8_t sub = bios->data[bios->fp.xlated_entry + script] + (bios->fp.link_c_increment && dcbent->or & OUTPUT_C ? 1 : 0);
2734         uint16_t scriptofs = le16_to_cpu(*((uint16_t *)(&bios->data[bios->init_script_tbls_ptr + sub * 2])));
2735
2736         if (!bios->fp.xlated_entry || !sub || !scriptofs)
2737                 return;
2738
2739         rundigitaloutscript(pScrn, scriptofs, dcbent, head);
2740
2741         if (script == LVDS_PANEL_OFF)
2742                 /* off-on delay in ms */
2743                 BIOS_USLEEP(le16_to_cpu(*(uint16_t *)&bios->data[bios->fp.xlated_entry + 7]));
2744 #ifdef __powerpc__
2745         /* Powerbook specific quirks */
2746         if (script == LVDS_RESET && ((pNv->Chipset & 0xffff) == 0x0179 || (pNv->Chipset & 0xffff) == 0x0329))
2747                 nv_write_tmds(pNv, dcbent->or, 0, 0x02, 0x72);
2748         if ((pNv->Chipset & 0xffff) == 0x0179 || (pNv->Chipset & 0xffff) == 0x0189 || (pNv->Chipset & 0xffff) == 0x0329) {
2749                 if (script == LVDS_PANEL_ON) {
2750                         nv32_wr(pScrn, NV_PBUS_DEBUG_DUALHEAD_CTL, nv32_rd(pScrn, NV_PBUS_DEBUG_DUALHEAD_CTL) | (1 << 31));
2751                         nv32_wr(pScrn, NV_CRTC_GPIO_EXT, nv32_rd(pScrn, NV_CRTC_GPIO_EXT) | 1);
2752                 }
2753                 if (script == LVDS_PANEL_OFF) {
2754                         nv32_wr(pScrn, NV_PBUS_DEBUG_DUALHEAD_CTL, nv32_rd(pScrn, NV_PBUS_DEBUG_DUALHEAD_CTL) & ~(1 << 31));
2755                         nv32_wr(pScrn, NV_CRTC_GPIO_EXT, nv32_rd(pScrn, NV_CRTC_GPIO_EXT) & ~3);
2756                 }
2757         }
2758 #endif
2759 }
2760
2761 static void run_lvds_table(ScrnInfoPtr pScrn, struct dcb_entry *dcbent, int head, enum LVDS_script script, int pxclk)
2762 {
2763         /* The BIT LVDS table's header has the information to setup the
2764          * necessary registers. Following the standard 4 byte header are:
2765          * A bitmask byte and a dual-link transition pxclk value for use in
2766          * selecting the init script when not using straps; 4 script pointers
2767          * for panel power, selected by output and on/off; and 8 table pointers
2768          * for panel init, the needed one determined by output, and bits in the
2769          * conf byte. These tables are similar to the TMDS tables, consisting
2770          * of a list of pxclks and script pointers.
2771          */
2772
2773         NVPtr pNv = NVPTR(pScrn);
2774         bios_t *bios = &pNv->VBIOS;
2775         unsigned int outputset = (dcbent->or == 4) ? 1 : 0;
2776         uint16_t scriptptr = 0, clktable;
2777         uint8_t clktableptr = 0;
2778
2779         /* for now we assume version 3.0 table - g80 support will need some changes */
2780
2781         switch (script) {
2782         case LVDS_INIT:
2783                 return;
2784         case LVDS_BACKLIGHT_ON:
2785         case LVDS_PANEL_ON:
2786                 scriptptr = le16_to_cpu(*(uint16_t *)&bios->data[bios->fp.lvdsmanufacturerpointer + 7 + outputset * 2]);
2787                 break;
2788         case LVDS_BACKLIGHT_OFF:
2789         case LVDS_PANEL_OFF:
2790                 scriptptr = le16_to_cpu(*(uint16_t *)&bios->data[bios->fp.lvdsmanufacturerpointer + 11 + outputset * 2]);
2791                 break;
2792         case LVDS_RESET:
2793                 if (dcbent->lvdsconf.use_straps_for_mode) {
2794                         if (bios->fp.dual_link)
2795                                 clktableptr += 2;
2796                         if (bios->fp.BITbit1)
2797                                 clktableptr++;
2798                 } else {
2799                         uint8_t fallback = bios->data[bios->fp.lvdsmanufacturerpointer + 4];
2800                         int fallbackcmpval = (dcbent->or == 4) ? 4 : 1;
2801
2802                         if (bios->fp.dual_link) {
2803                                 clktableptr += 2;
2804                                 fallbackcmpval *= 2;
2805                         }
2806                         if (fallbackcmpval & fallback)
2807                                 clktableptr++;
2808                 }
2809
2810                 /* adding outputset * 8 may not be correct */
2811                 clktable = le16_to_cpu(*(uint16_t *)&bios->data[bios->fp.lvdsmanufacturerpointer + 15 + clktableptr * 2 + outputset * 8]);
2812                 if (!clktable) {
2813                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Pixel clock comparison table not found\n");
2814                         return;
2815                 }
2816                 scriptptr = clkcmptable(bios, clktable, pxclk);
2817         }
2818
2819         if (!scriptptr) {
2820                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "LVDS output init script not found\n");
2821                 return;
2822         }
2823         rundigitaloutscript(pScrn, scriptptr, dcbent, head);
2824 }
2825
2826 void call_lvds_script(ScrnInfoPtr pScrn, struct dcb_entry *dcbent, int head, enum LVDS_script script, int pxclk)
2827 {
2828         /* LVDS operations are multiplexed in an effort to present a single API
2829          * which works with two vastly differing underlying structures.
2830          * This acts as the demux
2831          */
2832
2833         bios_t *bios = &NVPTR(pScrn)->VBIOS;
2834         uint8_t lvds_ver = bios->data[bios->fp.lvdsmanufacturerpointer];
2835         uint32_t sel_clk_binding;
2836         static int last_invoc = 0;
2837
2838         if (last_invoc == (script << 1 | head) || !lvds_ver)
2839                 return;
2840
2841         if (script == LVDS_PANEL_ON && bios->fp.reset_after_pclk_change)
2842                 call_lvds_script(pScrn, dcbent, head, LVDS_RESET, pxclk);
2843         if (script == LVDS_RESET && bios->fp.power_off_for_reset)
2844                 call_lvds_script(pScrn, dcbent, head, LVDS_PANEL_OFF, pxclk);
2845
2846         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Calling LVDS script %d:\n", script);
2847
2848         /* don't let script change pll->head binding */
2849         sel_clk_binding = nv32_rd(pScrn, NV_RAMDAC_SEL_CLK) & 0x50000;
2850
2851         if (lvds_ver < 0x30)
2852                 call_lvds_manufacturer_script(pScrn, dcbent, head, script);
2853         else
2854                 run_lvds_table(pScrn, dcbent, head, script, pxclk);
2855
2856         last_invoc = (script << 1 | head);
2857
2858         nv32_wr(pScrn, NV_RAMDAC_SEL_CLK, (nv32_rd(pScrn, NV_RAMDAC_SEL_CLK) & ~0x50000) | sel_clk_binding);
2859         /* some scripts set a value in NV_PBUS_POWERCTRL_2 and break video overlay */
2860         nv32_wr(pScrn, NV_PBUS_POWERCTRL_2, 0);
2861 }
2862
2863 struct fppointers {
2864         uint16_t fptablepointer;
2865         uint16_t fpxlatetableptr;
2866         int xlatwidth;
2867 };
2868
2869 struct lvdstableheader {
2870         uint8_t lvds_ver, headerlen, recordlen;
2871 };
2872
2873 static void parse_lvds_manufacturer_table_header(ScrnInfoPtr pScrn, bios_t *bios, struct lvdstableheader *lth)
2874 {
2875         /* BMP version (0xa) LVDS table has a simple header of version and
2876          * record length. The BIT LVDS table has the typical BIT table header:
2877          * version byte, header length byte, record length byte, and a byte for
2878          * the maximum number of records that can be held in the table */
2879
2880         uint8_t lvds_ver, headerlen, recordlen;
2881
2882         memset(lth, 0, sizeof(struct lvdstableheader));
2883
2884         if (bios->fp.lvdsmanufacturerpointer == 0x0) {
2885                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2886                            "Pointer to LVDS manufacturer table invalid\n");
2887                 return;
2888         }
2889
2890         lvds_ver = bios->data[bios->fp.lvdsmanufacturerpointer];
2891
2892         switch (lvds_ver) {
2893         case 0x0a:      /* pre NV40 */
2894                 headerlen = 2;
2895                 recordlen = bios->data[bios->fp.lvdsmanufacturerpointer + 1];
2896                 break;
2897         case 0x30:      /* NV4x */
2898                 headerlen = bios->data[bios->fp.lvdsmanufacturerpointer + 1];
2899                 if (headerlen < 0x1f) {
2900                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2901                                    "LVDS table header not understood\n");
2902                         return;
2903                 }
2904                 recordlen = bios->data[bios->fp.lvdsmanufacturerpointer + 2];
2905                 break;
2906         case 0x40:      /* G80/G90 */
2907                 headerlen = bios->data[bios->fp.lvdsmanufacturerpointer + 1];
2908                 if (headerlen < 0x7) {
2909                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2910                                    "LVDS table header not understood\n");
2911                         return;
2912                 }
2913                 recordlen = bios->data[bios->fp.lvdsmanufacturerpointer + 2];
2914                 break;
2915         default:
2916                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2917                            "LVDS table revision %d.%d not currently supported\n",
2918                            lvds_ver >> 4, lvds_ver & 0xf);
2919                 return;
2920         }
2921
2922         lth->lvds_ver = lvds_ver;
2923         lth->headerlen = headerlen;
2924         lth->recordlen = recordlen;
2925 }
2926
2927 static void parse_fp_mode_table(ScrnInfoPtr pScrn, bios_t *bios, struct fppointers *fpp)
2928 {
2929         uint8_t *fptable;
2930         uint8_t fptable_ver, headerlen = 0, recordlen, fpentries = 0xf, fpindex;
2931         int ofs;
2932         struct lvdstableheader lth;
2933         uint16_t modeofs;
2934         DisplayModePtr mode;
2935
2936         if (fpp->fptablepointer == 0x0) {
2937                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2938                            "Pointer to flat panel table invalid\n");
2939                 return;
2940         }
2941
2942         fptable = &bios->data[fpp->fptablepointer];
2943         fptable_ver = fptable[0];
2944
2945         switch (fptable_ver) {
2946         /* BMP version 0x5.0x11 BIOSen have version 1 like tables, but no version field,
2947          * and miss one of the spread spectrum/PWM bytes.
2948          * This could affect early GF2Go parts (not seen any appropriate ROMs though).
2949          * Here we assume that a version of 0x05 matches this case (combining with a
2950          * BMP version check would be better), as the common case for the panel type
2951          * field is 0x0005, and that is in fact what we are reading the first byte of. */
2952         case 0x05:      /* some NV10, 11, 15, 16 */
2953                 recordlen = 42;
2954                 ofs = 6;
2955                 break;
2956         case 0x10:      /* some NV15/16, and NV11+ */
2957                 recordlen = 44;
2958                 ofs = 7;
2959                 break;
2960         case 0x20:      /* NV40+ */
2961                 headerlen = fptable[1];
2962                 recordlen = fptable[2];
2963                 fpentries = fptable[3];
2964                 /* fptable[4] is the minimum RAMDAC_FP_HCRTC->RAMDAC_FP_HSYNC_START gap */
2965                 bios->digital_min_front_porch = fptable[4];
2966                 ofs = 0;
2967                 break;
2968         default:
2969                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2970                            "FP table revision %d.%d not currently supported\n",
2971                            fptable_ver >> 4, fptable_ver & 0xf);
2972                 return;
2973         }
2974
2975         /* non mobile only needs to set digital_min_front_porch */
2976         if (!(bios->feature_byte & FEATURE_MOBILE))
2977                 return;
2978
2979         parse_lvds_manufacturer_table_header(pScrn, bios, &lth);
2980
2981         switch (lth.lvds_ver) {
2982         case 0x0a:
2983                 /* make sure to match the 0xff strapping check below */
2984                 if ((bios->fp.strapping & 0xf) == 0xf)
2985                         bios->data[fpp->fpxlatetableptr + 0xf] = 0xf;
2986                 break;
2987         case 0x30:
2988         case 0x40:
2989                 fpp->fpxlatetableptr = bios->fp.lvdsmanufacturerpointer + lth.headerlen + 1;
2990                 fpp->xlatwidth = lth.recordlen;
2991         }
2992         if (fpp->fpxlatetableptr == 0x0) {
2993                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
2994                            "Pointer to flat panel xlat table invalid\n");
2995                 return;
2996         }
2997
2998         /* Query all modes and find one with a matching clock. */
2999         /* Note that this only serves as a backup solution if ddc fails. */
3000         if (lth.lvds_ver == 0x40) {
3001                 uint32_t clock, needed_clock;
3002                 int i, index = 0xF, matches = 0;
3003                 needed_clock = nv32_rd(pScrn, 0x00616404) & 0xFFFFF;
3004                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "LVDS clock seems to be %d KHz.\n", needed_clock);
3005
3006                 for (i = 0; i < fpentries; i++) {
3007                         modeofs = headerlen + recordlen * i;
3008                         clock = le16_to_cpu(*(uint16_t *)&fptable[modeofs]) * 10;
3009                         if (clock == needed_clock) {
3010                                 matches++;
3011                                 index = i;
3012                         }
3013                 }
3014
3015                 if (matches == 1)
3016                         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Found a mode with matching clock\n");
3017                 else
3018                         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Found %d modes, this is not useful\n", matches);
3019
3020                 if (matches != 1)
3021                         index = 0xF;
3022
3023                 fpindex = bios->data[fpp->fpxlatetableptr + index * fpp->xlatwidth];
3024                 bios->fp.strapping = ((fpindex & 0xF) << 4) | (fpindex & 0xF);
3025         } else {
3026                 fpindex = bios->data[fpp->fpxlatetableptr + bios->fp.strapping * fpp->xlatwidth];
3027                 bios->fp.strapping |= fpindex << 4;
3028         }
3029
3030         if (fpindex > fpentries) {
3031                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3032                            "Bad flat panel table index\n");
3033                 return;
3034         }
3035
3036         /* reserved values - means that ddc or hard coded edid should be used */
3037         if (bios->fp.strapping == 0xff) {
3038                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Ignoring FP table\n");
3039                 return;
3040         }
3041
3042         if (!(mode = xcalloc(1, sizeof(DisplayModeRec))))
3043                 return;
3044
3045         modeofs = headerlen + recordlen * fpindex + ofs;
3046         mode->Clock = le16_to_cpu(*(uint16_t *)&fptable[modeofs]) * 10;
3047         mode->HDisplay = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 4] + 1);
3048         mode->HSyncStart = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 10] + 1);
3049         mode->HSyncEnd = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 12] + 1);
3050         mode->HTotal = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 14] + 1);
3051         mode->VDisplay = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 18] + 1);
3052         mode->VSyncStart = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 24] + 1);
3053         mode->VSyncEnd = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 26] + 1);
3054         mode->VTotal = le16_to_cpu(*(uint16_t *)&fptable[modeofs + 28] + 1);
3055         mode->Flags |= (fptable[modeofs + 30] & 0x10) ? V_PHSYNC : V_NHSYNC;
3056         mode->Flags |= (fptable[modeofs + 30] & 0x1) ? V_PVSYNC : V_NVSYNC;
3057
3058         /* for version 1.0:
3059          * bytes 1-2 are "panel type", including bits on whether Colour/mono, single/dual link, and type (TFT etc.)
3060          * bytes 3-6 are bits per colour in RGBX
3061          *  9-10 is HActive
3062          * 11-12 is HDispEnd
3063          * 13-14 is HValid Start
3064          * 15-16 is HValid End
3065          * bytes 38-39 relate to spread spectrum settings
3066          * bytes 40-43 are something to do with PWM */
3067
3068         mode->status = MODE_OK;
3069         mode->type = M_T_DRIVER | M_T_PREFERRED;
3070         xf86SetModeDefaultName(mode);
3071
3072 //      if (XF86_CRTC_CONFIG_PTR(pScrn)->debug_modes) {
3073                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
3074                            "Found flat panel mode in BIOS tables:\n");
3075                 xf86PrintModeline(pScrn->scrnIndex, mode);
3076 //      }
3077
3078         bios->fp.native_mode = mode;
3079 }
3080
3081 void parse_lvds_manufacturer_table(ScrnInfoPtr pScrn, bios_t *bios, int pxclk)
3082 {
3083         /* The LVDS table header is (mostly) described in
3084          * parse_lvds_manufacturer_table_header(): the BIT header additionally
3085          * contains the dual-link transition pxclk (in 10s kHz), at byte 5 - if
3086          * straps are not being used for the panel, this specifies the frequency
3087          * at which modes should be set up in the dual link style.
3088          *
3089          * Following the header, the BMP (ver 0xa) table has several records,
3090          * indexed by a seperate xlat table, indexed in turn by the fp strap in
3091          * EXTDEV_BOOT. Each record had a config byte, followed by 6 script
3092          * numbers for use by INIT_SUB which controlled panel init and power,
3093          * and finally a dword of ms to sleep between power off and on
3094          * operations.
3095          *
3096          * In the BIT versions, the table following the header serves as an
3097          * integrated config and xlat table: the records in the table are
3098          * indexed by the FP strap nibble in EXTDEV_BOOT, and each record has
3099          * two bytes - the first as a config byte, the second for indexing the
3100          * fp mode table pointed to by the BIT 'D' table
3101          *
3102          * Due to the stage at which DDC is used in X's DDX design, the EDID res
3103          * for a panel isn't known at init, so the tests against the pixel clock
3104          * in the EDID case for selection of the correct table entry and setting
3105          * of the dual link flag cannot be done until later - this function may
3106          * be called at runtime with a non-zero pxclk argument to perform these
3107          * tests.
3108          */
3109
3110         unsigned int lvdsmanufacturerindex = 0;
3111         struct lvdstableheader lth;
3112         uint16_t lvdsofs;
3113
3114         parse_lvds_manufacturer_table_header(pScrn, bios, &lth);
3115
3116         switch (lth.lvds_ver) {
3117         case 0:         /* header parsing failed */
3118                 return;
3119         case 0x0a:      /* pre NV40 */
3120                 lvdsmanufacturerindex = bios->data[bios->fp.fpxlatemanufacturertableptr + (bios->fp.strapping & 0xf)];
3121
3122                 /* we're done if this isn't the EDID panel case */
3123                 if (pxclk == 0 || (bios->fp.strapping & 0xf) != 0xf)
3124                         break;
3125
3126                 /* change in behaviour guessed at nv30; see datapoints below */
3127                 if (bios->chip_version < 0x30) {
3128                         /* nv17 behaviour */
3129                         lvdsmanufacturerindex = bios->fp.if_is_24bit ? 2 : 0;
3130                         if (pxclk >= bios->fp.duallink_transition_clk)
3131                                 lvdsmanufacturerindex++;
3132                 } else {
3133                         /* nv31, nv34 behaviour */
3134                         lvdsmanufacturerindex = 0;
3135                         if (pxclk >= bios->fp.duallink_transition_clk)
3136                                 lvdsmanufacturerindex = 2;
3137                         if (pxclk >= 140000)
3138                                 lvdsmanufacturerindex = 3;
3139                 }
3140
3141                 /* nvidia set the high nibble of (cr57=f, cr58) to
3142                  * lvdsmanufacturerindex in this case; we don't */
3143                 break;
3144         case 0x30:      /* NV4x */
3145                 lvdsmanufacturerindex = bios->fp.strapping & 0xf;
3146                 break;
3147         case 0x40:      /* G80/G90 */
3148                 lvdsmanufacturerindex = bios->fp.strapping & 0xf;
3149                 break;
3150         default:
3151                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3152                            "LVDS table revision not currently supported\n");
3153                 return;
3154         }
3155
3156         lvdsofs = bios->fp.xlated_entry = bios->fp.lvdsmanufacturerpointer + lth.headerlen + lth.recordlen * lvdsmanufacturerindex;
3157         switch (lth.lvds_ver) {
3158         case 0x0a:
3159                 bios->fp.power_off_for_reset = bios->data[lvdsofs] & 1;
3160                 bios->fp.reset_after_pclk_change = bios->data[lvdsofs] & 2;
3161                 bios->fp.dual_link = bios->data[lvdsofs] & 4;
3162                 bios->fp.link_c_increment = bios->data[lvdsofs] & 8;
3163                 bios->fp.if_is_24bit = bios->data[lvdsofs] & 16;
3164                 break;
3165         case 0x30:
3166                 /* My money would be on there being a 24 bit interface bit in this table,
3167                  * but I have no example of a laptop bios with a 24 bit panel to confirm that.
3168                  * Hence we shout loudly if any bit other than bit 0 is set (I've not even
3169                  * seen bit 1)
3170                  */
3171                 if (bios->data[lvdsofs] > 1)
3172                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3173                                    "You have a very unusual laptop display; please report it\n");
3174                 /* no sign of the "power off for reset" or "reset for panel on" bits, but it's safer to assume we should */
3175                 bios->fp.power_off_for_reset = true;
3176                 bios->fp.reset_after_pclk_change = true;
3177                 bios->fp.dual_link = bios->data[lvdsofs] & 1;
3178                 bios->fp.BITbit1 = bios->data[lvdsofs] & 2;
3179                 bios->fp.duallink_transition_clk = le16_to_cpu(*(uint16_t *)&bios->data[bios->fp.lvdsmanufacturerpointer + 5]) * 10;
3180                 break;
3181         case 0x40:
3182                 /* fairly sure, but not 100% */
3183                 bios->fp.dual_link = bios->data[lvdsofs] & 1;
3184                 bios->fp.duallink_transition_clk = le16_to_cpu(*(uint16_t *)&bios->data[bios->fp.lvdsmanufacturerpointer + 5]) * 10;
3185                 break;
3186         }
3187
3188         /* set dual_link flag for EDID case */
3189         if ((bios->fp.strapping & 0xf) == 0xf && pxclk) {
3190                 if (pxclk >= bios->fp.duallink_transition_clk)
3191                         bios->fp.dual_link = true;
3192                 else
3193                         bios->fp.dual_link = false;
3194         }
3195 }
3196
3197 void run_tmds_table(ScrnInfoPtr pScrn, struct dcb_entry *dcbent, int head, int pxclk)
3198 {
3199         /* the pxclk parameter is in kHz
3200          *
3201          * This runs the TMDS regs setting code found on BIT bios cards
3202          *
3203          * For ffs(or) == 1 use the first table, for ffs(or) == 2 and
3204          * ffs(or) == 3, use the second.
3205          */
3206
3207         NVPtr pNv = NVPTR(pScrn);
3208         bios_t *bios = &pNv->VBIOS;
3209         uint16_t clktable = 0, scriptptr;
3210         uint32_t sel_clk_binding;
3211
3212         if (dcbent->location != LOC_ON_CHIP)
3213                 return;
3214
3215         switch (ffs(dcbent->or)) {
3216         case 1:
3217                 clktable = bios->tmds.output0_script_ptr;
3218                 break;
3219         case 2:
3220         case 3:
3221                 clktable = bios->tmds.output1_script_ptr;
3222                 break;
3223         }
3224
3225         if (!clktable) {
3226                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Pixel clock comparison table not found\n");
3227                 return;
3228         }
3229
3230         scriptptr = clkcmptable(bios, clktable, pxclk);
3231
3232         if (!scriptptr) {
3233                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "TMDS output init script not found\n");
3234                 return;
3235         }
3236
3237         /* don't let script change pll->head binding */
3238         sel_clk_binding = nv32_rd(pScrn, NV_RAMDAC_SEL_CLK) & 0x50000;
3239         rundigitaloutscript(pScrn, scriptptr, dcbent, head);
3240         nv32_wr(pScrn, NV_RAMDAC_SEL_CLK, (nv32_rd(pScrn, NV_RAMDAC_SEL_CLK) & ~0x50000) | sel_clk_binding);
3241 }
3242
3243 static int get_fp_strap(ScrnInfoPtr pScrn, bios_t *bios)
3244 {
3245         /* the fp strap is normally dictated by the "User Strap" in
3246          * PEXTDEV_BOOT_0[20:16], but on BMP cards when bit 2 of the
3247          * Internal_Flags struct at 0x48 is set, the user strap gets overriden
3248          * by the PCI subsystem ID during POST, but not before the previous user
3249          * strap has been committed to CR58 for CR57=0xf on head A, which may be
3250          * read and used instead
3251          */
3252
3253         /* Now comes the G80/G90 story, i've only got one hint.
3254          * I can read back the clock freq from register 0x00616404.
3255          * So for the moment just write 0xF here.
3256          */
3257
3258         if (bios->chip_version >= 0x80)
3259                 return 0xF;
3260
3261         if (bios->major_version < 5 && bios->data[0x48] & 0x4)
3262                 return (NVReadVgaCrtc5758(NVPTR(pScrn), 0, 0xf) & 0xf);
3263
3264         return ((nv32_rd(pScrn, NV_PEXTDEV_BOOT_0) >> 16) & 0xf);
3265 }
3266
3267 static void parse_bios_version(ScrnInfoPtr pScrn, bios_t *bios, uint16_t offset)
3268 {
3269         /* offset + 0  (8 bits): Micro version
3270          * offset + 1  (8 bits): Minor version
3271          * offset + 2  (8 bits): Chip version
3272          * offset + 3  (8 bits): Major version
3273          */
3274
3275         bios->major_version = bios->data[offset + 3];
3276         bios->chip_version = bios->data[offset + 2];
3277         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Bios version %02x.%02x.%02x.%02x\n",
3278                    bios->data[offset + 3], bios->data[offset + 2],
3279                    bios->data[offset + 1], bios->data[offset]);
3280 }
3281
3282 bool get_pll_limits(ScrnInfoPtr pScrn, uint32_t limit_match, struct pll_lims *pll_lim)
3283 {
3284         /* PLL limits table
3285          *
3286          * Version 0x10: NV31
3287          * One byte header (version), one record of 24 bytes
3288          * Version 0x11: NV36 - Not implemented
3289          * Seems to have same record style as 0x10, but 3 records rather than 1
3290          * Version 0x20: Found on Geforce 6 cards
3291          * Trivial 4 byte BIT header. 31 (0x1f) byte record length
3292          * Version 0x21: Found on Geforce 7, 8 and some Geforce 6 cards
3293          * 5 byte header, fifth byte of unknown purpose. 35 (0x23) byte record
3294          * length in general, some (integrated) have an extra configuration byte
3295          */
3296
3297         NVPtr pNv = NVPTR(pScrn);
3298         bios_t *bios = &pNv->VBIOS;
3299         uint8_t pll_lim_ver = 0, headerlen = 0, recordlen = 0, entries = 0;
3300         int pllindex = 0;
3301         uint32_t crystal_strap_mask, crystal_straps;
3302
3303         if (!bios->pll_limit_tbl_ptr) {
3304                 if (bios->chip_version >= 0x40 || bios->chip_version == 0x31 || bios->chip_version == 0x36) {
3305                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Pointer to PLL limits table invalid\n");
3306                         return false;
3307                 }
3308         } else
3309                 pll_lim_ver = bios->data[bios->pll_limit_tbl_ptr];
3310
3311         crystal_strap_mask = 1 << 6;
3312         /* open coded pNv->twoHeads test */
3313         if (bios->chip_version > 0x10 && bios->chip_version != 0x15 &&
3314             bios->chip_version != 0x1a && bios->chip_version != 0x20)
3315                 crystal_strap_mask |= 1 << 22;
3316         crystal_straps = nvReadEXTDEV(pNv, NV_PEXTDEV_BOOT_0) & crystal_strap_mask;
3317
3318         switch (pll_lim_ver) {
3319         /* we use version 0 to indicate a pre limit table bios (single stage pll)
3320          * and load the hard coded limits instead */
3321         case 0:
3322                 break;
3323         case 0x10:
3324         case 0x11: /* strictly v0x11 has 3 entries, but the last two don't seem to get used */
3325                 headerlen = 1;
3326                 recordlen = 0x18;
3327                 entries = 1;
3328                 pllindex = 0;
3329                 break;
3330         case 0x20:
3331         case 0x21:
3332                 headerlen = bios->data[bios->pll_limit_tbl_ptr + 1];
3333                 recordlen = bios->data[bios->pll_limit_tbl_ptr + 2];
3334                 entries = bios->data[bios->pll_limit_tbl_ptr + 3];
3335                 break;
3336         default:
3337                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3338                            "PLL limits table revision 0x%X not currently supported\n", pll_lim_ver);
3339                 return false;
3340         }
3341
3342         /* initialize all members to zero */
3343         memset(pll_lim, 0, sizeof(struct pll_lims));
3344
3345         if (pll_lim_ver == 0x10 || pll_lim_ver == 0x11) {
3346                 uint16_t plloffs = bios->pll_limit_tbl_ptr + headerlen + recordlen * pllindex;
3347
3348                 pll_lim->vco1.minfreq = le32_to_cpu(*((uint32_t *)(&bios->data[plloffs])));
3349                 pll_lim->vco1.maxfreq = le32_to_cpu(*((uint32_t *)(&bios->data[plloffs + 4])));
3350                 pll_lim->vco2.minfreq = le32_to_cpu(*((uint32_t *)(&bios->data[plloffs + 8])));
3351                 pll_lim->vco2.maxfreq = le32_to_cpu(*((uint32_t *)(&bios->data[plloffs + 12])));
3352                 pll_lim->vco1.min_inputfreq = le32_to_cpu(*((uint32_t *)(&bios->data[plloffs + 16])));
3353                 pll_lim->vco2.min_inputfreq = le32_to_cpu(*((uint32_t *)(&bios->data[plloffs + 20])));
3354                 pll_lim->vco1.max_inputfreq = pll_lim->vco2.max_inputfreq = INT_MAX;
3355
3356                 /* these values taken from nv30/31/36 */
3357                 pll_lim->vco1.min_n = 0x1;
3358                 if (bios->chip_version == 0x36)
3359                         pll_lim->vco1.min_n = 0x5;
3360                 pll_lim->vco1.max_n = 0xff;
3361                 pll_lim->vco1.min_m = 0x1;
3362                 pll_lim->vco1.max_m = 0xd;
3363                 pll_lim->vco2.min_n = 0x4;
3364                 /* on nv30, 31, 36 (i.e. all cards with two stage PLLs with this
3365                  * table version (apart from nv35)), N2 is compared to
3366                  * maxN2 (0x46) and 10 * maxM2 (0x4), so set maxN2 to 0x28 and
3367                  * save a comparison
3368                  */
3369                 pll_lim->vco2.max_n = 0x28;
3370                 if (bios->chip_version == 0x30 || bios->chip_version == 0x35)
3371                        /* only 5 bits available for N2 on nv30/35 */
3372                         pll_lim->vco2.max_n = 0x1f;
3373                 pll_lim->vco2.min_m = 0x1;
3374                 pll_lim->vco2.max_m = 0x4;
3375         } else if (pll_lim_ver) {       /* ver 0x20, 0x21 */
3376                 uint16_t plloffs = bios->pll_limit_tbl_ptr + headerlen;
3377                 uint32_t reg = 0; /* default match */
3378                 int i;
3379
3380                 /* first entry is default match, if nothing better. warn if reg field nonzero */
3381                 if (le32_to_cpu(*((uint32_t *)&bios->data[plloffs])))
3382                         xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3383                                    "Default PLL limit entry has non-zero register field\n");
3384
3385                 if (limit_match > MAX_PLL_TYPES)
3386                         /* we've been passed a reg as the match */
3387                         reg = limit_match;
3388                 else /* limit match is a pll type */
3389                         for (i = 1; i < entries && !reg; i++) {
3390                                 uint32_t cmpreg = le32_to_cpu(*((uint32_t *)(&bios->data[plloffs + recordlen * i])));
3391
3392                                 if (limit_match == NVPLL && (cmpreg == NV_RAMDAC_NVPLL || cmpreg == 0x4000))
3393                                         reg = cmpreg;
3394                                 if (limit_match == MPLL && (cmpreg == NV_RAMDAC_MPLL || cmpreg == 0x4020))
3395                                         reg = cmpreg;
3396                                 if (limit_match == VPLL1 && (cmpreg == NV_RAMDAC_VPLL || cmpreg == 0x4010))
3397                                         reg = cmpreg;
3398                                 if (limit_match == VPLL2 && (cmpreg == NV_RAMDAC_VPLL2 || cmpreg == 0x4018))
3399                                         reg = cmpreg;
3400                         }
3401
3402                 for (i = 1; i < entries; i++)
3403                         if (le32_to_cpu(*((uint32_t *)&bios->data[plloffs + recordlen * i])) == reg) {
3404                                 pllindex = i;
3405                                 break;
3406                         }
3407
3408                 plloffs += recordlen * pllindex;
3409
3410                 BIOSLOG(pScrn, "Loading PLL limits for reg 0x%08x\n", pllindex ? reg : 0);
3411
3412                 /* frequencies are stored in tables in MHz, kHz are more useful, so we convert */
3413
3414                 /* What output frequencies can each VCO generate? */
3415                 pll_lim->vco1.minfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 4]))) * 1000;
3416                 pll_lim->vco1.maxfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 6]))) * 1000;
3417                 pll_lim->vco2.minfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 8]))) * 1000;
3418                 pll_lim->vco2.maxfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 10]))) * 1000;
3419
3420                 /* What input frequencies do they accept (past the m-divider)? */
3421                 pll_lim->vco1.min_inputfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 12]))) * 1000;
3422                 pll_lim->vco2.min_inputfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 14]))) * 1000;
3423                 pll_lim->vco1.max_inputfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 16]))) * 1000;
3424                 pll_lim->vco2.max_inputfreq = le16_to_cpu(*((uint16_t *)(&bios->data[plloffs + 18]))) * 1000;
3425
3426                 /* What values are accepted as multiplier and divider? */
3427                 pll_lim->vco1.min_n = bios->data[plloffs + 20];
3428                 pll_lim->vco1.max_n = bios->data[plloffs + 21];
3429                 pll_lim->vco1.min_m = bios->data[plloffs + 22];
3430                 pll_lim->vco1.max_m = bios->data[plloffs + 23];
3431                 pll_lim->vco2.min_n = bios->data[plloffs + 24];
3432                 pll_lim->vco2.max_n = bios->data[plloffs + 25];
3433                 pll_lim->vco2.min_m = bios->data[plloffs + 26];
3434                 pll_lim->vco2.max_m = bios->data[plloffs + 27];
3435
3436                 pll_lim->unk1c = bios->data[plloffs + 28];
3437                 pll_lim->max_log2p_bias = bios->data[plloffs + 29];
3438                 pll_lim->log2p_bias = bios->data[plloffs + 30];
3439
3440                 if (recordlen > 0x22)
3441                         pll_lim->refclk = le32_to_cpu(*((uint32_t *)&bios->data[plloffs + 31]));
3442
3443                 if (recordlen > 0x23)
3444                         if (bios->data[plloffs + 35])
3445                                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3446                                            "Bits set in PLL configuration byte (%x)\n", bios->data[plloffs + 35]);
3447
3448                 /* C51 special not seen elsewhere */
3449                 if (bios->chip_version == 0x51 && !pll_lim->refclk) {
3450                         uint32_t sel_clk = nv32_rd(pScrn, NV_RAMDAC_SEL_CLK);
3451
3452                         if (((limit_match == NV_RAMDAC_VPLL || limit_match == VPLL1) && sel_clk & 0x20) ||
3453                             ((limit_match == NV_RAMDAC_VPLL2 || limit_match == VPLL2) && sel_clk & 0x80)) {
3454                                 if (nv_idx_port_rd(pScrn, NV_CIO_CRX__COLOR, NV_CIO_CRE_CHIP_ID_INDEX) < 0xa3)
3455                                         pll_lim->refclk = 200000;
3456                                 else
3457                                         pll_lim->refclk = 25000;
3458                         }
3459                 }
3460         }
3461
3462         /* By now any valid limit table ought to have set a max frequency for
3463          * vco1, so if it's zero it's either a pre limit table bios, or one
3464          * with an empty limit table (seen on nv18)
3465          */
3466         if (!pll_lim->vco1.maxfreq) {
3467                 pll_lim->vco1.minfreq = bios->fminvco;
3468                 pll_lim->vco1.maxfreq = bios->fmaxvco;
3469                 pll_lim->vco1.min_inputfreq = 0;
3470                 pll_lim->vco1.max_inputfreq = INT_MAX;
3471                 pll_lim->vco1.min_n = 0x1;
3472                 pll_lim->vco1.max_n = 0xff;
3473                 pll_lim->vco1.min_m = 0x1;
3474                 if (crystal_straps == 0) {
3475                         /* nv05 does this, nv11 doesn't, nv10 unknown */
3476                         if (bios->chip_version < 0x11)
3477                                 pll_lim->vco1.min_m = 0x7;
3478                         pll_lim->vco1.max_m = 0xd;
3479                 } else {
3480                         if (bios->chip_version < 0x11)
3481                                 pll_lim->vco1.min_m = 0x8;
3482                         pll_lim->vco1.max_m = 0xe;
3483                 }
3484         }
3485
3486         if (!pll_lim->refclk)
3487                 switch (crystal_straps) {
3488                 case 0:
3489                         pll_lim->refclk = 13500;
3490                         break;
3491                 case (1 << 6):
3492                         pll_lim->refclk = 14318;
3493                         break;
3494                 case (1 << 22):
3495                         pll_lim->refclk = 27000;
3496                         break;
3497                 case (1 << 22 | 1 << 6):
3498                         pll_lim->refclk = 25000;
3499                         break;
3500                 }
3501
3502 #if 0 /* for easy debugging */
3503         ErrorF("pll.vco1.minfreq: %d\n", pll_lim->vco1.minfreq);
3504         ErrorF("pll.vco1.maxfreq: %d\n", pll_lim->vco1.maxfreq);
3505         ErrorF("pll.vco2.minfreq: %d\n", pll_lim->vco2.minfreq);
3506         ErrorF("pll.vco2.maxfreq: %d\n", pll_lim->vco2.maxfreq);
3507
3508         ErrorF("pll.vco1.min_inputfreq: %d\n", pll_lim->vco1.min_inputfreq);
3509         ErrorF("pll.vco1.max_inputfreq: %d\n", pll_lim->vco1.max_inputfreq);
3510         ErrorF("pll.vco2.min_inputfreq: %d\n", pll_lim->vco2.min_inputfreq);
3511         ErrorF("pll.vco2.max_inputfreq: %d\n", pll_lim->vco2.max_inputfreq);
3512
3513         ErrorF("pll.vco1.min_n: %d\n", pll_lim->vco1.min_n);
3514         ErrorF("pll.vco1.max_n: %d\n", pll_lim->vco1.max_n);
3515         ErrorF("pll.vco1.min_m: %d\n", pll_lim->vco1.min_m);
3516         ErrorF("pll.vco1.max_m: %d\n", pll_lim->vco1.max_m);
3517         ErrorF("pll.vco2.min_n: %d\n", pll_lim->vco2.min_n);
3518         ErrorF("pll.vco2.max_n: %d\n", pll_lim->vco2.max_n);
3519         ErrorF("pll.vco2.min_m: %d\n", pll_lim->vco2.min_m);
3520         ErrorF("pll.vco2.max_m: %d\n", pll_lim->vco2.max_m);
3521
3522         ErrorF("pll.unk1c: %d\n", pll_lim->unk1c);
3523         ErrorF("pll.max_log2p_bias: %d\n", pll_lim->max_log2p_bias);
3524         ErrorF("pll.log2p_bias: %d\n", pll_lim->log2p_bias);
3525
3526         ErrorF("pll.refclk: %d\n", pll_lim->refclk);
3527 #endif
3528
3529         return true;
3530 }
3531
3532 static int parse_bit_C_tbl_entry(ScrnInfoPtr pScrn, bios_t *bios, bit_entry_t *bitentry)
3533 {
3534         /* offset + 8  (16 bits): PLL limits table pointer
3535          *
3536          * There's more in here, but that's unknown.
3537          */
3538
3539         if (bitentry->length < 10) {
3540                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Do not understand BIT C table\n");
3541                 return 0;
3542         }
3543
3544         bios->pll_limit_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 8])));
3545
3546         return 1;
3547 }
3548
3549 static int parse_bit_display_tbl_entry(ScrnInfoPtr pScrn, bios_t *bios, bit_entry_t *bitentry)
3550 {
3551         /* Parses the flat panel table segment that the bit entry points to.
3552          * Starting at bitentry->offset:
3553          *
3554          * offset + 0  (16 bits): ??? table pointer - seems to have 18 byte records beginning with a freq
3555          * offset + 2  (16 bits): mode table pointer
3556          */
3557
3558         struct fppointers fpp = { 0 };
3559
3560         if (bitentry->length != 4) {
3561                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Do not understand BIT display table\n");
3562                 return 0;
3563         }
3564
3565         fpp.fptablepointer = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 2])));
3566
3567         parse_fp_mode_table(pScrn, bios, &fpp);
3568
3569         return 1;
3570 }
3571
3572 static unsigned int parse_bit_init_tbl_entry(ScrnInfoPtr pScrn, bios_t *bios, bit_entry_t *bitentry)
3573 {
3574         /* Parses the init table segment that the bit entry points to.
3575          * Starting at bitentry->offset: 
3576          * 
3577          * offset + 0  (16 bits): init script tables pointer
3578          * offset + 2  (16 bits): macro index table pointer
3579          * offset + 4  (16 bits): macro table pointer
3580          * offset + 6  (16 bits): condition table pointer
3581          * offset + 8  (16 bits): io condition table pointer
3582          * offset + 10 (16 bits): io flag condition table pointer
3583          * offset + 12 (16 bits): init function table pointer
3584          *
3585          */
3586
3587         if (bitentry->length < 14) {
3588                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Do not understand init table\n");
3589                 return 0;
3590         }
3591
3592         bios->init_script_tbls_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset])));
3593         bios->macro_index_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 2])));
3594         bios->macro_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 4])));
3595         bios->condition_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 6])));
3596         bios->io_condition_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 8])));
3597         bios->io_flag_condition_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 10])));
3598         bios->init_function_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 12])));
3599
3600         return 1;
3601 }
3602
3603 static int parse_bit_i_tbl_entry(ScrnInfoPtr pScrn, bios_t *bios, bit_entry_t *bitentry)
3604 {
3605         /* BIT 'i' (info?) table
3606          *
3607          * offset + 0  (32 bits): BIOS version dword (as in B table)
3608          * offset + 5  (8  bits): BIOS feature byte (same as for BMP?)
3609          * offset + 13 (16 bits): pointer to table containing DAC load detection comparison values
3610          *
3611          * There's other things in the table, purpose unknown
3612          */
3613
3614         uint16_t daccmpoffset;
3615         uint8_t dacversion, dacheaderlen;
3616
3617         if (bitentry->length < 6) {
3618                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
3619                            "BIT i table not long enough for BIOS version and feature byte\n");
3620                 return 0;
3621         }
3622
3623         parse_bios_version(pScrn, bios, bitentry->offset);
3624
3625         /* bit 4 seems to indicate a mobile bios, other bits possibly as for BMP feature byte */
3626         bios->feature_byte = bios->data[bitentry->offset + 5];
3627
3628         if (bitentry->length < 15) {
3629                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3630                            "BIT i table not long enough for DAC load detection comparison table\n");
3631                 return 0;
3632         }
3633
3634         daccmpoffset = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 13])));
3635
3636         /* doesn't exist on g80 */
3637         if (!daccmpoffset)
3638                 return 1;
3639
3640         /* The first value in the table, following the header, is the comparison value
3641          * Purpose of subsequent values unknown -- TV load detection?
3642          */
3643
3644         dacversion = bios->data[daccmpoffset];
3645         dacheaderlen = bios->data[daccmpoffset + 1];
3646
3647         if (dacversion != 0x00 && dacversion != 0x10) {
3648                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
3649                            "DAC load detection comparison table version %d.%d not known\n",
3650                            dacversion >> 4, dacversion & 0xf);
3651                 return 0;
3652         }
3653
3654         bios->dactestval = le32_to_cpu(*((uint32_t *)(&bios->data[daccmpoffset + dacheaderlen])));
3655
3656         return 1;
3657 }
3658
3659 static int parse_bit_lvds_tbl_entry(ScrnInfoPtr pScrn, bios_t *bios, bit_entry_t *bitentry)
3660 {
3661         /* Parses the LVDS table segment that the bit entry points to.
3662          * Starting at bitentry->offset:
3663          *
3664          * offset + 0  (16 bits): LVDS strap xlate table pointer
3665          */
3666
3667         if (bitentry->length != 2) {
3668                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Do not understand BIT LVDS table\n");
3669                 return 0;
3670         }
3671
3672         /* no idea if it's still called the LVDS manufacturer table, but the concept's close enough */
3673         bios->fp.lvdsmanufacturerpointer = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset])));
3674         bios->fp.strapping = get_fp_strap(pScrn, bios);
3675
3676         parse_lvds_manufacturer_table(pScrn, bios, 0);
3677
3678         return 1;
3679 }
3680
3681 static int parse_bit_M_tbl_entry(ScrnInfoPtr pScrn, bios_t *bios, bit_entry_t *bitentry)
3682 {
3683         /* offset + 2  (8  bits): number of options in an INIT_RAM_RESTRICT_ZM_REG_GROUP opcode option set
3684          * offset + 3  (16 bits): pointer to strap xlate table for RAM restrict option selection
3685          *
3686          * There's a bunch of bits in this table other than the RAM restrict
3687          * stuff that we don't use - their use currently unknown
3688          */
3689
3690         int i;
3691
3692         /* Older bios versions don't have a sufficiently long table for what we want */
3693         if (bitentry->length < 0x5)
3694                 return 1;
3695
3696         /* set up multiplier for INIT_RAM_RESTRICT_ZM_REG_GROUP */
3697         for (i = 0; itbl_entry[i].name && (itbl_entry[i].id != 0x8f); i++)
3698                 ;
3699         itbl_entry[i].length_multiplier = bios->data[bitentry->offset + 2] * 4;
3700         init_ram_restrict_zm_reg_group_blocklen = itbl_entry[i].length_multiplier;
3701
3702         bios->ram_restrict_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset + 3])));
3703
3704         return 1;
3705 }
3706
3707 static int parse_bit_tmds_tbl_entry(ScrnInfoPtr pScrn, bios_t *bios, bit_entry_t *bitentry)
3708 {
3709         /* Parses the pointer to the TMDS table
3710          *
3711          * Starting at bitentry->offset:
3712          *
3713          * offset + 0  (16 bits): TMDS table pointer
3714          *
3715          * The TMDS table is typically found just before the DCB table, with a
3716          * characteristic signature of 0x11,0x13 (1.1 being version, 0x13 being
3717          * length?)
3718          *
3719          * At offset +7 is a pointer to a script, which I don't know how to run yet
3720          * At offset +9 is a pointer to another script, likewise
3721          * Offset +11 has a pointer to a table where the first word is a pxclk
3722          * frequency and the second word a pointer to a script, which should be
3723          * run if the comparison pxclk frequency is less than the pxclk desired.
3724          * This repeats for decreasing comparison frequencies
3725          * Offset +13 has a pointer to a similar table
3726          * The selection of table (and possibly +7/+9 script) is dictated by
3727          * "or" from the DCB.
3728          */
3729
3730         uint16_t tmdstableptr, script1, script2;
3731
3732         if (bitentry->length != 2) {
3733                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Do not understand BIT TMDS table\n");
3734                 return 0;
3735         }
3736
3737         tmdstableptr = le16_to_cpu(*((uint16_t *)(&bios->data[bitentry->offset])));
3738
3739         if (tmdstableptr == 0x0) {
3740                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Pointer to TMDS table invalid\n");
3741                 return 0;
3742         }
3743
3744         /* nv50+ has v2.0, but we don't parse it atm */
3745         if (bios->data[tmdstableptr] != 0x11) {
3746                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "TMDS table revision %d.%d not currently supported\n",
3747                            bios->data[tmdstableptr] >> 4, bios->data[tmdstableptr] & 0xf);
3748                 return 0;
3749         }
3750
3751         /* These two scripts are odd: they don't seem to get run even when they are not stubbed */
3752         script1 = le16_to_cpu(*((uint16_t *)&bios->data[tmdstableptr + 7]));
3753         script2 = le16_to_cpu(*((uint16_t *)&bios->data[tmdstableptr + 9]));
3754         if (bios->data[script1] != 'q' || bios->data[script2] != 'q')
3755                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING, "TMDS table script pointers not stubbed\n");
3756
3757         bios->tmds.output0_script_ptr = le16_to_cpu(*((uint16_t *)&bios->data[tmdstableptr + 11]));
3758         bios->tmds.output1_script_ptr = le16_to_cpu(*((uint16_t *)&bios->data[tmdstableptr + 13]));
3759
3760         return 1;
3761 }
3762
3763 static void parse_bit_structure(ScrnInfoPtr pScrn, bios_t *bios, const uint16_t bitoffset)
3764 {
3765         int entries = bios->data[bitoffset + 4];
3766         /* parse i first, I next (which needs C & M before it), and L before D */
3767         char parseorder[] = "iCMILDT";
3768         bit_entry_t bitentry;
3769         int i, j, offset;
3770
3771         for (i = 0; i < sizeof(parseorder); i++) {
3772                 for (j = 0, offset = bitoffset + 6; j < entries; j++, offset += 6) {
3773                         bitentry.id[0] = bios->data[offset];
3774                         bitentry.id[1] = bios->data[offset + 1];
3775                         bitentry.length = le16_to_cpu(*((uint16_t *)&bios->data[offset + 2]));
3776                         bitentry.offset = le16_to_cpu(*((uint16_t *)&bios->data[offset + 4]));
3777
3778                         if (bitentry.id[0] != parseorder[i])
3779                                 continue;
3780
3781                         switch (bitentry.id[0]) {
3782                         case 'C':
3783                                 parse_bit_C_tbl_entry(pScrn, bios, &bitentry);
3784                                 break;
3785                         case 'D':
3786                                 parse_bit_display_tbl_entry(pScrn, bios, &bitentry);
3787                                 break;
3788                         case 'I':
3789                                 parse_bit_init_tbl_entry(pScrn, bios, &bitentry);
3790                                 parse_init_tables(pScrn, bios);
3791                                 break;
3792                         case 'i': /* info? */
3793                                 parse_bit_i_tbl_entry(pScrn, bios, &bitentry);
3794                                 break;
3795                         case 'L':
3796                                 if (bios->feature_byte & FEATURE_MOBILE)
3797                                         parse_bit_lvds_tbl_entry(pScrn, bios, &bitentry);
3798                                 break;
3799                         case 'M': /* memory? */
3800                                 parse_bit_M_tbl_entry(pScrn, bios, &bitentry);
3801                                 break;
3802                         case 'T':
3803                                 parse_bit_tmds_tbl_entry(pScrn, bios, &bitentry);
3804                                 break;
3805                         }
3806                 }
3807         }
3808 }
3809
3810 static void parse_bmp_structure(ScrnInfoPtr pScrn, bios_t *bios, unsigned int offset)
3811 {
3812         /* Parse the BMP structure for useful things
3813          *
3814          * offset +   5: BMP major version
3815          * offset +   6: BMP minor version
3816          * offset +  10: BCD encoded BIOS version
3817          *
3818          * offset +  18: init script table pointer (for bios versions < 5.10h)
3819          * offset +  20: extra init script table pointer (for bios versions < 5.10h)
3820          *
3821          * offset +  24: memory init table pointer (used on early bios versions)
3822          * offset +  26: SDR memory sequencing setup data table
3823          * offset +  28: DDR memory sequencing setup data table
3824          *
3825          * offset +  54: index of I2C CRTC pair to use for CRT output
3826          * offset +  55: index of I2C CRTC pair to use for TV output
3827          * offset +  56: index of I2C CRTC pair to use for flat panel output
3828          * offset +  58: write CRTC index for I2C pair 0
3829          * offset +  59: read CRTC index for I2C pair 0
3830          * offset +  60: write CRTC index for I2C pair 1
3831          * offset +  61: read CRTC index for I2C pair 1
3832          *
3833          * offset +  67: maximum internal PLL frequency (single stage PLL)
3834          * offset +  71: minimum internal PLL frequency (single stage PLL)
3835          *
3836          * offset +  75: script table pointers, as for parse_bit_init_tbl_entry
3837          *
3838          * offset +  89: TMDS single link output A table pointer
3839          * offset +  91: TMDS single link output B table pointer
3840          * offset + 105: flat panel timings table pointer
3841          * offset + 107: flat panel strapping translation table pointer
3842          * offset + 117: LVDS manufacturer panel config table pointer
3843          * offset + 119: LVDS manufacturer strapping translation table pointer
3844          *
3845          * offset + 142: PLL limits table pointer
3846          */
3847
3848         NVPtr pNv = NVPTR(pScrn);
3849         uint8_t bmp_version_major, bmp_version_minor;
3850         uint16_t bmplength;
3851         struct fppointers fpp = { 0 };
3852         uint16_t legacy_scripts_offset, legacy_i2c_offset;
3853
3854         /* load needed defaults in case we can't parse this info */
3855         pNv->dcb_table.i2c_write[0] = NV_CIO_CRE_DDC_WR__INDEX;
3856         pNv->dcb_table.i2c_read[0] = NV_CIO_CRE_DDC_STATUS__INDEX;
3857         pNv->dcb_table.i2c_write[1] = NV_CIO_CRE_DDC0_WR__INDEX;
3858         pNv->dcb_table.i2c_read[1] = NV_CIO_CRE_DDC0_STATUS__INDEX;
3859         bios->digital_min_front_porch = 0x4b;
3860         bios->fmaxvco = 256000;
3861         bios->fminvco = 128000;
3862         bios->fp.duallink_transition_clk = 90000;
3863
3864         bmp_version_major = bios->data[offset + 5];
3865         bmp_version_minor = bios->data[offset + 6];
3866
3867         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "BMP version %d.%d\n",
3868                    bmp_version_major, bmp_version_minor);
3869
3870         /* Make sure that 0x36 is blank and can't be mistaken for a DCB pointer on early versions */
3871         if (bmp_version_major < 5)
3872                 *(uint16_t *)&bios->data[0x36] = 0;
3873
3874         /* Seems that the minor version was 1 for all major versions prior to 5 */
3875         /* Version 6 could theoretically exist, but I suspect BIT happened instead */
3876         if ((bmp_version_major < 5 && bmp_version_minor != 1) || bmp_version_major > 5) {
3877                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "You have an unsupported BMP version. Please send in your bios\n");
3878                 return;
3879         }
3880
3881         if (bmp_version_major == 0) /* nothing that's currently useful in this version */
3882                 return;
3883         else if (bmp_version_major == 1)
3884                 bmplength = 44; /* exact for 1.01 */
3885         else if (bmp_version_major == 2)
3886                 bmplength = 48; /* exact for 2.01 */
3887         else if (bmp_version_major == 3)
3888                 bmplength = 54; /* guessed - mem init tables added in this version */
3889         else if (bmp_version_major == 4 || bmp_version_minor < 0x1) /* don't know if 5.0 exists... */
3890                 bmplength = 62; /* guessed - BMP I2C indices added in version 4*/
3891         else if (bmp_version_minor < 0x6)
3892                 bmplength = 67; /* exact for 5.01 */
3893         else if (bmp_version_minor < 0x10)
3894                 bmplength = 75; /* exact for 5.06 */
3895         else if (bmp_version_minor == 0x10)
3896                 bmplength = 89; /* exact for 5.10h */
3897         else if (bmp_version_minor < 0x14)
3898                 bmplength = 118; /* exact for 5.11h */
3899         else if (bmp_version_minor < 0x24) /* not sure of version where pll limits came in;
3900                                             * certainly exist by 0x24 though */
3901                 /* length not exact: this is long enough to get lvds members */
3902                 bmplength = 123;
3903         else if (bmp_version_minor < 0x27)
3904                 /* length not exact: this is long enough to get pll limit member */
3905                 bmplength = 144;
3906         else
3907                 /* length not exact: this is long enough to get dual link transition clock */
3908                 bmplength = 158;
3909
3910         /* checksum */
3911         if (nv_cksum(bios->data + offset, 8)) {
3912                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Bad BMP checksum\n");
3913                 return;
3914         }
3915
3916         /* bit 4 seems to indicate a mobile bios, bit 5 that the flat panel
3917          * tables are present, and bit 6 a tv bios */
3918         bios->feature_byte = bios->data[offset + 9];
3919
3920         parse_bios_version(pScrn, bios, offset + 10);
3921
3922         legacy_scripts_offset = offset + 18;
3923         if (bmp_version_major < 2)
3924                 legacy_scripts_offset -= 4;
3925         bios->init_script_tbls_ptr = le16_to_cpu(*(uint16_t *)&bios->data[legacy_scripts_offset]);
3926         bios->extra_init_script_tbl_ptr = le16_to_cpu(*(uint16_t *)&bios->data[legacy_scripts_offset + 2]);
3927
3928         if (bmp_version_major > 2) {    /* appears in BMP 3 */
3929                 bios->legacy.mem_init_tbl_ptr = le16_to_cpu(*(uint16_t *)&bios->data[offset + 24]);
3930                 bios->legacy.sdr_seq_tbl_ptr = le16_to_cpu(*(uint16_t *)&bios->data[offset + 26]);
3931                 bios->legacy.ddr_seq_tbl_ptr = le16_to_cpu(*(uint16_t *)&bios->data[offset + 28]);
3932         }
3933
3934         legacy_i2c_offset = 0x48;       /* BMP version 2 & 3 */
3935         if (bmplength > 61)
3936                 legacy_i2c_offset = offset + 54;
3937         bios->legacy.i2c_indices.crt = bios->data[legacy_i2c_offset];
3938         bios->legacy.i2c_indices.tv = bios->data[legacy_i2c_offset + 1];
3939         bios->legacy.i2c_indices.panel = bios->data[legacy_i2c_offset + 2];
3940         pNv->dcb_table.i2c_write[0] = bios->data[legacy_i2c_offset + 4];
3941         pNv->dcb_table.i2c_read[0] = bios->data[legacy_i2c_offset + 5];
3942         pNv->dcb_table.i2c_write[1] = bios->data[legacy_i2c_offset + 6];
3943         pNv->dcb_table.i2c_read[1] = bios->data[legacy_i2c_offset + 7];
3944
3945         if (bmplength > 74) {
3946                 bios->fmaxvco = le32_to_cpu(*((uint32_t *)&bios->data[offset + 67]));
3947                 bios->fminvco = le32_to_cpu(*((uint32_t *)&bios->data[offset + 71]));
3948         }
3949         if (bmplength > 88) {
3950                 bit_entry_t initbitentry;
3951                 initbitentry.length = 14;
3952                 initbitentry.offset = offset + 75;
3953                 parse_bit_init_tbl_entry(pScrn, bios, &initbitentry);
3954         }
3955         if (bmplength > 94) {
3956                 bios->tmds.output0_script_ptr = le16_to_cpu(*((uint16_t *)&bios->data[offset + 89]));
3957                 bios->tmds.output1_script_ptr = le16_to_cpu(*((uint16_t *)&bios->data[offset + 91]));
3958                 /* it seems the old style lvds script pointer (which I've not observed in use) gets
3959                  * reused as the 18/24 bit panel interface default for EDID equipped panels */
3960                 bios->fp.if_is_24bit = bios->data[offset + 95] & 1;
3961         }
3962         if (bmplength > 108) {
3963                 fpp.fptablepointer = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 105])));
3964                 fpp.fpxlatetableptr = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 107])));
3965                 fpp.xlatwidth = 1;
3966         }
3967         if (bmplength > 120) {
3968                 bios->fp.lvdsmanufacturerpointer = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 117])));
3969                 bios->fp.fpxlatemanufacturertableptr = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 119])));
3970         }
3971         if (bmplength > 143)
3972                 bios->pll_limit_tbl_ptr = le16_to_cpu(*((uint16_t *)(&bios->data[offset + 142])));
3973
3974         if (bmplength > 157)
3975                 bios->fp.duallink_transition_clk = le16_to_cpu(*((uint16_t *)&bios->data[offset + 156])) * 10;
3976
3977         /* want pll_limit_tbl_ptr set (if available) before init is run */
3978         if (bmp_version_major < 5 || bmp_version_minor < 0x10) {
3979                 init_exec_t iexec = {true, false};
3980                 if (bios->init_script_tbls_ptr)
3981                         parse_init_table(pScrn, bios, bios->init_script_tbls_ptr, &iexec);
3982                 if (bios->extra_init_script_tbl_ptr)
3983                         parse_init_table(pScrn, bios, bios->extra_init_script_tbl_ptr, &iexec);
3984         } else
3985                 parse_init_tables(pScrn, bios);
3986
3987         /* If it's not a laptop, you probably don't care about fptables */
3988         if (!(bios->feature_byte & FEATURE_MOBILE))
3989                 return;
3990
3991         bios->fp.strapping = get_fp_strap(pScrn, bios);
3992         parse_lvds_manufacturer_table(pScrn, bios, 0);
3993         parse_fp_mode_table(pScrn, bios, &fpp);
3994 }
3995
3996 static uint16_t findstr(uint8_t *data, int n, const uint8_t *str, int len)
3997 {
3998         int i, j;
3999
4000         for (i = 0; i <= (n - len); i++) {
4001                 for (j = 0; j < len; j++)
4002                         if (data[i + j] != str[j])
4003                                 break;
4004                 if (j == len)
4005                         return i;
4006         }
4007
4008         return 0;
4009 }
4010
4011 static void
4012 read_dcb_i2c_entry(ScrnInfoPtr pScrn, uint8_t dcb_version, uint16_t i2ctabptr, int index)
4013 {
4014         NVPtr pNv = NVPTR(pScrn);
4015         bios_t *bios = &pNv->VBIOS;
4016         uint8_t *i2ctable = &bios->data[i2ctabptr];
4017         uint8_t headerlen = 0;
4018         int i2c_entries = MAX_NUM_DCB_ENTRIES;
4019         int recordoffset = 0, rdofs = 1, wrofs = 0;
4020
4021         if (!i2ctabptr)
4022                 return;
4023
4024         if (dcb_version >= 0x30) {
4025                 if (i2ctable[0] != dcb_version) /* necessary? */
4026                         xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4027                                    "DCB I2C table version mismatch (%02X vs %02X)\n",
4028                                    i2ctable[0], dcb_version);
4029                 headerlen = i2ctable[1];
4030                 i2c_entries = i2ctable[2];
4031
4032                 /* same address offset used for read and write for C51 and G80 */
4033                 if (bios->chip_version == 0x51)
4034                         rdofs = wrofs = 1;
4035                 if (i2ctable[0] >= 0x40)
4036                         rdofs = wrofs = 0;
4037         }
4038         /* it's your own fault if you call this function on a DCB 1.1 BIOS --
4039          * the test below is for DCB 1.2
4040          */
4041         if (dcb_version < 0x14) {
4042                 recordoffset = 2;
4043                 rdofs = 0;
4044                 wrofs = 1;
4045         }
4046
4047         if (index == 0xf)
4048                 return;
4049         if (index > i2c_entries) {
4050                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4051                            "DCB I2C index too big (%d > %d)\n",
4052                            index, i2ctable[2]);
4053                 return;
4054         }
4055         if (i2ctable[headerlen + 4 * index + 3] == 0xff) {
4056                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4057                            "DCB I2C entry invalid\n");
4058                 return;
4059         }
4060
4061         if (bios->chip_version == 0x51) {
4062                 int port_type = i2ctable[headerlen + 4 * index + 3];
4063
4064                 if (port_type != 4)
4065                         xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4066                                    "DCB I2C table has port type %d\n", port_type);
4067         }
4068         if (i2ctable[0] >= 0x40) {
4069                 int port_type = i2ctable[headerlen + 4 * index + 3];
4070
4071                 if (port_type != 5)
4072                         xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4073                                    "DCB I2C table has port type %d\n", port_type);
4074         }
4075
4076         pNv->dcb_table.i2c_read[index] = i2ctable[headerlen + recordoffset + rdofs + 4 * index];
4077         pNv->dcb_table.i2c_write[index] = i2ctable[headerlen + recordoffset + wrofs + 4 * index];
4078 }
4079
4080 static bool
4081 parse_dcb_entry(ScrnInfoPtr pScrn, int index, uint8_t dcb_version, uint16_t i2ctabptr, uint32_t conn, uint32_t conf)
4082 {
4083         NVPtr pNv = NVPTR(pScrn);
4084         struct dcb_entry *entry = &pNv->dcb_table.entry[index];
4085
4086         memset(entry, 0, sizeof (struct dcb_entry));
4087
4088         entry->index = index;
4089         /* safe defaults for a crt */
4090         entry->type = 0;
4091         entry->i2c_index = 0;
4092         entry->heads = 1;
4093         entry->bus = 0;
4094         entry->location = LOC_ON_CHIP;
4095         entry->or = 1;
4096         entry->duallink_possible = false;
4097
4098         if (dcb_version >= 0x20) {
4099                 entry->type = conn & 0xf;
4100                 entry->i2c_index = (conn >> 4) & 0xf;
4101                 entry->heads = (conn >> 8) & 0xf;
4102                 entry->bus = (conn >> 16) & 0xf;
4103                 entry->location = (conn >> 20) & 0xf;
4104                 entry->or = (conn >> 24) & 0xf;
4105                 /* Normal entries consist of a single bit, but dual link has the
4106                  * adjacent more significant bit set too
4107                  */
4108                 if ((1 << (ffs(entry->or) - 1)) * 3 == entry->or)
4109                         entry->duallink_possible = true;
4110
4111                 switch (entry->type) {
4112                 case OUTPUT_LVDS:
4113                         {
4114                         uint32_t mask;
4115                         if (conf & 0x1)
4116                                 entry->lvdsconf.use_straps_for_mode = true;
4117                         if (dcb_version < 0x22) {
4118                                 mask = ~0xd;
4119                                 /* both 0x4 and 0x8 show up in v2.0 tables; assume they mean
4120                                  * the same thing, which is probably wrong, but might work */
4121                                 if (conf & 0x4 || conf & 0x8)
4122                                         entry->lvdsconf.use_power_scripts = true;
4123                         } else {
4124                                 mask = ~0x5;
4125                                 if (conf & 0x4)
4126                                         entry->lvdsconf.use_power_scripts = true;
4127                         }
4128                         if (conf & mask) {
4129                                 /* I'm bored of getting this reported; left as a reminder for someone to fix it */
4130                                 if (dcb_version >= 0x40) {
4131                                         xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4132                                                    "G80+ LVDS not initialized by driver; ignoring conf bits\n");
4133                                         break;
4134                                 }
4135                                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4136                                            "Unknown LVDS configuration bits, please report\n");
4137                                 /* cause output setting to fail, so message is seen */
4138                                 pNv->dcb_table.entries = 0;
4139                                 return false;
4140                         }
4141                         break;
4142                         }
4143                 case 0xe:
4144                         /* weird type that appears on g80 mobile bios; nv driver treats it as a terminator */
4145                         return false;
4146                 }
4147                 read_dcb_i2c_entry(pScrn, dcb_version, i2ctabptr, entry->i2c_index);
4148         } else if (dcb_version >= 0x14 ) {
4149                 if (conn != 0xf0003f00 && conn != 0xf2247f10 &&
4150                     conn != 0xf2204001 && conn != 0xf2204301 && conn != 0xf2204311 && conn != 0xf2208001 && conn != 0xf2244001 && conn != 0xf2244301 && conn != 0xf2244311 && conn != 0xf4204011 && conn != 0xf4208011 && conn != 0xf4248011 &&
4151                     conn != 0xf2045f14 && conn != 0xf2205004) {
4152                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4153                                    "Unknown DCB 1.4 / 1.5 entry, please report\n");
4154
4155                         /* cause output setting to fail for non-TVs, so message is seen */
4156                         if ((conn & 0xf) != 0x1)
4157                                 pNv->dcb_table.entries = 0;
4158
4159                         return false;
4160                 }
4161                 /* most of the below is a "best guess" atm */
4162                 entry->type = conn & 0xf;
4163                 if (entry->type == 4) { /* digital */
4164                         if (conn & 0x10)
4165                                 entry->type = OUTPUT_LVDS;
4166                         else
4167                                 entry->type = OUTPUT_TMDS;
4168                 }
4169                 /* what's in bits 5-13? could be some brooktree/chrontel/philips thing, in tv case */
4170                 entry->i2c_index = (conn >> 14) & 0xf;
4171                 /* raw heads field is in range 0-1, so move to 1-2 */
4172                 entry->heads = ((conn >> 18) & 0x7) + 1;
4173                 entry->location = (conn >> 21) & 0xf;
4174                 entry->bus = (conn >> 25) & 0x7;
4175                 /* set or to be same as heads -- hopefully safe enough */
4176                 entry->or = entry->heads;
4177
4178                 switch (entry->type) {
4179                 case OUTPUT_LVDS:
4180                         /* this is probably buried in conn's unknown bits */
4181                         entry->lvdsconf.use_power_scripts = true;
4182                         break;
4183                 case OUTPUT_TMDS:
4184                         /* invent a DVI-A output, by copying the fields of the DVI-D output
4185                          * reported to work by math_b on an NV20(!) */
4186                         memcpy(&entry[1], &entry[0], sizeof(struct dcb_entry));
4187                         entry[1].index = ++index;
4188                         entry[1].type = OUTPUT_ANALOG;
4189                         xf86DrvMsg(pScrn->scrnIndex, X_NOTICE,
4190                                    "Concocting additional DCB entry for analogue encoder on DVI output\n");
4191                         pNv->dcb_table.entries++;
4192                 }
4193                 read_dcb_i2c_entry(pScrn, dcb_version, i2ctabptr, entry->i2c_index);
4194         } else if (dcb_version >= 0x12) {
4195                 /* v1.2 tables normally have the same 5 entries, which are not
4196                  * specific to the card, so use the defaults for a crt */
4197                 /* DCB v1.2 does have an I2C table that read_dcb_i2c_table can handle, but cards
4198                  * exist (seen on nv11) where the pointer to the table points to the wrong
4199                  * place, so for now, we rely on the indices parsed in parse_bmp_structure
4200                  */
4201                 entry->i2c_index = pNv->VBIOS.legacy.i2c_indices.crt;
4202         } else { /* pre DCB / v1.1 - use the safe defaults for a crt */
4203                 xf86DrvMsg(pScrn->scrnIndex, X_NOTICE,
4204                            "No information in BIOS output table; assuming a CRT output exists\n");
4205                 entry->i2c_index = pNv->VBIOS.legacy.i2c_indices.crt;
4206         }
4207
4208         if (entry->type == OUTPUT_LVDS && pNv->VBIOS.fp.strapping != 0xff)
4209                 entry->lvdsconf.use_straps_for_mode = true;
4210
4211         pNv->dcb_table.entries++;
4212
4213         return true;
4214 }
4215
4216 void merge_like_dcb_entries(ScrnInfoPtr pScrn)
4217 {
4218         /* DCB v2.0 lists each output combination separately.
4219          * Here we merge compatible entries to have fewer outputs, with more options
4220          */
4221
4222         NVPtr pNv = NVPTR(pScrn);
4223         int i, newentries = 0;
4224
4225         for (i = 0; i < pNv->dcb_table.entries; i++) {
4226                 struct dcb_entry *ient = &pNv->dcb_table.entry[i];
4227                 int j;
4228
4229                 for (j = i + 1; j < pNv->dcb_table.entries; j++) {
4230                         struct dcb_entry *jent = &pNv->dcb_table.entry[j];
4231
4232                         if (jent->type == 100) /* already merged entry */
4233                                 continue;
4234
4235                         /* merge heads field when all other fields the same */
4236                         if (jent->i2c_index == ient->i2c_index && jent->type == ient->type && jent->location == ient->location && jent->or == ient->or) {
4237                                 xf86DrvMsg(pScrn->scrnIndex, X_INFO,
4238                                            "Merging DCB entries %d and %d\n", i, j);
4239                                 ient->heads |= jent->heads;
4240                                 jent->type = 100; /* dummy value */
4241                         }
4242                 }
4243         }
4244
4245         /* Compact entries merged into others out of dcb_table */
4246         for (i = 0; i < pNv->dcb_table.entries; i++) {
4247                 if ( pNv->dcb_table.entry[i].type == 100 )
4248                         continue;
4249
4250                 if (newentries != i)
4251                         memcpy(&pNv->dcb_table.entry[newentries], &pNv->dcb_table.entry[i], sizeof(struct dcb_entry));
4252                 newentries++;
4253         }
4254
4255         pNv->dcb_table.entries = newentries;
4256 }
4257
4258 static unsigned int parse_dcb_table(ScrnInfoPtr pScrn, bios_t *bios)
4259 {
4260         NVPtr pNv = NVPTR(pScrn);
4261         uint16_t dcbptr, i2ctabptr = 0;
4262         uint8_t *dcbtable;
4263         uint8_t dcb_version, headerlen = 0x4, entries = MAX_NUM_DCB_ENTRIES;
4264         bool configblock = true;
4265         int recordlength = 8, confofs = 4;
4266         int i;
4267
4268         pNv->dcb_table.entries = 0;
4269
4270         /* get the offset from 0x36 */
4271         dcbptr = le16_to_cpu(*(uint16_t *)&bios->data[0x36]);
4272
4273         if (dcbptr == 0x0) {
4274                 xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
4275                            "No Display Configuration Block pointer found\n");
4276                 /* this situation likely means a really old card, pre DCB, so we'll add the safe CRT entry */
4277                 parse_dcb_entry(pScrn, 0, 0, 0, 0, 0);
4278                 return 1;
4279         }
4280
4281         dcbtable = &bios->data[dcbptr];
4282
4283         /* get DCB version */
4284         dcb_version = dcbtable[0];
4285         xf86DrvMsg(pScrn->scrnIndex, X_INFO,
4286                    "Found Display Configuration Block version %d.%d\n",
4287                    dcb_version >> 4, dcb_version & 0xf);
4288
4289         if (dcb_version >= 0x20) { /* NV17+ */
4290                 uint32_t sig;
4291
4292                 if (dcb_version >= 0x30) { /* NV40+ */
4293                         headerlen = dcbtable[1];
4294                         entries = dcbtable[2];
4295                         recordlength = dcbtable[3];
4296                         i2ctabptr = le16_to_cpu(*(uint16_t *)&dcbtable[4]);
4297                         sig = le32_to_cpu(*(uint32_t *)&dcbtable[6]);
4298                 } else {
4299                         i2ctabptr = le16_to_cpu(*(uint16_t *)&dcbtable[2]);
4300                         sig = le32_to_cpu(*(uint32_t *)&dcbtable[4]);
4301                         headerlen = 8;
4302                 }
4303
4304                 if (sig != 0x4edcbdcb) {
4305                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4306                                    "Bad Display Configuration Block signature (%08X)\n", sig);
4307                         return 0;
4308                 }
4309         } else if (dcb_version >= 0x14) { /* some NV15/16, and NV11+ */
4310                 char sig[8] = { 0 };
4311
4312                 strncpy(sig, (char *)&dcbtable[-7], 7);
4313                 i2ctabptr = le16_to_cpu(*(uint16_t *)&dcbtable[2]);
4314                 recordlength = 10;
4315                 confofs = 6;
4316
4317                 if (strcmp(sig, "DEV_REC")) {
4318                         xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4319                                    "Bad Display Configuration Block signature (%s)\n", sig);
4320                         return 0;
4321                 }
4322         } else if (dcb_version >= 0x12) { /* some NV6/10, and NV15+ */
4323                 i2ctabptr = le16_to_cpu(*(uint16_t *)&dcbtable[2]);
4324                 configblock = false;
4325         } else {        /* NV5+, maybe NV4 */
4326                 /* DCB 1.1 seems to be quite unhelpful - we'll just add the safe CRT entry */
4327                 parse_dcb_entry(pScrn, 0, dcb_version, 0, 0, 0);
4328                 return 1;
4329         }
4330
4331         if (entries >= MAX_NUM_DCB_ENTRIES)
4332                 entries = MAX_NUM_DCB_ENTRIES;
4333
4334         for (i = 0; i < entries; i++) {
4335                 uint32_t connection, config = 0;
4336
4337                 connection = le32_to_cpu(*(uint32_t *)&dcbtable[headerlen + recordlength * i]);
4338                 if (configblock)
4339                         config = le32_to_cpu(*(uint32_t *)&dcbtable[headerlen + confofs + recordlength * i]);
4340
4341                 /* Should we allow discontinuous DCBs? Certainly DCB I2C tables can be discontinuous */
4342                 if ((connection & 0x0000000f) == 0x0000000f) /* end of records */
4343                         break;
4344                 if (connection == 0x00000000) /* seen on an NV11 with DCB v1.5 */
4345                         break;
4346
4347                 xf86DrvMsg(pScrn->scrnIndex, X_NOTICE, "Raw DCB entry %d: %08x %08x\n",
4348                            pNv->dcb_table.entries, connection, config);
4349
4350                 if (!parse_dcb_entry(pScrn, pNv->dcb_table.entries, dcb_version, i2ctabptr, connection, config))
4351                         break;
4352         }
4353
4354         merge_like_dcb_entries(pScrn);
4355
4356         return pNv->dcb_table.entries;
4357 }
4358
4359 static void load_nv17_hw_sequencer_ucode(ScrnInfoPtr pScrn, bios_t *bios, uint16_t hwsq_offset, int entry)
4360 {
4361         /* BMP based cards, from NV17, need a microcode loading to correctly
4362          * control the GPIO etc for LVDS panels
4363          *
4364          * BIT based cards seem to do this directly in the init scripts
4365          *
4366          * The microcode entries are found by the "HWSQ" signature.
4367          * The header following has the number of entries, and the entry size
4368          *
4369          * An entry consists of a dword to write to the sequencer control reg
4370          * (0x00001304), followed by the ucode bytes, written sequentially,
4371          * starting at reg 0x00001400
4372          */
4373
4374         uint8_t bytes_to_write;
4375         uint16_t hwsq_entry_offset;
4376         int i;
4377
4378         if (bios->data[hwsq_offset] <= entry) {
4379                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4380                            "Too few entries in HW sequencer table for requested entry\n");
4381                 return;
4382         }
4383
4384         bytes_to_write = bios->data[hwsq_offset + 1];
4385
4386         if (bytes_to_write != 36) {
4387                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR, "Unknown HW sequencer entry size\n");
4388                 return;
4389         }
4390
4391         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Loading NV17 power sequencing microcode\n");
4392
4393         hwsq_entry_offset = hwsq_offset + 2 + entry * bytes_to_write;
4394
4395         /* set sequencer control */
4396         nv32_wr(pScrn, 0x00001304, le32_to_cpu(*(uint32_t *)&bios->data[hwsq_entry_offset]));
4397         bytes_to_write -= 4;
4398
4399         /* write ucode */
4400         for (i = 0; i < bytes_to_write; i += 4)
4401                 nv32_wr(pScrn, 0x00001400 + i, le32_to_cpu(*(uint32_t *)&bios->data[hwsq_entry_offset + i + 4]));
4402
4403         /* twiddle NV_PBUS_DEBUG_4 */
4404         nv32_wr(pScrn, NV_PBUS_DEBUG_4, nv32_rd(pScrn, NV_PBUS_DEBUG_4) | 0x18);
4405 }
4406
4407 static void read_bios_edid(ScrnInfoPtr pScrn)
4408 {
4409         bios_t *bios = &NVPTR(pScrn)->VBIOS;
4410         const uint8_t edid_sig[] = { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 };
4411         uint16_t offset = 0, newoffset;
4412         int searchlen = NV_PROM_SIZE, i;
4413
4414         while (searchlen) {
4415                 if (!(newoffset = findstr(&bios->data[offset], searchlen, edid_sig, 8)))
4416                         return;
4417                 offset += newoffset;
4418                 if (!nv_cksum(&bios->data[offset], EDID1_LEN))
4419                         break;
4420
4421                 searchlen -= offset;
4422                 offset++;
4423         }
4424
4425         xf86DrvMsg(pScrn->scrnIndex, X_INFO, "Found EDID in BIOS\n");
4426
4427         if (!(bios->fp.edid = xalloc(EDID1_LEN)))
4428                 return;
4429         for (i = 0; i < EDID1_LEN; i++)
4430                 bios->fp.edid[i] = bios->data[offset + i];
4431 }
4432
4433 bool NVInitVBIOS(ScrnInfoPtr pScrn)
4434 {
4435         NVPtr pNv = NVPTR(pScrn);
4436
4437         memset(&pNv->VBIOS, 0, sizeof(bios_t));
4438         if (!(pNv->VBIOS.data = xalloc(NV_PROM_SIZE)))
4439                 return false;
4440
4441         if (!NVShadowVBIOS(pScrn, pNv->VBIOS.data)) {
4442                 xfree(pNv->VBIOS.data);
4443                 return false;
4444         }
4445
4446         pNv->VBIOS.length = pNv->VBIOS.data[2] * 512;
4447         if (pNv->VBIOS.length > NV_PROM_SIZE)
4448                 pNv->VBIOS.length = NV_PROM_SIZE;
4449
4450         return true;
4451 }
4452
4453 bool NVRunVBIOSInit(ScrnInfoPtr pScrn)
4454 {
4455         NVPtr pNv = NVPTR(pScrn);
4456         const uint8_t bmp_signature[] = { 0xff, 0x7f, 'N', 'V', 0x0 };
4457         const uint8_t bit_signature[] = { 0xff, 0xb8, 'B', 'I', 'T' };
4458         int offset, ret = 0;
4459
4460         NVLockVgaCrtcs(pNv, false);
4461         if (pNv->twoHeads)
4462                 NVSetOwner(pNv, crtchead);
4463
4464         if ((offset = findstr(pNv->VBIOS.data, pNv->VBIOS.length, bit_signature, sizeof(bit_signature)))) {
4465                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "BIT BIOS found\n");
4466                 parse_bit_structure(pScrn, &pNv->VBIOS, offset + 6);
4467         } else if ((offset = findstr(pNv->VBIOS.data, pNv->VBIOS.length, bmp_signature, sizeof(bmp_signature)))) {
4468                 const uint8_t hwsq_signature[] = { 'H', 'W', 'S', 'Q' };
4469                 int hwsq_offset;
4470
4471                 if ((hwsq_offset = findstr(pNv->VBIOS.data, pNv->VBIOS.length, hwsq_signature, sizeof(hwsq_signature))))
4472                         /* always use entry 0? */
4473                         load_nv17_hw_sequencer_ucode(pScrn, &pNv->VBIOS, hwsq_offset + sizeof(hwsq_signature), 0);
4474
4475                 xf86DrvMsg(pScrn->scrnIndex, X_INFO, "BMP BIOS found\n");
4476                 parse_bmp_structure(pScrn, &pNv->VBIOS, offset);
4477         } else {
4478                 xf86DrvMsg(pScrn->scrnIndex, X_ERROR,
4479                            "No known BIOS signature found\n");
4480                 ret = 1;
4481         }
4482
4483         NVLockVgaCrtcs(pNv, true);
4484         if (pNv->twoHeads)
4485                 NVSetOwner(pNv, crtchead);
4486
4487         if (ret)
4488                 return false;
4489
4490         return true;
4491 }
4492
4493 unsigned int NVParseBios(ScrnInfoPtr pScrn)
4494 {
4495         NVPtr pNv = NVPTR(pScrn);
4496         uint32_t saved_nv_pextdev_boot_0;
4497         int i;
4498
4499         if (!NVInitVBIOS(pScrn))
4500                 return 0;
4501
4502         /* these will need remembering across a suspend */
4503         saved_nv_pextdev_boot_0 = nv32_rd(pScrn, NV_PEXTDEV_BOOT_0);
4504         saved_nv_pfb_cfg0 = nv32_rd(pScrn, NV_PFB_CFG0);
4505
4506         /* init script execution disabled */
4507         pNv->VBIOS.execute = false;
4508
4509         nv32_wr(pScrn, NV_PEXTDEV_BOOT_0, saved_nv_pextdev_boot_0);
4510
4511         if (!NVRunVBIOSInit(pScrn))
4512                 return 0;
4513
4514         parse_dcb_table(pScrn, &pNv->VBIOS);
4515
4516         for (i = 0 ; i < pNv->dcb_table.entries; i++)
4517                 if (pNv->dcb_table.entry[i].type == OUTPUT_LVDS)
4518                         call_lvds_script(pScrn, &pNv->dcb_table.entry[i], nv_get_digital_bound_head(pNv, pNv->dcb_table.entry[i].or), LVDS_INIT, 0);
4519
4520         if (pNv->VBIOS.feature_byte & FEATURE_MOBILE && !pNv->VBIOS.fp.native_mode)
4521                 read_bios_edid(pScrn);
4522
4523         /* allow subsequent scripts to execute */
4524         pNv->VBIOS.execute = true;
4525
4526         return 1;
4527 }