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