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