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