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