nouveau_bios.c revision 5206b524c9b4e289ab0565e7bffd503d2e671c6e
1/*
2 * Copyright 2005-2006 Erik Waling
3 * Copyright 2006 Stephane Marchesin
4 * Copyright 2007-2009 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 "drmP.h"
26#define NV_DEBUG_NOTRACE
27#include "nouveau_drv.h"
28#include "nouveau_hw.h"
29#include "nouveau_encoder.h"
30#include "nouveau_gpio.h"
31
32#include <linux/io-mapping.h>
33
34/* these defines are made up */
35#define NV_CIO_CRE_44_HEADA 0x0
36#define NV_CIO_CRE_44_HEADB 0x3
37#define FEATURE_MOBILE 0x10	/* also FEATURE_QUADRO for BMP */
38
39#define EDID1_LEN 128
40
41#define BIOSLOG(sip, fmt, arg...) NV_DEBUG(sip->dev, fmt, ##arg)
42#define LOG_OLD_VALUE(x)
43
44struct init_exec {
45	bool execute;
46	bool repeat;
47};
48
49static bool nv_cksum(const uint8_t *data, unsigned int length)
50{
51	/*
52	 * There's a few checksums in the BIOS, so here's a generic checking
53	 * function.
54	 */
55	int i;
56	uint8_t sum = 0;
57
58	for (i = 0; i < length; i++)
59		sum += data[i];
60
61	if (sum)
62		return true;
63
64	return false;
65}
66
67static int
68score_vbios(struct nvbios *bios, const bool writeable)
69{
70	if (!bios->data || bios->data[0] != 0x55 || bios->data[1] != 0xAA) {
71		NV_TRACEWARN(bios->dev, "... BIOS signature not found\n");
72		return 0;
73	}
74
75	if (nv_cksum(bios->data, bios->data[2] * 512)) {
76		NV_TRACEWARN(bios->dev, "... BIOS checksum invalid\n");
77		/* if a ro image is somewhat bad, it's probably all rubbish */
78		return writeable ? 2 : 1;
79	}
80
81	NV_TRACE(bios->dev, "... appears to be valid\n");
82	return 3;
83}
84
85static void
86bios_shadow_prom(struct nvbios *bios)
87{
88	struct drm_device *dev = bios->dev;
89	struct drm_nouveau_private *dev_priv = dev->dev_private;
90	u32 pcireg, access;
91	u16 pcir;
92	int i;
93
94	/* enable access to rom */
95	if (dev_priv->card_type >= NV_50)
96		pcireg = 0x088050;
97	else
98		pcireg = NV_PBUS_PCI_NV_20;
99	access = nv_mask(dev, pcireg, 0x00000001, 0x00000000);
100
101	/* bail if no rom signature, with a workaround for a PROM reading
102	 * issue on some chipsets.  the first read after a period of
103	 * inactivity returns the wrong result, so retry the first header
104	 * byte a few times before giving up as a workaround
105	 */
106	i = 16;
107	do {
108		if (nv_rd08(dev, NV_PROM_OFFSET + 0) == 0x55)
109			break;
110	} while (i--);
111
112	if (!i || nv_rd08(dev, NV_PROM_OFFSET + 1) != 0xaa)
113		goto out;
114
115	/* additional check (see note below) - read PCI record header */
116	pcir = nv_rd08(dev, NV_PROM_OFFSET + 0x18) |
117	       nv_rd08(dev, NV_PROM_OFFSET + 0x19) << 8;
118	if (nv_rd08(dev, NV_PROM_OFFSET + pcir + 0) != 'P' ||
119	    nv_rd08(dev, NV_PROM_OFFSET + pcir + 1) != 'C' ||
120	    nv_rd08(dev, NV_PROM_OFFSET + pcir + 2) != 'I' ||
121	    nv_rd08(dev, NV_PROM_OFFSET + pcir + 3) != 'R')
122		goto out;
123
124	/* read entire bios image to system memory */
125	bios->length = nv_rd08(dev, NV_PROM_OFFSET + 2) * 512;
126	bios->data = kmalloc(bios->length, GFP_KERNEL);
127	if (bios->data) {
128		for (i = 0; i < bios->length; i++)
129			bios->data[i] = nv_rd08(dev, NV_PROM_OFFSET + i);
130	}
131
132out:
133	/* disable access to rom */
134	nv_wr32(dev, pcireg, access);
135}
136
137static void
138bios_shadow_pramin(struct nvbios *bios)
139{
140	struct drm_device *dev = bios->dev;
141	struct drm_nouveau_private *dev_priv = dev->dev_private;
142	u32 bar0 = 0;
143	int i;
144
145	if (dev_priv->card_type >= NV_50) {
146		u64 addr = (u64)(nv_rd32(dev, 0x619f04) & 0xffffff00) << 8;
147		if (!addr) {
148			addr  = (u64)nv_rd32(dev, 0x001700) << 16;
149			addr += 0xf0000;
150		}
151
152		bar0 = nv_mask(dev, 0x001700, 0xffffffff, addr >> 16);
153	}
154
155	/* bail if no rom signature */
156	if (nv_rd08(dev, NV_PRAMIN_OFFSET + 0) != 0x55 ||
157	    nv_rd08(dev, NV_PRAMIN_OFFSET + 1) != 0xaa)
158		goto out;
159
160	bios->length = nv_rd08(dev, NV_PRAMIN_OFFSET + 2) * 512;
161	bios->data = kmalloc(bios->length, GFP_KERNEL);
162	if (bios->data) {
163		for (i = 0; i < bios->length; i++)
164			bios->data[i] = nv_rd08(dev, NV_PRAMIN_OFFSET + i);
165	}
166
167out:
168	if (dev_priv->card_type >= NV_50)
169		nv_wr32(dev, 0x001700, bar0);
170}
171
172static void
173bios_shadow_pci(struct nvbios *bios)
174{
175	struct pci_dev *pdev = bios->dev->pdev;
176	size_t length;
177
178	if (!pci_enable_rom(pdev)) {
179		void __iomem *rom = pci_map_rom(pdev, &length);
180		if (rom && length) {
181			bios->data = kmalloc(length, GFP_KERNEL);
182			if (bios->data) {
183				memcpy_fromio(bios->data, rom, length);
184				bios->length = length;
185			}
186		}
187		if (rom)
188			pci_unmap_rom(pdev, rom);
189
190		pci_disable_rom(pdev);
191	}
192}
193
194static void
195bios_shadow_acpi(struct nvbios *bios)
196{
197	struct pci_dev *pdev = bios->dev->pdev;
198	int ptr, len, ret;
199	u8 data[3];
200
201	if (!nouveau_acpi_rom_supported(pdev))
202		return;
203
204	ret = nouveau_acpi_get_bios_chunk(data, 0, sizeof(data));
205	if (ret != sizeof(data))
206		return;
207
208	bios->length = min(data[2] * 512, 65536);
209	bios->data = kmalloc(bios->length, GFP_KERNEL);
210	if (!bios->data)
211		return;
212
213	len = bios->length;
214	ptr = 0;
215	while (len) {
216		int size = (len > ROM_BIOS_PAGE) ? ROM_BIOS_PAGE : len;
217
218		ret = nouveau_acpi_get_bios_chunk(bios->data, ptr, size);
219		if (ret != size) {
220			kfree(bios->data);
221			bios->data = NULL;
222			return;
223		}
224
225		len -= size;
226		ptr += size;
227	}
228}
229
230struct methods {
231	const char desc[8];
232	void (*shadow)(struct nvbios *);
233	const bool rw;
234	int score;
235	u32 size;
236	u8 *data;
237};
238
239static bool
240bios_shadow(struct drm_device *dev)
241{
242	struct methods shadow_methods[] = {
243		{ "PRAMIN", bios_shadow_pramin, true, 0, 0, NULL },
244		{ "PROM", bios_shadow_prom, false, 0, 0, NULL },
245		{ "ACPI", bios_shadow_acpi, true, 0, 0, NULL },
246		{ "PCIROM", bios_shadow_pci, true, 0, 0, NULL },
247		{}
248	};
249	struct drm_nouveau_private *dev_priv = dev->dev_private;
250	struct nvbios *bios = &dev_priv->vbios;
251	struct methods *mthd, *best;
252
253	if (nouveau_vbios) {
254		mthd = shadow_methods;
255		do {
256			if (strcasecmp(nouveau_vbios, mthd->desc))
257				continue;
258			NV_INFO(dev, "VBIOS source: %s\n", mthd->desc);
259
260			mthd->shadow(bios);
261			mthd->score = score_vbios(bios, mthd->rw);
262			if (mthd->score)
263				return true;
264		} while ((++mthd)->shadow);
265
266		NV_ERROR(dev, "VBIOS source \'%s\' invalid\n", nouveau_vbios);
267	}
268
269	mthd = shadow_methods;
270	do {
271		NV_TRACE(dev, "Checking %s for VBIOS\n", mthd->desc);
272		mthd->shadow(bios);
273		mthd->score = score_vbios(bios, mthd->rw);
274		mthd->size = bios->length;
275		mthd->data = bios->data;
276	} while (mthd->score != 3 && (++mthd)->shadow);
277
278	mthd = shadow_methods;
279	best = mthd;
280	do {
281		if (mthd->score > best->score) {
282			kfree(best->data);
283			best = mthd;
284		}
285	} while ((++mthd)->shadow);
286
287	if (best->score) {
288		NV_TRACE(dev, "Using VBIOS from %s\n", best->desc);
289		bios->length = best->size;
290		bios->data = best->data;
291		return true;
292	}
293
294	NV_ERROR(dev, "No valid VBIOS image found\n");
295	return false;
296}
297
298struct init_tbl_entry {
299	char *name;
300	uint8_t id;
301	/* Return:
302	 *  > 0: success, length of opcode
303	 *    0: success, but abort further parsing of table (INIT_DONE etc)
304	 *  < 0: failure, table parsing will be aborted
305	 */
306	int (*handler)(struct nvbios *, uint16_t, struct init_exec *);
307};
308
309static int parse_init_table(struct nvbios *, uint16_t, struct init_exec *);
310
311#define MACRO_INDEX_SIZE	2
312#define MACRO_SIZE		8
313#define CONDITION_SIZE		12
314#define IO_FLAG_CONDITION_SIZE	9
315#define IO_CONDITION_SIZE	5
316#define MEM_INIT_SIZE		66
317
318static void still_alive(void)
319{
320#if 0
321	sync();
322	mdelay(2);
323#endif
324}
325
326static uint32_t
327munge_reg(struct nvbios *bios, uint32_t reg)
328{
329	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
330	struct dcb_entry *dcbent = bios->display.output;
331
332	if (dev_priv->card_type < NV_50)
333		return reg;
334
335	if (reg & 0x80000000) {
336		BUG_ON(bios->display.crtc < 0);
337		reg += bios->display.crtc * 0x800;
338	}
339
340	if (reg & 0x40000000) {
341		BUG_ON(!dcbent);
342
343		reg += (ffs(dcbent->or) - 1) * 0x800;
344		if ((reg & 0x20000000) && !(dcbent->sorconf.link & 1))
345			reg += 0x00000080;
346	}
347
348	reg &= ~0xe0000000;
349	return reg;
350}
351
352static int
353valid_reg(struct nvbios *bios, uint32_t reg)
354{
355	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
356	struct drm_device *dev = bios->dev;
357
358	/* C51 has misaligned regs on purpose. Marvellous */
359	if (reg & 0x2 ||
360	    (reg & 0x1 && dev_priv->vbios.chip_version != 0x51))
361		NV_ERROR(dev, "======= misaligned reg 0x%08X =======\n", reg);
362
363	/* warn on C51 regs that haven't been verified accessible in tracing */
364	if (reg & 0x1 && dev_priv->vbios.chip_version == 0x51 &&
365	    reg != 0x130d && reg != 0x1311 && reg != 0x60081d)
366		NV_WARN(dev, "=== C51 misaligned reg 0x%08X not verified ===\n",
367			reg);
368
369	if (reg >= (8*1024*1024)) {
370		NV_ERROR(dev, "=== reg 0x%08x out of mapped bounds ===\n", reg);
371		return 0;
372	}
373
374	return 1;
375}
376
377static bool
378valid_idx_port(struct nvbios *bios, uint16_t port)
379{
380	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
381	struct drm_device *dev = bios->dev;
382
383	/*
384	 * If adding more ports here, the read/write functions below will need
385	 * updating so that the correct mmio range (PRMCIO, PRMDIO, PRMVIO) is
386	 * used for the port in question
387	 */
388	if (dev_priv->card_type < NV_50) {
389		if (port == NV_CIO_CRX__COLOR)
390			return true;
391		if (port == NV_VIO_SRX)
392			return true;
393	} else {
394		if (port == NV_CIO_CRX__COLOR)
395			return true;
396	}
397
398	NV_ERROR(dev, "========== unknown indexed io port 0x%04X ==========\n",
399		 port);
400
401	return false;
402}
403
404static bool
405valid_port(struct nvbios *bios, uint16_t port)
406{
407	struct drm_device *dev = bios->dev;
408
409	/*
410	 * If adding more ports here, the read/write functions below will need
411	 * updating so that the correct mmio range (PRMCIO, PRMDIO, PRMVIO) is
412	 * used for the port in question
413	 */
414	if (port == NV_VIO_VSE2)
415		return true;
416
417	NV_ERROR(dev, "========== unknown io port 0x%04X ==========\n", port);
418
419	return false;
420}
421
422static uint32_t
423bios_rd32(struct nvbios *bios, uint32_t reg)
424{
425	uint32_t data;
426
427	reg = munge_reg(bios, reg);
428	if (!valid_reg(bios, reg))
429		return 0;
430
431	/*
432	 * C51 sometimes uses regs with bit0 set in the address. For these
433	 * cases there should exist a translation in a BIOS table to an IO
434	 * port address which the BIOS uses for accessing the reg
435	 *
436	 * These only seem to appear for the power control regs to a flat panel,
437	 * and the GPIO regs at 0x60081*.  In C51 mmio traces the normal regs
438	 * for 0x1308 and 0x1310 are used - hence the mask below.  An S3
439	 * suspend-resume mmio trace from a C51 will be required to see if this
440	 * is true for the power microcode in 0x14.., or whether the direct IO
441	 * port access method is needed
442	 */
443	if (reg & 0x1)
444		reg &= ~0x1;
445
446	data = nv_rd32(bios->dev, reg);
447
448	BIOSLOG(bios, "	Read:  Reg: 0x%08X, Data: 0x%08X\n", reg, data);
449
450	return data;
451}
452
453static void
454bios_wr32(struct nvbios *bios, uint32_t reg, uint32_t data)
455{
456	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
457
458	reg = munge_reg(bios, reg);
459	if (!valid_reg(bios, reg))
460		return;
461
462	/* see note in bios_rd32 */
463	if (reg & 0x1)
464		reg &= 0xfffffffe;
465
466	LOG_OLD_VALUE(bios_rd32(bios, reg));
467	BIOSLOG(bios, "	Write: Reg: 0x%08X, Data: 0x%08X\n", reg, data);
468
469	if (dev_priv->vbios.execute) {
470		still_alive();
471		nv_wr32(bios->dev, reg, data);
472	}
473}
474
475static uint8_t
476bios_idxprt_rd(struct nvbios *bios, uint16_t port, uint8_t index)
477{
478	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
479	struct drm_device *dev = bios->dev;
480	uint8_t data;
481
482	if (!valid_idx_port(bios, port))
483		return 0;
484
485	if (dev_priv->card_type < NV_50) {
486		if (port == NV_VIO_SRX)
487			data = NVReadVgaSeq(dev, bios->state.crtchead, index);
488		else	/* assume NV_CIO_CRX__COLOR */
489			data = NVReadVgaCrtc(dev, bios->state.crtchead, index);
490	} else {
491		uint32_t data32;
492
493		data32 = bios_rd32(bios, NV50_PDISPLAY_VGACRTC(index & ~3));
494		data = (data32 >> ((index & 3) << 3)) & 0xff;
495	}
496
497	BIOSLOG(bios, "	Indexed IO read:  Port: 0x%04X, Index: 0x%02X, "
498		      "Head: 0x%02X, Data: 0x%02X\n",
499		port, index, bios->state.crtchead, data);
500	return data;
501}
502
503static void
504bios_idxprt_wr(struct nvbios *bios, uint16_t port, uint8_t index, uint8_t data)
505{
506	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
507	struct drm_device *dev = bios->dev;
508
509	if (!valid_idx_port(bios, port))
510		return;
511
512	/*
513	 * The current head is maintained in the nvbios member  state.crtchead.
514	 * We trap changes to CR44 and update the head variable and hence the
515	 * register set written.
516	 * As CR44 only exists on CRTC0, we update crtchead to head0 in advance
517	 * of the write, and to head1 after the write
518	 */
519	if (port == NV_CIO_CRX__COLOR && index == NV_CIO_CRE_44 &&
520	    data != NV_CIO_CRE_44_HEADB)
521		bios->state.crtchead = 0;
522
523	LOG_OLD_VALUE(bios_idxprt_rd(bios, port, index));
524	BIOSLOG(bios, "	Indexed IO write: Port: 0x%04X, Index: 0x%02X, "
525		      "Head: 0x%02X, Data: 0x%02X\n",
526		port, index, bios->state.crtchead, data);
527
528	if (bios->execute && dev_priv->card_type < NV_50) {
529		still_alive();
530		if (port == NV_VIO_SRX)
531			NVWriteVgaSeq(dev, bios->state.crtchead, index, data);
532		else	/* assume NV_CIO_CRX__COLOR */
533			NVWriteVgaCrtc(dev, bios->state.crtchead, index, data);
534	} else
535	if (bios->execute) {
536		uint32_t data32, shift = (index & 3) << 3;
537
538		still_alive();
539
540		data32  = bios_rd32(bios, NV50_PDISPLAY_VGACRTC(index & ~3));
541		data32 &= ~(0xff << shift);
542		data32 |= (data << shift);
543		bios_wr32(bios, NV50_PDISPLAY_VGACRTC(index & ~3), data32);
544	}
545
546	if (port == NV_CIO_CRX__COLOR &&
547	    index == NV_CIO_CRE_44 && data == NV_CIO_CRE_44_HEADB)
548		bios->state.crtchead = 1;
549}
550
551static uint8_t
552bios_port_rd(struct nvbios *bios, uint16_t port)
553{
554	uint8_t data, head = bios->state.crtchead;
555
556	if (!valid_port(bios, port))
557		return 0;
558
559	data = NVReadPRMVIO(bios->dev, head, NV_PRMVIO0_OFFSET + port);
560
561	BIOSLOG(bios, "	IO read:  Port: 0x%04X, Head: 0x%02X, Data: 0x%02X\n",
562		port, head, data);
563
564	return data;
565}
566
567static void
568bios_port_wr(struct nvbios *bios, uint16_t port, uint8_t data)
569{
570	int head = bios->state.crtchead;
571
572	if (!valid_port(bios, port))
573		return;
574
575	LOG_OLD_VALUE(bios_port_rd(bios, port));
576	BIOSLOG(bios, "	IO write: Port: 0x%04X, Head: 0x%02X, Data: 0x%02X\n",
577		port, head, data);
578
579	if (!bios->execute)
580		return;
581
582	still_alive();
583	NVWritePRMVIO(bios->dev, head, NV_PRMVIO0_OFFSET + port, data);
584}
585
586static bool
587io_flag_condition_met(struct nvbios *bios, uint16_t offset, uint8_t cond)
588{
589	/*
590	 * The IO flag condition entry has 2 bytes for the CRTC port; 1 byte
591	 * for the CRTC index; 1 byte for the mask to apply to the value
592	 * retrieved from the CRTC; 1 byte for the shift right to apply to the
593	 * masked CRTC value; 2 bytes for the offset to the flag array, to
594	 * which the shifted value is added; 1 byte for the mask applied to the
595	 * value read from the flag array; and 1 byte for the value to compare
596	 * against the masked byte from the flag table.
597	 */
598
599	uint16_t condptr = bios->io_flag_condition_tbl_ptr + cond * IO_FLAG_CONDITION_SIZE;
600	uint16_t crtcport = ROM16(bios->data[condptr]);
601	uint8_t crtcindex = bios->data[condptr + 2];
602	uint8_t mask = bios->data[condptr + 3];
603	uint8_t shift = bios->data[condptr + 4];
604	uint16_t flagarray = ROM16(bios->data[condptr + 5]);
605	uint8_t flagarraymask = bios->data[condptr + 7];
606	uint8_t cmpval = bios->data[condptr + 8];
607	uint8_t data;
608
609	BIOSLOG(bios, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, "
610		      "Shift: 0x%02X, FlagArray: 0x%04X, FAMask: 0x%02X, "
611		      "Cmpval: 0x%02X\n",
612		offset, crtcport, crtcindex, mask, shift, flagarray, flagarraymask, cmpval);
613
614	data = bios_idxprt_rd(bios, crtcport, crtcindex);
615
616	data = bios->data[flagarray + ((data & mask) >> shift)];
617	data &= flagarraymask;
618
619	BIOSLOG(bios, "0x%04X: Checking if 0x%02X equals 0x%02X\n",
620		offset, data, cmpval);
621
622	return (data == cmpval);
623}
624
625static bool
626bios_condition_met(struct nvbios *bios, uint16_t offset, uint8_t cond)
627{
628	/*
629	 * The condition table entry has 4 bytes for the address of the
630	 * register to check, 4 bytes for a mask to apply to the register and
631	 * 4 for a test comparison value
632	 */
633
634	uint16_t condptr = bios->condition_tbl_ptr + cond * CONDITION_SIZE;
635	uint32_t reg = ROM32(bios->data[condptr]);
636	uint32_t mask = ROM32(bios->data[condptr + 4]);
637	uint32_t cmpval = ROM32(bios->data[condptr + 8]);
638	uint32_t data;
639
640	BIOSLOG(bios, "0x%04X: Cond: 0x%02X, Reg: 0x%08X, Mask: 0x%08X\n",
641		offset, cond, reg, mask);
642
643	data = bios_rd32(bios, reg) & mask;
644
645	BIOSLOG(bios, "0x%04X: Checking if 0x%08X equals 0x%08X\n",
646		offset, data, cmpval);
647
648	return (data == cmpval);
649}
650
651static bool
652io_condition_met(struct nvbios *bios, uint16_t offset, uint8_t cond)
653{
654	/*
655	 * The IO condition entry has 2 bytes for the IO port address; 1 byte
656	 * for the index to write to io_port; 1 byte for the mask to apply to
657	 * the byte read from io_port+1; and 1 byte for the value to compare
658	 * against the masked byte.
659	 */
660
661	uint16_t condptr = bios->io_condition_tbl_ptr + cond * IO_CONDITION_SIZE;
662	uint16_t io_port = ROM16(bios->data[condptr]);
663	uint8_t port_index = bios->data[condptr + 2];
664	uint8_t mask = bios->data[condptr + 3];
665	uint8_t cmpval = bios->data[condptr + 4];
666
667	uint8_t data = bios_idxprt_rd(bios, io_port, port_index) & mask;
668
669	BIOSLOG(bios, "0x%04X: Checking if 0x%02X equals 0x%02X\n",
670		offset, data, cmpval);
671
672	return (data == cmpval);
673}
674
675static int
676nv50_pll_set(struct drm_device *dev, uint32_t reg, uint32_t clk)
677{
678	struct drm_nouveau_private *dev_priv = dev->dev_private;
679	struct nouveau_pll_vals pll;
680	struct pll_lims pll_limits;
681	u32 ctrl, mask, coef;
682	int ret;
683
684	ret = get_pll_limits(dev, reg, &pll_limits);
685	if (ret)
686		return ret;
687
688	clk = nouveau_calc_pll_mnp(dev, &pll_limits, clk, &pll);
689	if (!clk)
690		return -ERANGE;
691
692	coef = pll.N1 << 8 | pll.M1;
693	ctrl = pll.log2P << 16;
694	mask = 0x00070000;
695	if (reg == 0x004008) {
696		mask |= 0x01f80000;
697		ctrl |= (pll_limits.log2p_bias << 19);
698		ctrl |= (pll.log2P << 22);
699	}
700
701	if (!dev_priv->vbios.execute)
702		return 0;
703
704	nv_mask(dev, reg + 0, mask, ctrl);
705	nv_wr32(dev, reg + 4, coef);
706	return 0;
707}
708
709static int
710setPLL(struct nvbios *bios, uint32_t reg, uint32_t clk)
711{
712	struct drm_device *dev = bios->dev;
713	struct drm_nouveau_private *dev_priv = dev->dev_private;
714	/* clk in kHz */
715	struct pll_lims pll_lim;
716	struct nouveau_pll_vals pllvals;
717	int ret;
718
719	if (dev_priv->card_type >= NV_50)
720		return nv50_pll_set(dev, reg, clk);
721
722	/* high regs (such as in the mac g5 table) are not -= 4 */
723	ret = get_pll_limits(dev, reg > 0x405c ? reg : reg - 4, &pll_lim);
724	if (ret)
725		return ret;
726
727	clk = nouveau_calc_pll_mnp(dev, &pll_lim, clk, &pllvals);
728	if (!clk)
729		return -ERANGE;
730
731	if (bios->execute) {
732		still_alive();
733		nouveau_hw_setpll(dev, reg, &pllvals);
734	}
735
736	return 0;
737}
738
739static int dcb_entry_idx_from_crtchead(struct drm_device *dev)
740{
741	struct drm_nouveau_private *dev_priv = dev->dev_private;
742	struct nvbios *bios = &dev_priv->vbios;
743
744	/*
745	 * For the results of this function to be correct, CR44 must have been
746	 * set (using bios_idxprt_wr to set crtchead), CR58 set for CR57 = 0,
747	 * and the DCB table parsed, before the script calling the function is
748	 * run.  run_digital_op_script is example of how to do such setup
749	 */
750
751	uint8_t dcb_entry = NVReadVgaCrtc5758(dev, bios->state.crtchead, 0);
752
753	if (dcb_entry > bios->dcb.entries) {
754		NV_ERROR(dev, "CR58 doesn't have a valid DCB entry currently "
755				"(%02X)\n", dcb_entry);
756		dcb_entry = 0x7f;	/* unused / invalid marker */
757	}
758
759	return dcb_entry;
760}
761
762static struct nouveau_i2c_chan *
763init_i2c_device_find(struct drm_device *dev, int i2c_index)
764{
765	if (i2c_index == 0xff) {
766		struct drm_nouveau_private *dev_priv = dev->dev_private;
767		struct dcb_table *dcb = &dev_priv->vbios.dcb;
768		/* note: dcb_entry_idx_from_crtchead needs pre-script set-up */
769		int idx = dcb_entry_idx_from_crtchead(dev);
770
771		i2c_index = NV_I2C_DEFAULT(0);
772		if (idx != 0x7f && dcb->entry[idx].i2c_upper_default)
773			i2c_index = NV_I2C_DEFAULT(1);
774	}
775
776	return nouveau_i2c_find(dev, i2c_index);
777}
778
779static uint32_t
780get_tmds_index_reg(struct drm_device *dev, uint8_t mlv)
781{
782	/*
783	 * For mlv < 0x80, it is an index into a table of TMDS base addresses.
784	 * For mlv == 0x80 use the "or" value of the dcb_entry indexed by
785	 * CR58 for CR57 = 0 to index a table of offsets to the basic
786	 * 0x6808b0 address.
787	 * For mlv == 0x81 use the "or" value of the dcb_entry indexed by
788	 * CR58 for CR57 = 0 to index a table of offsets to the basic
789	 * 0x6808b0 address, and then flip the offset by 8.
790	 */
791
792	struct drm_nouveau_private *dev_priv = dev->dev_private;
793	struct nvbios *bios = &dev_priv->vbios;
794	const int pramdac_offset[13] = {
795		0, 0, 0x8, 0, 0x2000, 0, 0, 0, 0x2008, 0, 0, 0, 0x2000 };
796	const uint32_t pramdac_table[4] = {
797		0x6808b0, 0x6808b8, 0x6828b0, 0x6828b8 };
798
799	if (mlv >= 0x80) {
800		int dcb_entry, dacoffset;
801
802		/* note: dcb_entry_idx_from_crtchead needs pre-script set-up */
803		dcb_entry = dcb_entry_idx_from_crtchead(dev);
804		if (dcb_entry == 0x7f)
805			return 0;
806		dacoffset = pramdac_offset[bios->dcb.entry[dcb_entry].or];
807		if (mlv == 0x81)
808			dacoffset ^= 8;
809		return 0x6808b0 + dacoffset;
810	} else {
811		if (mlv >= ARRAY_SIZE(pramdac_table)) {
812			NV_ERROR(dev, "Magic Lookup Value too big (%02X)\n",
813									mlv);
814			return 0;
815		}
816		return pramdac_table[mlv];
817	}
818}
819
820static int
821init_io_restrict_prog(struct nvbios *bios, uint16_t offset,
822		      struct init_exec *iexec)
823{
824	/*
825	 * INIT_IO_RESTRICT_PROG   opcode: 0x32 ('2')
826	 *
827	 * offset      (8  bit): opcode
828	 * offset + 1  (16 bit): CRTC port
829	 * offset + 3  (8  bit): CRTC index
830	 * offset + 4  (8  bit): mask
831	 * offset + 5  (8  bit): shift
832	 * offset + 6  (8  bit): count
833	 * offset + 7  (32 bit): register
834	 * offset + 11 (32 bit): configuration 1
835	 * ...
836	 *
837	 * Starting at offset + 11 there are "count" 32 bit values.
838	 * To find out which value to use read index "CRTC index" on "CRTC
839	 * port", AND this value with "mask" and then bit shift right "shift"
840	 * bits.  Read the appropriate value using this index and write to
841	 * "register"
842	 */
843
844	uint16_t crtcport = ROM16(bios->data[offset + 1]);
845	uint8_t crtcindex = bios->data[offset + 3];
846	uint8_t mask = bios->data[offset + 4];
847	uint8_t shift = bios->data[offset + 5];
848	uint8_t count = bios->data[offset + 6];
849	uint32_t reg = ROM32(bios->data[offset + 7]);
850	uint8_t config;
851	uint32_t configval;
852	int len = 11 + count * 4;
853
854	if (!iexec->execute)
855		return len;
856
857	BIOSLOG(bios, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, "
858		      "Shift: 0x%02X, Count: 0x%02X, Reg: 0x%08X\n",
859		offset, crtcport, crtcindex, mask, shift, count, reg);
860
861	config = (bios_idxprt_rd(bios, crtcport, crtcindex) & mask) >> shift;
862	if (config > count) {
863		NV_ERROR(bios->dev,
864			 "0x%04X: Config 0x%02X exceeds maximal bound 0x%02X\n",
865			 offset, config, count);
866		return len;
867	}
868
869	configval = ROM32(bios->data[offset + 11 + config * 4]);
870
871	BIOSLOG(bios, "0x%04X: Writing config %02X\n", offset, config);
872
873	bios_wr32(bios, reg, configval);
874
875	return len;
876}
877
878static int
879init_repeat(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
880{
881	/*
882	 * INIT_REPEAT   opcode: 0x33 ('3')
883	 *
884	 * offset      (8 bit): opcode
885	 * offset + 1  (8 bit): count
886	 *
887	 * Execute script following this opcode up to INIT_REPEAT_END
888	 * "count" times
889	 */
890
891	uint8_t count = bios->data[offset + 1];
892	uint8_t i;
893
894	/* no iexec->execute check by design */
895
896	BIOSLOG(bios, "0x%04X: Repeating following segment %d times\n",
897		offset, count);
898
899	iexec->repeat = true;
900
901	/*
902	 * count - 1, as the script block will execute once when we leave this
903	 * opcode -- this is compatible with bios behaviour as:
904	 * a) the block is always executed at least once, even if count == 0
905	 * b) the bios interpreter skips to the op following INIT_END_REPEAT,
906	 * while we don't
907	 */
908	for (i = 0; i < count - 1; i++)
909		parse_init_table(bios, offset + 2, iexec);
910
911	iexec->repeat = false;
912
913	return 2;
914}
915
916static int
917init_io_restrict_pll(struct nvbios *bios, uint16_t offset,
918		     struct init_exec *iexec)
919{
920	/*
921	 * INIT_IO_RESTRICT_PLL   opcode: 0x34 ('4')
922	 *
923	 * offset      (8  bit): opcode
924	 * offset + 1  (16 bit): CRTC port
925	 * offset + 3  (8  bit): CRTC index
926	 * offset + 4  (8  bit): mask
927	 * offset + 5  (8  bit): shift
928	 * offset + 6  (8  bit): IO flag condition index
929	 * offset + 7  (8  bit): count
930	 * offset + 8  (32 bit): register
931	 * offset + 12 (16 bit): frequency 1
932	 * ...
933	 *
934	 * Starting at offset + 12 there are "count" 16 bit frequencies (10kHz).
935	 * Set PLL register "register" to coefficients for frequency n,
936	 * selected by reading index "CRTC index" of "CRTC port" ANDed with
937	 * "mask" and shifted right by "shift".
938	 *
939	 * If "IO flag condition index" > 0, and condition met, double
940	 * frequency before setting it.
941	 */
942
943	uint16_t crtcport = ROM16(bios->data[offset + 1]);
944	uint8_t crtcindex = bios->data[offset + 3];
945	uint8_t mask = bios->data[offset + 4];
946	uint8_t shift = bios->data[offset + 5];
947	int8_t io_flag_condition_idx = bios->data[offset + 6];
948	uint8_t count = bios->data[offset + 7];
949	uint32_t reg = ROM32(bios->data[offset + 8]);
950	uint8_t config;
951	uint16_t freq;
952	int len = 12 + count * 2;
953
954	if (!iexec->execute)
955		return len;
956
957	BIOSLOG(bios, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, "
958		      "Shift: 0x%02X, IO Flag Condition: 0x%02X, "
959		      "Count: 0x%02X, Reg: 0x%08X\n",
960		offset, crtcport, crtcindex, mask, shift,
961		io_flag_condition_idx, count, reg);
962
963	config = (bios_idxprt_rd(bios, crtcport, crtcindex) & mask) >> shift;
964	if (config > count) {
965		NV_ERROR(bios->dev,
966			 "0x%04X: Config 0x%02X exceeds maximal bound 0x%02X\n",
967			 offset, config, count);
968		return len;
969	}
970
971	freq = ROM16(bios->data[offset + 12 + config * 2]);
972
973	if (io_flag_condition_idx > 0) {
974		if (io_flag_condition_met(bios, offset, io_flag_condition_idx)) {
975			BIOSLOG(bios, "0x%04X: Condition fulfilled -- "
976				      "frequency doubled\n", offset);
977			freq *= 2;
978		} else
979			BIOSLOG(bios, "0x%04X: Condition not fulfilled -- "
980				      "frequency unchanged\n", offset);
981	}
982
983	BIOSLOG(bios, "0x%04X: Reg: 0x%08X, Config: 0x%02X, Freq: %d0kHz\n",
984		offset, reg, config, freq);
985
986	setPLL(bios, reg, freq * 10);
987
988	return len;
989}
990
991static int
992init_end_repeat(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
993{
994	/*
995	 * INIT_END_REPEAT   opcode: 0x36 ('6')
996	 *
997	 * offset      (8 bit): opcode
998	 *
999	 * Marks the end of the block for INIT_REPEAT to repeat
1000	 */
1001
1002	/* no iexec->execute check by design */
1003
1004	/*
1005	 * iexec->repeat flag necessary to go past INIT_END_REPEAT opcode when
1006	 * we're not in repeat mode
1007	 */
1008	if (iexec->repeat)
1009		return 0;
1010
1011	return 1;
1012}
1013
1014static int
1015init_copy(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1016{
1017	/*
1018	 * INIT_COPY   opcode: 0x37 ('7')
1019	 *
1020	 * offset      (8  bit): opcode
1021	 * offset + 1  (32 bit): register
1022	 * offset + 5  (8  bit): shift
1023	 * offset + 6  (8  bit): srcmask
1024	 * offset + 7  (16 bit): CRTC port
1025	 * offset + 9  (8 bit): CRTC index
1026	 * offset + 10  (8 bit): mask
1027	 *
1028	 * Read index "CRTC index" on "CRTC port", AND with "mask", OR with
1029	 * (REGVAL("register") >> "shift" & "srcmask") and write-back to CRTC
1030	 * port
1031	 */
1032
1033	uint32_t reg = ROM32(bios->data[offset + 1]);
1034	uint8_t shift = bios->data[offset + 5];
1035	uint8_t srcmask = bios->data[offset + 6];
1036	uint16_t crtcport = ROM16(bios->data[offset + 7]);
1037	uint8_t crtcindex = bios->data[offset + 9];
1038	uint8_t mask = bios->data[offset + 10];
1039	uint32_t data;
1040	uint8_t crtcdata;
1041
1042	if (!iexec->execute)
1043		return 11;
1044
1045	BIOSLOG(bios, "0x%04X: Reg: 0x%08X, Shift: 0x%02X, SrcMask: 0x%02X, "
1046		      "Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X\n",
1047		offset, reg, shift, srcmask, crtcport, crtcindex, mask);
1048
1049	data = bios_rd32(bios, reg);
1050
1051	if (shift < 0x80)
1052		data >>= shift;
1053	else
1054		data <<= (0x100 - shift);
1055
1056	data &= srcmask;
1057
1058	crtcdata  = bios_idxprt_rd(bios, crtcport, crtcindex) & mask;
1059	crtcdata |= (uint8_t)data;
1060	bios_idxprt_wr(bios, crtcport, crtcindex, crtcdata);
1061
1062	return 11;
1063}
1064
1065static int
1066init_not(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1067{
1068	/*
1069	 * INIT_NOT   opcode: 0x38 ('8')
1070	 *
1071	 * offset      (8  bit): opcode
1072	 *
1073	 * Invert the current execute / no-execute condition (i.e. "else")
1074	 */
1075	if (iexec->execute)
1076		BIOSLOG(bios, "0x%04X: ------ Skipping following commands  ------\n", offset);
1077	else
1078		BIOSLOG(bios, "0x%04X: ------ Executing following commands ------\n", offset);
1079
1080	iexec->execute = !iexec->execute;
1081	return 1;
1082}
1083
1084static int
1085init_io_flag_condition(struct nvbios *bios, uint16_t offset,
1086		       struct init_exec *iexec)
1087{
1088	/*
1089	 * INIT_IO_FLAG_CONDITION   opcode: 0x39 ('9')
1090	 *
1091	 * offset      (8 bit): opcode
1092	 * offset + 1  (8 bit): condition number
1093	 *
1094	 * Check condition "condition number" in the IO flag condition table.
1095	 * If condition not met skip subsequent opcodes until condition is
1096	 * inverted (INIT_NOT), or we hit INIT_RESUME
1097	 */
1098
1099	uint8_t cond = bios->data[offset + 1];
1100
1101	if (!iexec->execute)
1102		return 2;
1103
1104	if (io_flag_condition_met(bios, offset, cond))
1105		BIOSLOG(bios, "0x%04X: Condition fulfilled -- continuing to execute\n", offset);
1106	else {
1107		BIOSLOG(bios, "0x%04X: Condition not fulfilled -- skipping following commands\n", offset);
1108		iexec->execute = false;
1109	}
1110
1111	return 2;
1112}
1113
1114static int
1115init_dp_condition(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1116{
1117	/*
1118	 * INIT_DP_CONDITION   opcode: 0x3A ('')
1119	 *
1120	 * offset      (8 bit): opcode
1121	 * offset + 1  (8 bit): "sub" opcode
1122	 * offset + 2  (8 bit): unknown
1123	 *
1124	 */
1125
1126	struct dcb_entry *dcb = bios->display.output;
1127	struct drm_device *dev = bios->dev;
1128	uint8_t cond = bios->data[offset + 1];
1129	uint8_t *table, *entry;
1130
1131	BIOSLOG(bios, "0x%04X: subop 0x%02X\n", offset, cond);
1132
1133	if (!iexec->execute)
1134		return 3;
1135
1136	table = nouveau_dp_bios_data(dev, dcb, &entry);
1137	if (!table)
1138		return 3;
1139
1140	switch (cond) {
1141	case 0:
1142		entry = dcb_conn(dev, dcb->connector);
1143		if (!entry || entry[0] != DCB_CONNECTOR_eDP)
1144			iexec->execute = false;
1145		break;
1146	case 1:
1147	case 2:
1148		if ((table[0]  < 0x40 && !(entry[5] & cond)) ||
1149		    (table[0] == 0x40 && !(entry[4] & cond)))
1150			iexec->execute = false;
1151		break;
1152	case 5:
1153	{
1154		struct nouveau_i2c_chan *auxch;
1155		int ret;
1156
1157		auxch = nouveau_i2c_find(dev, bios->display.output->i2c_index);
1158		if (!auxch) {
1159			NV_ERROR(dev, "0x%04X: couldn't get auxch\n", offset);
1160			return 3;
1161		}
1162
1163		ret = nouveau_dp_auxch(auxch, 9, 0xd, &cond, 1);
1164		if (ret) {
1165			NV_ERROR(dev, "0x%04X: auxch rd fail: %d\n", offset, ret);
1166			return 3;
1167		}
1168
1169		if (!(cond & 1))
1170			iexec->execute = false;
1171	}
1172		break;
1173	default:
1174		NV_WARN(dev, "0x%04X: unknown INIT_3A op: %d\n", offset, cond);
1175		break;
1176	}
1177
1178	if (iexec->execute)
1179		BIOSLOG(bios, "0x%04X: continuing to execute\n", offset);
1180	else
1181		BIOSLOG(bios, "0x%04X: skipping following commands\n", offset);
1182
1183	return 3;
1184}
1185
1186static int
1187init_op_3b(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1188{
1189	/*
1190	 * INIT_3B   opcode: 0x3B ('')
1191	 *
1192	 * offset      (8 bit): opcode
1193	 * offset + 1  (8 bit): crtc index
1194	 *
1195	 */
1196
1197	uint8_t or = ffs(bios->display.output->or) - 1;
1198	uint8_t index = bios->data[offset + 1];
1199	uint8_t data;
1200
1201	if (!iexec->execute)
1202		return 2;
1203
1204	data = bios_idxprt_rd(bios, 0x3d4, index);
1205	bios_idxprt_wr(bios, 0x3d4, index, data & ~(1 << or));
1206	return 2;
1207}
1208
1209static int
1210init_op_3c(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1211{
1212	/*
1213	 * INIT_3C   opcode: 0x3C ('')
1214	 *
1215	 * offset      (8 bit): opcode
1216	 * offset + 1  (8 bit): crtc index
1217	 *
1218	 */
1219
1220	uint8_t or = ffs(bios->display.output->or) - 1;
1221	uint8_t index = bios->data[offset + 1];
1222	uint8_t data;
1223
1224	if (!iexec->execute)
1225		return 2;
1226
1227	data = bios_idxprt_rd(bios, 0x3d4, index);
1228	bios_idxprt_wr(bios, 0x3d4, index, data | (1 << or));
1229	return 2;
1230}
1231
1232static int
1233init_idx_addr_latched(struct nvbios *bios, uint16_t offset,
1234		      struct init_exec *iexec)
1235{
1236	/*
1237	 * INIT_INDEX_ADDRESS_LATCHED   opcode: 0x49 ('I')
1238	 *
1239	 * offset      (8  bit): opcode
1240	 * offset + 1  (32 bit): control register
1241	 * offset + 5  (32 bit): data register
1242	 * offset + 9  (32 bit): mask
1243	 * offset + 13 (32 bit): data
1244	 * offset + 17 (8  bit): count
1245	 * offset + 18 (8  bit): address 1
1246	 * offset + 19 (8  bit): data 1
1247	 * ...
1248	 *
1249	 * For each of "count" address and data pairs, write "data n" to
1250	 * "data register", read the current value of "control register",
1251	 * and write it back once ANDed with "mask", ORed with "data",
1252	 * and ORed with "address n"
1253	 */
1254
1255	uint32_t controlreg = ROM32(bios->data[offset + 1]);
1256	uint32_t datareg = ROM32(bios->data[offset + 5]);
1257	uint32_t mask = ROM32(bios->data[offset + 9]);
1258	uint32_t data = ROM32(bios->data[offset + 13]);
1259	uint8_t count = bios->data[offset + 17];
1260	int len = 18 + count * 2;
1261	uint32_t value;
1262	int i;
1263
1264	if (!iexec->execute)
1265		return len;
1266
1267	BIOSLOG(bios, "0x%04X: ControlReg: 0x%08X, DataReg: 0x%08X, "
1268		      "Mask: 0x%08X, Data: 0x%08X, Count: 0x%02X\n",
1269		offset, controlreg, datareg, mask, data, count);
1270
1271	for (i = 0; i < count; i++) {
1272		uint8_t instaddress = bios->data[offset + 18 + i * 2];
1273		uint8_t instdata = bios->data[offset + 19 + i * 2];
1274
1275		BIOSLOG(bios, "0x%04X: Address: 0x%02X, Data: 0x%02X\n",
1276			offset, instaddress, instdata);
1277
1278		bios_wr32(bios, datareg, instdata);
1279		value  = bios_rd32(bios, controlreg) & mask;
1280		value |= data;
1281		value |= instaddress;
1282		bios_wr32(bios, controlreg, value);
1283	}
1284
1285	return len;
1286}
1287
1288static int
1289init_io_restrict_pll2(struct nvbios *bios, uint16_t offset,
1290		      struct init_exec *iexec)
1291{
1292	/*
1293	 * INIT_IO_RESTRICT_PLL2   opcode: 0x4A ('J')
1294	 *
1295	 * offset      (8  bit): opcode
1296	 * offset + 1  (16 bit): CRTC port
1297	 * offset + 3  (8  bit): CRTC index
1298	 * offset + 4  (8  bit): mask
1299	 * offset + 5  (8  bit): shift
1300	 * offset + 6  (8  bit): count
1301	 * offset + 7  (32 bit): register
1302	 * offset + 11 (32 bit): frequency 1
1303	 * ...
1304	 *
1305	 * Starting at offset + 11 there are "count" 32 bit frequencies (kHz).
1306	 * Set PLL register "register" to coefficients for frequency n,
1307	 * selected by reading index "CRTC index" of "CRTC port" ANDed with
1308	 * "mask" and shifted right by "shift".
1309	 */
1310
1311	uint16_t crtcport = ROM16(bios->data[offset + 1]);
1312	uint8_t crtcindex = bios->data[offset + 3];
1313	uint8_t mask = bios->data[offset + 4];
1314	uint8_t shift = bios->data[offset + 5];
1315	uint8_t count = bios->data[offset + 6];
1316	uint32_t reg = ROM32(bios->data[offset + 7]);
1317	int len = 11 + count * 4;
1318	uint8_t config;
1319	uint32_t freq;
1320
1321	if (!iexec->execute)
1322		return len;
1323
1324	BIOSLOG(bios, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, "
1325		      "Shift: 0x%02X, Count: 0x%02X, Reg: 0x%08X\n",
1326		offset, crtcport, crtcindex, mask, shift, count, reg);
1327
1328	if (!reg)
1329		return len;
1330
1331	config = (bios_idxprt_rd(bios, crtcport, crtcindex) & mask) >> shift;
1332	if (config > count) {
1333		NV_ERROR(bios->dev,
1334			 "0x%04X: Config 0x%02X exceeds maximal bound 0x%02X\n",
1335			 offset, config, count);
1336		return len;
1337	}
1338
1339	freq = ROM32(bios->data[offset + 11 + config * 4]);
1340
1341	BIOSLOG(bios, "0x%04X: Reg: 0x%08X, Config: 0x%02X, Freq: %dkHz\n",
1342		offset, reg, config, freq);
1343
1344	setPLL(bios, reg, freq);
1345
1346	return len;
1347}
1348
1349static int
1350init_pll2(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1351{
1352	/*
1353	 * INIT_PLL2   opcode: 0x4B ('K')
1354	 *
1355	 * offset      (8  bit): opcode
1356	 * offset + 1  (32 bit): register
1357	 * offset + 5  (32 bit): freq
1358	 *
1359	 * Set PLL register "register" to coefficients for frequency "freq"
1360	 */
1361
1362	uint32_t reg = ROM32(bios->data[offset + 1]);
1363	uint32_t freq = ROM32(bios->data[offset + 5]);
1364
1365	if (!iexec->execute)
1366		return 9;
1367
1368	BIOSLOG(bios, "0x%04X: Reg: 0x%04X, Freq: %dkHz\n",
1369		offset, reg, freq);
1370
1371	setPLL(bios, reg, freq);
1372	return 9;
1373}
1374
1375static int
1376init_i2c_byte(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1377{
1378	/*
1379	 * INIT_I2C_BYTE   opcode: 0x4C ('L')
1380	 *
1381	 * offset      (8 bit): opcode
1382	 * offset + 1  (8 bit): DCB I2C table entry index
1383	 * offset + 2  (8 bit): I2C slave address
1384	 * offset + 3  (8 bit): count
1385	 * offset + 4  (8 bit): I2C register 1
1386	 * offset + 5  (8 bit): mask 1
1387	 * offset + 6  (8 bit): data 1
1388	 * ...
1389	 *
1390	 * For each of "count" registers given by "I2C register n" on the device
1391	 * addressed by "I2C slave address" on the I2C bus given by
1392	 * "DCB I2C table entry index", read the register, AND the result with
1393	 * "mask n" and OR it with "data n" before writing it back to the device
1394	 */
1395
1396	struct drm_device *dev = bios->dev;
1397	uint8_t i2c_index = bios->data[offset + 1];
1398	uint8_t i2c_address = bios->data[offset + 2] >> 1;
1399	uint8_t count = bios->data[offset + 3];
1400	struct nouveau_i2c_chan *chan;
1401	int len = 4 + count * 3;
1402	int ret, i;
1403
1404	if (!iexec->execute)
1405		return len;
1406
1407	BIOSLOG(bios, "0x%04X: DCBI2CIndex: 0x%02X, I2CAddress: 0x%02X, "
1408		      "Count: 0x%02X\n",
1409		offset, i2c_index, i2c_address, count);
1410
1411	chan = init_i2c_device_find(dev, i2c_index);
1412	if (!chan) {
1413		NV_ERROR(dev, "0x%04X: i2c bus not found\n", offset);
1414		return len;
1415	}
1416
1417	for (i = 0; i < count; i++) {
1418		uint8_t reg = bios->data[offset + 4 + i * 3];
1419		uint8_t mask = bios->data[offset + 5 + i * 3];
1420		uint8_t data = bios->data[offset + 6 + i * 3];
1421		union i2c_smbus_data val;
1422
1423		ret = i2c_smbus_xfer(&chan->adapter, i2c_address, 0,
1424				     I2C_SMBUS_READ, reg,
1425				     I2C_SMBUS_BYTE_DATA, &val);
1426		if (ret < 0) {
1427			NV_ERROR(dev, "0x%04X: i2c rd fail: %d\n", offset, ret);
1428			return len;
1429		}
1430
1431		BIOSLOG(bios, "0x%04X: I2CReg: 0x%02X, Value: 0x%02X, "
1432			      "Mask: 0x%02X, Data: 0x%02X\n",
1433			offset, reg, val.byte, mask, data);
1434
1435		if (!bios->execute)
1436			continue;
1437
1438		val.byte &= mask;
1439		val.byte |= data;
1440		ret = i2c_smbus_xfer(&chan->adapter, i2c_address, 0,
1441				     I2C_SMBUS_WRITE, reg,
1442				     I2C_SMBUS_BYTE_DATA, &val);
1443		if (ret < 0) {
1444			NV_ERROR(dev, "0x%04X: i2c wr fail: %d\n", offset, ret);
1445			return len;
1446		}
1447	}
1448
1449	return len;
1450}
1451
1452static int
1453init_zm_i2c_byte(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1454{
1455	/*
1456	 * INIT_ZM_I2C_BYTE   opcode: 0x4D ('M')
1457	 *
1458	 * offset      (8 bit): opcode
1459	 * offset + 1  (8 bit): DCB I2C table entry index
1460	 * offset + 2  (8 bit): I2C slave address
1461	 * offset + 3  (8 bit): count
1462	 * offset + 4  (8 bit): I2C register 1
1463	 * offset + 5  (8 bit): data 1
1464	 * ...
1465	 *
1466	 * For each of "count" registers given by "I2C register n" on the device
1467	 * addressed by "I2C slave address" on the I2C bus given by
1468	 * "DCB I2C table entry index", set the register to "data n"
1469	 */
1470
1471	struct drm_device *dev = bios->dev;
1472	uint8_t i2c_index = bios->data[offset + 1];
1473	uint8_t i2c_address = bios->data[offset + 2] >> 1;
1474	uint8_t count = bios->data[offset + 3];
1475	struct nouveau_i2c_chan *chan;
1476	int len = 4 + count * 2;
1477	int ret, i;
1478
1479	if (!iexec->execute)
1480		return len;
1481
1482	BIOSLOG(bios, "0x%04X: DCBI2CIndex: 0x%02X, I2CAddress: 0x%02X, "
1483		      "Count: 0x%02X\n",
1484		offset, i2c_index, i2c_address, count);
1485
1486	chan = init_i2c_device_find(dev, i2c_index);
1487	if (!chan) {
1488		NV_ERROR(dev, "0x%04X: i2c bus not found\n", offset);
1489		return len;
1490	}
1491
1492	for (i = 0; i < count; i++) {
1493		uint8_t reg = bios->data[offset + 4 + i * 2];
1494		union i2c_smbus_data val;
1495
1496		val.byte = bios->data[offset + 5 + i * 2];
1497
1498		BIOSLOG(bios, "0x%04X: I2CReg: 0x%02X, Data: 0x%02X\n",
1499			offset, reg, val.byte);
1500
1501		if (!bios->execute)
1502			continue;
1503
1504		ret = i2c_smbus_xfer(&chan->adapter, i2c_address, 0,
1505				     I2C_SMBUS_WRITE, reg,
1506				     I2C_SMBUS_BYTE_DATA, &val);
1507		if (ret < 0) {
1508			NV_ERROR(dev, "0x%04X: i2c wr fail: %d\n", offset, ret);
1509			return len;
1510		}
1511	}
1512
1513	return len;
1514}
1515
1516static int
1517init_zm_i2c(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1518{
1519	/*
1520	 * INIT_ZM_I2C   opcode: 0x4E ('N')
1521	 *
1522	 * offset      (8 bit): opcode
1523	 * offset + 1  (8 bit): DCB I2C table entry index
1524	 * offset + 2  (8 bit): I2C slave address
1525	 * offset + 3  (8 bit): count
1526	 * offset + 4  (8 bit): data 1
1527	 * ...
1528	 *
1529	 * Send "count" bytes ("data n") to the device addressed by "I2C slave
1530	 * address" on the I2C bus given by "DCB I2C table entry index"
1531	 */
1532
1533	struct drm_device *dev = bios->dev;
1534	uint8_t i2c_index = bios->data[offset + 1];
1535	uint8_t i2c_address = bios->data[offset + 2] >> 1;
1536	uint8_t count = bios->data[offset + 3];
1537	int len = 4 + count;
1538	struct nouveau_i2c_chan *chan;
1539	struct i2c_msg msg;
1540	uint8_t data[256];
1541	int ret, i;
1542
1543	if (!iexec->execute)
1544		return len;
1545
1546	BIOSLOG(bios, "0x%04X: DCBI2CIndex: 0x%02X, I2CAddress: 0x%02X, "
1547		      "Count: 0x%02X\n",
1548		offset, i2c_index, i2c_address, count);
1549
1550	chan = init_i2c_device_find(dev, i2c_index);
1551	if (!chan) {
1552		NV_ERROR(dev, "0x%04X: i2c bus not found\n", offset);
1553		return len;
1554	}
1555
1556	for (i = 0; i < count; i++) {
1557		data[i] = bios->data[offset + 4 + i];
1558
1559		BIOSLOG(bios, "0x%04X: Data: 0x%02X\n", offset, data[i]);
1560	}
1561
1562	if (bios->execute) {
1563		msg.addr = i2c_address;
1564		msg.flags = 0;
1565		msg.len = count;
1566		msg.buf = data;
1567		ret = i2c_transfer(&chan->adapter, &msg, 1);
1568		if (ret != 1) {
1569			NV_ERROR(dev, "0x%04X: i2c wr fail: %d\n", offset, ret);
1570			return len;
1571		}
1572	}
1573
1574	return len;
1575}
1576
1577static int
1578init_tmds(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1579{
1580	/*
1581	 * INIT_TMDS   opcode: 0x4F ('O')	(non-canon name)
1582	 *
1583	 * offset      (8 bit): opcode
1584	 * offset + 1  (8 bit): magic lookup value
1585	 * offset + 2  (8 bit): TMDS address
1586	 * offset + 3  (8 bit): mask
1587	 * offset + 4  (8 bit): data
1588	 *
1589	 * Read the data reg for TMDS address "TMDS address", AND it with mask
1590	 * and OR it with data, then write it back
1591	 * "magic lookup value" determines which TMDS base address register is
1592	 * used -- see get_tmds_index_reg()
1593	 */
1594
1595	struct drm_device *dev = bios->dev;
1596	uint8_t mlv = bios->data[offset + 1];
1597	uint32_t tmdsaddr = bios->data[offset + 2];
1598	uint8_t mask = bios->data[offset + 3];
1599	uint8_t data = bios->data[offset + 4];
1600	uint32_t reg, value;
1601
1602	if (!iexec->execute)
1603		return 5;
1604
1605	BIOSLOG(bios, "0x%04X: MagicLookupValue: 0x%02X, TMDSAddr: 0x%02X, "
1606		      "Mask: 0x%02X, Data: 0x%02X\n",
1607		offset, mlv, tmdsaddr, mask, data);
1608
1609	reg = get_tmds_index_reg(bios->dev, mlv);
1610	if (!reg) {
1611		NV_ERROR(dev, "0x%04X: no tmds_index_reg\n", offset);
1612		return 5;
1613	}
1614
1615	bios_wr32(bios, reg,
1616		  tmdsaddr | NV_PRAMDAC_FP_TMDS_CONTROL_WRITE_DISABLE);
1617	value = (bios_rd32(bios, reg + 4) & mask) | data;
1618	bios_wr32(bios, reg + 4, value);
1619	bios_wr32(bios, reg, tmdsaddr);
1620
1621	return 5;
1622}
1623
1624static int
1625init_zm_tmds_group(struct nvbios *bios, uint16_t offset,
1626		   struct init_exec *iexec)
1627{
1628	/*
1629	 * INIT_ZM_TMDS_GROUP   opcode: 0x50 ('P')	(non-canon name)
1630	 *
1631	 * offset      (8 bit): opcode
1632	 * offset + 1  (8 bit): magic lookup value
1633	 * offset + 2  (8 bit): count
1634	 * offset + 3  (8 bit): addr 1
1635	 * offset + 4  (8 bit): data 1
1636	 * ...
1637	 *
1638	 * For each of "count" TMDS address and data pairs write "data n" to
1639	 * "addr n".  "magic lookup value" determines which TMDS base address
1640	 * register is used -- see get_tmds_index_reg()
1641	 */
1642
1643	struct drm_device *dev = bios->dev;
1644	uint8_t mlv = bios->data[offset + 1];
1645	uint8_t count = bios->data[offset + 2];
1646	int len = 3 + count * 2;
1647	uint32_t reg;
1648	int i;
1649
1650	if (!iexec->execute)
1651		return len;
1652
1653	BIOSLOG(bios, "0x%04X: MagicLookupValue: 0x%02X, Count: 0x%02X\n",
1654		offset, mlv, count);
1655
1656	reg = get_tmds_index_reg(bios->dev, mlv);
1657	if (!reg) {
1658		NV_ERROR(dev, "0x%04X: no tmds_index_reg\n", offset);
1659		return len;
1660	}
1661
1662	for (i = 0; i < count; i++) {
1663		uint8_t tmdsaddr = bios->data[offset + 3 + i * 2];
1664		uint8_t tmdsdata = bios->data[offset + 4 + i * 2];
1665
1666		bios_wr32(bios, reg + 4, tmdsdata);
1667		bios_wr32(bios, reg, tmdsaddr);
1668	}
1669
1670	return len;
1671}
1672
1673static int
1674init_cr_idx_adr_latch(struct nvbios *bios, uint16_t offset,
1675		      struct init_exec *iexec)
1676{
1677	/*
1678	 * INIT_CR_INDEX_ADDRESS_LATCHED   opcode: 0x51 ('Q')
1679	 *
1680	 * offset      (8 bit): opcode
1681	 * offset + 1  (8 bit): CRTC index1
1682	 * offset + 2  (8 bit): CRTC index2
1683	 * offset + 3  (8 bit): baseaddr
1684	 * offset + 4  (8 bit): count
1685	 * offset + 5  (8 bit): data 1
1686	 * ...
1687	 *
1688	 * For each of "count" address and data pairs, write "baseaddr + n" to
1689	 * "CRTC index1" and "data n" to "CRTC index2"
1690	 * Once complete, restore initial value read from "CRTC index1"
1691	 */
1692	uint8_t crtcindex1 = bios->data[offset + 1];
1693	uint8_t crtcindex2 = bios->data[offset + 2];
1694	uint8_t baseaddr = bios->data[offset + 3];
1695	uint8_t count = bios->data[offset + 4];
1696	int len = 5 + count;
1697	uint8_t oldaddr, data;
1698	int i;
1699
1700	if (!iexec->execute)
1701		return len;
1702
1703	BIOSLOG(bios, "0x%04X: Index1: 0x%02X, Index2: 0x%02X, "
1704		      "BaseAddr: 0x%02X, Count: 0x%02X\n",
1705		offset, crtcindex1, crtcindex2, baseaddr, count);
1706
1707	oldaddr = bios_idxprt_rd(bios, NV_CIO_CRX__COLOR, crtcindex1);
1708
1709	for (i = 0; i < count; i++) {
1710		bios_idxprt_wr(bios, NV_CIO_CRX__COLOR, crtcindex1,
1711				     baseaddr + i);
1712		data = bios->data[offset + 5 + i];
1713		bios_idxprt_wr(bios, NV_CIO_CRX__COLOR, crtcindex2, data);
1714	}
1715
1716	bios_idxprt_wr(bios, NV_CIO_CRX__COLOR, crtcindex1, oldaddr);
1717
1718	return len;
1719}
1720
1721static int
1722init_cr(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1723{
1724	/*
1725	 * INIT_CR   opcode: 0x52 ('R')
1726	 *
1727	 * offset      (8  bit): opcode
1728	 * offset + 1  (8  bit): CRTC index
1729	 * offset + 2  (8  bit): mask
1730	 * offset + 3  (8  bit): data
1731	 *
1732	 * Assign the value of at "CRTC index" ANDed with mask and ORed with
1733	 * data back to "CRTC index"
1734	 */
1735
1736	uint8_t crtcindex = bios->data[offset + 1];
1737	uint8_t mask = bios->data[offset + 2];
1738	uint8_t data = bios->data[offset + 3];
1739	uint8_t value;
1740
1741	if (!iexec->execute)
1742		return 4;
1743
1744	BIOSLOG(bios, "0x%04X: Index: 0x%02X, Mask: 0x%02X, Data: 0x%02X\n",
1745		offset, crtcindex, mask, data);
1746
1747	value  = bios_idxprt_rd(bios, NV_CIO_CRX__COLOR, crtcindex) & mask;
1748	value |= data;
1749	bios_idxprt_wr(bios, NV_CIO_CRX__COLOR, crtcindex, value);
1750
1751	return 4;
1752}
1753
1754static int
1755init_zm_cr(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1756{
1757	/*
1758	 * INIT_ZM_CR   opcode: 0x53 ('S')
1759	 *
1760	 * offset      (8 bit): opcode
1761	 * offset + 1  (8 bit): CRTC index
1762	 * offset + 2  (8 bit): value
1763	 *
1764	 * Assign "value" to CRTC register with index "CRTC index".
1765	 */
1766
1767	uint8_t crtcindex = ROM32(bios->data[offset + 1]);
1768	uint8_t data = bios->data[offset + 2];
1769
1770	if (!iexec->execute)
1771		return 3;
1772
1773	bios_idxprt_wr(bios, NV_CIO_CRX__COLOR, crtcindex, data);
1774
1775	return 3;
1776}
1777
1778static int
1779init_zm_cr_group(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1780{
1781	/*
1782	 * INIT_ZM_CR_GROUP   opcode: 0x54 ('T')
1783	 *
1784	 * offset      (8 bit): opcode
1785	 * offset + 1  (8 bit): count
1786	 * offset + 2  (8 bit): CRTC index 1
1787	 * offset + 3  (8 bit): value 1
1788	 * ...
1789	 *
1790	 * For "count", assign "value n" to CRTC register with index
1791	 * "CRTC index n".
1792	 */
1793
1794	uint8_t count = bios->data[offset + 1];
1795	int len = 2 + count * 2;
1796	int i;
1797
1798	if (!iexec->execute)
1799		return len;
1800
1801	for (i = 0; i < count; i++)
1802		init_zm_cr(bios, offset + 2 + 2 * i - 1, iexec);
1803
1804	return len;
1805}
1806
1807static int
1808init_condition_time(struct nvbios *bios, uint16_t offset,
1809		    struct init_exec *iexec)
1810{
1811	/*
1812	 * INIT_CONDITION_TIME   opcode: 0x56 ('V')
1813	 *
1814	 * offset      (8 bit): opcode
1815	 * offset + 1  (8 bit): condition number
1816	 * offset + 2  (8 bit): retries / 50
1817	 *
1818	 * Check condition "condition number" in the condition table.
1819	 * Bios code then sleeps for 2ms if the condition is not met, and
1820	 * repeats up to "retries" times, but on one C51 this has proved
1821	 * insufficient.  In mmiotraces the driver sleeps for 20ms, so we do
1822	 * this, and bail after "retries" times, or 2s, whichever is less.
1823	 * If still not met after retries, clear execution flag for this table.
1824	 */
1825
1826	uint8_t cond = bios->data[offset + 1];
1827	uint16_t retries = bios->data[offset + 2] * 50;
1828	unsigned cnt;
1829
1830	if (!iexec->execute)
1831		return 3;
1832
1833	if (retries > 100)
1834		retries = 100;
1835
1836	BIOSLOG(bios, "0x%04X: Condition: 0x%02X, Retries: 0x%02X\n",
1837		offset, cond, retries);
1838
1839	if (!bios->execute) /* avoid 2s delays when "faking" execution */
1840		retries = 1;
1841
1842	for (cnt = 0; cnt < retries; cnt++) {
1843		if (bios_condition_met(bios, offset, cond)) {
1844			BIOSLOG(bios, "0x%04X: Condition met, continuing\n",
1845								offset);
1846			break;
1847		} else {
1848			BIOSLOG(bios, "0x%04X: "
1849				"Condition not met, sleeping for 20ms\n",
1850								offset);
1851			mdelay(20);
1852		}
1853	}
1854
1855	if (!bios_condition_met(bios, offset, cond)) {
1856		NV_WARN(bios->dev,
1857			"0x%04X: Condition still not met after %dms, "
1858			"skipping following opcodes\n", offset, 20 * retries);
1859		iexec->execute = false;
1860	}
1861
1862	return 3;
1863}
1864
1865static int
1866init_ltime(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1867{
1868	/*
1869	 * INIT_LTIME   opcode: 0x57 ('V')
1870	 *
1871	 * offset      (8  bit): opcode
1872	 * offset + 1  (16 bit): time
1873	 *
1874	 * Sleep for "time" milliseconds.
1875	 */
1876
1877	unsigned time = ROM16(bios->data[offset + 1]);
1878
1879	if (!iexec->execute)
1880		return 3;
1881
1882	BIOSLOG(bios, "0x%04X: Sleeping for 0x%04X milliseconds\n",
1883		offset, time);
1884
1885	mdelay(time);
1886
1887	return 3;
1888}
1889
1890static int
1891init_zm_reg_sequence(struct nvbios *bios, uint16_t offset,
1892		     struct init_exec *iexec)
1893{
1894	/*
1895	 * INIT_ZM_REG_SEQUENCE   opcode: 0x58 ('X')
1896	 *
1897	 * offset      (8  bit): opcode
1898	 * offset + 1  (32 bit): base register
1899	 * offset + 5  (8  bit): count
1900	 * offset + 6  (32 bit): value 1
1901	 * ...
1902	 *
1903	 * Starting at offset + 6 there are "count" 32 bit values.
1904	 * For "count" iterations set "base register" + 4 * current_iteration
1905	 * to "value current_iteration"
1906	 */
1907
1908	uint32_t basereg = ROM32(bios->data[offset + 1]);
1909	uint32_t count = bios->data[offset + 5];
1910	int len = 6 + count * 4;
1911	int i;
1912
1913	if (!iexec->execute)
1914		return len;
1915
1916	BIOSLOG(bios, "0x%04X: BaseReg: 0x%08X, Count: 0x%02X\n",
1917		offset, basereg, count);
1918
1919	for (i = 0; i < count; i++) {
1920		uint32_t reg = basereg + i * 4;
1921		uint32_t data = ROM32(bios->data[offset + 6 + i * 4]);
1922
1923		bios_wr32(bios, reg, data);
1924	}
1925
1926	return len;
1927}
1928
1929static int
1930init_sub_direct(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1931{
1932	/*
1933	 * INIT_SUB_DIRECT   opcode: 0x5B ('[')
1934	 *
1935	 * offset      (8  bit): opcode
1936	 * offset + 1  (16 bit): subroutine offset (in bios)
1937	 *
1938	 * Calls a subroutine that will execute commands until INIT_DONE
1939	 * is found.
1940	 */
1941
1942	uint16_t sub_offset = ROM16(bios->data[offset + 1]);
1943
1944	if (!iexec->execute)
1945		return 3;
1946
1947	BIOSLOG(bios, "0x%04X: Executing subroutine at 0x%04X\n",
1948		offset, sub_offset);
1949
1950	parse_init_table(bios, sub_offset, iexec);
1951
1952	BIOSLOG(bios, "0x%04X: End of 0x%04X subroutine\n", offset, sub_offset);
1953
1954	return 3;
1955}
1956
1957static int
1958init_jump(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1959{
1960	/*
1961	 * INIT_JUMP   opcode: 0x5C ('\')
1962	 *
1963	 * offset      (8  bit): opcode
1964	 * offset + 1  (16 bit): offset (in bios)
1965	 *
1966	 * Continue execution of init table from 'offset'
1967	 */
1968
1969	uint16_t jmp_offset = ROM16(bios->data[offset + 1]);
1970
1971	if (!iexec->execute)
1972		return 3;
1973
1974	BIOSLOG(bios, "0x%04X: Jump to 0x%04X\n", offset, jmp_offset);
1975	return jmp_offset - offset;
1976}
1977
1978static int
1979init_i2c_if(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
1980{
1981	/*
1982	 * INIT_I2C_IF   opcode: 0x5E ('^')
1983	 *
1984	 * offset      (8 bit): opcode
1985	 * offset + 1  (8 bit): DCB I2C table entry index
1986	 * offset + 2  (8 bit): I2C slave address
1987	 * offset + 3  (8 bit): I2C register
1988	 * offset + 4  (8 bit): mask
1989	 * offset + 5  (8 bit): data
1990	 *
1991	 * Read the register given by "I2C register" on the device addressed
1992	 * by "I2C slave address" on the I2C bus given by "DCB I2C table
1993	 * entry index". Compare the result AND "mask" to "data".
1994	 * If they're not equal, skip subsequent opcodes until condition is
1995	 * inverted (INIT_NOT), or we hit INIT_RESUME
1996	 */
1997
1998	uint8_t i2c_index = bios->data[offset + 1];
1999	uint8_t i2c_address = bios->data[offset + 2] >> 1;
2000	uint8_t reg = bios->data[offset + 3];
2001	uint8_t mask = bios->data[offset + 4];
2002	uint8_t data = bios->data[offset + 5];
2003	struct nouveau_i2c_chan *chan;
2004	union i2c_smbus_data val;
2005	int ret;
2006
2007	/* no execute check by design */
2008
2009	BIOSLOG(bios, "0x%04X: DCBI2CIndex: 0x%02X, I2CAddress: 0x%02X\n",
2010		offset, i2c_index, i2c_address);
2011
2012	chan = init_i2c_device_find(bios->dev, i2c_index);
2013	if (!chan)
2014		return -ENODEV;
2015
2016	ret = i2c_smbus_xfer(&chan->adapter, i2c_address, 0,
2017			     I2C_SMBUS_READ, reg,
2018			     I2C_SMBUS_BYTE_DATA, &val);
2019	if (ret < 0) {
2020		BIOSLOG(bios, "0x%04X: I2CReg: 0x%02X, Value: [no device], "
2021			      "Mask: 0x%02X, Data: 0x%02X\n",
2022			offset, reg, mask, data);
2023		iexec->execute = 0;
2024		return 6;
2025	}
2026
2027	BIOSLOG(bios, "0x%04X: I2CReg: 0x%02X, Value: 0x%02X, "
2028		      "Mask: 0x%02X, Data: 0x%02X\n",
2029		offset, reg, val.byte, mask, data);
2030
2031	iexec->execute = ((val.byte & mask) == data);
2032
2033	return 6;
2034}
2035
2036static int
2037init_copy_nv_reg(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2038{
2039	/*
2040	 * INIT_COPY_NV_REG   opcode: 0x5F ('_')
2041	 *
2042	 * offset      (8  bit): opcode
2043	 * offset + 1  (32 bit): src reg
2044	 * offset + 5  (8  bit): shift
2045	 * offset + 6  (32 bit): src mask
2046	 * offset + 10 (32 bit): xor
2047	 * offset + 14 (32 bit): dst reg
2048	 * offset + 18 (32 bit): dst mask
2049	 *
2050	 * Shift REGVAL("src reg") right by (signed) "shift", AND result with
2051	 * "src mask", then XOR with "xor". Write this OR'd with
2052	 * (REGVAL("dst reg") AND'd with "dst mask") to "dst reg"
2053	 */
2054
2055	uint32_t srcreg = *((uint32_t *)(&bios->data[offset + 1]));
2056	uint8_t shift = bios->data[offset + 5];
2057	uint32_t srcmask = *((uint32_t *)(&bios->data[offset + 6]));
2058	uint32_t xor = *((uint32_t *)(&bios->data[offset + 10]));
2059	uint32_t dstreg = *((uint32_t *)(&bios->data[offset + 14]));
2060	uint32_t dstmask = *((uint32_t *)(&bios->data[offset + 18]));
2061	uint32_t srcvalue, dstvalue;
2062
2063	if (!iexec->execute)
2064		return 22;
2065
2066	BIOSLOG(bios, "0x%04X: SrcReg: 0x%08X, Shift: 0x%02X, SrcMask: 0x%08X, "
2067		      "Xor: 0x%08X, DstReg: 0x%08X, DstMask: 0x%08X\n",
2068		offset, srcreg, shift, srcmask, xor, dstreg, dstmask);
2069
2070	srcvalue = bios_rd32(bios, srcreg);
2071
2072	if (shift < 0x80)
2073		srcvalue >>= shift;
2074	else
2075		srcvalue <<= (0x100 - shift);
2076
2077	srcvalue = (srcvalue & srcmask) ^ xor;
2078
2079	dstvalue = bios_rd32(bios, dstreg) & dstmask;
2080
2081	bios_wr32(bios, dstreg, dstvalue | srcvalue);
2082
2083	return 22;
2084}
2085
2086static int
2087init_zm_index_io(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2088{
2089	/*
2090	 * INIT_ZM_INDEX_IO   opcode: 0x62 ('b')
2091	 *
2092	 * offset      (8  bit): opcode
2093	 * offset + 1  (16 bit): CRTC port
2094	 * offset + 3  (8  bit): CRTC index
2095	 * offset + 4  (8  bit): data
2096	 *
2097	 * Write "data" to index "CRTC index" of "CRTC port"
2098	 */
2099	uint16_t crtcport = ROM16(bios->data[offset + 1]);
2100	uint8_t crtcindex = bios->data[offset + 3];
2101	uint8_t data = bios->data[offset + 4];
2102
2103	if (!iexec->execute)
2104		return 5;
2105
2106	bios_idxprt_wr(bios, crtcport, crtcindex, data);
2107
2108	return 5;
2109}
2110
2111static inline void
2112bios_md32(struct nvbios *bios, uint32_t reg,
2113	  uint32_t mask, uint32_t val)
2114{
2115	bios_wr32(bios, reg, (bios_rd32(bios, reg) & ~mask) | val);
2116}
2117
2118static uint32_t
2119peek_fb(struct drm_device *dev, struct io_mapping *fb,
2120	uint32_t off)
2121{
2122	uint32_t val = 0;
2123
2124	if (off < pci_resource_len(dev->pdev, 1)) {
2125		uint8_t __iomem *p =
2126			io_mapping_map_atomic_wc(fb, off & PAGE_MASK);
2127
2128		val = ioread32(p + (off & ~PAGE_MASK));
2129
2130		io_mapping_unmap_atomic(p);
2131	}
2132
2133	return val;
2134}
2135
2136static void
2137poke_fb(struct drm_device *dev, struct io_mapping *fb,
2138	uint32_t off, uint32_t val)
2139{
2140	if (off < pci_resource_len(dev->pdev, 1)) {
2141		uint8_t __iomem *p =
2142			io_mapping_map_atomic_wc(fb, off & PAGE_MASK);
2143
2144		iowrite32(val, p + (off & ~PAGE_MASK));
2145		wmb();
2146
2147		io_mapping_unmap_atomic(p);
2148	}
2149}
2150
2151static inline bool
2152read_back_fb(struct drm_device *dev, struct io_mapping *fb,
2153	     uint32_t off, uint32_t val)
2154{
2155	poke_fb(dev, fb, off, val);
2156	return val == peek_fb(dev, fb, off);
2157}
2158
2159static int
2160nv04_init_compute_mem(struct nvbios *bios)
2161{
2162	struct drm_device *dev = bios->dev;
2163	uint32_t patt = 0xdeadbeef;
2164	struct io_mapping *fb;
2165	int i;
2166
2167	/* Map the framebuffer aperture */
2168	fb = io_mapping_create_wc(pci_resource_start(dev->pdev, 1),
2169				  pci_resource_len(dev->pdev, 1));
2170	if (!fb)
2171		return -ENOMEM;
2172
2173	/* Sequencer and refresh off */
2174	NVWriteVgaSeq(dev, 0, 1, NVReadVgaSeq(dev, 0, 1) | 0x20);
2175	bios_md32(bios, NV04_PFB_DEBUG_0, 0, NV04_PFB_DEBUG_0_REFRESH_OFF);
2176
2177	bios_md32(bios, NV04_PFB_BOOT_0, ~0,
2178		  NV04_PFB_BOOT_0_RAM_AMOUNT_16MB |
2179		  NV04_PFB_BOOT_0_RAM_WIDTH_128 |
2180		  NV04_PFB_BOOT_0_RAM_TYPE_SGRAM_16MBIT);
2181
2182	for (i = 0; i < 4; i++)
2183		poke_fb(dev, fb, 4 * i, patt);
2184
2185	poke_fb(dev, fb, 0x400000, patt + 1);
2186
2187	if (peek_fb(dev, fb, 0) == patt + 1) {
2188		bios_md32(bios, NV04_PFB_BOOT_0, NV04_PFB_BOOT_0_RAM_TYPE,
2189			  NV04_PFB_BOOT_0_RAM_TYPE_SDRAM_16MBIT);
2190		bios_md32(bios, NV04_PFB_DEBUG_0,
2191			  NV04_PFB_DEBUG_0_REFRESH_OFF, 0);
2192
2193		for (i = 0; i < 4; i++)
2194			poke_fb(dev, fb, 4 * i, patt);
2195
2196		if ((peek_fb(dev, fb, 0xc) & 0xffff) != (patt & 0xffff))
2197			bios_md32(bios, NV04_PFB_BOOT_0,
2198				  NV04_PFB_BOOT_0_RAM_WIDTH_128 |
2199				  NV04_PFB_BOOT_0_RAM_AMOUNT,
2200				  NV04_PFB_BOOT_0_RAM_AMOUNT_8MB);
2201
2202	} else if ((peek_fb(dev, fb, 0xc) & 0xffff0000) !=
2203		   (patt & 0xffff0000)) {
2204		bios_md32(bios, NV04_PFB_BOOT_0,
2205			  NV04_PFB_BOOT_0_RAM_WIDTH_128 |
2206			  NV04_PFB_BOOT_0_RAM_AMOUNT,
2207			  NV04_PFB_BOOT_0_RAM_AMOUNT_4MB);
2208
2209	} else if (peek_fb(dev, fb, 0) != patt) {
2210		if (read_back_fb(dev, fb, 0x800000, patt))
2211			bios_md32(bios, NV04_PFB_BOOT_0,
2212				  NV04_PFB_BOOT_0_RAM_AMOUNT,
2213				  NV04_PFB_BOOT_0_RAM_AMOUNT_8MB);
2214		else
2215			bios_md32(bios, NV04_PFB_BOOT_0,
2216				  NV04_PFB_BOOT_0_RAM_AMOUNT,
2217				  NV04_PFB_BOOT_0_RAM_AMOUNT_4MB);
2218
2219		bios_md32(bios, NV04_PFB_BOOT_0, NV04_PFB_BOOT_0_RAM_TYPE,
2220			  NV04_PFB_BOOT_0_RAM_TYPE_SGRAM_8MBIT);
2221
2222	} else if (!read_back_fb(dev, fb, 0x800000, patt)) {
2223		bios_md32(bios, NV04_PFB_BOOT_0, NV04_PFB_BOOT_0_RAM_AMOUNT,
2224			  NV04_PFB_BOOT_0_RAM_AMOUNT_8MB);
2225
2226	}
2227
2228	/* Refresh on, sequencer on */
2229	bios_md32(bios, NV04_PFB_DEBUG_0, NV04_PFB_DEBUG_0_REFRESH_OFF, 0);
2230	NVWriteVgaSeq(dev, 0, 1, NVReadVgaSeq(dev, 0, 1) & ~0x20);
2231
2232	io_mapping_free(fb);
2233	return 0;
2234}
2235
2236static const uint8_t *
2237nv05_memory_config(struct nvbios *bios)
2238{
2239	/* Defaults for BIOSes lacking a memory config table */
2240	static const uint8_t default_config_tab[][2] = {
2241		{ 0x24, 0x00 },
2242		{ 0x28, 0x00 },
2243		{ 0x24, 0x01 },
2244		{ 0x1f, 0x00 },
2245		{ 0x0f, 0x00 },
2246		{ 0x17, 0x00 },
2247		{ 0x06, 0x00 },
2248		{ 0x00, 0x00 }
2249	};
2250	int i = (bios_rd32(bios, NV_PEXTDEV_BOOT_0) &
2251		 NV_PEXTDEV_BOOT_0_RAMCFG) >> 2;
2252
2253	if (bios->legacy.mem_init_tbl_ptr)
2254		return &bios->data[bios->legacy.mem_init_tbl_ptr + 2 * i];
2255	else
2256		return default_config_tab[i];
2257}
2258
2259static int
2260nv05_init_compute_mem(struct nvbios *bios)
2261{
2262	struct drm_device *dev = bios->dev;
2263	const uint8_t *ramcfg = nv05_memory_config(bios);
2264	uint32_t patt = 0xdeadbeef;
2265	struct io_mapping *fb;
2266	int i, v;
2267
2268	/* Map the framebuffer aperture */
2269	fb = io_mapping_create_wc(pci_resource_start(dev->pdev, 1),
2270				  pci_resource_len(dev->pdev, 1));
2271	if (!fb)
2272		return -ENOMEM;
2273
2274	/* Sequencer off */
2275	NVWriteVgaSeq(dev, 0, 1, NVReadVgaSeq(dev, 0, 1) | 0x20);
2276
2277	if (bios_rd32(bios, NV04_PFB_BOOT_0) & NV04_PFB_BOOT_0_UMA_ENABLE)
2278		goto out;
2279
2280	bios_md32(bios, NV04_PFB_DEBUG_0, NV04_PFB_DEBUG_0_REFRESH_OFF, 0);
2281
2282	/* If present load the hardcoded scrambling table */
2283	if (bios->legacy.mem_init_tbl_ptr) {
2284		uint32_t *scramble_tab = (uint32_t *)&bios->data[
2285			bios->legacy.mem_init_tbl_ptr + 0x10];
2286
2287		for (i = 0; i < 8; i++)
2288			bios_wr32(bios, NV04_PFB_SCRAMBLE(i),
2289				  ROM32(scramble_tab[i]));
2290	}
2291
2292	/* Set memory type/width/length defaults depending on the straps */
2293	bios_md32(bios, NV04_PFB_BOOT_0, 0x3f, ramcfg[0]);
2294
2295	if (ramcfg[1] & 0x80)
2296		bios_md32(bios, NV04_PFB_CFG0, 0, NV04_PFB_CFG0_SCRAMBLE);
2297
2298	bios_md32(bios, NV04_PFB_CFG1, 0x700001, (ramcfg[1] & 1) << 20);
2299	bios_md32(bios, NV04_PFB_CFG1, 0, 1);
2300
2301	/* Probe memory bus width */
2302	for (i = 0; i < 4; i++)
2303		poke_fb(dev, fb, 4 * i, patt);
2304
2305	if (peek_fb(dev, fb, 0xc) != patt)
2306		bios_md32(bios, NV04_PFB_BOOT_0,
2307			  NV04_PFB_BOOT_0_RAM_WIDTH_128, 0);
2308
2309	/* Probe memory length */
2310	v = bios_rd32(bios, NV04_PFB_BOOT_0) & NV04_PFB_BOOT_0_RAM_AMOUNT;
2311
2312	if (v == NV04_PFB_BOOT_0_RAM_AMOUNT_32MB &&
2313	    (!read_back_fb(dev, fb, 0x1000000, ++patt) ||
2314	     !read_back_fb(dev, fb, 0, ++patt)))
2315		bios_md32(bios, NV04_PFB_BOOT_0, NV04_PFB_BOOT_0_RAM_AMOUNT,
2316			  NV04_PFB_BOOT_0_RAM_AMOUNT_16MB);
2317
2318	if (v == NV04_PFB_BOOT_0_RAM_AMOUNT_16MB &&
2319	    !read_back_fb(dev, fb, 0x800000, ++patt))
2320		bios_md32(bios, NV04_PFB_BOOT_0, NV04_PFB_BOOT_0_RAM_AMOUNT,
2321			  NV04_PFB_BOOT_0_RAM_AMOUNT_8MB);
2322
2323	if (!read_back_fb(dev, fb, 0x400000, ++patt))
2324		bios_md32(bios, NV04_PFB_BOOT_0, NV04_PFB_BOOT_0_RAM_AMOUNT,
2325			  NV04_PFB_BOOT_0_RAM_AMOUNT_4MB);
2326
2327out:
2328	/* Sequencer on */
2329	NVWriteVgaSeq(dev, 0, 1, NVReadVgaSeq(dev, 0, 1) & ~0x20);
2330
2331	io_mapping_free(fb);
2332	return 0;
2333}
2334
2335static int
2336nv10_init_compute_mem(struct nvbios *bios)
2337{
2338	struct drm_device *dev = bios->dev;
2339	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
2340	const int mem_width[] = { 0x10, 0x00, 0x20 };
2341	const int mem_width_count = (dev_priv->chipset >= 0x17 ? 3 : 2);
2342	uint32_t patt = 0xdeadbeef;
2343	struct io_mapping *fb;
2344	int i, j, k;
2345
2346	/* Map the framebuffer aperture */
2347	fb = io_mapping_create_wc(pci_resource_start(dev->pdev, 1),
2348				  pci_resource_len(dev->pdev, 1));
2349	if (!fb)
2350		return -ENOMEM;
2351
2352	bios_wr32(bios, NV10_PFB_REFCTRL, NV10_PFB_REFCTRL_VALID_1);
2353
2354	/* Probe memory bus width */
2355	for (i = 0; i < mem_width_count; i++) {
2356		bios_md32(bios, NV04_PFB_CFG0, 0x30, mem_width[i]);
2357
2358		for (j = 0; j < 4; j++) {
2359			for (k = 0; k < 4; k++)
2360				poke_fb(dev, fb, 0x1c, 0);
2361
2362			poke_fb(dev, fb, 0x1c, patt);
2363			poke_fb(dev, fb, 0x3c, 0);
2364
2365			if (peek_fb(dev, fb, 0x1c) == patt)
2366				goto mem_width_found;
2367		}
2368	}
2369
2370mem_width_found:
2371	patt <<= 1;
2372
2373	/* Probe amount of installed memory */
2374	for (i = 0; i < 4; i++) {
2375		int off = bios_rd32(bios, NV04_PFB_FIFO_DATA) - 0x100000;
2376
2377		poke_fb(dev, fb, off, patt);
2378		poke_fb(dev, fb, 0, 0);
2379
2380		peek_fb(dev, fb, 0);
2381		peek_fb(dev, fb, 0);
2382		peek_fb(dev, fb, 0);
2383		peek_fb(dev, fb, 0);
2384
2385		if (peek_fb(dev, fb, off) == patt)
2386			goto amount_found;
2387	}
2388
2389	/* IC missing - disable the upper half memory space. */
2390	bios_md32(bios, NV04_PFB_CFG0, 0x1000, 0);
2391
2392amount_found:
2393	io_mapping_free(fb);
2394	return 0;
2395}
2396
2397static int
2398nv20_init_compute_mem(struct nvbios *bios)
2399{
2400	struct drm_device *dev = bios->dev;
2401	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
2402	uint32_t mask = (dev_priv->chipset >= 0x25 ? 0x300 : 0x900);
2403	uint32_t amount, off;
2404	struct io_mapping *fb;
2405
2406	/* Map the framebuffer aperture */
2407	fb = io_mapping_create_wc(pci_resource_start(dev->pdev, 1),
2408				  pci_resource_len(dev->pdev, 1));
2409	if (!fb)
2410		return -ENOMEM;
2411
2412	bios_wr32(bios, NV10_PFB_REFCTRL, NV10_PFB_REFCTRL_VALID_1);
2413
2414	/* Allow full addressing */
2415	bios_md32(bios, NV04_PFB_CFG0, 0, mask);
2416
2417	amount = bios_rd32(bios, NV04_PFB_FIFO_DATA);
2418	for (off = amount; off > 0x2000000; off -= 0x2000000)
2419		poke_fb(dev, fb, off - 4, off);
2420
2421	amount = bios_rd32(bios, NV04_PFB_FIFO_DATA);
2422	if (amount != peek_fb(dev, fb, amount - 4))
2423		/* IC missing - disable the upper half memory space. */
2424		bios_md32(bios, NV04_PFB_CFG0, mask, 0);
2425
2426	io_mapping_free(fb);
2427	return 0;
2428}
2429
2430static int
2431init_compute_mem(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2432{
2433	/*
2434	 * INIT_COMPUTE_MEM   opcode: 0x63 ('c')
2435	 *
2436	 * offset      (8 bit): opcode
2437	 *
2438	 * This opcode is meant to set the PFB memory config registers
2439	 * appropriately so that we can correctly calculate how much VRAM it
2440	 * has (on nv10 and better chipsets the amount of installed VRAM is
2441	 * subsequently reported in NV_PFB_CSTATUS (0x10020C)).
2442	 *
2443	 * The implementation of this opcode in general consists of several
2444	 * parts:
2445	 *
2446	 * 1) Determination of memory type and density. Only necessary for
2447	 *    really old chipsets, the memory type reported by the strap bits
2448	 *    (0x101000) is assumed to be accurate on nv05 and newer.
2449	 *
2450	 * 2) Determination of the memory bus width. Usually done by a cunning
2451	 *    combination of writes to offsets 0x1c and 0x3c in the fb, and
2452	 *    seeing whether the written values are read back correctly.
2453	 *
2454	 *    Only necessary on nv0x-nv1x and nv34, on the other cards we can
2455	 *    trust the straps.
2456	 *
2457	 * 3) Determination of how many of the card's RAM pads have ICs
2458	 *    attached, usually done by a cunning combination of writes to an
2459	 *    offset slightly less than the maximum memory reported by
2460	 *    NV_PFB_CSTATUS, then seeing if the test pattern can be read back.
2461	 *
2462	 * This appears to be a NOP on IGPs and NV4x or newer chipsets, both io
2463	 * logs of the VBIOS and kmmio traces of the binary driver POSTing the
2464	 * card show nothing being done for this opcode. Why is it still listed
2465	 * in the table?!
2466	 */
2467
2468	/* no iexec->execute check by design */
2469
2470	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
2471	int ret;
2472
2473	if (dev_priv->chipset >= 0x40 ||
2474	    dev_priv->chipset == 0x1a ||
2475	    dev_priv->chipset == 0x1f)
2476		ret = 0;
2477	else if (dev_priv->chipset >= 0x20 &&
2478		 dev_priv->chipset != 0x34)
2479		ret = nv20_init_compute_mem(bios);
2480	else if (dev_priv->chipset >= 0x10)
2481		ret = nv10_init_compute_mem(bios);
2482	else if (dev_priv->chipset >= 0x5)
2483		ret = nv05_init_compute_mem(bios);
2484	else
2485		ret = nv04_init_compute_mem(bios);
2486
2487	if (ret)
2488		return ret;
2489
2490	return 1;
2491}
2492
2493static int
2494init_reset(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2495{
2496	/*
2497	 * INIT_RESET   opcode: 0x65 ('e')
2498	 *
2499	 * offset      (8  bit): opcode
2500	 * offset + 1  (32 bit): register
2501	 * offset + 5  (32 bit): value1
2502	 * offset + 9  (32 bit): value2
2503	 *
2504	 * Assign "value1" to "register", then assign "value2" to "register"
2505	 */
2506
2507	uint32_t reg = ROM32(bios->data[offset + 1]);
2508	uint32_t value1 = ROM32(bios->data[offset + 5]);
2509	uint32_t value2 = ROM32(bios->data[offset + 9]);
2510	uint32_t pci_nv_19, pci_nv_20;
2511
2512	/* no iexec->execute check by design */
2513
2514	pci_nv_19 = bios_rd32(bios, NV_PBUS_PCI_NV_19);
2515	bios_wr32(bios, NV_PBUS_PCI_NV_19, pci_nv_19 & ~0xf00);
2516
2517	bios_wr32(bios, reg, value1);
2518
2519	udelay(10);
2520
2521	bios_wr32(bios, reg, value2);
2522	bios_wr32(bios, NV_PBUS_PCI_NV_19, pci_nv_19);
2523
2524	pci_nv_20 = bios_rd32(bios, NV_PBUS_PCI_NV_20);
2525	pci_nv_20 &= ~NV_PBUS_PCI_NV_20_ROM_SHADOW_ENABLED;	/* 0xfffffffe */
2526	bios_wr32(bios, NV_PBUS_PCI_NV_20, pci_nv_20);
2527
2528	return 13;
2529}
2530
2531static int
2532init_configure_mem(struct nvbios *bios, uint16_t offset,
2533		   struct init_exec *iexec)
2534{
2535	/*
2536	 * INIT_CONFIGURE_MEM   opcode: 0x66 ('f')
2537	 *
2538	 * offset      (8 bit): opcode
2539	 *
2540	 * Equivalent to INIT_DONE on bios version 3 or greater.
2541	 * For early bios versions, sets up the memory registers, using values
2542	 * taken from the memory init table
2543	 */
2544
2545	/* no iexec->execute check by design */
2546
2547	uint16_t meminitoffs = bios->legacy.mem_init_tbl_ptr + MEM_INIT_SIZE * (bios_idxprt_rd(bios, NV_CIO_CRX__COLOR, NV_CIO_CRE_SCRATCH4__INDEX) >> 4);
2548	uint16_t seqtbloffs = bios->legacy.sdr_seq_tbl_ptr, meminitdata = meminitoffs + 6;
2549	uint32_t reg, data;
2550
2551	if (bios->major_version > 2)
2552		return 0;
2553
2554	bios_idxprt_wr(bios, NV_VIO_SRX, NV_VIO_SR_CLOCK_INDEX, bios_idxprt_rd(
2555		       bios, NV_VIO_SRX, NV_VIO_SR_CLOCK_INDEX) | 0x20);
2556
2557	if (bios->data[meminitoffs] & 1)
2558		seqtbloffs = bios->legacy.ddr_seq_tbl_ptr;
2559
2560	for (reg = ROM32(bios->data[seqtbloffs]);
2561	     reg != 0xffffffff;
2562	     reg = ROM32(bios->data[seqtbloffs += 4])) {
2563
2564		switch (reg) {
2565		case NV04_PFB_PRE:
2566			data = NV04_PFB_PRE_CMD_PRECHARGE;
2567			break;
2568		case NV04_PFB_PAD:
2569			data = NV04_PFB_PAD_CKE_NORMAL;
2570			break;
2571		case NV04_PFB_REF:
2572			data = NV04_PFB_REF_CMD_REFRESH;
2573			break;
2574		default:
2575			data = ROM32(bios->data[meminitdata]);
2576			meminitdata += 4;
2577			if (data == 0xffffffff)
2578				continue;
2579		}
2580
2581		bios_wr32(bios, reg, data);
2582	}
2583
2584	return 1;
2585}
2586
2587static int
2588init_configure_clk(struct nvbios *bios, uint16_t offset,
2589		   struct init_exec *iexec)
2590{
2591	/*
2592	 * INIT_CONFIGURE_CLK   opcode: 0x67 ('g')
2593	 *
2594	 * offset      (8 bit): opcode
2595	 *
2596	 * Equivalent to INIT_DONE on bios version 3 or greater.
2597	 * For early bios versions, sets up the NVClk and MClk PLLs, using
2598	 * values taken from the memory init table
2599	 */
2600
2601	/* no iexec->execute check by design */
2602
2603	uint16_t meminitoffs = bios->legacy.mem_init_tbl_ptr + MEM_INIT_SIZE * (bios_idxprt_rd(bios, NV_CIO_CRX__COLOR, NV_CIO_CRE_SCRATCH4__INDEX) >> 4);
2604	int clock;
2605
2606	if (bios->major_version > 2)
2607		return 0;
2608
2609	clock = ROM16(bios->data[meminitoffs + 4]) * 10;
2610	setPLL(bios, NV_PRAMDAC_NVPLL_COEFF, clock);
2611
2612	clock = ROM16(bios->data[meminitoffs + 2]) * 10;
2613	if (bios->data[meminitoffs] & 1) /* DDR */
2614		clock *= 2;
2615	setPLL(bios, NV_PRAMDAC_MPLL_COEFF, clock);
2616
2617	return 1;
2618}
2619
2620static int
2621init_configure_preinit(struct nvbios *bios, uint16_t offset,
2622		       struct init_exec *iexec)
2623{
2624	/*
2625	 * INIT_CONFIGURE_PREINIT   opcode: 0x68 ('h')
2626	 *
2627	 * offset      (8 bit): opcode
2628	 *
2629	 * Equivalent to INIT_DONE on bios version 3 or greater.
2630	 * For early bios versions, does early init, loading ram and crystal
2631	 * configuration from straps into CR3C
2632	 */
2633
2634	/* no iexec->execute check by design */
2635
2636	uint32_t straps = bios_rd32(bios, NV_PEXTDEV_BOOT_0);
2637	uint8_t cr3c = ((straps << 2) & 0xf0) | (straps & 0x40) >> 6;
2638
2639	if (bios->major_version > 2)
2640		return 0;
2641
2642	bios_idxprt_wr(bios, NV_CIO_CRX__COLOR,
2643			     NV_CIO_CRE_SCRATCH4__INDEX, cr3c);
2644
2645	return 1;
2646}
2647
2648static int
2649init_io(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2650{
2651	/*
2652	 * INIT_IO   opcode: 0x69 ('i')
2653	 *
2654	 * offset      (8  bit): opcode
2655	 * offset + 1  (16 bit): CRTC port
2656	 * offset + 3  (8  bit): mask
2657	 * offset + 4  (8  bit): data
2658	 *
2659	 * Assign ((IOVAL("crtc port") & "mask") | "data") to "crtc port"
2660	 */
2661
2662	struct drm_nouveau_private *dev_priv = bios->dev->dev_private;
2663	uint16_t crtcport = ROM16(bios->data[offset + 1]);
2664	uint8_t mask = bios->data[offset + 3];
2665	uint8_t data = bios->data[offset + 4];
2666
2667	if (!iexec->execute)
2668		return 5;
2669
2670	BIOSLOG(bios, "0x%04X: Port: 0x%04X, Mask: 0x%02X, Data: 0x%02X\n",
2671		offset, crtcport, mask, data);
2672
2673	/*
2674	 * I have no idea what this does, but NVIDIA do this magic sequence
2675	 * in the places where this INIT_IO happens..
2676	 */
2677	if (dev_priv->card_type >= NV_50 && crtcport == 0x3c3 && data == 1) {
2678		int i;
2679
2680		bios_wr32(bios, 0x614100, (bios_rd32(
2681			  bios, 0x614100) & 0x0fffffff) | 0x00800000);
2682
2683		bios_wr32(bios, 0x00e18c, bios_rd32(
2684			  bios, 0x00e18c) | 0x00020000);
2685
2686		bios_wr32(bios, 0x614900, (bios_rd32(
2687			  bios, 0x614900) & 0x0fffffff) | 0x00800000);
2688
2689		bios_wr32(bios, 0x000200, bios_rd32(
2690			  bios, 0x000200) & ~0x40000000);
2691
2692		mdelay(10);
2693
2694		bios_wr32(bios, 0x00e18c, bios_rd32(
2695			  bios, 0x00e18c) & ~0x00020000);
2696
2697		bios_wr32(bios, 0x000200, bios_rd32(
2698			  bios, 0x000200) | 0x40000000);
2699
2700		bios_wr32(bios, 0x614100, 0x00800018);
2701		bios_wr32(bios, 0x614900, 0x00800018);
2702
2703		mdelay(10);
2704
2705		bios_wr32(bios, 0x614100, 0x10000018);
2706		bios_wr32(bios, 0x614900, 0x10000018);
2707
2708		for (i = 0; i < 3; i++)
2709			bios_wr32(bios, 0x614280 + (i*0x800), bios_rd32(
2710				  bios, 0x614280 + (i*0x800)) & 0xf0f0f0f0);
2711
2712		for (i = 0; i < 2; i++)
2713			bios_wr32(bios, 0x614300 + (i*0x800), bios_rd32(
2714				  bios, 0x614300 + (i*0x800)) & 0xfffff0f0);
2715
2716		for (i = 0; i < 3; i++)
2717			bios_wr32(bios, 0x614380 + (i*0x800), bios_rd32(
2718				  bios, 0x614380 + (i*0x800)) & 0xfffff0f0);
2719
2720		for (i = 0; i < 2; i++)
2721			bios_wr32(bios, 0x614200 + (i*0x800), bios_rd32(
2722				  bios, 0x614200 + (i*0x800)) & 0xfffffff0);
2723
2724		for (i = 0; i < 2; i++)
2725			bios_wr32(bios, 0x614108 + (i*0x800), bios_rd32(
2726				  bios, 0x614108 + (i*0x800)) & 0x0fffffff);
2727		return 5;
2728	}
2729
2730	bios_port_wr(bios, crtcport, (bios_port_rd(bios, crtcport) & mask) |
2731									data);
2732	return 5;
2733}
2734
2735static int
2736init_sub(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2737{
2738	/*
2739	 * INIT_SUB   opcode: 0x6B ('k')
2740	 *
2741	 * offset      (8 bit): opcode
2742	 * offset + 1  (8 bit): script number
2743	 *
2744	 * Execute script number "script number", as a subroutine
2745	 */
2746
2747	uint8_t sub = bios->data[offset + 1];
2748
2749	if (!iexec->execute)
2750		return 2;
2751
2752	BIOSLOG(bios, "0x%04X: Calling script %d\n", offset, sub);
2753
2754	parse_init_table(bios,
2755			 ROM16(bios->data[bios->init_script_tbls_ptr + sub * 2]),
2756			 iexec);
2757
2758	BIOSLOG(bios, "0x%04X: End of script %d\n", offset, sub);
2759
2760	return 2;
2761}
2762
2763static int
2764init_ram_condition(struct nvbios *bios, uint16_t offset,
2765		   struct init_exec *iexec)
2766{
2767	/*
2768	 * INIT_RAM_CONDITION   opcode: 0x6D ('m')
2769	 *
2770	 * offset      (8 bit): opcode
2771	 * offset + 1  (8 bit): mask
2772	 * offset + 2  (8 bit): cmpval
2773	 *
2774	 * Test if (NV04_PFB_BOOT_0 & "mask") equals "cmpval".
2775	 * If condition not met skip subsequent opcodes until condition is
2776	 * inverted (INIT_NOT), or we hit INIT_RESUME
2777	 */
2778
2779	uint8_t mask = bios->data[offset + 1];
2780	uint8_t cmpval = bios->data[offset + 2];
2781	uint8_t data;
2782
2783	if (!iexec->execute)
2784		return 3;
2785
2786	data = bios_rd32(bios, NV04_PFB_BOOT_0) & mask;
2787
2788	BIOSLOG(bios, "0x%04X: Checking if 0x%08X equals 0x%08X\n",
2789		offset, data, cmpval);
2790
2791	if (data == cmpval)
2792		BIOSLOG(bios, "0x%04X: Condition fulfilled -- continuing to execute\n", offset);
2793	else {
2794		BIOSLOG(bios, "0x%04X: Condition not fulfilled -- skipping following commands\n", offset);
2795		iexec->execute = false;
2796	}
2797
2798	return 3;
2799}
2800
2801static int
2802init_nv_reg(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2803{
2804	/*
2805	 * INIT_NV_REG   opcode: 0x6E ('n')
2806	 *
2807	 * offset      (8  bit): opcode
2808	 * offset + 1  (32 bit): register
2809	 * offset + 5  (32 bit): mask
2810	 * offset + 9  (32 bit): data
2811	 *
2812	 * Assign ((REGVAL("register") & "mask") | "data") to "register"
2813	 */
2814
2815	uint32_t reg = ROM32(bios->data[offset + 1]);
2816	uint32_t mask = ROM32(bios->data[offset + 5]);
2817	uint32_t data = ROM32(bios->data[offset + 9]);
2818
2819	if (!iexec->execute)
2820		return 13;
2821
2822	BIOSLOG(bios, "0x%04X: Reg: 0x%08X, Mask: 0x%08X, Data: 0x%08X\n",
2823		offset, reg, mask, data);
2824
2825	bios_wr32(bios, reg, (bios_rd32(bios, reg) & mask) | data);
2826
2827	return 13;
2828}
2829
2830static int
2831init_macro(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2832{
2833	/*
2834	 * INIT_MACRO   opcode: 0x6F ('o')
2835	 *
2836	 * offset      (8 bit): opcode
2837	 * offset + 1  (8 bit): macro number
2838	 *
2839	 * Look up macro index "macro number" in the macro index table.
2840	 * The macro index table entry has 1 byte for the index in the macro
2841	 * table, and 1 byte for the number of times to repeat the macro.
2842	 * The macro table entry has 4 bytes for the register address and
2843	 * 4 bytes for the value to write to that register
2844	 */
2845
2846	uint8_t macro_index_tbl_idx = bios->data[offset + 1];
2847	uint16_t tmp = bios->macro_index_tbl_ptr + (macro_index_tbl_idx * MACRO_INDEX_SIZE);
2848	uint8_t macro_tbl_idx = bios->data[tmp];
2849	uint8_t count = bios->data[tmp + 1];
2850	uint32_t reg, data;
2851	int i;
2852
2853	if (!iexec->execute)
2854		return 2;
2855
2856	BIOSLOG(bios, "0x%04X: Macro: 0x%02X, MacroTableIndex: 0x%02X, "
2857		      "Count: 0x%02X\n",
2858		offset, macro_index_tbl_idx, macro_tbl_idx, count);
2859
2860	for (i = 0; i < count; i++) {
2861		uint16_t macroentryptr = bios->macro_tbl_ptr + (macro_tbl_idx + i) * MACRO_SIZE;
2862
2863		reg = ROM32(bios->data[macroentryptr]);
2864		data = ROM32(bios->data[macroentryptr + 4]);
2865
2866		bios_wr32(bios, reg, data);
2867	}
2868
2869	return 2;
2870}
2871
2872static int
2873init_done(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2874{
2875	/*
2876	 * INIT_DONE   opcode: 0x71 ('q')
2877	 *
2878	 * offset      (8  bit): opcode
2879	 *
2880	 * End the current script
2881	 */
2882
2883	/* mild retval abuse to stop parsing this table */
2884	return 0;
2885}
2886
2887static int
2888init_resume(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2889{
2890	/*
2891	 * INIT_RESUME   opcode: 0x72 ('r')
2892	 *
2893	 * offset      (8  bit): opcode
2894	 *
2895	 * End the current execute / no-execute condition
2896	 */
2897
2898	if (iexec->execute)
2899		return 1;
2900
2901	iexec->execute = true;
2902	BIOSLOG(bios, "0x%04X: ---- Executing following commands ----\n", offset);
2903
2904	return 1;
2905}
2906
2907static int
2908init_time(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2909{
2910	/*
2911	 * INIT_TIME   opcode: 0x74 ('t')
2912	 *
2913	 * offset      (8  bit): opcode
2914	 * offset + 1  (16 bit): time
2915	 *
2916	 * Sleep for "time" microseconds.
2917	 */
2918
2919	unsigned time = ROM16(bios->data[offset + 1]);
2920
2921	if (!iexec->execute)
2922		return 3;
2923
2924	BIOSLOG(bios, "0x%04X: Sleeping for 0x%04X microseconds\n",
2925		offset, time);
2926
2927	if (time < 1000)
2928		udelay(time);
2929	else
2930		mdelay((time + 900) / 1000);
2931
2932	return 3;
2933}
2934
2935static int
2936init_condition(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2937{
2938	/*
2939	 * INIT_CONDITION   opcode: 0x75 ('u')
2940	 *
2941	 * offset      (8 bit): opcode
2942	 * offset + 1  (8 bit): condition number
2943	 *
2944	 * Check condition "condition number" in the condition table.
2945	 * If condition not met skip subsequent opcodes until condition is
2946	 * inverted (INIT_NOT), or we hit INIT_RESUME
2947	 */
2948
2949	uint8_t cond = bios->data[offset + 1];
2950
2951	if (!iexec->execute)
2952		return 2;
2953
2954	BIOSLOG(bios, "0x%04X: Condition: 0x%02X\n", offset, cond);
2955
2956	if (bios_condition_met(bios, offset, cond))
2957		BIOSLOG(bios, "0x%04X: Condition fulfilled -- continuing to execute\n", offset);
2958	else {
2959		BIOSLOG(bios, "0x%04X: Condition not fulfilled -- skipping following commands\n", offset);
2960		iexec->execute = false;
2961	}
2962
2963	return 2;
2964}
2965
2966static int
2967init_io_condition(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2968{
2969	/*
2970	 * INIT_IO_CONDITION  opcode: 0x76
2971	 *
2972	 * offset      (8 bit): opcode
2973	 * offset + 1  (8 bit): condition number
2974	 *
2975	 * Check condition "condition number" in the io condition table.
2976	 * If condition not met skip subsequent opcodes until condition is
2977	 * inverted (INIT_NOT), or we hit INIT_RESUME
2978	 */
2979
2980	uint8_t cond = bios->data[offset + 1];
2981
2982	if (!iexec->execute)
2983		return 2;
2984
2985	BIOSLOG(bios, "0x%04X: IO condition: 0x%02X\n", offset, cond);
2986
2987	if (io_condition_met(bios, offset, cond))
2988		BIOSLOG(bios, "0x%04X: Condition fulfilled -- continuing to execute\n", offset);
2989	else {
2990		BIOSLOG(bios, "0x%04X: Condition not fulfilled -- skipping following commands\n", offset);
2991		iexec->execute = false;
2992	}
2993
2994	return 2;
2995}
2996
2997static int
2998init_index_io(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
2999{
3000	/*
3001	 * INIT_INDEX_IO   opcode: 0x78 ('x')
3002	 *
3003	 * offset      (8  bit): opcode
3004	 * offset + 1  (16 bit): CRTC port
3005	 * offset + 3  (8  bit): CRTC index
3006	 * offset + 4  (8  bit): mask
3007	 * offset + 5  (8  bit): data
3008	 *
3009	 * Read value at index "CRTC index" on "CRTC port", AND with "mask",
3010	 * OR with "data", write-back
3011	 */
3012
3013	uint16_t crtcport = ROM16(bios->data[offset + 1]);
3014	uint8_t crtcindex = bios->data[offset + 3];
3015	uint8_t mask = bios->data[offset + 4];
3016	uint8_t data = bios->data[offset + 5];
3017	uint8_t value;
3018
3019	if (!iexec->execute)
3020		return 6;
3021
3022	BIOSLOG(bios, "0x%04X: Port: 0x%04X, Index: 0x%02X, Mask: 0x%02X, "
3023		      "Data: 0x%02X\n",
3024		offset, crtcport, crtcindex, mask, data);
3025
3026	value = (bios_idxprt_rd(bios, crtcport, crtcindex) & mask) | data;
3027	bios_idxprt_wr(bios, crtcport, crtcindex, value);
3028
3029	return 6;
3030}
3031
3032static int
3033init_pll(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3034{
3035	/*
3036	 * INIT_PLL   opcode: 0x79 ('y')
3037	 *
3038	 * offset      (8  bit): opcode
3039	 * offset + 1  (32 bit): register
3040	 * offset + 5  (16 bit): freq
3041	 *
3042	 * Set PLL register "register" to coefficients for frequency (10kHz)
3043	 * "freq"
3044	 */
3045
3046	uint32_t reg = ROM32(bios->data[offset + 1]);
3047	uint16_t freq = ROM16(bios->data[offset + 5]);
3048
3049	if (!iexec->execute)
3050		return 7;
3051
3052	BIOSLOG(bios, "0x%04X: Reg: 0x%08X, Freq: %d0kHz\n", offset, reg, freq);
3053
3054	setPLL(bios, reg, freq * 10);
3055
3056	return 7;
3057}
3058
3059static int
3060init_zm_reg(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3061{
3062	/*
3063	 * INIT_ZM_REG   opcode: 0x7A ('z')
3064	 *
3065	 * offset      (8  bit): opcode
3066	 * offset + 1  (32 bit): register
3067	 * offset + 5  (32 bit): value
3068	 *
3069	 * Assign "value" to "register"
3070	 */
3071
3072	uint32_t reg = ROM32(bios->data[offset + 1]);
3073	uint32_t value = ROM32(bios->data[offset + 5]);
3074
3075	if (!iexec->execute)
3076		return 9;
3077
3078	if (reg == 0x000200)
3079		value |= 1;
3080
3081	bios_wr32(bios, reg, value);
3082
3083	return 9;
3084}
3085
3086static int
3087init_ram_restrict_pll(struct nvbios *bios, uint16_t offset,
3088		      struct init_exec *iexec)
3089{
3090	/*
3091	 * INIT_RAM_RESTRICT_PLL   opcode: 0x87 ('')
3092	 *
3093	 * offset      (8 bit): opcode
3094	 * offset + 1  (8 bit): PLL type
3095	 * offset + 2 (32 bit): frequency 0
3096	 *
3097	 * Uses the RAMCFG strap of PEXTDEV_BOOT as an index into the table at
3098	 * ram_restrict_table_ptr.  The value read from there is used to select
3099	 * a frequency from the table starting at 'frequency 0' to be
3100	 * programmed into the PLL corresponding to 'type'.
3101	 *
3102	 * The PLL limits table on cards using this opcode has a mapping of
3103	 * 'type' to the relevant registers.
3104	 */
3105
3106	struct drm_device *dev = bios->dev;
3107	uint32_t strap = (bios_rd32(bios, NV_PEXTDEV_BOOT_0) & 0x0000003c) >> 2;
3108	uint8_t index = bios->data[bios->ram_restrict_tbl_ptr + strap];
3109	uint8_t type = bios->data[offset + 1];
3110	uint32_t freq = ROM32(bios->data[offset + 2 + (index * 4)]);
3111	uint8_t *pll_limits = &bios->data[bios->pll_limit_tbl_ptr], *entry;
3112	int len = 2 + bios->ram_restrict_group_count * 4;
3113	int i;
3114
3115	if (!iexec->execute)
3116		return len;
3117
3118	if (!bios->pll_limit_tbl_ptr || (pll_limits[0] & 0xf0) != 0x30) {
3119		NV_ERROR(dev, "PLL limits table not version 3.x\n");
3120		return len; /* deliberate, allow default clocks to remain */
3121	}
3122
3123	entry = pll_limits + pll_limits[1];
3124	for (i = 0; i < pll_limits[3]; i++, entry += pll_limits[2]) {
3125		if (entry[0] == type) {
3126			uint32_t reg = ROM32(entry[3]);
3127
3128			BIOSLOG(bios, "0x%04X: "
3129				      "Type %02x Reg 0x%08x Freq %dKHz\n",
3130				offset, type, reg, freq);
3131
3132			setPLL(bios, reg, freq);
3133			return len;
3134		}
3135	}
3136
3137	NV_ERROR(dev, "PLL type 0x%02x not found in PLL limits table", type);
3138	return len;
3139}
3140
3141static int
3142init_8c(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3143{
3144	/*
3145	 * INIT_8C   opcode: 0x8C ('')
3146	 *
3147	 * NOP so far....
3148	 *
3149	 */
3150
3151	return 1;
3152}
3153
3154static int
3155init_8d(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3156{
3157	/*
3158	 * INIT_8D   opcode: 0x8D ('')
3159	 *
3160	 * NOP so far....
3161	 *
3162	 */
3163
3164	return 1;
3165}
3166
3167static int
3168init_gpio(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3169{
3170	/*
3171	 * INIT_GPIO   opcode: 0x8E ('')
3172	 *
3173	 * offset      (8 bit): opcode
3174	 *
3175	 * Loop over all entries in the DCB GPIO table, and initialise
3176	 * each GPIO according to various values listed in each entry
3177	 */
3178
3179	if (iexec->execute && bios->execute)
3180		nouveau_gpio_reset(bios->dev);
3181
3182	return 1;
3183}
3184
3185static int
3186init_ram_restrict_zm_reg_group(struct nvbios *bios, uint16_t offset,
3187			       struct init_exec *iexec)
3188{
3189	/*
3190	 * INIT_RAM_RESTRICT_ZM_REG_GROUP   opcode: 0x8F ('')
3191	 *
3192	 * offset      (8  bit): opcode
3193	 * offset + 1  (32 bit): reg
3194	 * offset + 5  (8  bit): regincrement
3195	 * offset + 6  (8  bit): count
3196	 * offset + 7  (32 bit): value 1,1
3197	 * ...
3198	 *
3199	 * Use the RAMCFG strap of PEXTDEV_BOOT as an index into the table at
3200	 * ram_restrict_table_ptr. The value read from here is 'n', and
3201	 * "value 1,n" gets written to "reg". This repeats "count" times and on
3202	 * each iteration 'm', "reg" increases by "regincrement" and
3203	 * "value m,n" is used. The extent of n is limited by a number read
3204	 * from the 'M' BIT table, herein called "blocklen"
3205	 */
3206
3207	uint32_t reg = ROM32(bios->data[offset + 1]);
3208	uint8_t regincrement = bios->data[offset + 5];
3209	uint8_t count = bios->data[offset + 6];
3210	uint32_t strap_ramcfg, data;
3211	/* previously set by 'M' BIT table */
3212	uint16_t blocklen = bios->ram_restrict_group_count * 4;
3213	int len = 7 + count * blocklen;
3214	uint8_t index;
3215	int i;
3216
3217	/* critical! to know the length of the opcode */;
3218	if (!blocklen) {
3219		NV_ERROR(bios->dev,
3220			 "0x%04X: Zero block length - has the M table "
3221			 "been parsed?\n", offset);
3222		return -EINVAL;
3223	}
3224
3225	if (!iexec->execute)
3226		return len;
3227
3228	strap_ramcfg = (bios_rd32(bios, NV_PEXTDEV_BOOT_0) >> 2) & 0xf;
3229	index = bios->data[bios->ram_restrict_tbl_ptr + strap_ramcfg];
3230
3231	BIOSLOG(bios, "0x%04X: Reg: 0x%08X, RegIncrement: 0x%02X, "
3232		      "Count: 0x%02X, StrapRamCfg: 0x%02X, Index: 0x%02X\n",
3233		offset, reg, regincrement, count, strap_ramcfg, index);
3234
3235	for (i = 0; i < count; i++) {
3236		data = ROM32(bios->data[offset + 7 + index * 4 + blocklen * i]);
3237
3238		bios_wr32(bios, reg, data);
3239
3240		reg += regincrement;
3241	}
3242
3243	return len;
3244}
3245
3246static int
3247init_copy_zm_reg(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3248{
3249	/*
3250	 * INIT_COPY_ZM_REG   opcode: 0x90 ('')
3251	 *
3252	 * offset      (8  bit): opcode
3253	 * offset + 1  (32 bit): src reg
3254	 * offset + 5  (32 bit): dst reg
3255	 *
3256	 * Put contents of "src reg" into "dst reg"
3257	 */
3258
3259	uint32_t srcreg = ROM32(bios->data[offset + 1]);
3260	uint32_t dstreg = ROM32(bios->data[offset + 5]);
3261
3262	if (!iexec->execute)
3263		return 9;
3264
3265	bios_wr32(bios, dstreg, bios_rd32(bios, srcreg));
3266
3267	return 9;
3268}
3269
3270static int
3271init_zm_reg_group_addr_latched(struct nvbios *bios, uint16_t offset,
3272			       struct init_exec *iexec)
3273{
3274	/*
3275	 * INIT_ZM_REG_GROUP_ADDRESS_LATCHED   opcode: 0x91 ('')
3276	 *
3277	 * offset      (8  bit): opcode
3278	 * offset + 1  (32 bit): dst reg
3279	 * offset + 5  (8  bit): count
3280	 * offset + 6  (32 bit): data 1
3281	 * ...
3282	 *
3283	 * For each of "count" values write "data n" to "dst reg"
3284	 */
3285
3286	uint32_t reg = ROM32(bios->data[offset + 1]);
3287	uint8_t count = bios->data[offset + 5];
3288	int len = 6 + count * 4;
3289	int i;
3290
3291	if (!iexec->execute)
3292		return len;
3293
3294	for (i = 0; i < count; i++) {
3295		uint32_t data = ROM32(bios->data[offset + 6 + 4 * i]);
3296		bios_wr32(bios, reg, data);
3297	}
3298
3299	return len;
3300}
3301
3302static int
3303init_reserved(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3304{
3305	/*
3306	 * INIT_RESERVED   opcode: 0x92 ('')
3307	 *
3308	 * offset      (8 bit): opcode
3309	 *
3310	 * Seemingly does nothing
3311	 */
3312
3313	return 1;
3314}
3315
3316static int
3317init_96(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3318{
3319	/*
3320	 * INIT_96   opcode: 0x96 ('')
3321	 *
3322	 * offset      (8  bit): opcode
3323	 * offset + 1  (32 bit): sreg
3324	 * offset + 5  (8  bit): sshift
3325	 * offset + 6  (8  bit): smask
3326	 * offset + 7  (8  bit): index
3327	 * offset + 8  (32 bit): reg
3328	 * offset + 12 (32 bit): mask
3329	 * offset + 16 (8  bit): shift
3330	 *
3331	 */
3332
3333	uint16_t xlatptr = bios->init96_tbl_ptr + (bios->data[offset + 7] * 2);
3334	uint32_t reg = ROM32(bios->data[offset + 8]);
3335	uint32_t mask = ROM32(bios->data[offset + 12]);
3336	uint32_t val;
3337
3338	val = bios_rd32(bios, ROM32(bios->data[offset + 1]));
3339	if (bios->data[offset + 5] < 0x80)
3340		val >>= bios->data[offset + 5];
3341	else
3342		val <<= (0x100 - bios->data[offset + 5]);
3343	val &= bios->data[offset + 6];
3344
3345	val   = bios->data[ROM16(bios->data[xlatptr]) + val];
3346	val <<= bios->data[offset + 16];
3347
3348	if (!iexec->execute)
3349		return 17;
3350
3351	bios_wr32(bios, reg, (bios_rd32(bios, reg) & mask) | val);
3352	return 17;
3353}
3354
3355static int
3356init_97(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3357{
3358	/*
3359	 * INIT_97   opcode: 0x97 ('')
3360	 *
3361	 * offset      (8  bit): opcode
3362	 * offset + 1  (32 bit): register
3363	 * offset + 5  (32 bit): mask
3364	 * offset + 9  (32 bit): value
3365	 *
3366	 * Adds "value" to "register" preserving the fields specified
3367	 * by "mask"
3368	 */
3369
3370	uint32_t reg = ROM32(bios->data[offset + 1]);
3371	uint32_t mask = ROM32(bios->data[offset + 5]);
3372	uint32_t add = ROM32(bios->data[offset + 9]);
3373	uint32_t val;
3374
3375	val = bios_rd32(bios, reg);
3376	val = (val & mask) | ((val + add) & ~mask);
3377
3378	if (!iexec->execute)
3379		return 13;
3380
3381	bios_wr32(bios, reg, val);
3382	return 13;
3383}
3384
3385static int
3386init_auxch(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3387{
3388	/*
3389	 * INIT_AUXCH   opcode: 0x98 ('')
3390	 *
3391	 * offset      (8  bit): opcode
3392	 * offset + 1  (32 bit): address
3393	 * offset + 5  (8  bit): count
3394	 * offset + 6  (8  bit): mask 0
3395	 * offset + 7  (8  bit): data 0
3396	 *  ...
3397	 *
3398	 */
3399
3400	struct drm_device *dev = bios->dev;
3401	struct nouveau_i2c_chan *auxch;
3402	uint32_t addr = ROM32(bios->data[offset + 1]);
3403	uint8_t count = bios->data[offset + 5];
3404	int len = 6 + count * 2;
3405	int ret, i;
3406
3407	if (!bios->display.output) {
3408		NV_ERROR(dev, "INIT_AUXCH: no active output\n");
3409		return len;
3410	}
3411
3412	auxch = init_i2c_device_find(dev, bios->display.output->i2c_index);
3413	if (!auxch) {
3414		NV_ERROR(dev, "INIT_AUXCH: couldn't get auxch %d\n",
3415			 bios->display.output->i2c_index);
3416		return len;
3417	}
3418
3419	if (!iexec->execute)
3420		return len;
3421
3422	offset += 6;
3423	for (i = 0; i < count; i++, offset += 2) {
3424		uint8_t data;
3425
3426		ret = nouveau_dp_auxch(auxch, 9, addr, &data, 1);
3427		if (ret) {
3428			NV_ERROR(dev, "INIT_AUXCH: rd auxch fail %d\n", ret);
3429			return len;
3430		}
3431
3432		data &= bios->data[offset + 0];
3433		data |= bios->data[offset + 1];
3434
3435		ret = nouveau_dp_auxch(auxch, 8, addr, &data, 1);
3436		if (ret) {
3437			NV_ERROR(dev, "INIT_AUXCH: wr auxch fail %d\n", ret);
3438			return len;
3439		}
3440	}
3441
3442	return len;
3443}
3444
3445static int
3446init_zm_auxch(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3447{
3448	/*
3449	 * INIT_ZM_AUXCH   opcode: 0x99 ('')
3450	 *
3451	 * offset      (8  bit): opcode
3452	 * offset + 1  (32 bit): address
3453	 * offset + 5  (8  bit): count
3454	 * offset + 6  (8  bit): data 0
3455	 *  ...
3456	 *
3457	 */
3458
3459	struct drm_device *dev = bios->dev;
3460	struct nouveau_i2c_chan *auxch;
3461	uint32_t addr = ROM32(bios->data[offset + 1]);
3462	uint8_t count = bios->data[offset + 5];
3463	int len = 6 + count;
3464	int ret, i;
3465
3466	if (!bios->display.output) {
3467		NV_ERROR(dev, "INIT_ZM_AUXCH: no active output\n");
3468		return len;
3469	}
3470
3471	auxch = init_i2c_device_find(dev, bios->display.output->i2c_index);
3472	if (!auxch) {
3473		NV_ERROR(dev, "INIT_ZM_AUXCH: couldn't get auxch %d\n",
3474			 bios->display.output->i2c_index);
3475		return len;
3476	}
3477
3478	if (!iexec->execute)
3479		return len;
3480
3481	offset += 6;
3482	for (i = 0; i < count; i++, offset++) {
3483		ret = nouveau_dp_auxch(auxch, 8, addr, &bios->data[offset], 1);
3484		if (ret) {
3485			NV_ERROR(dev, "INIT_ZM_AUXCH: wr auxch fail %d\n", ret);
3486			return len;
3487		}
3488	}
3489
3490	return len;
3491}
3492
3493static int
3494init_i2c_long_if(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3495{
3496	/*
3497	 * INIT_I2C_LONG_IF   opcode: 0x9A ('')
3498	 *
3499	 * offset      (8 bit): opcode
3500	 * offset + 1  (8 bit): DCB I2C table entry index
3501	 * offset + 2  (8 bit): I2C slave address
3502	 * offset + 3  (16 bit): I2C register
3503	 * offset + 5  (8 bit): mask
3504	 * offset + 6  (8 bit): data
3505	 *
3506	 * Read the register given by "I2C register" on the device addressed
3507	 * by "I2C slave address" on the I2C bus given by "DCB I2C table
3508	 * entry index". Compare the result AND "mask" to "data".
3509	 * If they're not equal, skip subsequent opcodes until condition is
3510	 * inverted (INIT_NOT), or we hit INIT_RESUME
3511	 */
3512
3513	uint8_t i2c_index = bios->data[offset + 1];
3514	uint8_t i2c_address = bios->data[offset + 2] >> 1;
3515	uint8_t reglo = bios->data[offset + 3];
3516	uint8_t reghi = bios->data[offset + 4];
3517	uint8_t mask = bios->data[offset + 5];
3518	uint8_t data = bios->data[offset + 6];
3519	struct nouveau_i2c_chan *chan;
3520	uint8_t buf0[2] = { reghi, reglo };
3521	uint8_t buf1[1];
3522	struct i2c_msg msg[2] = {
3523		{ i2c_address, 0, 1, buf0 },
3524		{ i2c_address, I2C_M_RD, 1, buf1 },
3525	};
3526	int ret;
3527
3528	/* no execute check by design */
3529
3530	BIOSLOG(bios, "0x%04X: DCBI2CIndex: 0x%02X, I2CAddress: 0x%02X\n",
3531		offset, i2c_index, i2c_address);
3532
3533	chan = init_i2c_device_find(bios->dev, i2c_index);
3534	if (!chan)
3535		return -ENODEV;
3536
3537
3538	ret = i2c_transfer(&chan->adapter, msg, 2);
3539	if (ret < 0) {
3540		BIOSLOG(bios, "0x%04X: I2CReg: 0x%02X:0x%02X, Value: [no device], "
3541			      "Mask: 0x%02X, Data: 0x%02X\n",
3542			offset, reghi, reglo, mask, data);
3543		iexec->execute = 0;
3544		return 7;
3545	}
3546
3547	BIOSLOG(bios, "0x%04X: I2CReg: 0x%02X:0x%02X, Value: 0x%02X, "
3548		      "Mask: 0x%02X, Data: 0x%02X\n",
3549		offset, reghi, reglo, buf1[0], mask, data);
3550
3551	iexec->execute = ((buf1[0] & mask) == data);
3552
3553	return 7;
3554}
3555
3556static struct init_tbl_entry itbl_entry[] = {
3557	/* command name                       , id  , length  , offset  , mult    , command handler                 */
3558	/* INIT_PROG (0x31, 15, 10, 4) removed due to no example of use */
3559	{ "INIT_IO_RESTRICT_PROG"             , 0x32, init_io_restrict_prog           },
3560	{ "INIT_REPEAT"                       , 0x33, init_repeat                     },
3561	{ "INIT_IO_RESTRICT_PLL"              , 0x34, init_io_restrict_pll            },
3562	{ "INIT_END_REPEAT"                   , 0x36, init_end_repeat                 },
3563	{ "INIT_COPY"                         , 0x37, init_copy                       },
3564	{ "INIT_NOT"                          , 0x38, init_not                        },
3565	{ "INIT_IO_FLAG_CONDITION"            , 0x39, init_io_flag_condition          },
3566	{ "INIT_DP_CONDITION"                 , 0x3A, init_dp_condition               },
3567	{ "INIT_OP_3B"                        , 0x3B, init_op_3b                      },
3568	{ "INIT_OP_3C"                        , 0x3C, init_op_3c                      },
3569	{ "INIT_INDEX_ADDRESS_LATCHED"        , 0x49, init_idx_addr_latched           },
3570	{ "INIT_IO_RESTRICT_PLL2"             , 0x4A, init_io_restrict_pll2           },
3571	{ "INIT_PLL2"                         , 0x4B, init_pll2                       },
3572	{ "INIT_I2C_BYTE"                     , 0x4C, init_i2c_byte                   },
3573	{ "INIT_ZM_I2C_BYTE"                  , 0x4D, init_zm_i2c_byte                },
3574	{ "INIT_ZM_I2C"                       , 0x4E, init_zm_i2c                     },
3575	{ "INIT_TMDS"                         , 0x4F, init_tmds                       },
3576	{ "INIT_ZM_TMDS_GROUP"                , 0x50, init_zm_tmds_group              },
3577	{ "INIT_CR_INDEX_ADDRESS_LATCHED"     , 0x51, init_cr_idx_adr_latch           },
3578	{ "INIT_CR"                           , 0x52, init_cr                         },
3579	{ "INIT_ZM_CR"                        , 0x53, init_zm_cr                      },
3580	{ "INIT_ZM_CR_GROUP"                  , 0x54, init_zm_cr_group                },
3581	{ "INIT_CONDITION_TIME"               , 0x56, init_condition_time             },
3582	{ "INIT_LTIME"                        , 0x57, init_ltime                      },
3583	{ "INIT_ZM_REG_SEQUENCE"              , 0x58, init_zm_reg_sequence            },
3584	/* INIT_INDIRECT_REG (0x5A, 7, 0, 0) removed due to no example of use */
3585	{ "INIT_SUB_DIRECT"                   , 0x5B, init_sub_direct                 },
3586	{ "INIT_JUMP"                         , 0x5C, init_jump                       },
3587	{ "INIT_I2C_IF"                       , 0x5E, init_i2c_if                     },
3588	{ "INIT_COPY_NV_REG"                  , 0x5F, init_copy_nv_reg                },
3589	{ "INIT_ZM_INDEX_IO"                  , 0x62, init_zm_index_io                },
3590	{ "INIT_COMPUTE_MEM"                  , 0x63, init_compute_mem                },
3591	{ "INIT_RESET"                        , 0x65, init_reset                      },
3592	{ "INIT_CONFIGURE_MEM"                , 0x66, init_configure_mem              },
3593	{ "INIT_CONFIGURE_CLK"                , 0x67, init_configure_clk              },
3594	{ "INIT_CONFIGURE_PREINIT"            , 0x68, init_configure_preinit          },
3595	{ "INIT_IO"                           , 0x69, init_io                         },
3596	{ "INIT_SUB"                          , 0x6B, init_sub                        },
3597	{ "INIT_RAM_CONDITION"                , 0x6D, init_ram_condition              },
3598	{ "INIT_NV_REG"                       , 0x6E, init_nv_reg                     },
3599	{ "INIT_MACRO"                        , 0x6F, init_macro                      },
3600	{ "INIT_DONE"                         , 0x71, init_done                       },
3601	{ "INIT_RESUME"                       , 0x72, init_resume                     },
3602	/* INIT_RAM_CONDITION2 (0x73, 9, 0, 0) removed due to no example of use */
3603	{ "INIT_TIME"                         , 0x74, init_time                       },
3604	{ "INIT_CONDITION"                    , 0x75, init_condition                  },
3605	{ "INIT_IO_CONDITION"                 , 0x76, init_io_condition               },
3606	{ "INIT_INDEX_IO"                     , 0x78, init_index_io                   },
3607	{ "INIT_PLL"                          , 0x79, init_pll                        },
3608	{ "INIT_ZM_REG"                       , 0x7A, init_zm_reg                     },
3609	{ "INIT_RAM_RESTRICT_PLL"             , 0x87, init_ram_restrict_pll           },
3610	{ "INIT_8C"                           , 0x8C, init_8c                         },
3611	{ "INIT_8D"                           , 0x8D, init_8d                         },
3612	{ "INIT_GPIO"                         , 0x8E, init_gpio                       },
3613	{ "INIT_RAM_RESTRICT_ZM_REG_GROUP"    , 0x8F, init_ram_restrict_zm_reg_group  },
3614	{ "INIT_COPY_ZM_REG"                  , 0x90, init_copy_zm_reg                },
3615	{ "INIT_ZM_REG_GROUP_ADDRESS_LATCHED" , 0x91, init_zm_reg_group_addr_latched  },
3616	{ "INIT_RESERVED"                     , 0x92, init_reserved                   },
3617	{ "INIT_96"                           , 0x96, init_96                         },
3618	{ "INIT_97"                           , 0x97, init_97                         },
3619	{ "INIT_AUXCH"                        , 0x98, init_auxch                      },
3620	{ "INIT_ZM_AUXCH"                     , 0x99, init_zm_auxch                   },
3621	{ "INIT_I2C_LONG_IF"                  , 0x9A, init_i2c_long_if                },
3622	{ NULL                                , 0   , NULL                            }
3623};
3624
3625#define MAX_TABLE_OPS 1000
3626
3627static int
3628parse_init_table(struct nvbios *bios, uint16_t offset, struct init_exec *iexec)
3629{
3630	/*
3631	 * Parses all commands in an init table.
3632	 *
3633	 * We start out executing all commands found in the init table. Some
3634	 * opcodes may change the status of iexec->execute to SKIP, which will
3635	 * cause the following opcodes to perform no operation until the value
3636	 * is changed back to EXECUTE.
3637	 */
3638
3639	int count = 0, i, ret;
3640	uint8_t id;
3641
3642	/* catch NULL script pointers */
3643	if (offset == 0)
3644		return 0;
3645
3646	/*
3647	 * Loop until INIT_DONE causes us to break out of the loop
3648	 * (or until offset > bios length just in case... )
3649	 * (and no more than MAX_TABLE_OPS iterations, just in case... )
3650	 */
3651	while ((offset < bios->length) && (count++ < MAX_TABLE_OPS)) {
3652		id = bios->data[offset];
3653
3654		/* Find matching id in itbl_entry */
3655		for (i = 0; itbl_entry[i].name && (itbl_entry[i].id != id); i++)
3656			;
3657
3658		if (!itbl_entry[i].name) {
3659			NV_ERROR(bios->dev,
3660				 "0x%04X: Init table command not found: "
3661				 "0x%02X\n", offset, id);
3662			return -ENOENT;
3663		}
3664
3665		BIOSLOG(bios, "0x%04X: [ (0x%02X) - %s ]\n", offset,
3666			itbl_entry[i].id, itbl_entry[i].name);
3667
3668		/* execute eventual command handler */
3669		ret = (*itbl_entry[i].handler)(bios, offset, iexec);
3670		if (ret < 0) {
3671			NV_ERROR(bios->dev, "0x%04X: Failed parsing init "
3672				 "table opcode: %s %d\n", offset,
3673				 itbl_entry[i].name, ret);
3674		}
3675
3676		if (ret <= 0)
3677			break;
3678
3679		/*
3680		 * Add the offset of the current command including all data
3681		 * of that command. The offset will then be pointing on the
3682		 * next op code.
3683		 */
3684		offset += ret;
3685	}
3686
3687	if (offset >= bios->length)
3688		NV_WARN(bios->dev,
3689			"Offset 0x%04X greater than known bios image length.  "
3690			"Corrupt image?\n", offset);
3691	if (count >= MAX_TABLE_OPS)
3692		NV_WARN(bios->dev,
3693			"More than %d opcodes to a table is unlikely, "
3694			"is the bios image corrupt?\n", MAX_TABLE_OPS);
3695
3696	return 0;
3697}
3698
3699static void
3700parse_init_tables(struct nvbios *bios)
3701{
3702	/* Loops and calls parse_init_table() for each present table. */
3703
3704	int i = 0;
3705	uint16_t table;
3706	struct init_exec iexec = {true, false};
3707
3708	if (bios->old_style_init) {
3709		if (bios->init_script_tbls_ptr)
3710			parse_init_table(bios, bios->init_script_tbls_ptr, &iexec);
3711		if (bios->extra_init_script_tbl_ptr)
3712			parse_init_table(bios, bios->extra_init_script_tbl_ptr, &iexec);
3713
3714		return;
3715	}
3716
3717	while ((table = ROM16(bios->data[bios->init_script_tbls_ptr + i]))) {
3718		NV_INFO(bios->dev,
3719			"Parsing VBIOS init table %d at offset 0x%04X\n",
3720			i / 2, table);
3721		BIOSLOG(bios, "0x%04X: ------ Executing following commands ------\n", table);
3722
3723		parse_init_table(bios, table, &iexec);
3724		i += 2;
3725	}
3726}
3727
3728static uint16_t clkcmptable(struct nvbios *bios, uint16_t clktable, int pxclk)
3729{
3730	int compare_record_len, i = 0;
3731	uint16_t compareclk, scriptptr = 0;
3732
3733	if (bios->major_version < 5) /* pre BIT */
3734		compare_record_len = 3;
3735	else
3736		compare_record_len = 4;
3737
3738	do {
3739		compareclk = ROM16(bios->data[clktable + compare_record_len * i]);
3740		if (pxclk >= compareclk * 10) {
3741			if (bios->major_version < 5) {
3742				uint8_t tmdssub = bios->data[clktable + 2 + compare_record_len * i];
3743				scriptptr = ROM16(bios->data[bios->init_script_tbls_ptr + tmdssub * 2]);
3744			} else
3745				scriptptr = ROM16(bios->data[clktable + 2 + compare_record_len * i]);
3746			break;
3747		}
3748		i++;
3749	} while (compareclk);
3750
3751	return scriptptr;
3752}
3753
3754static void
3755run_digital_op_script(struct drm_device *dev, uint16_t scriptptr,
3756		      struct dcb_entry *dcbent, int head, bool dl)
3757{
3758	struct drm_nouveau_private *dev_priv = dev->dev_private;
3759	struct nvbios *bios = &dev_priv->vbios;
3760	struct init_exec iexec = {true, false};
3761
3762	NV_TRACE(dev, "0x%04X: Parsing digital output script table\n",
3763		 scriptptr);
3764	bios_idxprt_wr(bios, NV_CIO_CRX__COLOR, NV_CIO_CRE_44,
3765		       head ? NV_CIO_CRE_44_HEADB : NV_CIO_CRE_44_HEADA);
3766	/* note: if dcb entries have been merged, index may be misleading */
3767	NVWriteVgaCrtc5758(dev, head, 0, dcbent->index);
3768	parse_init_table(bios, scriptptr, &iexec);
3769
3770	nv04_dfp_bind_head(dev, dcbent, head, dl);
3771}
3772
3773static int call_lvds_manufacturer_script(struct drm_device *dev, struct dcb_entry *dcbent, int head, enum LVDS_script script)
3774{
3775	struct drm_nouveau_private *dev_priv = dev->dev_private;
3776	struct nvbios *bios = &dev_priv->vbios;
3777	uint8_t sub = bios->data[bios->fp.xlated_entry + script] + (bios->fp.link_c_increment && dcbent->or & OUTPUT_C ? 1 : 0);
3778	uint16_t scriptofs = ROM16(bios->data[bios->init_script_tbls_ptr + sub * 2]);
3779
3780	if (!bios->fp.xlated_entry || !sub || !scriptofs)
3781		return -EINVAL;
3782
3783	run_digital_op_script(dev, scriptofs, dcbent, head, bios->fp.dual_link);
3784
3785	if (script == LVDS_PANEL_OFF) {
3786		/* off-on delay in ms */
3787		mdelay(ROM16(bios->data[bios->fp.xlated_entry + 7]));
3788	}
3789#ifdef __powerpc__
3790	/* Powerbook specific quirks */
3791	if (script == LVDS_RESET &&
3792	    (dev->pci_device == 0x0179 || dev->pci_device == 0x0189 ||
3793	     dev->pci_device == 0x0329))
3794		nv_write_tmds(dev, dcbent->or, 0, 0x02, 0x72);
3795#endif
3796
3797	return 0;
3798}
3799
3800static int run_lvds_table(struct drm_device *dev, struct dcb_entry *dcbent, int head, enum LVDS_script script, int pxclk)
3801{
3802	/*
3803	 * The BIT LVDS table's header has the information to setup the
3804	 * necessary registers. Following the standard 4 byte header are:
3805	 * A bitmask byte and a dual-link transition pxclk value for use in
3806	 * selecting the init script when not using straps; 4 script pointers
3807	 * for panel power, selected by output and on/off; and 8 table pointers
3808	 * for panel init, the needed one determined by output, and bits in the
3809	 * conf byte. These tables are similar to the TMDS tables, consisting
3810	 * of a list of pxclks and script pointers.
3811	 */
3812	struct drm_nouveau_private *dev_priv = dev->dev_private;
3813	struct nvbios *bios = &dev_priv->vbios;
3814	unsigned int outputset = (dcbent->or == 4) ? 1 : 0;
3815	uint16_t scriptptr = 0, clktable;
3816
3817	/*
3818	 * For now we assume version 3.0 table - g80 support will need some
3819	 * changes
3820	 */
3821
3822	switch (script) {
3823	case LVDS_INIT:
3824		return -ENOSYS;
3825	case LVDS_BACKLIGHT_ON:
3826	case LVDS_PANEL_ON:
3827		scriptptr = ROM16(bios->data[bios->fp.lvdsmanufacturerpointer + 7 + outputset * 2]);
3828		break;
3829	case LVDS_BACKLIGHT_OFF:
3830	case LVDS_PANEL_OFF:
3831		scriptptr = ROM16(bios->data[bios->fp.lvdsmanufacturerpointer + 11 + outputset * 2]);
3832		break;
3833	case LVDS_RESET:
3834		clktable = bios->fp.lvdsmanufacturerpointer + 15;
3835		if (dcbent->or == 4)
3836			clktable += 8;
3837
3838		if (dcbent->lvdsconf.use_straps_for_mode) {
3839			if (bios->fp.dual_link)
3840				clktable += 4;
3841			if (bios->fp.if_is_24bit)
3842				clktable += 2;
3843		} else {
3844			/* using EDID */
3845			int cmpval_24bit = (dcbent->or == 4) ? 4 : 1;
3846
3847			if (bios->fp.dual_link) {
3848				clktable += 4;
3849				cmpval_24bit <<= 1;
3850			}
3851
3852			if (bios->fp.strapless_is_24bit & cmpval_24bit)
3853				clktable += 2;
3854		}
3855
3856		clktable = ROM16(bios->data[clktable]);
3857		if (!clktable) {
3858			NV_ERROR(dev, "Pixel clock comparison table not found\n");
3859			return -ENOENT;
3860		}
3861		scriptptr = clkcmptable(bios, clktable, pxclk);
3862	}
3863
3864	if (!scriptptr) {
3865		NV_ERROR(dev, "LVDS output init script not found\n");
3866		return -ENOENT;
3867	}
3868	run_digital_op_script(dev, scriptptr, dcbent, head, bios->fp.dual_link);
3869
3870	return 0;
3871}
3872
3873int call_lvds_script(struct drm_device *dev, struct dcb_entry *dcbent, int head, enum LVDS_script script, int pxclk)
3874{
3875	/*
3876	 * LVDS operations are multiplexed in an effort to present a single API
3877	 * which works with two vastly differing underlying structures.
3878	 * This acts as the demux
3879	 */
3880
3881	struct drm_nouveau_private *dev_priv = dev->dev_private;
3882	struct nvbios *bios = &dev_priv->vbios;
3883	uint8_t lvds_ver = bios->data[bios->fp.lvdsmanufacturerpointer];
3884	uint32_t sel_clk_binding, sel_clk;
3885	int ret;
3886
3887	if (bios->fp.last_script_invoc == (script << 1 | head) || !lvds_ver ||
3888	    (lvds_ver >= 0x30 && script == LVDS_INIT))
3889		return 0;
3890
3891	if (!bios->fp.lvds_init_run) {
3892		bios->fp.lvds_init_run = true;
3893		call_lvds_script(dev, dcbent, head, LVDS_INIT, pxclk);
3894	}
3895
3896	if (script == LVDS_PANEL_ON && bios->fp.reset_after_pclk_change)
3897		call_lvds_script(dev, dcbent, head, LVDS_RESET, pxclk);
3898	if (script == LVDS_RESET && bios->fp.power_off_for_reset)
3899		call_lvds_script(dev, dcbent, head, LVDS_PANEL_OFF, pxclk);
3900
3901	NV_TRACE(dev, "Calling LVDS script %d:\n", script);
3902
3903	/* don't let script change pll->head binding */
3904	sel_clk_binding = bios_rd32(bios, NV_PRAMDAC_SEL_CLK) & 0x50000;
3905
3906	if (lvds_ver < 0x30)
3907		ret = call_lvds_manufacturer_script(dev, dcbent, head, script);
3908	else
3909		ret = run_lvds_table(dev, dcbent, head, script, pxclk);
3910
3911	bios->fp.last_script_invoc = (script << 1 | head);
3912
3913	sel_clk = NVReadRAMDAC(dev, 0, NV_PRAMDAC_SEL_CLK) & ~0x50000;
3914	NVWriteRAMDAC(dev, 0, NV_PRAMDAC_SEL_CLK, sel_clk | sel_clk_binding);
3915	/* some scripts set a value in NV_PBUS_POWERCTRL_2 and break video overlay */
3916	nvWriteMC(dev, NV_PBUS_POWERCTRL_2, 0);
3917
3918	return ret;
3919}
3920
3921struct lvdstableheader {
3922	uint8_t lvds_ver, headerlen, recordlen;
3923};
3924
3925static int parse_lvds_manufacturer_table_header(struct drm_device *dev, struct nvbios *bios, struct lvdstableheader *lth)
3926{
3927	/*
3928	 * BMP version (0xa) LVDS table has a simple header of version and
3929	 * record length. The BIT LVDS table has the typical BIT table header:
3930	 * version byte, header length byte, record length byte, and a byte for
3931	 * the maximum number of records that can be held in the table.
3932	 */
3933
3934	uint8_t lvds_ver, headerlen, recordlen;
3935
3936	memset(lth, 0, sizeof(struct lvdstableheader));
3937
3938	if (bios->fp.lvdsmanufacturerpointer == 0x0) {
3939		NV_ERROR(dev, "Pointer to LVDS manufacturer table invalid\n");
3940		return -EINVAL;
3941	}
3942
3943	lvds_ver = bios->data[bios->fp.lvdsmanufacturerpointer];
3944
3945	switch (lvds_ver) {
3946	case 0x0a:	/* pre NV40 */
3947		headerlen = 2;
3948		recordlen = bios->data[bios->fp.lvdsmanufacturerpointer + 1];
3949		break;
3950	case 0x30:	/* NV4x */
3951		headerlen = bios->data[bios->fp.lvdsmanufacturerpointer + 1];
3952		if (headerlen < 0x1f) {
3953			NV_ERROR(dev, "LVDS table header not understood\n");
3954			return -EINVAL;
3955		}
3956		recordlen = bios->data[bios->fp.lvdsmanufacturerpointer + 2];
3957		break;
3958	case 0x40:	/* G80/G90 */
3959		headerlen = bios->data[bios->fp.lvdsmanufacturerpointer + 1];
3960		if (headerlen < 0x7) {
3961			NV_ERROR(dev, "LVDS table header not understood\n");
3962			return -EINVAL;
3963		}
3964		recordlen = bios->data[bios->fp.lvdsmanufacturerpointer + 2];
3965		break;
3966	default:
3967		NV_ERROR(dev,
3968			 "LVDS table revision %d.%d not currently supported\n",
3969			 lvds_ver >> 4, lvds_ver & 0xf);
3970		return -ENOSYS;
3971	}
3972
3973	lth->lvds_ver = lvds_ver;
3974	lth->headerlen = headerlen;
3975	lth->recordlen = recordlen;
3976
3977	return 0;
3978}
3979
3980static int
3981get_fp_strap(struct drm_device *dev, struct nvbios *bios)
3982{
3983	struct drm_nouveau_private *dev_priv = dev->dev_private;
3984
3985	/*
3986	 * The fp strap is normally dictated by the "User Strap" in
3987	 * PEXTDEV_BOOT_0[20:16], but on BMP cards when bit 2 of the
3988	 * Internal_Flags struct at 0x48 is set, the user strap gets overriden
3989	 * by the PCI subsystem ID during POST, but not before the previous user
3990	 * strap has been committed to CR58 for CR57=0xf on head A, which may be
3991	 * read and used instead
3992	 */
3993
3994	if (bios->major_version < 5 && bios->data[0x48] & 0x4)
3995		return NVReadVgaCrtc5758(dev, 0, 0xf) & 0xf;
3996
3997	if (dev_priv->card_type >= NV_50)
3998		return (bios_rd32(bios, NV_PEXTDEV_BOOT_0) >> 24) & 0xf;
3999	else
4000		return (bios_rd32(bios, NV_PEXTDEV_BOOT_0) >> 16) & 0xf;
4001}
4002
4003static int parse_fp_mode_table(struct drm_device *dev, struct nvbios *bios)
4004{
4005	uint8_t *fptable;
4006	uint8_t fptable_ver, headerlen = 0, recordlen, fpentries = 0xf, fpindex;
4007	int ret, ofs, fpstrapping;
4008	struct lvdstableheader lth;
4009
4010	if (bios->fp.fptablepointer == 0x0) {
4011		/* Apple cards don't have the fp table; the laptops use DDC */
4012		/* The table is also missing on some x86 IGPs */
4013#ifndef __powerpc__
4014		NV_ERROR(dev, "Pointer to flat panel table invalid\n");
4015#endif
4016		bios->digital_min_front_porch = 0x4b;
4017		return 0;
4018	}
4019
4020	fptable = &bios->data[bios->fp.fptablepointer];
4021	fptable_ver = fptable[0];
4022
4023	switch (fptable_ver) {
4024	/*
4025	 * BMP version 0x5.0x11 BIOSen have version 1 like tables, but no
4026	 * version field, and miss one of the spread spectrum/PWM bytes.
4027	 * This could affect early GF2Go parts (not seen any appropriate ROMs
4028	 * though). Here we assume that a version of 0x05 matches this case
4029	 * (combining with a BMP version check would be better), as the
4030	 * common case for the panel type field is 0x0005, and that is in
4031	 * fact what we are reading the first byte of.
4032	 */
4033	case 0x05:	/* some NV10, 11, 15, 16 */
4034		recordlen = 42;
4035		ofs = -1;
4036		break;
4037	case 0x10:	/* some NV15/16, and NV11+ */
4038		recordlen = 44;
4039		ofs = 0;
4040		break;
4041	case 0x20:	/* NV40+ */
4042		headerlen = fptable[1];
4043		recordlen = fptable[2];
4044		fpentries = fptable[3];
4045		/*
4046		 * fptable[4] is the minimum
4047		 * RAMDAC_FP_HCRTC -> RAMDAC_FP_HSYNC_START gap
4048		 */
4049		bios->digital_min_front_porch = fptable[4];
4050		ofs = -7;
4051		break;
4052	default:
4053		NV_ERROR(dev,
4054			 "FP table revision %d.%d not currently supported\n",
4055			 fptable_ver >> 4, fptable_ver & 0xf);
4056		return -ENOSYS;
4057	}
4058
4059	if (!bios->is_mobile) /* !mobile only needs digital_min_front_porch */
4060		return 0;
4061
4062	ret = parse_lvds_manufacturer_table_header(dev, bios, &lth);
4063	if (ret)
4064		return ret;
4065
4066	if (lth.lvds_ver == 0x30 || lth.lvds_ver == 0x40) {
4067		bios->fp.fpxlatetableptr = bios->fp.lvdsmanufacturerpointer +
4068							lth.headerlen + 1;
4069		bios->fp.xlatwidth = lth.recordlen;
4070	}
4071	if (bios->fp.fpxlatetableptr == 0x0) {
4072		NV_ERROR(dev, "Pointer to flat panel xlat table invalid\n");
4073		return -EINVAL;
4074	}
4075
4076	fpstrapping = get_fp_strap(dev, bios);
4077
4078	fpindex = bios->data[bios->fp.fpxlatetableptr +
4079					fpstrapping * bios->fp.xlatwidth];
4080
4081	if (fpindex > fpentries) {
4082		NV_ERROR(dev, "Bad flat panel table index\n");
4083		return -ENOENT;
4084	}
4085
4086	/* nv4x cards need both a strap value and fpindex of 0xf to use DDC */
4087	if (lth.lvds_ver > 0x10)
4088		bios->fp_no_ddc = fpstrapping != 0xf || fpindex != 0xf;
4089
4090	/*
4091	 * If either the strap or xlated fpindex value are 0xf there is no
4092	 * panel using a strap-derived bios mode present.  this condition
4093	 * includes, but is different from, the DDC panel indicator above
4094	 */
4095	if (fpstrapping == 0xf || fpindex == 0xf)
4096		return 0;
4097
4098	bios->fp.mode_ptr = bios->fp.fptablepointer + headerlen +
4099			    recordlen * fpindex + ofs;
4100
4101	NV_TRACE(dev, "BIOS FP mode: %dx%d (%dkHz pixel clock)\n",
4102		 ROM16(bios->data[bios->fp.mode_ptr + 11]) + 1,
4103		 ROM16(bios->data[bios->fp.mode_ptr + 25]) + 1,
4104		 ROM16(bios->data[bios->fp.mode_ptr + 7]) * 10);
4105
4106	return 0;
4107}
4108
4109bool nouveau_bios_fp_mode(struct drm_device *dev, struct drm_display_mode *mode)
4110{
4111	struct drm_nouveau_private *dev_priv = dev->dev_private;
4112	struct nvbios *bios = &dev_priv->vbios;
4113	uint8_t *mode_entry = &bios->data[bios->fp.mode_ptr];
4114
4115	if (!mode)	/* just checking whether we can produce a mode */
4116		return bios->fp.mode_ptr;
4117
4118	memset(mode, 0, sizeof(struct drm_display_mode));
4119	/*
4120	 * For version 1.0 (version in byte 0):
4121	 * bytes 1-2 are "panel type", including bits on whether Colour/mono,
4122	 * single/dual link, and type (TFT etc.)
4123	 * bytes 3-6 are bits per colour in RGBX
4124	 */
4125	mode->clock = ROM16(mode_entry[7]) * 10;
4126	/* bytes 9-10 is HActive */
4127	mode->hdisplay = ROM16(mode_entry[11]) + 1;
4128	/*
4129	 * bytes 13-14 is HValid Start
4130	 * bytes 15-16 is HValid End
4131	 */
4132	mode->hsync_start = ROM16(mode_entry[17]) + 1;
4133	mode->hsync_end = ROM16(mode_entry[19]) + 1;
4134	mode->htotal = ROM16(mode_entry[21]) + 1;
4135	/* bytes 23-24, 27-30 similarly, but vertical */
4136	mode->vdisplay = ROM16(mode_entry[25]) + 1;
4137	mode->vsync_start = ROM16(mode_entry[31]) + 1;
4138	mode->vsync_end = ROM16(mode_entry[33]) + 1;
4139	mode->vtotal = ROM16(mode_entry[35]) + 1;
4140	mode->flags |= (mode_entry[37] & 0x10) ?
4141			DRM_MODE_FLAG_PHSYNC : DRM_MODE_FLAG_NHSYNC;
4142	mode->flags |= (mode_entry[37] & 0x1) ?
4143			DRM_MODE_FLAG_PVSYNC : DRM_MODE_FLAG_NVSYNC;
4144	/*
4145	 * bytes 38-39 relate to spread spectrum settings
4146	 * bytes 40-43 are something to do with PWM
4147	 */
4148
4149	mode->status = MODE_OK;
4150	mode->type = DRM_MODE_TYPE_DRIVER | DRM_MODE_TYPE_PREFERRED;
4151	drm_mode_set_name(mode);
4152	return bios->fp.mode_ptr;
4153}
4154
4155int nouveau_bios_parse_lvds_table(struct drm_device *dev, int pxclk, bool *dl, bool *if_is_24bit)
4156{
4157	/*
4158	 * The LVDS table header is (mostly) described in
4159	 * parse_lvds_manufacturer_table_header(): the BIT header additionally
4160	 * contains the dual-link transition pxclk (in 10s kHz), at byte 5 - if
4161	 * straps are not being used for the panel, this specifies the frequency
4162	 * at which modes should be set up in the dual link style.
4163	 *
4164	 * Following the header, the BMP (ver 0xa) table has several records,
4165	 * indexed by a separate xlat table, indexed in turn by the fp strap in
4166	 * EXTDEV_BOOT. Each record had a config byte, followed by 6 script
4167	 * numbers for use by INIT_SUB which controlled panel init and power,
4168	 * and finally a dword of ms to sleep between power off and on
4169	 * operations.
4170	 *
4171	 * In the BIT versions, the table following the header serves as an
4172	 * integrated config and xlat table: the records in the table are
4173	 * indexed by the FP strap nibble in EXTDEV_BOOT, and each record has
4174	 * two bytes - the first as a config byte, the second for indexing the
4175	 * fp mode table pointed to by the BIT 'D' table
4176	 *
4177	 * DDC is not used until after card init, so selecting the correct table
4178	 * entry and setting the dual link flag for EDID equipped panels,
4179	 * requiring tests against the native-mode pixel clock, cannot be done
4180	 * until later, when this function should be called with non-zero pxclk
4181	 */
4182	struct drm_nouveau_private *dev_priv = dev->dev_private;
4183	struct nvbios *bios = &dev_priv->vbios;
4184	int fpstrapping = get_fp_strap(dev, bios), lvdsmanufacturerindex = 0;
4185	struct lvdstableheader lth;
4186	uint16_t lvdsofs;
4187	int ret, chip_version = bios->chip_version;
4188
4189	ret = parse_lvds_manufacturer_table_header(dev, bios, &lth);
4190	if (ret)
4191		return ret;
4192
4193	switch (lth.lvds_ver) {
4194	case 0x0a:	/* pre NV40 */
4195		lvdsmanufacturerindex = bios->data[
4196					bios->fp.fpxlatemanufacturertableptr +
4197					fpstrapping];
4198
4199		/* we're done if this isn't the EDID panel case */
4200		if (!pxclk)
4201			break;
4202
4203		if (chip_version < 0x25) {
4204			/* nv17 behaviour
4205			 *
4206			 * It seems the old style lvds script pointer is reused
4207			 * to select 18/24 bit colour depth for EDID panels.
4208			 */
4209			lvdsmanufacturerindex =
4210				(bios->legacy.lvds_single_a_script_ptr & 1) ?
4211									2 : 0;
4212			if (pxclk >= bios->fp.duallink_transition_clk)
4213				lvdsmanufacturerindex++;
4214		} else if (chip_version < 0x30) {
4215			/* nv28 behaviour (off-chip encoder)
4216			 *
4217			 * nv28 does a complex dance of first using byte 121 of
4218			 * the EDID to choose the lvdsmanufacturerindex, then
4219			 * later attempting to match the EDID manufacturer and
4220			 * product IDs in a table (signature 'pidt' (panel id
4221			 * table?)), setting an lvdsmanufacturerindex of 0 and
4222			 * an fp strap of the match index (or 0xf if none)
4223			 */
4224			lvdsmanufacturerindex = 0;
4225		} else {
4226			/* nv31, nv34 behaviour */
4227			lvdsmanufacturerindex = 0;
4228			if (pxclk >= bios->fp.duallink_transition_clk)
4229				lvdsmanufacturerindex = 2;
4230			if (pxclk >= 140000)
4231				lvdsmanufacturerindex = 3;
4232		}
4233
4234		/*
4235		 * nvidia set the high nibble of (cr57=f, cr58) to
4236		 * lvdsmanufacturerindex in this case; we don't
4237		 */
4238		break;
4239	case 0x30:	/* NV4x */
4240	case 0x40:	/* G80/G90 */
4241		lvdsmanufacturerindex = fpstrapping;
4242		break;
4243	default:
4244		NV_ERROR(dev, "LVDS table revision not currently supported\n");
4245		return -ENOSYS;
4246	}
4247
4248	lvdsofs = bios->fp.xlated_entry = bios->fp.lvdsmanufacturerpointer + lth.headerlen + lth.recordlen * lvdsmanufacturerindex;
4249	switch (lth.lvds_ver) {
4250	case 0x0a:
4251		bios->fp.power_off_for_reset = bios->data[lvdsofs] & 1;
4252		bios->fp.reset_after_pclk_change = bios->data[lvdsofs] & 2;
4253		bios->fp.dual_link = bios->data[lvdsofs] & 4;
4254		bios->fp.link_c_increment = bios->data[lvdsofs] & 8;
4255		*if_is_24bit = bios->data[lvdsofs] & 16;
4256		break;
4257	case 0x30:
4258	case 0x40:
4259		/*
4260		 * No sign of the "power off for reset" or "reset for panel
4261		 * on" bits, but it's safer to assume we should
4262		 */
4263		bios->fp.power_off_for_reset = true;
4264		bios->fp.reset_after_pclk_change = true;
4265
4266		/*
4267		 * It's ok lvdsofs is wrong for nv4x edid case; dual_link is
4268		 * over-written, and if_is_24bit isn't used
4269		 */
4270		bios->fp.dual_link = bios->data[lvdsofs] & 1;
4271		bios->fp.if_is_24bit = bios->data[lvdsofs] & 2;
4272		bios->fp.strapless_is_24bit = bios->data[bios->fp.lvdsmanufacturerpointer + 4];
4273		bios->fp.duallink_transition_clk = ROM16(bios->data[bios->fp.lvdsmanufacturerpointer + 5]) * 10;
4274		break;
4275	}
4276
4277	/* set dual_link flag for EDID case */
4278	if (pxclk && (chip_version < 0x25 || chip_version > 0x28))
4279		bios->fp.dual_link = (pxclk >= bios->fp.duallink_transition_clk);
4280
4281	*dl = bios->fp.dual_link;
4282
4283	return 0;
4284}
4285
4286/* BIT 'U'/'d' table encoder subtables have hashes matching them to
4287 * a particular set of encoders.
4288 *
4289 * This function returns true if a particular DCB entry matches.
4290 */
4291bool
4292bios_encoder_match(struct dcb_entry *dcb, u32 hash)
4293{
4294	if ((hash & 0x000000f0) != (dcb->location << 4))
4295		return false;
4296	if ((hash & 0x0000000f) != dcb->type)
4297		return false;
4298	if (!(hash & (dcb->or << 16)))
4299		return false;
4300
4301	switch (dcb->type) {
4302	case OUTPUT_TMDS:
4303	case OUTPUT_LVDS:
4304	case OUTPUT_DP:
4305		if (hash & 0x00c00000) {
4306			if (!(hash & (dcb->sorconf.link << 22)))
4307				return false;
4308		}
4309	default:
4310		return true;
4311	}
4312}
4313
4314int
4315nouveau_bios_run_display_table(struct drm_device *dev, u16 type, int pclk,
4316			       struct dcb_entry *dcbent, int crtc)
4317{
4318	/*
4319	 * The display script table is located by the BIT 'U' table.
4320	 *
4321	 * It contains an array of pointers to various tables describing
4322	 * a particular output type.  The first 32-bits of the output
4323	 * tables contains similar information to a DCB entry, and is
4324	 * used to decide whether that particular table is suitable for
4325	 * the output you want to access.
4326	 *
4327	 * The "record header length" field here seems to indicate the
4328	 * offset of the first configuration entry in the output tables.
4329	 * This is 10 on most cards I've seen, but 12 has been witnessed
4330	 * on DP cards, and there's another script pointer within the
4331	 * header.
4332	 *
4333	 * offset + 0   ( 8 bits): version
4334	 * offset + 1   ( 8 bits): header length
4335	 * offset + 2   ( 8 bits): record length
4336	 * offset + 3   ( 8 bits): number of records
4337	 * offset + 4   ( 8 bits): record header length
4338	 * offset + 5   (16 bits): pointer to first output script table
4339	 */
4340
4341	struct drm_nouveau_private *dev_priv = dev->dev_private;
4342	struct nvbios *bios = &dev_priv->vbios;
4343	uint8_t *table = &bios->data[bios->display.script_table_ptr];
4344	uint8_t *otable = NULL;
4345	uint16_t script;
4346	int i;
4347
4348	if (!bios->display.script_table_ptr) {
4349		NV_ERROR(dev, "No pointer to output script table\n");
4350		return 1;
4351	}
4352
4353	/*
4354	 * Nothing useful has been in any of the pre-2.0 tables I've seen,
4355	 * so until they are, we really don't need to care.
4356	 */
4357	if (table[0] < 0x20)
4358		return 1;
4359
4360	if (table[0] != 0x20 && table[0] != 0x21) {
4361		NV_ERROR(dev, "Output script table version 0x%02x unknown\n",
4362			 table[0]);
4363		return 1;
4364	}
4365
4366	/*
4367	 * The output script tables describing a particular output type
4368	 * look as follows:
4369	 *
4370	 * offset + 0   (32 bits): output this table matches (hash of DCB)
4371	 * offset + 4   ( 8 bits): unknown
4372	 * offset + 5   ( 8 bits): number of configurations
4373	 * offset + 6   (16 bits): pointer to some script
4374	 * offset + 8   (16 bits): pointer to some script
4375	 *
4376	 * headerlen == 10
4377	 * offset + 10           : configuration 0
4378	 *
4379	 * headerlen == 12
4380	 * offset + 10           : pointer to some script
4381	 * offset + 12           : configuration 0
4382	 *
4383	 * Each config entry is as follows:
4384	 *
4385	 * offset + 0   (16 bits): unknown, assumed to be a match value
4386	 * offset + 2   (16 bits): pointer to script table (clock set?)
4387	 * offset + 4   (16 bits): pointer to script table (reset?)
4388	 *
4389	 * There doesn't appear to be a count value to say how many
4390	 * entries exist in each script table, instead, a 0 value in
4391	 * the first 16-bit word seems to indicate both the end of the
4392	 * list and the default entry.  The second 16-bit word in the
4393	 * script tables is a pointer to the script to execute.
4394	 */
4395
4396	NV_DEBUG_KMS(dev, "Searching for output entry for %d %d %d\n",
4397			dcbent->type, dcbent->location, dcbent->or);
4398	for (i = 0; i < table[3]; i++) {
4399		otable = ROMPTR(dev, table[table[1] + (i * table[2])]);
4400		if (otable && bios_encoder_match(dcbent, ROM32(otable[0])))
4401			break;
4402	}
4403
4404	if (!otable) {
4405		NV_DEBUG_KMS(dev, "failed to match any output table\n");
4406		return 1;
4407	}
4408
4409	if (pclk < -2 || pclk > 0) {
4410		/* Try to find matching script table entry */
4411		for (i = 0; i < otable[5]; i++) {
4412			if (ROM16(otable[table[4] + i*6]) == type)
4413				break;
4414		}
4415
4416		if (i == otable[5]) {
4417			NV_ERROR(dev, "Table 0x%04x not found for %d/%d, "
4418				      "using first\n",
4419				 type, dcbent->type, dcbent->or);
4420			i = 0;
4421		}
4422	}
4423
4424	if (pclk == 0) {
4425		script = ROM16(otable[6]);
4426		if (!script) {
4427			NV_DEBUG_KMS(dev, "output script 0 not found\n");
4428			return 1;
4429		}
4430
4431		NV_DEBUG_KMS(dev, "0x%04X: parsing output script 0\n", script);
4432		nouveau_bios_run_init_table(dev, script, dcbent, crtc);
4433	} else
4434	if (pclk == -1) {
4435		script = ROM16(otable[8]);
4436		if (!script) {
4437			NV_DEBUG_KMS(dev, "output script 1 not found\n");
4438			return 1;
4439		}
4440
4441		NV_DEBUG_KMS(dev, "0x%04X: parsing output script 1\n", script);
4442		nouveau_bios_run_init_table(dev, script, dcbent, crtc);
4443	} else
4444	if (pclk == -2) {
4445		if (table[4] >= 12)
4446			script = ROM16(otable[10]);
4447		else
4448			script = 0;
4449		if (!script) {
4450			NV_DEBUG_KMS(dev, "output script 2 not found\n");
4451			return 1;
4452		}
4453
4454		NV_DEBUG_KMS(dev, "0x%04X: parsing output script 2\n", script);
4455		nouveau_bios_run_init_table(dev, script, dcbent, crtc);
4456	} else
4457	if (pclk > 0) {
4458		script = ROM16(otable[table[4] + i*6 + 2]);
4459		if (script)
4460			script = clkcmptable(bios, script, pclk);
4461		if (!script) {
4462			NV_DEBUG_KMS(dev, "clock script 0 not found\n");
4463			return 1;
4464		}
4465
4466		NV_DEBUG_KMS(dev, "0x%04X: parsing clock script 0\n", script);
4467		nouveau_bios_run_init_table(dev, script, dcbent, crtc);
4468	} else
4469	if (pclk < 0) {
4470		script = ROM16(otable[table[4] + i*6 + 4]);
4471		if (script)
4472			script = clkcmptable(bios, script, -pclk);
4473		if (!script) {
4474			NV_DEBUG_KMS(dev, "clock script 1 not found\n");
4475			return 1;
4476		}
4477
4478		NV_DEBUG_KMS(dev, "0x%04X: parsing clock script 1\n", script);
4479		nouveau_bios_run_init_table(dev, script, dcbent, crtc);
4480	}
4481
4482	return 0;
4483}
4484
4485
4486int run_tmds_table(struct drm_device *dev, struct dcb_entry *dcbent, int head, int pxclk)
4487{
4488	/*
4489	 * the pxclk parameter is in kHz
4490	 *
4491	 * This runs the TMDS regs setting code found on BIT bios cards
4492	 *
4493	 * For ffs(or) == 1 use the first table, for ffs(or) == 2 and
4494	 * ffs(or) == 3, use the second.
4495	 */
4496
4497	struct drm_nouveau_private *dev_priv = dev->dev_private;
4498	struct nvbios *bios = &dev_priv->vbios;
4499	int cv = bios->chip_version;
4500	uint16_t clktable = 0, scriptptr;
4501	uint32_t sel_clk_binding, sel_clk;
4502
4503	/* pre-nv17 off-chip tmds uses scripts, post nv17 doesn't */
4504	if (cv >= 0x17 && cv != 0x1a && cv != 0x20 &&
4505	    dcbent->location != DCB_LOC_ON_CHIP)
4506		return 0;
4507
4508	switch (ffs(dcbent->or)) {
4509	case 1:
4510		clktable = bios->tmds.output0_script_ptr;
4511		break;
4512	case 2:
4513	case 3:
4514		clktable = bios->tmds.output1_script_ptr;
4515		break;
4516	}
4517
4518	if (!clktable) {
4519		NV_ERROR(dev, "Pixel clock comparison table not found\n");
4520		return -EINVAL;
4521	}
4522
4523	scriptptr = clkcmptable(bios, clktable, pxclk);
4524
4525	if (!scriptptr) {
4526		NV_ERROR(dev, "TMDS output init script not found\n");
4527		return -ENOENT;
4528	}
4529
4530	/* don't let script change pll->head binding */
4531	sel_clk_binding = bios_rd32(bios, NV_PRAMDAC_SEL_CLK) & 0x50000;
4532	run_digital_op_script(dev, scriptptr, dcbent, head, pxclk >= 165000);
4533	sel_clk = NVReadRAMDAC(dev, 0, NV_PRAMDAC_SEL_CLK) & ~0x50000;
4534	NVWriteRAMDAC(dev, 0, NV_PRAMDAC_SEL_CLK, sel_clk | sel_clk_binding);
4535
4536	return 0;
4537}
4538
4539struct pll_mapping {
4540	u8  type;
4541	u32 reg;
4542};
4543
4544static struct pll_mapping nv04_pll_mapping[] = {
4545	{ PLL_CORE  , NV_PRAMDAC_NVPLL_COEFF },
4546	{ PLL_MEMORY, NV_PRAMDAC_MPLL_COEFF },
4547	{ PLL_VPLL0 , NV_PRAMDAC_VPLL_COEFF },
4548	{ PLL_VPLL1 , NV_RAMDAC_VPLL2 },
4549	{}
4550};
4551
4552static struct pll_mapping nv40_pll_mapping[] = {
4553	{ PLL_CORE  , 0x004000 },
4554	{ PLL_MEMORY, 0x004020 },
4555	{ PLL_VPLL0 , NV_PRAMDAC_VPLL_COEFF },
4556	{ PLL_VPLL1 , NV_RAMDAC_VPLL2 },
4557	{}
4558};
4559
4560static struct pll_mapping nv50_pll_mapping[] = {
4561	{ PLL_CORE  , 0x004028 },
4562	{ PLL_SHADER, 0x004020 },
4563	{ PLL_UNK03 , 0x004000 },
4564	{ PLL_MEMORY, 0x004008 },
4565	{ PLL_UNK40 , 0x00e810 },
4566	{ PLL_UNK41 , 0x00e818 },
4567	{ PLL_UNK42 , 0x00e824 },
4568	{ PLL_VPLL0 , 0x614100 },
4569	{ PLL_VPLL1 , 0x614900 },
4570	{}
4571};
4572
4573static struct pll_mapping nv84_pll_mapping[] = {
4574	{ PLL_CORE  , 0x004028 },
4575	{ PLL_SHADER, 0x004020 },
4576	{ PLL_MEMORY, 0x004008 },
4577	{ PLL_VDEC  , 0x004030 },
4578	{ PLL_UNK41 , 0x00e818 },
4579	{ PLL_VPLL0 , 0x614100 },
4580	{ PLL_VPLL1 , 0x614900 },
4581	{}
4582};
4583
4584u32
4585get_pll_register(struct drm_device *dev, enum pll_types type)
4586{
4587	struct drm_nouveau_private *dev_priv = dev->dev_private;
4588	struct nvbios *bios = &dev_priv->vbios;
4589	struct pll_mapping *map;
4590	int i;
4591
4592	if (dev_priv->card_type < NV_40)
4593		map = nv04_pll_mapping;
4594	else
4595	if (dev_priv->card_type < NV_50)
4596		map = nv40_pll_mapping;
4597	else {
4598		u8 *plim = &bios->data[bios->pll_limit_tbl_ptr];
4599
4600		if (plim[0] >= 0x30) {
4601			u8 *entry = plim + plim[1];
4602			for (i = 0; i < plim[3]; i++, entry += plim[2]) {
4603				if (entry[0] == type)
4604					return ROM32(entry[3]);
4605			}
4606
4607			return 0;
4608		}
4609
4610		if (dev_priv->chipset == 0x50)
4611			map = nv50_pll_mapping;
4612		else
4613			map = nv84_pll_mapping;
4614	}
4615
4616	while (map->reg) {
4617		if (map->type == type)
4618			return map->reg;
4619		map++;
4620	}
4621
4622	return 0;
4623}
4624
4625int get_pll_limits(struct drm_device *dev, uint32_t limit_match, struct pll_lims *pll_lim)
4626{
4627	/*
4628	 * PLL limits table
4629	 *
4630	 * Version 0x10: NV30, NV31
4631	 * One byte header (version), one record of 24 bytes
4632	 * Version 0x11: NV36 - Not implemented
4633	 * Seems to have same record style as 0x10, but 3 records rather than 1
4634	 * Version 0x20: Found on Geforce 6 cards
4635	 * Trivial 4 byte BIT header. 31 (0x1f) byte record length
4636	 * Version 0x21: Found on Geforce 7, 8 and some Geforce 6 cards
4637	 * 5 byte header, fifth byte of unknown purpose. 35 (0x23) byte record
4638	 * length in general, some (integrated) have an extra configuration byte
4639	 * Version 0x30: Found on Geforce 8, separates the register mapping
4640	 * from the limits tables.
4641	 */
4642
4643	struct drm_nouveau_private *dev_priv = dev->dev_private;
4644	struct nvbios *bios = &dev_priv->vbios;
4645	int cv = bios->chip_version, pllindex = 0;
4646	uint8_t pll_lim_ver = 0, headerlen = 0, recordlen = 0, entries = 0;
4647	uint32_t crystal_strap_mask, crystal_straps;
4648
4649	if (!bios->pll_limit_tbl_ptr) {
4650		if (cv == 0x30 || cv == 0x31 || cv == 0x35 || cv == 0x36 ||
4651		    cv >= 0x40) {
4652			NV_ERROR(dev, "Pointer to PLL limits table invalid\n");
4653			return -EINVAL;
4654		}
4655	} else
4656		pll_lim_ver = bios->data[bios->pll_limit_tbl_ptr];
4657
4658	crystal_strap_mask = 1 << 6;
4659	/* open coded dev->twoHeads test */
4660	if (cv > 0x10 && cv != 0x15 && cv != 0x1a && cv != 0x20)
4661		crystal_strap_mask |= 1 << 22;
4662	crystal_straps = nvReadEXTDEV(dev, NV_PEXTDEV_BOOT_0) &
4663							crystal_strap_mask;
4664
4665	switch (pll_lim_ver) {
4666	/*
4667	 * We use version 0 to indicate a pre limit table bios (single stage
4668	 * pll) and load the hard coded limits instead.
4669	 */
4670	case 0:
4671		break;
4672	case 0x10:
4673	case 0x11:
4674		/*
4675		 * Strictly v0x11 has 3 entries, but the last two don't seem
4676		 * to get used.
4677		 */
4678		headerlen = 1;
4679		recordlen = 0x18;
4680		entries = 1;
4681		pllindex = 0;
4682		break;
4683	case 0x20:
4684	case 0x21:
4685	case 0x30:
4686	case 0x40:
4687		headerlen = bios->data[bios->pll_limit_tbl_ptr + 1];
4688		recordlen = bios->data[bios->pll_limit_tbl_ptr + 2];
4689		entries = bios->data[bios->pll_limit_tbl_ptr + 3];
4690		break;
4691	default:
4692		NV_ERROR(dev, "PLL limits table revision 0x%X not currently "
4693				"supported\n", pll_lim_ver);
4694		return -ENOSYS;
4695	}
4696
4697	/* initialize all members to zero */
4698	memset(pll_lim, 0, sizeof(struct pll_lims));
4699
4700	/* if we were passed a type rather than a register, figure
4701	 * out the register and store it
4702	 */
4703	if (limit_match > PLL_MAX)
4704		pll_lim->reg = limit_match;
4705	else {
4706		pll_lim->reg = get_pll_register(dev, limit_match);
4707		if (!pll_lim->reg)
4708			return -ENOENT;
4709	}
4710
4711	if (pll_lim_ver == 0x10 || pll_lim_ver == 0x11) {
4712		uint8_t *pll_rec = &bios->data[bios->pll_limit_tbl_ptr + headerlen + recordlen * pllindex];
4713
4714		pll_lim->vco1.minfreq = ROM32(pll_rec[0]);
4715		pll_lim->vco1.maxfreq = ROM32(pll_rec[4]);
4716		pll_lim->vco2.minfreq = ROM32(pll_rec[8]);
4717		pll_lim->vco2.maxfreq = ROM32(pll_rec[12]);
4718		pll_lim->vco1.min_inputfreq = ROM32(pll_rec[16]);
4719		pll_lim->vco2.min_inputfreq = ROM32(pll_rec[20]);
4720		pll_lim->vco1.max_inputfreq = pll_lim->vco2.max_inputfreq = INT_MAX;
4721
4722		/* these values taken from nv30/31/36 */
4723		pll_lim->vco1.min_n = 0x1;
4724		if (cv == 0x36)
4725			pll_lim->vco1.min_n = 0x5;
4726		pll_lim->vco1.max_n = 0xff;
4727		pll_lim->vco1.min_m = 0x1;
4728		pll_lim->vco1.max_m = 0xd;
4729		pll_lim->vco2.min_n = 0x4;
4730		/*
4731		 * On nv30, 31, 36 (i.e. all cards with two stage PLLs with this
4732		 * table version (apart from nv35)), N2 is compared to
4733		 * maxN2 (0x46) and 10 * maxM2 (0x4), so set maxN2 to 0x28 and
4734		 * save a comparison
4735		 */
4736		pll_lim->vco2.max_n = 0x28;
4737		if (cv == 0x30 || cv == 0x35)
4738			/* only 5 bits available for N2 on nv30/35 */
4739			pll_lim->vco2.max_n = 0x1f;
4740		pll_lim->vco2.min_m = 0x1;
4741		pll_lim->vco2.max_m = 0x4;
4742		pll_lim->max_log2p = 0x7;
4743		pll_lim->max_usable_log2p = 0x6;
4744	} else if (pll_lim_ver == 0x20 || pll_lim_ver == 0x21) {
4745		uint16_t plloffs = bios->pll_limit_tbl_ptr + headerlen;
4746		uint8_t *pll_rec;
4747		int i;
4748
4749		/*
4750		 * First entry is default match, if nothing better. warn if
4751		 * reg field nonzero
4752		 */
4753		if (ROM32(bios->data[plloffs]))
4754			NV_WARN(dev, "Default PLL limit entry has non-zero "
4755				       "register field\n");
4756
4757		for (i = 1; i < entries; i++)
4758			if (ROM32(bios->data[plloffs + recordlen * i]) == pll_lim->reg) {
4759				pllindex = i;
4760				break;
4761			}
4762
4763		if ((dev_priv->card_type >= NV_50) && (pllindex == 0)) {
4764			NV_ERROR(dev, "Register 0x%08x not found in PLL "
4765				 "limits table", pll_lim->reg);
4766			return -ENOENT;
4767		}
4768
4769		pll_rec = &bios->data[plloffs + recordlen * pllindex];
4770
4771		BIOSLOG(bios, "Loading PLL limits for reg 0x%08x\n",
4772			pllindex ? pll_lim->reg : 0);
4773
4774		/*
4775		 * Frequencies are stored in tables in MHz, kHz are more
4776		 * useful, so we convert.
4777		 */
4778
4779		/* What output frequencies can each VCO generate? */
4780		pll_lim->vco1.minfreq = ROM16(pll_rec[4]) * 1000;
4781		pll_lim->vco1.maxfreq = ROM16(pll_rec[6]) * 1000;
4782		pll_lim->vco2.minfreq = ROM16(pll_rec[8]) * 1000;
4783		pll_lim->vco2.maxfreq = ROM16(pll_rec[10]) * 1000;
4784
4785		/* What input frequencies they accept (past the m-divider)? */
4786		pll_lim->vco1.min_inputfreq = ROM16(pll_rec[12]) * 1000;
4787		pll_lim->vco2.min_inputfreq = ROM16(pll_rec[14]) * 1000;
4788		pll_lim->vco1.max_inputfreq = ROM16(pll_rec[16]) * 1000;
4789		pll_lim->vco2.max_inputfreq = ROM16(pll_rec[18]) * 1000;
4790
4791		/* What values are accepted as multiplier and divider? */
4792		pll_lim->vco1.min_n = pll_rec[20];
4793		pll_lim->vco1.max_n = pll_rec[21];
4794		pll_lim->vco1.min_m = pll_rec[22];
4795		pll_lim->vco1.max_m = pll_rec[23];
4796		pll_lim->vco2.min_n = pll_rec[24];
4797		pll_lim->vco2.max_n = pll_rec[25];
4798		pll_lim->vco2.min_m = pll_rec[26];
4799		pll_lim->vco2.max_m = pll_rec[27];
4800
4801		pll_lim->max_usable_log2p = pll_lim->max_log2p = pll_rec[29];
4802		if (pll_lim->max_log2p > 0x7)
4803			/* pll decoding in nv_hw.c assumes never > 7 */
4804			NV_WARN(dev, "Max log2 P value greater than 7 (%d)\n",
4805				pll_lim->max_log2p);
4806		if (cv < 0x60)
4807			pll_lim->max_usable_log2p = 0x6;
4808		pll_lim->log2p_bias = pll_rec[30];
4809
4810		if (recordlen > 0x22)
4811			pll_lim->refclk = ROM32(pll_rec[31]);
4812
4813		if (recordlen > 0x23 && pll_rec[35])
4814			NV_WARN(dev,
4815				"Bits set in PLL configuration byte (%x)\n",
4816				pll_rec[35]);
4817
4818		/* C51 special not seen elsewhere */
4819		if (cv == 0x51 && !pll_lim->refclk) {
4820			uint32_t sel_clk = bios_rd32(bios, NV_PRAMDAC_SEL_CLK);
4821
4822			if ((pll_lim->reg == NV_PRAMDAC_VPLL_COEFF && sel_clk & 0x20) ||
4823			    (pll_lim->reg == NV_RAMDAC_VPLL2 && sel_clk & 0x80)) {
4824				if (bios_idxprt_rd(bios, NV_CIO_CRX__COLOR, NV_CIO_CRE_CHIP_ID_INDEX) < 0xa3)
4825					pll_lim->refclk = 200000;
4826				else
4827					pll_lim->refclk = 25000;
4828			}
4829		}
4830	} else if (pll_lim_ver == 0x30) { /* ver 0x30 */
4831		uint8_t *entry = &bios->data[bios->pll_limit_tbl_ptr + headerlen];
4832		uint8_t *record = NULL;
4833		int i;
4834
4835		BIOSLOG(bios, "Loading PLL limits for register 0x%08x\n",
4836			pll_lim->reg);
4837
4838		for (i = 0; i < entries; i++, entry += recordlen) {
4839			if (ROM32(entry[3]) == pll_lim->reg) {
4840				record = &bios->data[ROM16(entry[1])];
4841				break;
4842			}
4843		}
4844
4845		if (!record) {
4846			NV_ERROR(dev, "Register 0x%08x not found in PLL "
4847				 "limits table", pll_lim->reg);
4848			return -ENOENT;
4849		}
4850
4851		pll_lim->vco1.minfreq = ROM16(record[0]) * 1000;
4852		pll_lim->vco1.maxfreq = ROM16(record[2]) * 1000;
4853		pll_lim->vco2.minfreq = ROM16(record[4]) * 1000;
4854		pll_lim->vco2.maxfreq = ROM16(record[6]) * 1000;
4855		pll_lim->vco1.min_inputfreq = ROM16(record[8]) * 1000;
4856		pll_lim->vco2.min_inputfreq = ROM16(record[10]) * 1000;
4857		pll_lim->vco1.max_inputfreq = ROM16(record[12]) * 1000;
4858		pll_lim->vco2.max_inputfreq = ROM16(record[14]) * 1000;
4859		pll_lim->vco1.min_n = record[16];
4860		pll_lim->vco1.max_n = record[17];
4861		pll_lim->vco1.min_m = record[18];
4862		pll_lim->vco1.max_m = record[19];
4863		pll_lim->vco2.min_n = record[20];
4864		pll_lim->vco2.max_n = record[21];
4865		pll_lim->vco2.min_m = record[22];
4866		pll_lim->vco2.max_m = record[23];
4867		pll_lim->max_usable_log2p = pll_lim->max_log2p = record[25];
4868		pll_lim->log2p_bias = record[27];
4869		pll_lim->refclk = ROM32(record[28]);
4870	} else if (pll_lim_ver) { /* ver 0x40 */
4871		uint8_t *entry = &bios->data[bios->pll_limit_tbl_ptr + headerlen];
4872		uint8_t *record = NULL;
4873		int i;
4874
4875		BIOSLOG(bios, "Loading PLL limits for register 0x%08x\n",
4876			pll_lim->reg);
4877
4878		for (i = 0; i < entries; i++, entry += recordlen) {
4879			if (ROM32(entry[3]) == pll_lim->reg) {
4880				record = &bios->data[ROM16(entry[1])];
4881				break;
4882			}
4883		}
4884
4885		if (!record) {
4886			NV_ERROR(dev, "Register 0x%08x not found in PLL "
4887				 "limits table", pll_lim->reg);
4888			return -ENOENT;
4889		}
4890
4891		pll_lim->vco1.minfreq = ROM16(record[0]) * 1000;
4892		pll_lim->vco1.maxfreq = ROM16(record[2]) * 1000;
4893		pll_lim->vco1.min_inputfreq = ROM16(record[4]) * 1000;
4894		pll_lim->vco1.max_inputfreq = ROM16(record[6]) * 1000;
4895		pll_lim->vco1.min_m = record[8];
4896		pll_lim->vco1.max_m = record[9];
4897		pll_lim->vco1.min_n = record[10];
4898		pll_lim->vco1.max_n = record[11];
4899		pll_lim->min_p = record[12];
4900		pll_lim->max_p = record[13];
4901		pll_lim->refclk = ROM16(entry[9]) * 1000;
4902	}
4903
4904	/*
4905	 * By now any valid limit table ought to have set a max frequency for
4906	 * vco1, so if it's zero it's either a pre limit table bios, or one
4907	 * with an empty limit table (seen on nv18)
4908	 */
4909	if (!pll_lim->vco1.maxfreq) {
4910		pll_lim->vco1.minfreq = bios->fminvco;
4911		pll_lim->vco1.maxfreq = bios->fmaxvco;
4912		pll_lim->vco1.min_inputfreq = 0;
4913		pll_lim->vco1.max_inputfreq = INT_MAX;
4914		pll_lim->vco1.min_n = 0x1;
4915		pll_lim->vco1.max_n = 0xff;
4916		pll_lim->vco1.min_m = 0x1;
4917		if (crystal_straps == 0) {
4918			/* nv05 does this, nv11 doesn't, nv10 unknown */
4919			if (cv < 0x11)
4920				pll_lim->vco1.min_m = 0x7;
4921			pll_lim->vco1.max_m = 0xd;
4922		} else {
4923			if (cv < 0x11)
4924				pll_lim->vco1.min_m = 0x8;
4925			pll_lim->vco1.max_m = 0xe;
4926		}
4927		if (cv < 0x17 || cv == 0x1a || cv == 0x20)
4928			pll_lim->max_log2p = 4;
4929		else
4930			pll_lim->max_log2p = 5;
4931		pll_lim->max_usable_log2p = pll_lim->max_log2p;
4932	}
4933
4934	if (!pll_lim->refclk)
4935		switch (crystal_straps) {
4936		case 0:
4937			pll_lim->refclk = 13500;
4938			break;
4939		case (1 << 6):
4940			pll_lim->refclk = 14318;
4941			break;
4942		case (1 << 22):
4943			pll_lim->refclk = 27000;
4944			break;
4945		case (1 << 22 | 1 << 6):
4946			pll_lim->refclk = 25000;
4947			break;
4948		}
4949
4950	NV_DEBUG(dev, "pll.vco1.minfreq: %d\n", pll_lim->vco1.minfreq);
4951	NV_DEBUG(dev, "pll.vco1.maxfreq: %d\n", pll_lim->vco1.maxfreq);
4952	NV_DEBUG(dev, "pll.vco1.min_inputfreq: %d\n", pll_lim->vco1.min_inputfreq);
4953	NV_DEBUG(dev, "pll.vco1.max_inputfreq: %d\n", pll_lim->vco1.max_inputfreq);
4954	NV_DEBUG(dev, "pll.vco1.min_n: %d\n", pll_lim->vco1.min_n);
4955	NV_DEBUG(dev, "pll.vco1.max_n: %d\n", pll_lim->vco1.max_n);
4956	NV_DEBUG(dev, "pll.vco1.min_m: %d\n", pll_lim->vco1.min_m);
4957	NV_DEBUG(dev, "pll.vco1.max_m: %d\n", pll_lim->vco1.max_m);
4958	if (pll_lim->vco2.maxfreq) {
4959		NV_DEBUG(dev, "pll.vco2.minfreq: %d\n", pll_lim->vco2.minfreq);
4960		NV_DEBUG(dev, "pll.vco2.maxfreq: %d\n", pll_lim->vco2.maxfreq);
4961		NV_DEBUG(dev, "pll.vco2.min_inputfreq: %d\n", pll_lim->vco2.min_inputfreq);
4962		NV_DEBUG(dev, "pll.vco2.max_inputfreq: %d\n", pll_lim->vco2.max_inputfreq);
4963		NV_DEBUG(dev, "pll.vco2.min_n: %d\n", pll_lim->vco2.min_n);
4964		NV_DEBUG(dev, "pll.vco2.max_n: %d\n", pll_lim->vco2.max_n);
4965		NV_DEBUG(dev, "pll.vco2.min_m: %d\n", pll_lim->vco2.min_m);
4966		NV_DEBUG(dev, "pll.vco2.max_m: %d\n", pll_lim->vco2.max_m);
4967	}
4968	if (!pll_lim->max_p) {
4969		NV_DEBUG(dev, "pll.max_log2p: %d\n", pll_lim->max_log2p);
4970		NV_DEBUG(dev, "pll.log2p_bias: %d\n", pll_lim->log2p_bias);
4971	} else {
4972		NV_DEBUG(dev, "pll.min_p: %d\n", pll_lim->min_p);
4973		NV_DEBUG(dev, "pll.max_p: %d\n", pll_lim->max_p);
4974	}
4975	NV_DEBUG(dev, "pll.refclk: %d\n", pll_lim->refclk);
4976
4977	return 0;
4978}
4979
4980static void parse_bios_version(struct drm_device *dev, struct nvbios *bios, uint16_t offset)
4981{
4982	/*
4983	 * offset + 0  (8 bits): Micro version
4984	 * offset + 1  (8 bits): Minor version
4985	 * offset + 2  (8 bits): Chip version
4986	 * offset + 3  (8 bits): Major version
4987	 */
4988
4989	bios->major_version = bios->data[offset + 3];
4990	bios->chip_version = bios->data[offset + 2];
4991	NV_TRACE(dev, "Bios version %02x.%02x.%02x.%02x\n",
4992		 bios->data[offset + 3], bios->data[offset + 2],
4993		 bios->data[offset + 1], bios->data[offset]);
4994}
4995
4996static void parse_script_table_pointers(struct nvbios *bios, uint16_t offset)
4997{
4998	/*
4999	 * Parses the init table segment for pointers used in script execution.
5000	 *
5001	 * offset + 0  (16 bits): init script tables pointer
5002	 * offset + 2  (16 bits): macro index table pointer
5003	 * offset + 4  (16 bits): macro table pointer
5004	 * offset + 6  (16 bits): condition table pointer
5005	 * offset + 8  (16 bits): io condition table pointer
5006	 * offset + 10 (16 bits): io flag condition table pointer
5007	 * offset + 12 (16 bits): init function table pointer
5008	 */
5009
5010	bios->init_script_tbls_ptr = ROM16(bios->data[offset]);
5011	bios->macro_index_tbl_ptr = ROM16(bios->data[offset + 2]);
5012	bios->macro_tbl_ptr = ROM16(bios->data[offset + 4]);
5013	bios->condition_tbl_ptr = ROM16(bios->data[offset + 6]);
5014	bios->io_condition_tbl_ptr = ROM16(bios->data[offset + 8]);
5015	bios->io_flag_condition_tbl_ptr = ROM16(bios->data[offset + 10]);
5016	bios->init_function_tbl_ptr = ROM16(bios->data[offset + 12]);
5017}
5018
5019static int parse_bit_A_tbl_entry(struct drm_device *dev, struct nvbios *bios, struct bit_entry *bitentry)
5020{
5021	/*
5022	 * Parses the load detect values for g80 cards.
5023	 *
5024	 * offset + 0 (16 bits): loadval table pointer
5025	 */
5026
5027	uint16_t load_table_ptr;
5028	uint8_t version, headerlen, entrylen, num_entries;
5029
5030	if (bitentry->length != 3) {
5031		NV_ERROR(dev, "Do not understand BIT A table\n");
5032		return -EINVAL;
5033	}
5034
5035	load_table_ptr = ROM16(bios->data[bitentry->offset]);
5036
5037	if (load_table_ptr == 0x0) {
5038		NV_DEBUG(dev, "Pointer to BIT loadval table invalid\n");
5039		return -EINVAL;
5040	}
5041
5042	version = bios->data[load_table_ptr];
5043
5044	if (version != 0x10) {
5045		NV_ERROR(dev, "BIT loadval table version %d.%d not supported\n",
5046			 version >> 4, version & 0xF);
5047		return -ENOSYS;
5048	}
5049
5050	headerlen = bios->data[load_table_ptr + 1];
5051	entrylen = bios->data[load_table_ptr + 2];
5052	num_entries = bios->data[load_table_ptr + 3];
5053
5054	if (headerlen != 4 || entrylen != 4 || num_entries != 2) {
5055		NV_ERROR(dev, "Do not understand BIT loadval table\n");
5056		return -EINVAL;
5057	}
5058
5059	/* First entry is normal dac, 2nd tv-out perhaps? */
5060	bios->dactestval = ROM32(bios->data[load_table_ptr + headerlen]) & 0x3ff;
5061
5062	return 0;
5063}
5064
5065static int parse_bit_C_tbl_entry(struct drm_device *dev, struct nvbios *bios, struct bit_entry *bitentry)
5066{
5067	/*
5068	 * offset + 8  (16 bits): PLL limits table pointer
5069	 *
5070	 * There's more in here, but that's unknown.
5071	 */
5072
5073	if (bitentry->length < 10) {
5074		NV_ERROR(dev, "Do not understand BIT C table\n");
5075		return -EINVAL;
5076	}
5077
5078	bios->pll_limit_tbl_ptr = ROM16(bios->data[bitentry->offset + 8]);
5079
5080	return 0;
5081}
5082
5083static int parse_bit_display_tbl_entry(struct drm_device *dev, struct nvbios *bios, struct bit_entry *bitentry)
5084{
5085	/*
5086	 * Parses the flat panel table segment that the bit entry points to.
5087	 * Starting at bitentry->offset:
5088	 *
5089	 * offset + 0  (16 bits): ??? table pointer - seems to have 18 byte
5090	 * records beginning with a freq.
5091	 * offset + 2  (16 bits): mode table pointer
5092	 */
5093
5094	if (bitentry->length != 4) {
5095		NV_ERROR(dev, "Do not understand BIT display table\n");
5096		return -EINVAL;
5097	}
5098
5099	bios->fp.fptablepointer = ROM16(bios->data[bitentry->offset + 2]);
5100
5101	return 0;
5102}
5103
5104static int parse_bit_init_tbl_entry(struct drm_device *dev, struct nvbios *bios, struct bit_entry *bitentry)
5105{
5106	/*
5107	 * Parses the init table segment that the bit entry points to.
5108	 *
5109	 * See parse_script_table_pointers for layout
5110	 */
5111
5112	if (bitentry->length < 14) {
5113		NV_ERROR(dev, "Do not understand init table\n");
5114		return -EINVAL;
5115	}
5116
5117	parse_script_table_pointers(bios, bitentry->offset);
5118
5119	if (bitentry->length >= 16)
5120		bios->some_script_ptr = ROM16(bios->data[bitentry->offset + 14]);
5121	if (bitentry->length >= 18)
5122		bios->init96_tbl_ptr = ROM16(bios->data[bitentry->offset + 16]);
5123
5124	return 0;
5125}
5126
5127static int parse_bit_i_tbl_entry(struct drm_device *dev, struct nvbios *bios, struct bit_entry *bitentry)
5128{
5129	/*
5130	 * BIT 'i' (info?) table
5131	 *
5132	 * offset + 0  (32 bits): BIOS version dword (as in B table)
5133	 * offset + 5  (8  bits): BIOS feature byte (same as for BMP?)
5134	 * offset + 13 (16 bits): pointer to table containing DAC load
5135	 * detection comparison values
5136	 *
5137	 * There's other things in the table, purpose unknown
5138	 */
5139
5140	uint16_t daccmpoffset;
5141	uint8_t dacver, dacheaderlen;
5142
5143	if (bitentry->length < 6) {
5144		NV_ERROR(dev, "BIT i table too short for needed information\n");
5145		return -EINVAL;
5146	}
5147
5148	parse_bios_version(dev, bios, bitentry->offset);
5149
5150	/*
5151	 * bit 4 seems to indicate a mobile bios (doesn't suffer from BMP's
5152	 * Quadro identity crisis), other bits possibly as for BMP feature byte
5153	 */
5154	bios->feature_byte = bios->data[bitentry->offset + 5];
5155	bios->is_mobile = bios->feature_byte & FEATURE_MOBILE;
5156
5157	if (bitentry->length < 15) {
5158		NV_WARN(dev, "BIT i table not long enough for DAC load "
5159			       "detection comparison table\n");
5160		return -EINVAL;
5161	}
5162
5163	daccmpoffset = ROM16(bios->data[bitentry->offset + 13]);
5164
5165	/* doesn't exist on g80 */
5166	if (!daccmpoffset)
5167		return 0;
5168
5169	/*
5170	 * The first value in the table, following the header, is the
5171	 * comparison value, the second entry is a comparison value for
5172	 * TV load detection.
5173	 */
5174
5175	dacver = bios->data[daccmpoffset];
5176	dacheaderlen = bios->data[daccmpoffset + 1];
5177
5178	if (dacver != 0x00 && dacver != 0x10) {
5179		NV_WARN(dev, "DAC load detection comparison table version "
5180			       "%d.%d not known\n", dacver >> 4, dacver & 0xf);
5181		return -ENOSYS;
5182	}
5183
5184	bios->dactestval = ROM32(bios->data[daccmpoffset + dacheaderlen]);
5185	bios->tvdactestval = ROM32(bios->data[daccmpoffset + dacheaderlen + 4]);
5186
5187	return 0;
5188}
5189
5190static int parse_bit_lvds_tbl_entry(struct drm_device *dev, struct nvbios *bios, struct bit_entry *bitentry)
5191{
5192	/*
5193	 * Parses the LVDS table segment that the bit entry points to.
5194	 * Starting at bitentry->offset:
5195	 *
5196	 * offset + 0  (16 bits): LVDS strap xlate table pointer
5197	 */
5198
5199	if (bitentry->length != 2) {
5200		NV_ERROR(dev, "Do not understand BIT LVDS table\n");
5201		return -EINVAL;
5202	}
5203
5204	/*
5205	 * No idea if it's still called the LVDS manufacturer table, but
5206	 * the concept's close enough.
5207	 */
5208	bios->fp.lvdsmanufacturerpointer = ROM16(bios->data[bitentry->offset]);
5209
5210	return 0;
5211}
5212
5213static int
5214parse_bit_M_tbl_entry(struct drm_device *dev, struct nvbios *bios,
5215		      struct bit_entry *bitentry)
5216{
5217	/*
5218	 * offset + 2  (8  bits): number of options in an
5219	 * 	INIT_RAM_RESTRICT_ZM_REG_GROUP opcode option set
5220	 * offset + 3  (16 bits): pointer to strap xlate table for RAM
5221	 * 	restrict option selection
5222	 *
5223	 * There's a bunch of bits in this table other than the RAM restrict
5224	 * stuff that we don't use - their use currently unknown
5225	 */
5226
5227	/*
5228	 * Older bios versions don't have a sufficiently long table for
5229	 * what we want
5230	 */
5231	if (bitentry->length < 0x5)
5232		return 0;
5233
5234	if (bitentry->version < 2) {
5235		bios->ram_restrict_group_count = bios->data[bitentry->offset + 2];
5236		bios->ram_restrict_tbl_ptr = ROM16(bios->data[bitentry->offset + 3]);
5237	} else {
5238		bios->ram_restrict_group_count = bios->data[bitentry->offset + 0];
5239		bios->ram_restrict_tbl_ptr = ROM16(bios->data[bitentry->offset + 1]);
5240	}
5241
5242	return 0;
5243}
5244
5245static int parse_bit_tmds_tbl_entry(struct drm_device *dev, struct nvbios *bios, struct bit_entry *bitentry)
5246{
5247	/*
5248	 * Parses the pointer to the TMDS table
5249	 *
5250	 * Starting at bitentry->offset:
5251	 *
5252	 * offset + 0  (16 bits): TMDS table pointer
5253	 *
5254	 * The TMDS table is typically found just before the DCB table, with a
5255	 * characteristic signature of 0x11,0x13 (1.1 being version, 0x13 being
5256	 * length?)
5257	 *
5258	 * At offset +7 is a pointer to a script, which I don't know how to
5259	 * run yet.
5260	 * At offset +9 is a pointer to another script, likewise
5261	 * Offset +11 has a pointer to a table where the first word is a pxclk
5262	 * frequency and the second word a pointer to a script, which should be
5263	 * run if the comparison pxclk frequency is less than the pxclk desired.
5264	 * This repeats for decreasing comparison frequencies
5265	 * Offset +13 has a pointer to a similar table
5266	 * The selection of table (and possibly +7/+9 script) is dictated by
5267	 * "or" from the DCB.
5268	 */
5269
5270	uint16_t tmdstableptr, script1, script2;
5271
5272	if (bitentry->length != 2) {
5273		NV_ERROR(dev, "Do not understand BIT TMDS table\n");
5274		return -EINVAL;
5275	}
5276
5277	tmdstableptr = ROM16(bios->data[bitentry->offset]);
5278	if (!tmdstableptr) {
5279		NV_ERROR(dev, "Pointer to TMDS table invalid\n");
5280		return -EINVAL;
5281	}
5282
5283	NV_INFO(dev, "TMDS table version %d.%d\n",
5284		bios->data[tmdstableptr] >> 4, bios->data[tmdstableptr] & 0xf);
5285
5286	/* nv50+ has v2.0, but we don't parse it atm */
5287	if (bios->data[tmdstableptr] != 0x11)
5288		return -ENOSYS;
5289
5290	/*
5291	 * These two scripts are odd: they don't seem to get run even when
5292	 * they are not stubbed.
5293	 */
5294	script1 = ROM16(bios->data[tmdstableptr + 7]);
5295	script2 = ROM16(bios->data[tmdstableptr + 9]);
5296	if (bios->data[script1] != 'q' || bios->data[script2] != 'q')
5297		NV_WARN(dev, "TMDS table script pointers not stubbed\n");
5298
5299	bios->tmds.output0_script_ptr = ROM16(bios->data[tmdstableptr + 11]);
5300	bios->tmds.output1_script_ptr = ROM16(bios->data[tmdstableptr + 13]);
5301
5302	return 0;
5303}
5304
5305static int
5306parse_bit_U_tbl_entry(struct drm_device *dev, struct nvbios *bios,
5307		      struct bit_entry *bitentry)
5308{
5309	/*
5310	 * Parses the pointer to the G80 output script tables
5311	 *
5312	 * Starting at bitentry->offset:
5313	 *
5314	 * offset + 0  (16 bits): output script table pointer
5315	 */
5316
5317	uint16_t outputscripttableptr;
5318
5319	if (bitentry->length != 3) {
5320		NV_ERROR(dev, "Do not understand BIT U table\n");
5321		return -EINVAL;
5322	}
5323
5324	outputscripttableptr = ROM16(bios->data[bitentry->offset]);
5325	bios->display.script_table_ptr = outputscripttableptr;
5326	return 0;
5327}
5328
5329struct bit_table {
5330	const char id;
5331	int (* const parse_fn)(struct drm_device *, struct nvbios *, struct bit_entry *);
5332};
5333
5334#define BIT_TABLE(id, funcid) ((struct bit_table){ id, parse_bit_##funcid##_tbl_entry })
5335
5336int
5337bit_table(struct drm_device *dev, u8 id, struct bit_entry *bit)
5338{
5339	struct drm_nouveau_private *dev_priv = dev->dev_private;
5340	struct nvbios *bios = &dev_priv->vbios;
5341	u8 entries, *entry;
5342
5343	if (bios->type != NVBIOS_BIT)
5344		return -ENODEV;
5345
5346	entries = bios->data[bios->offset + 10];
5347	entry   = &bios->data[bios->offset + 12];
5348	while (entries--) {
5349		if (entry[0] == id) {
5350			bit->id = entry[0];
5351			bit->version = entry[1];
5352			bit->length = ROM16(entry[2]);
5353			bit->offset = ROM16(entry[4]);
5354			bit->data = ROMPTR(dev, entry[4]);
5355			return 0;
5356		}
5357
5358		entry += bios->data[bios->offset + 9];
5359	}
5360
5361	return -ENOENT;
5362}
5363
5364static int
5365parse_bit_table(struct nvbios *bios, const uint16_t bitoffset,
5366		struct bit_table *table)
5367{
5368	struct drm_device *dev = bios->dev;
5369	struct bit_entry bitentry;
5370
5371	if (bit_table(dev, table->id, &bitentry) == 0)
5372		return table->parse_fn(dev, bios, &bitentry);
5373
5374	NV_INFO(dev, "BIT table '%c' not found\n", table->id);
5375	return -ENOSYS;
5376}
5377
5378static int
5379parse_bit_structure(struct nvbios *bios, const uint16_t bitoffset)
5380{
5381	int ret;
5382
5383	/*
5384	 * The only restriction on parsing order currently is having 'i' first
5385	 * for use of bios->*_version or bios->feature_byte while parsing;
5386	 * functions shouldn't be actually *doing* anything apart from pulling
5387	 * data from the image into the bios struct, thus no interdependencies
5388	 */
5389	ret = parse_bit_table(bios, bitoffset, &BIT_TABLE('i', i));
5390	if (ret) /* info? */
5391		return ret;
5392	if (bios->major_version >= 0x60) /* g80+ */
5393		parse_bit_table(bios, bitoffset, &BIT_TABLE('A', A));
5394	ret = parse_bit_table(bios, bitoffset, &BIT_TABLE('C', C));
5395	if (ret)
5396		return ret;
5397	parse_bit_table(bios, bitoffset, &BIT_TABLE('D', display));
5398	ret = parse_bit_table(bios, bitoffset, &BIT_TABLE('I', init));
5399	if (ret)
5400		return ret;
5401	parse_bit_table(bios, bitoffset, &BIT_TABLE('M', M)); /* memory? */
5402	parse_bit_table(bios, bitoffset, &BIT_TABLE('L', lvds));
5403	parse_bit_table(bios, bitoffset, &BIT_TABLE('T', tmds));
5404	parse_bit_table(bios, bitoffset, &BIT_TABLE('U', U));
5405
5406	return 0;
5407}
5408
5409static int parse_bmp_structure(struct drm_device *dev, struct nvbios *bios, unsigned int offset)
5410{
5411	/*
5412	 * Parses the BMP structure for useful things, but does not act on them
5413	 *
5414	 * offset +   5: BMP major version
5415	 * offset +   6: BMP minor version
5416	 * offset +   9: BMP feature byte
5417	 * offset +  10: BCD encoded BIOS version
5418	 *
5419	 * offset +  18: init script table pointer (for bios versions < 5.10h)
5420	 * offset +  20: extra init script table pointer (for bios
5421	 * versions < 5.10h)
5422	 *
5423	 * offset +  24: memory init table pointer (used on early bios versions)
5424	 * offset +  26: SDR memory sequencing setup data table
5425	 * offset +  28: DDR memory sequencing setup data table
5426	 *
5427	 * offset +  54: index of I2C CRTC pair to use for CRT output
5428	 * offset +  55: index of I2C CRTC pair to use for TV output
5429	 * offset +  56: index of I2C CRTC pair to use for flat panel output
5430	 * offset +  58: write CRTC index for I2C pair 0
5431	 * offset +  59: read CRTC index for I2C pair 0
5432	 * offset +  60: write CRTC index for I2C pair 1
5433	 * offset +  61: read CRTC index for I2C pair 1
5434	 *
5435	 * offset +  67: maximum internal PLL frequency (single stage PLL)
5436	 * offset +  71: minimum internal PLL frequency (single stage PLL)
5437	 *
5438	 * offset +  75: script table pointers, as described in
5439	 * parse_script_table_pointers
5440	 *
5441	 * offset +  89: TMDS single link output A table pointer
5442	 * offset +  91: TMDS single link output B table pointer
5443	 * offset +  95: LVDS single link output A table pointer
5444	 * offset + 105: flat panel timings table pointer
5445	 * offset + 107: flat panel strapping translation table pointer
5446	 * offset + 117: LVDS manufacturer panel config table pointer
5447	 * offset + 119: LVDS manufacturer strapping translation table pointer
5448	 *
5449	 * offset + 142: PLL limits table pointer
5450	 *
5451	 * offset + 156: minimum pixel clock for LVDS dual link
5452	 */
5453
5454	uint8_t *bmp = &bios->data[offset], bmp_version_major, bmp_version_minor;
5455	uint16_t bmplength;
5456	uint16_t legacy_scripts_offset, legacy_i2c_offset;
5457
5458	/* load needed defaults in case we can't parse this info */
5459	bios->digital_min_front_porch = 0x4b;
5460	bios->fmaxvco = 256000;
5461	bios->fminvco = 128000;
5462	bios->fp.duallink_transition_clk = 90000;
5463
5464	bmp_version_major = bmp[5];
5465	bmp_version_minor = bmp[6];
5466
5467	NV_TRACE(dev, "BMP version %d.%d\n",
5468		 bmp_version_major, bmp_version_minor);
5469
5470	/*
5471	 * Make sure that 0x36 is blank and can't be mistaken for a DCB
5472	 * pointer on early versions
5473	 */
5474	if (bmp_version_major < 5)
5475		*(uint16_t *)&bios->data[0x36] = 0;
5476
5477	/*
5478	 * Seems that the minor version was 1 for all major versions prior
5479	 * to 5. Version 6 could theoretically exist, but I suspect BIT
5480	 * happened instead.
5481	 */
5482	if ((bmp_version_major < 5 && bmp_version_minor != 1) || bmp_version_major > 5) {
5483		NV_ERROR(dev, "You have an unsupported BMP version. "
5484				"Please send in your bios\n");
5485		return -ENOSYS;
5486	}
5487
5488	if (bmp_version_major == 0)
5489		/* nothing that's currently useful in this version */
5490		return 0;
5491	else if (bmp_version_major == 1)
5492		bmplength = 44; /* exact for 1.01 */
5493	else if (bmp_version_major == 2)
5494		bmplength = 48; /* exact for 2.01 */
5495	else if (bmp_version_major == 3)
5496		bmplength = 54;
5497		/* guessed - mem init tables added in this version */
5498	else if (bmp_version_major == 4 || bmp_version_minor < 0x1)
5499		/* don't know if 5.0 exists... */
5500		bmplength = 62;
5501		/* guessed - BMP I2C indices added in version 4*/
5502	else if (bmp_version_minor < 0x6)
5503		bmplength = 67; /* exact for 5.01 */
5504	else if (bmp_version_minor < 0x10)
5505		bmplength = 75; /* exact for 5.06 */
5506	else if (bmp_version_minor == 0x10)
5507		bmplength = 89; /* exact for 5.10h */
5508	else if (bmp_version_minor < 0x14)
5509		bmplength = 118; /* exact for 5.11h */
5510	else if (bmp_version_minor < 0x24)
5511		/*
5512		 * Not sure of version where pll limits came in;
5513		 * certainly exist by 0x24 though.
5514		 */
5515		/* length not exact: this is long enough to get lvds members */
5516		bmplength = 123;
5517	else if (bmp_version_minor < 0x27)
5518		/*
5519		 * Length not exact: this is long enough to get pll limit
5520		 * member
5521		 */
5522		bmplength = 144;
5523	else
5524		/*
5525		 * Length not exact: this is long enough to get dual link
5526		 * transition clock.
5527		 */
5528		bmplength = 158;
5529
5530	/* checksum */
5531	if (nv_cksum(bmp, 8)) {
5532		NV_ERROR(dev, "Bad BMP checksum\n");
5533		return -EINVAL;
5534	}
5535
5536	/*
5537	 * Bit 4 seems to indicate either a mobile bios or a quadro card --
5538	 * mobile behaviour consistent (nv11+), quadro only seen nv18gl-nv36gl
5539	 * (not nv10gl), bit 5 that the flat panel tables are present, and
5540	 * bit 6 a tv bios.
5541	 */
5542	bios->feature_byte = bmp[9];
5543
5544	parse_bios_version(dev, bios, offset + 10);
5545
5546	if (bmp_version_major < 5 || bmp_version_minor < 0x10)
5547		bios->old_style_init = true;
5548	legacy_scripts_offset = 18;
5549	if (bmp_version_major < 2)
5550		legacy_scripts_offset -= 4;
5551	bios->init_script_tbls_ptr = ROM16(bmp[legacy_scripts_offset]);
5552	bios->extra_init_script_tbl_ptr = ROM16(bmp[legacy_scripts_offset + 2]);
5553
5554	if (bmp_version_major > 2) {	/* appears in BMP 3 */
5555		bios->legacy.mem_init_tbl_ptr = ROM16(bmp[24]);
5556		bios->legacy.sdr_seq_tbl_ptr = ROM16(bmp[26]);
5557		bios->legacy.ddr_seq_tbl_ptr = ROM16(bmp[28]);
5558	}
5559
5560	legacy_i2c_offset = 0x48;	/* BMP version 2 & 3 */
5561	if (bmplength > 61)
5562		legacy_i2c_offset = offset + 54;
5563	bios->legacy.i2c_indices.crt = bios->data[legacy_i2c_offset];
5564	bios->legacy.i2c_indices.tv = bios->data[legacy_i2c_offset + 1];
5565	bios->legacy.i2c_indices.panel = bios->data[legacy_i2c_offset + 2];
5566
5567	if (bmplength > 74) {
5568		bios->fmaxvco = ROM32(bmp[67]);
5569		bios->fminvco = ROM32(bmp[71]);
5570	}
5571	if (bmplength > 88)
5572		parse_script_table_pointers(bios, offset + 75);
5573	if (bmplength > 94) {
5574		bios->tmds.output0_script_ptr = ROM16(bmp[89]);
5575		bios->tmds.output1_script_ptr = ROM16(bmp[91]);
5576		/*
5577		 * Never observed in use with lvds scripts, but is reused for
5578		 * 18/24 bit panel interface default for EDID equipped panels
5579		 * (if_is_24bit not set directly to avoid any oscillation).
5580		 */
5581		bios->legacy.lvds_single_a_script_ptr = ROM16(bmp[95]);
5582	}
5583	if (bmplength > 108) {
5584		bios->fp.fptablepointer = ROM16(bmp[105]);
5585		bios->fp.fpxlatetableptr = ROM16(bmp[107]);
5586		bios->fp.xlatwidth = 1;
5587	}
5588	if (bmplength > 120) {
5589		bios->fp.lvdsmanufacturerpointer = ROM16(bmp[117]);
5590		bios->fp.fpxlatemanufacturertableptr = ROM16(bmp[119]);
5591	}
5592	if (bmplength > 143)
5593		bios->pll_limit_tbl_ptr = ROM16(bmp[142]);
5594
5595	if (bmplength > 157)
5596		bios->fp.duallink_transition_clk = ROM16(bmp[156]) * 10;
5597
5598	return 0;
5599}
5600
5601static uint16_t findstr(uint8_t *data, int n, const uint8_t *str, int len)
5602{
5603	int i, j;
5604
5605	for (i = 0; i <= (n - len); i++) {
5606		for (j = 0; j < len; j++)
5607			if (data[i + j] != str[j])
5608				break;
5609		if (j == len)
5610			return i;
5611	}
5612
5613	return 0;
5614}
5615
5616void *
5617dcb_table(struct drm_device *dev)
5618{
5619	struct drm_nouveau_private *dev_priv = dev->dev_private;
5620	u8 *dcb = NULL;
5621
5622	if (dev_priv->card_type > NV_04)
5623		dcb = ROMPTR(dev, dev_priv->vbios.data[0x36]);
5624	if (!dcb) {
5625		NV_WARNONCE(dev, "No DCB data found in VBIOS\n");
5626		return NULL;
5627	}
5628
5629	if (dcb[0] >= 0x41) {
5630		NV_WARNONCE(dev, "DCB version 0x%02x unknown\n", dcb[0]);
5631		return NULL;
5632	} else
5633	if (dcb[0] >= 0x30) {
5634		if (ROM32(dcb[6]) == 0x4edcbdcb)
5635			return dcb;
5636	} else
5637	if (dcb[0] >= 0x20) {
5638		if (ROM32(dcb[4]) == 0x4edcbdcb)
5639			return dcb;
5640	} else
5641	if (dcb[0] >= 0x15) {
5642		if (!memcmp(&dcb[-7], "DEV_REC", 7))
5643			return dcb;
5644	} else {
5645		/*
5646		 * v1.4 (some NV15/16, NV11+) seems the same as v1.5, but
5647		 * always has the same single (crt) entry, even when tv-out
5648		 * present, so the conclusion is this version cannot really
5649		 * be used.
5650		 *
5651		 * v1.2 tables (some NV6/10, and NV15+) normally have the
5652		 * same 5 entries, which are not specific to the card and so
5653		 * no use.
5654		 *
5655		 * v1.2 does have an I2C table that read_dcb_i2c_table can
5656		 * handle, but cards exist (nv11 in #14821) with a bad i2c
5657		 * table pointer, so use the indices parsed in
5658		 * parse_bmp_structure.
5659		 *
5660		 * v1.1 (NV5+, maybe some NV4) is entirely unhelpful
5661		 */
5662		NV_WARNONCE(dev, "No useful DCB data in VBIOS\n");
5663		return NULL;
5664	}
5665
5666	NV_WARNONCE(dev, "DCB header validation failed\n");
5667	return NULL;
5668}
5669
5670void *
5671dcb_outp(struct drm_device *dev, u8 idx)
5672{
5673	u8 *dcb = dcb_table(dev);
5674	if (dcb && dcb[0] >= 0x30) {
5675		if (idx < dcb[2])
5676			return dcb + dcb[1] + (idx * dcb[3]);
5677	} else
5678	if (dcb && dcb[0] >= 0x20) {
5679		u8 *i2c = ROMPTR(dev, dcb[2]);
5680		u8 *ent = dcb + 8 + (idx * 8);
5681		if (i2c && ent < i2c)
5682			return ent;
5683	} else
5684	if (dcb && dcb[0] >= 0x15) {
5685		u8 *i2c = ROMPTR(dev, dcb[2]);
5686		u8 *ent = dcb + 4 + (idx * 10);
5687		if (i2c && ent < i2c)
5688			return ent;
5689	}
5690
5691	return NULL;
5692}
5693
5694int
5695dcb_outp_foreach(struct drm_device *dev, void *data,
5696		 int (*exec)(struct drm_device *, void *, int idx, u8 *outp))
5697{
5698	int ret, idx = -1;
5699	u8 *outp = NULL;
5700	while ((outp = dcb_outp(dev, ++idx))) {
5701		if (ROM32(outp[0]) == 0x00000000)
5702			break; /* seen on an NV11 with DCB v1.5 */
5703		if (ROM32(outp[0]) == 0xffffffff)
5704			break; /* seen on an NV17 with DCB v2.0 */
5705
5706		if ((outp[0] & 0x0f) == OUTPUT_UNUSED)
5707			continue;
5708		if ((outp[0] & 0x0f) == OUTPUT_EOL)
5709			break;
5710
5711		ret = exec(dev, data, idx, outp);
5712		if (ret)
5713			return ret;
5714	}
5715
5716	return 0;
5717}
5718
5719u8 *
5720dcb_conntab(struct drm_device *dev)
5721{
5722	u8 *dcb = dcb_table(dev);
5723	if (dcb && dcb[0] >= 0x30 && dcb[1] >= 0x16) {
5724		u8 *conntab = ROMPTR(dev, dcb[0x14]);
5725		if (conntab && conntab[0] >= 0x30 && conntab[0] <= 0x40)
5726			return conntab;
5727	}
5728	return NULL;
5729}
5730
5731u8 *
5732dcb_conn(struct drm_device *dev, u8 idx)
5733{
5734	u8 *conntab = dcb_conntab(dev);
5735	if (conntab && idx < conntab[2])
5736		return conntab + conntab[1] + (idx * conntab[3]);
5737	return NULL;
5738}
5739
5740static struct dcb_entry *new_dcb_entry(struct dcb_table *dcb)
5741{
5742	struct dcb_entry *entry = &dcb->entry[dcb->entries];
5743
5744	memset(entry, 0, sizeof(struct dcb_entry));
5745	entry->index = dcb->entries++;
5746
5747	return entry;
5748}
5749
5750static void fabricate_dcb_output(struct dcb_table *dcb, int type, int i2c,
5751				 int heads, int or)
5752{
5753	struct dcb_entry *entry = new_dcb_entry(dcb);
5754
5755	entry->type = type;
5756	entry->i2c_index = i2c;
5757	entry->heads = heads;
5758	if (type != OUTPUT_ANALOG)
5759		entry->location = !DCB_LOC_ON_CHIP; /* ie OFF CHIP */
5760	entry->or = or;
5761}
5762
5763static bool
5764parse_dcb20_entry(struct drm_device *dev, struct dcb_table *dcb,
5765		  uint32_t conn, uint32_t conf, struct dcb_entry *entry)
5766{
5767	entry->type = conn & 0xf;
5768	entry->i2c_index = (conn >> 4) & 0xf;
5769	entry->heads = (conn >> 8) & 0xf;
5770	entry->connector = (conn >> 12) & 0xf;
5771	entry->bus = (conn >> 16) & 0xf;
5772	entry->location = (conn >> 20) & 0x3;
5773	entry->or = (conn >> 24) & 0xf;
5774
5775	switch (entry->type) {
5776	case OUTPUT_ANALOG:
5777		/*
5778		 * Although the rest of a CRT conf dword is usually
5779		 * zeros, mac biosen have stuff there so we must mask
5780		 */
5781		entry->crtconf.maxfreq = (dcb->version < 0x30) ?
5782					 (conf & 0xffff) * 10 :
5783					 (conf & 0xff) * 10000;
5784		break;
5785	case OUTPUT_LVDS:
5786		{
5787		uint32_t mask;
5788		if (conf & 0x1)
5789			entry->lvdsconf.use_straps_for_mode = true;
5790		if (dcb->version < 0x22) {
5791			mask = ~0xd;
5792			/*
5793			 * The laptop in bug 14567 lies and claims to not use
5794			 * straps when it does, so assume all DCB 2.0 laptops
5795			 * use straps, until a broken EDID using one is produced
5796			 */
5797			entry->lvdsconf.use_straps_for_mode = true;
5798			/*
5799			 * Both 0x4 and 0x8 show up in v2.0 tables; assume they
5800			 * mean the same thing (probably wrong, but might work)
5801			 */
5802			if (conf & 0x4 || conf & 0x8)
5803				entry->lvdsconf.use_power_scripts = true;
5804		} else {
5805			mask = ~0x7;
5806			if (conf & 0x2)
5807				entry->lvdsconf.use_acpi_for_edid = true;
5808			if (conf & 0x4)
5809				entry->lvdsconf.use_power_scripts = true;
5810			entry->lvdsconf.sor.link = (conf & 0x00000030) >> 4;
5811		}
5812		if (conf & mask) {
5813			/*
5814			 * Until we even try to use these on G8x, it's
5815			 * useless reporting unknown bits.  They all are.
5816			 */
5817			if (dcb->version >= 0x40)
5818				break;
5819
5820			NV_ERROR(dev, "Unknown LVDS configuration bits, "
5821				      "please report\n");
5822		}
5823		break;
5824		}
5825	case OUTPUT_TV:
5826	{
5827		if (dcb->version >= 0x30)
5828			entry->tvconf.has_component_output = conf & (0x8 << 4);
5829		else
5830			entry->tvconf.has_component_output = false;
5831
5832		break;
5833	}
5834	case OUTPUT_DP:
5835		entry->dpconf.sor.link = (conf & 0x00000030) >> 4;
5836		switch ((conf & 0x00e00000) >> 21) {
5837		case 0:
5838			entry->dpconf.link_bw = 162000;
5839			break;
5840		default:
5841			entry->dpconf.link_bw = 270000;
5842			break;
5843		}
5844		switch ((conf & 0x0f000000) >> 24) {
5845		case 0xf:
5846			entry->dpconf.link_nr = 4;
5847			break;
5848		case 0x3:
5849			entry->dpconf.link_nr = 2;
5850			break;
5851		default:
5852			entry->dpconf.link_nr = 1;
5853			break;
5854		}
5855		break;
5856	case OUTPUT_TMDS:
5857		if (dcb->version >= 0x40)
5858			entry->tmdsconf.sor.link = (conf & 0x00000030) >> 4;
5859		else if (dcb->version >= 0x30)
5860			entry->tmdsconf.slave_addr = (conf & 0x00000700) >> 8;
5861		else if (dcb->version >= 0x22)
5862			entry->tmdsconf.slave_addr = (conf & 0x00000070) >> 4;
5863
5864		break;
5865	case OUTPUT_EOL:
5866		/* weird g80 mobile type that "nv" treats as a terminator */
5867		dcb->entries--;
5868		return false;
5869	default:
5870		break;
5871	}
5872
5873	if (dcb->version < 0x40) {
5874		/* Normal entries consist of a single bit, but dual link has
5875		 * the next most significant bit set too
5876		 */
5877		entry->duallink_possible =
5878			((1 << (ffs(entry->or) - 1)) * 3 == entry->or);
5879	} else {
5880		entry->duallink_possible = (entry->sorconf.link == 3);
5881	}
5882
5883	/* unsure what DCB version introduces this, 3.0? */
5884	if (conf & 0x100000)
5885		entry->i2c_upper_default = true;
5886
5887	return true;
5888}
5889
5890static bool
5891parse_dcb15_entry(struct drm_device *dev, struct dcb_table *dcb,
5892		  uint32_t conn, uint32_t conf, struct dcb_entry *entry)
5893{
5894	switch (conn & 0x0000000f) {
5895	case 0:
5896		entry->type = OUTPUT_ANALOG;
5897		break;
5898	case 1:
5899		entry->type = OUTPUT_TV;
5900		break;
5901	case 2:
5902	case 4:
5903		if (conn & 0x10)
5904			entry->type = OUTPUT_LVDS;
5905		else
5906			entry->type = OUTPUT_TMDS;
5907		break;
5908	case 3:
5909		entry->type = OUTPUT_LVDS;
5910		break;
5911	default:
5912		NV_ERROR(dev, "Unknown DCB type %d\n", conn & 0x0000000f);
5913		return false;
5914	}
5915
5916	entry->i2c_index = (conn & 0x0003c000) >> 14;
5917	entry->heads = ((conn & 0x001c0000) >> 18) + 1;
5918	entry->or = entry->heads; /* same as heads, hopefully safe enough */
5919	entry->location = (conn & 0x01e00000) >> 21;
5920	entry->bus = (conn & 0x0e000000) >> 25;
5921	entry->duallink_possible = false;
5922
5923	switch (entry->type) {
5924	case OUTPUT_ANALOG:
5925		entry->crtconf.maxfreq = (conf & 0xffff) * 10;
5926		break;
5927	case OUTPUT_TV:
5928		entry->tvconf.has_component_output = false;
5929		break;
5930	case OUTPUT_LVDS:
5931		if ((conn & 0x00003f00) >> 8 != 0x10)
5932			entry->lvdsconf.use_straps_for_mode = true;
5933		entry->lvdsconf.use_power_scripts = true;
5934		break;
5935	default:
5936		break;
5937	}
5938
5939	return true;
5940}
5941
5942static
5943void merge_like_dcb_entries(struct drm_device *dev, struct dcb_table *dcb)
5944{
5945	/*
5946	 * DCB v2.0 lists each output combination separately.
5947	 * Here we merge compatible entries to have fewer outputs, with
5948	 * more options
5949	 */
5950
5951	int i, newentries = 0;
5952
5953	for (i = 0; i < dcb->entries; i++) {
5954		struct dcb_entry *ient = &dcb->entry[i];
5955		int j;
5956
5957		for (j = i + 1; j < dcb->entries; j++) {
5958			struct dcb_entry *jent = &dcb->entry[j];
5959
5960			if (jent->type == 100) /* already merged entry */
5961				continue;
5962
5963			/* merge heads field when all other fields the same */
5964			if (jent->i2c_index == ient->i2c_index &&
5965			    jent->type == ient->type &&
5966			    jent->location == ient->location &&
5967			    jent->or == ient->or) {
5968				NV_TRACE(dev, "Merging DCB entries %d and %d\n",
5969					 i, j);
5970				ient->heads |= jent->heads;
5971				jent->type = 100; /* dummy value */
5972			}
5973		}
5974	}
5975
5976	/* Compact entries merged into others out of dcb */
5977	for (i = 0; i < dcb->entries; i++) {
5978		if (dcb->entry[i].type == 100)
5979			continue;
5980
5981		if (newentries != i) {
5982			dcb->entry[newentries] = dcb->entry[i];
5983			dcb->entry[newentries].index = newentries;
5984		}
5985		newentries++;
5986	}
5987
5988	dcb->entries = newentries;
5989}
5990
5991static bool
5992apply_dcb_encoder_quirks(struct drm_device *dev, int idx, u32 *conn, u32 *conf)
5993{
5994	struct drm_nouveau_private *dev_priv = dev->dev_private;
5995	struct dcb_table *dcb = &dev_priv->vbios.dcb;
5996
5997	/* Dell Precision M6300
5998	 *   DCB entry 2: 02025312 00000010
5999	 *   DCB entry 3: 02026312 00000020
6000	 *
6001	 * Identical, except apparently a different connector on a
6002	 * different SOR link.  Not a clue how we're supposed to know
6003	 * which one is in use if it even shares an i2c line...
6004	 *
6005	 * Ignore the connector on the second SOR link to prevent
6006	 * nasty problems until this is sorted (assuming it's not a
6007	 * VBIOS bug).
6008	 */
6009	if (nv_match_device(dev, 0x040d, 0x1028, 0x019b)) {
6010		if (*conn == 0x02026312 && *conf == 0x00000020)
6011			return false;
6012	}
6013
6014	/* GeForce3 Ti 200
6015	 *
6016	 * DCB reports an LVDS output that should be TMDS:
6017	 *   DCB entry 1: f2005014 ffffffff
6018	 */
6019	if (nv_match_device(dev, 0x0201, 0x1462, 0x8851)) {
6020		if (*conn == 0xf2005014 && *conf == 0xffffffff) {
6021			fabricate_dcb_output(dcb, OUTPUT_TMDS, 1, 1, 1);
6022			return false;
6023		}
6024	}
6025
6026	/* XFX GT-240X-YA
6027	 *
6028	 * So many things wrong here, replace the entire encoder table..
6029	 */
6030	if (nv_match_device(dev, 0x0ca3, 0x1682, 0x3003)) {
6031		if (idx == 0) {
6032			*conn = 0x02001300; /* VGA, connector 1 */
6033			*conf = 0x00000028;
6034		} else
6035		if (idx == 1) {
6036			*conn = 0x01010312; /* DVI, connector 0 */
6037			*conf = 0x00020030;
6038		} else
6039		if (idx == 2) {
6040			*conn = 0x01010310; /* VGA, connector 0 */
6041			*conf = 0x00000028;
6042		} else
6043		if (idx == 3) {
6044			*conn = 0x02022362; /* HDMI, connector 2 */
6045			*conf = 0x00020010;
6046		} else {
6047			*conn = 0x0000000e; /* EOL */
6048			*conf = 0x00000000;
6049		}
6050	}
6051
6052	/* Some other twisted XFX board (rhbz#694914)
6053	 *
6054	 * The DVI/VGA encoder combo that's supposed to represent the
6055	 * DVI-I connector actually point at two different ones, and
6056	 * the HDMI connector ends up paired with the VGA instead.
6057	 *
6058	 * Connector table is missing anything for VGA at all, pointing it
6059	 * an invalid conntab entry 2 so we figure it out ourself.
6060	 */
6061	if (nv_match_device(dev, 0x0615, 0x1682, 0x2605)) {
6062		if (idx == 0) {
6063			*conn = 0x02002300; /* VGA, connector 2 */
6064			*conf = 0x00000028;
6065		} else
6066		if (idx == 1) {
6067			*conn = 0x01010312; /* DVI, connector 0 */
6068			*conf = 0x00020030;
6069		} else
6070		if (idx == 2) {
6071			*conn = 0x04020310; /* VGA, connector 0 */
6072			*conf = 0x00000028;
6073		} else
6074		if (idx == 3) {
6075			*conn = 0x02021322; /* HDMI, connector 1 */
6076			*conf = 0x00020010;
6077		} else {
6078			*conn = 0x0000000e; /* EOL */
6079			*conf = 0x00000000;
6080		}
6081	}
6082
6083	return true;
6084}
6085
6086static void
6087fabricate_dcb_encoder_table(struct drm_device *dev, struct nvbios *bios)
6088{
6089	struct dcb_table *dcb = &bios->dcb;
6090	int all_heads = (nv_two_heads(dev) ? 3 : 1);
6091
6092#ifdef __powerpc__
6093	/* Apple iMac G4 NV17 */
6094	if (of_machine_is_compatible("PowerMac4,5")) {
6095		fabricate_dcb_output(dcb, OUTPUT_TMDS, 0, all_heads, 1);
6096		fabricate_dcb_output(dcb, OUTPUT_ANALOG, 1, all_heads, 2);
6097		return;
6098	}
6099#endif
6100
6101	/* Make up some sane defaults */
6102	fabricate_dcb_output(dcb, OUTPUT_ANALOG,
6103			     bios->legacy.i2c_indices.crt, 1, 1);
6104
6105	if (nv04_tv_identify(dev, bios->legacy.i2c_indices.tv) >= 0)
6106		fabricate_dcb_output(dcb, OUTPUT_TV,
6107				     bios->legacy.i2c_indices.tv,
6108				     all_heads, 0);
6109
6110	else if (bios->tmds.output0_script_ptr ||
6111		 bios->tmds.output1_script_ptr)
6112		fabricate_dcb_output(dcb, OUTPUT_TMDS,
6113				     bios->legacy.i2c_indices.panel,
6114				     all_heads, 1);
6115}
6116
6117static int
6118parse_dcb_entry(struct drm_device *dev, void *data, int idx, u8 *outp)
6119{
6120	struct drm_nouveau_private *dev_priv = dev->dev_private;
6121	struct dcb_table *dcb = &dev_priv->vbios.dcb;
6122	u32 conf = (dcb->version >= 0x20) ? ROM32(outp[4]) : ROM32(outp[6]);
6123	u32 conn = ROM32(outp[0]);
6124	bool ret;
6125
6126	if (apply_dcb_encoder_quirks(dev, idx, &conn, &conf)) {
6127		struct dcb_entry *entry = new_dcb_entry(dcb);
6128
6129		NV_TRACEWARN(dev, "DCB outp %02d: %08x %08x\n", idx, conn, conf);
6130
6131		if (dcb->version >= 0x20)
6132			ret = parse_dcb20_entry(dev, dcb, conn, conf, entry);
6133		else
6134			ret = parse_dcb15_entry(dev, dcb, conn, conf, entry);
6135		if (!ret)
6136			return 1; /* stop parsing */
6137
6138		/* Ignore the I2C index for on-chip TV-out, as there
6139		 * are cards with bogus values (nv31m in bug 23212),
6140		 * and it's otherwise useless.
6141		 */
6142		if (entry->type == OUTPUT_TV &&
6143		    entry->location == DCB_LOC_ON_CHIP)
6144			entry->i2c_index = 0x0f;
6145	}
6146
6147	return 0;
6148}
6149
6150static void
6151dcb_fake_connectors(struct nvbios *bios)
6152{
6153	struct dcb_table *dcbt = &bios->dcb;
6154	u8 map[16] = { };
6155	int i, idx = 0;
6156
6157	/* heuristic: if we ever get a non-zero connector field, assume
6158	 * that all the indices are valid and we don't need fake them.
6159	 *
6160	 * and, as usual, a blacklist of boards with bad bios data..
6161	 */
6162	if (!nv_match_device(bios->dev, 0x0392, 0x107d, 0x20a2)) {
6163		for (i = 0; i < dcbt->entries; i++) {
6164			if (dcbt->entry[i].connector)
6165				return;
6166		}
6167	}
6168
6169	/* no useful connector info available, we need to make it up
6170	 * ourselves.  the rule here is: anything on the same i2c bus
6171	 * is considered to be on the same connector.  any output
6172	 * without an associated i2c bus is assigned its own unique
6173	 * connector index.
6174	 */
6175	for (i = 0; i < dcbt->entries; i++) {
6176		u8 i2c = dcbt->entry[i].i2c_index;
6177		if (i2c == 0x0f) {
6178			dcbt->entry[i].connector = idx++;
6179		} else {
6180			if (!map[i2c])
6181				map[i2c] = ++idx;
6182			dcbt->entry[i].connector = map[i2c] - 1;
6183		}
6184	}
6185
6186	/* if we created more than one connector, destroy the connector
6187	 * table - just in case it has random, rather than stub, entries.
6188	 */
6189	if (i > 1) {
6190		u8 *conntab = dcb_conntab(bios->dev);
6191		if (conntab)
6192			conntab[0] = 0x00;
6193	}
6194}
6195
6196static int
6197parse_dcb_table(struct drm_device *dev, struct nvbios *bios)
6198{
6199	struct dcb_table *dcb = &bios->dcb;
6200	u8 *dcbt, *conn;
6201	int idx;
6202
6203	dcbt = dcb_table(dev);
6204	if (!dcbt) {
6205		/* handle pre-DCB boards */
6206		if (bios->type == NVBIOS_BMP) {
6207			fabricate_dcb_encoder_table(dev, bios);
6208			return 0;
6209		}
6210
6211		return -EINVAL;
6212	}
6213
6214	NV_TRACE(dev, "DCB version %d.%d\n", dcbt[0] >> 4, dcbt[0] & 0xf);
6215
6216	dcb->version = dcbt[0];
6217	dcb_outp_foreach(dev, NULL, parse_dcb_entry);
6218
6219	/*
6220	 * apart for v2.1+ not being known for requiring merging, this
6221	 * guarantees dcbent->index is the index of the entry in the rom image
6222	 */
6223	if (dcb->version < 0x21)
6224		merge_like_dcb_entries(dev, dcb);
6225
6226	if (!dcb->entries)
6227		return -ENXIO;
6228
6229	/* dump connector table entries to log, if any exist */
6230	idx = -1;
6231	while ((conn = dcb_conn(dev, ++idx))) {
6232		if (conn[0] != 0xff) {
6233			NV_TRACE(dev, "DCB conn %02d: ", idx);
6234			if (dcb_conntab(dev)[3] < 4)
6235				printk("%04x\n", ROM16(conn[0]));
6236			else
6237				printk("%08x\n", ROM32(conn[0]));
6238		}
6239	}
6240	dcb_fake_connectors(bios);
6241	return 0;
6242}
6243
6244static int load_nv17_hwsq_ucode_entry(struct drm_device *dev, struct nvbios *bios, uint16_t hwsq_offset, int entry)
6245{
6246	/*
6247	 * The header following the "HWSQ" signature has the number of entries,
6248	 * and the entry size
6249	 *
6250	 * An entry consists of a dword to write to the sequencer control reg
6251	 * (0x00001304), followed by the ucode bytes, written sequentially,
6252	 * starting at reg 0x00001400
6253	 */
6254
6255	uint8_t bytes_to_write;
6256	uint16_t hwsq_entry_offset;
6257	int i;
6258
6259	if (bios->data[hwsq_offset] <= entry) {
6260		NV_ERROR(dev, "Too few entries in HW sequencer table for "
6261				"requested entry\n");
6262		return -ENOENT;
6263	}
6264
6265	bytes_to_write = bios->data[hwsq_offset + 1];
6266
6267	if (bytes_to_write != 36) {
6268		NV_ERROR(dev, "Unknown HW sequencer entry size\n");
6269		return -EINVAL;
6270	}
6271
6272	NV_TRACE(dev, "Loading NV17 power sequencing microcode\n");
6273
6274	hwsq_entry_offset = hwsq_offset + 2 + entry * bytes_to_write;
6275
6276	/* set sequencer control */
6277	bios_wr32(bios, 0x00001304, ROM32(bios->data[hwsq_entry_offset]));
6278	bytes_to_write -= 4;
6279
6280	/* write ucode */
6281	for (i = 0; i < bytes_to_write; i += 4)
6282		bios_wr32(bios, 0x00001400 + i, ROM32(bios->data[hwsq_entry_offset + i + 4]));
6283
6284	/* twiddle NV_PBUS_DEBUG_4 */
6285	bios_wr32(bios, NV_PBUS_DEBUG_4, bios_rd32(bios, NV_PBUS_DEBUG_4) | 0x18);
6286
6287	return 0;
6288}
6289
6290static int load_nv17_hw_sequencer_ucode(struct drm_device *dev,
6291					struct nvbios *bios)
6292{
6293	/*
6294	 * BMP based cards, from NV17, need a microcode loading to correctly
6295	 * control the GPIO etc for LVDS panels
6296	 *
6297	 * BIT based cards seem to do this directly in the init scripts
6298	 *
6299	 * The microcode entries are found by the "HWSQ" signature.
6300	 */
6301
6302	const uint8_t hwsq_signature[] = { 'H', 'W', 'S', 'Q' };
6303	const int sz = sizeof(hwsq_signature);
6304	int hwsq_offset;
6305
6306	hwsq_offset = findstr(bios->data, bios->length, hwsq_signature, sz);
6307	if (!hwsq_offset)
6308		return 0;
6309
6310	/* always use entry 0? */
6311	return load_nv17_hwsq_ucode_entry(dev, bios, hwsq_offset + sz, 0);
6312}
6313
6314uint8_t *nouveau_bios_embedded_edid(struct drm_device *dev)
6315{
6316	struct drm_nouveau_private *dev_priv = dev->dev_private;
6317	struct nvbios *bios = &dev_priv->vbios;
6318	const uint8_t edid_sig[] = {
6319			0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 };
6320	uint16_t offset = 0;
6321	uint16_t newoffset;
6322	int searchlen = NV_PROM_SIZE;
6323
6324	if (bios->fp.edid)
6325		return bios->fp.edid;
6326
6327	while (searchlen) {
6328		newoffset = findstr(&bios->data[offset], searchlen,
6329								edid_sig, 8);
6330		if (!newoffset)
6331			return NULL;
6332		offset += newoffset;
6333		if (!nv_cksum(&bios->data[offset], EDID1_LEN))
6334			break;
6335
6336		searchlen -= offset;
6337		offset++;
6338	}
6339
6340	NV_TRACE(dev, "Found EDID in BIOS\n");
6341
6342	return bios->fp.edid = &bios->data[offset];
6343}
6344
6345void
6346nouveau_bios_run_init_table(struct drm_device *dev, uint16_t table,
6347			    struct dcb_entry *dcbent, int crtc)
6348{
6349	struct drm_nouveau_private *dev_priv = dev->dev_private;
6350	struct nvbios *bios = &dev_priv->vbios;
6351	struct init_exec iexec = { true, false };
6352
6353	spin_lock_bh(&bios->lock);
6354	bios->display.output = dcbent;
6355	bios->display.crtc = crtc;
6356	parse_init_table(bios, table, &iexec);
6357	bios->display.output = NULL;
6358	spin_unlock_bh(&bios->lock);
6359}
6360
6361void
6362nouveau_bios_init_exec(struct drm_device *dev, uint16_t table)
6363{
6364	struct drm_nouveau_private *dev_priv = dev->dev_private;
6365	struct nvbios *bios = &dev_priv->vbios;
6366	struct init_exec iexec = { true, false };
6367
6368	parse_init_table(bios, table, &iexec);
6369}
6370
6371static bool NVInitVBIOS(struct drm_device *dev)
6372{
6373	struct drm_nouveau_private *dev_priv = dev->dev_private;
6374	struct nvbios *bios = &dev_priv->vbios;
6375
6376	memset(bios, 0, sizeof(struct nvbios));
6377	spin_lock_init(&bios->lock);
6378	bios->dev = dev;
6379
6380	return bios_shadow(dev);
6381}
6382
6383static int nouveau_parse_vbios_struct(struct drm_device *dev)
6384{
6385	struct drm_nouveau_private *dev_priv = dev->dev_private;
6386	struct nvbios *bios = &dev_priv->vbios;
6387	const uint8_t bit_signature[] = { 0xff, 0xb8, 'B', 'I', 'T' };
6388	const uint8_t bmp_signature[] = { 0xff, 0x7f, 'N', 'V', 0x0 };
6389	int offset;
6390
6391	offset = findstr(bios->data, bios->length,
6392					bit_signature, sizeof(bit_signature));
6393	if (offset) {
6394		NV_TRACE(dev, "BIT BIOS found\n");
6395		bios->type = NVBIOS_BIT;
6396		bios->offset = offset;
6397		return parse_bit_structure(bios, offset + 6);
6398	}
6399
6400	offset = findstr(bios->data, bios->length,
6401					bmp_signature, sizeof(bmp_signature));
6402	if (offset) {
6403		NV_TRACE(dev, "BMP BIOS found\n");
6404		bios->type = NVBIOS_BMP;
6405		bios->offset = offset;
6406		return parse_bmp_structure(dev, bios, offset);
6407	}
6408
6409	NV_ERROR(dev, "No known BIOS signature found\n");
6410	return -ENODEV;
6411}
6412
6413int
6414nouveau_run_vbios_init(struct drm_device *dev)
6415{
6416	struct drm_nouveau_private *dev_priv = dev->dev_private;
6417	struct nvbios *bios = &dev_priv->vbios;
6418	int i, ret = 0;
6419
6420	/* Reset the BIOS head to 0. */
6421	bios->state.crtchead = 0;
6422
6423	if (bios->major_version < 5)	/* BMP only */
6424		load_nv17_hw_sequencer_ucode(dev, bios);
6425
6426	if (bios->execute) {
6427		bios->fp.last_script_invoc = 0;
6428		bios->fp.lvds_init_run = false;
6429	}
6430
6431	parse_init_tables(bios);
6432
6433	/*
6434	 * Runs some additional script seen on G8x VBIOSen.  The VBIOS'
6435	 * parser will run this right after the init tables, the binary
6436	 * driver appears to run it at some point later.
6437	 */
6438	if (bios->some_script_ptr) {
6439		struct init_exec iexec = {true, false};
6440
6441		NV_INFO(dev, "Parsing VBIOS init table at offset 0x%04X\n",
6442			bios->some_script_ptr);
6443		parse_init_table(bios, bios->some_script_ptr, &iexec);
6444	}
6445
6446	if (dev_priv->card_type >= NV_50) {
6447		for (i = 0; i < bios->dcb.entries; i++) {
6448			nouveau_bios_run_display_table(dev, 0, 0,
6449						       &bios->dcb.entry[i], -1);
6450		}
6451	}
6452
6453	return ret;
6454}
6455
6456static bool
6457nouveau_bios_posted(struct drm_device *dev)
6458{
6459	struct drm_nouveau_private *dev_priv = dev->dev_private;
6460	unsigned htotal;
6461
6462	if (dev_priv->card_type >= NV_50) {
6463		if (NVReadVgaCrtc(dev, 0, 0x00) == 0 &&
6464		    NVReadVgaCrtc(dev, 0, 0x1a) == 0)
6465			return false;
6466		return true;
6467	}
6468
6469	htotal  = NVReadVgaCrtc(dev, 0, 0x06);
6470	htotal |= (NVReadVgaCrtc(dev, 0, 0x07) & 0x01) << 8;
6471	htotal |= (NVReadVgaCrtc(dev, 0, 0x07) & 0x20) << 4;
6472	htotal |= (NVReadVgaCrtc(dev, 0, 0x25) & 0x01) << 10;
6473	htotal |= (NVReadVgaCrtc(dev, 0, 0x41) & 0x01) << 11;
6474
6475	return (htotal != 0);
6476}
6477
6478int
6479nouveau_bios_init(struct drm_device *dev)
6480{
6481	struct drm_nouveau_private *dev_priv = dev->dev_private;
6482	struct nvbios *bios = &dev_priv->vbios;
6483	int ret;
6484
6485	if (!NVInitVBIOS(dev))
6486		return -ENODEV;
6487
6488	ret = nouveau_parse_vbios_struct(dev);
6489	if (ret)
6490		return ret;
6491
6492	ret = nouveau_i2c_init(dev);
6493	if (ret)
6494		return ret;
6495
6496	ret = nouveau_mxm_init(dev);
6497	if (ret)
6498		return ret;
6499
6500	ret = parse_dcb_table(dev, bios);
6501	if (ret)
6502		return ret;
6503
6504	if (!bios->major_version)	/* we don't run version 0 bios */
6505		return 0;
6506
6507	/* init script execution disabled */
6508	bios->execute = false;
6509
6510	/* ... unless card isn't POSTed already */
6511	if (!nouveau_bios_posted(dev)) {
6512		NV_INFO(dev, "Adaptor not initialised, "
6513			"running VBIOS init tables.\n");
6514		bios->execute = true;
6515	}
6516	if (nouveau_force_post)
6517		bios->execute = true;
6518
6519	ret = nouveau_run_vbios_init(dev);
6520	if (ret)
6521		return ret;
6522
6523	/* feature_byte on BMP is poor, but init always sets CR4B */
6524	if (bios->major_version < 5)
6525		bios->is_mobile = NVReadVgaCrtc(dev, 0, NV_CIO_CRE_4B) & 0x40;
6526
6527	/* all BIT systems need p_f_m_t for digital_min_front_porch */
6528	if (bios->is_mobile || bios->major_version >= 5)
6529		ret = parse_fp_mode_table(dev, bios);
6530
6531	/* allow subsequent scripts to execute */
6532	bios->execute = true;
6533
6534	return 0;
6535}
6536
6537void
6538nouveau_bios_takedown(struct drm_device *dev)
6539{
6540	struct drm_nouveau_private *dev_priv = dev->dev_private;
6541
6542	nouveau_mxm_fini(dev);
6543	nouveau_i2c_fini(dev);
6544
6545	kfree(dev_priv->vbios.data);
6546}
6547