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