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