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