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