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