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