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