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