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