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