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