1/*
2	Copyright 2007-2011 Haiku, Inc.  All rights reserved.
3	Distributed under the terms of the MIT license.
4
5	Authors:
6	Gerald Zajac
7*/
8
9#include <KernelExport.h>
10#include <PCI.h>
11#include <drivers/bios.h>
12#include <malloc.h>
13#include <stdio.h>
14#include <string.h>
15#include <graphic_driver.h>
16#include <boot_item.h>
17
18#include "DriverInterface.h"
19
20
21#undef TRACE
22
23#ifdef ENABLE_DEBUG_TRACE
24#	define TRACE(x...) dprintf("ati: " x)
25#else
26#	define TRACE(x...) ;
27#endif
28
29
30#define ATI_ACCELERANT_NAME    "ati.accelerant"
31
32#define ROUND_TO_PAGE_SIZE(x) (((x) + (B_PAGE_SIZE) - 1) & ~((B_PAGE_SIZE) - 1))
33
34#define VESA_MODES_BOOT_INFO "vesa_modes/v1"
35
36#define SKD_HANDLER_INSTALLED 0x80000000
37#define MAX_DEVICES		4
38#define DEVICE_FORMAT	"%04X_%04X_%02X%02X%02X"
39
40#define M64_BIOS_SIZE		0x10000		// 64KB
41#define R128_BIOS_SIZE		0x10000		// 64KB
42
43int32 api_version = B_CUR_DRIVER_API_VERSION;	// revision of driver API used
44
45#define VENDOR_ID 0x1002	// ATI vendor ID
46
47// Mach64 register definitions.
48#define M64_CLOCK_INTERNAL	4
49#define M64_CONFIG_CHIP_ID	0x0CE0		// offset in register area
50#define M64_CFG_CHIP_TYPE	0x0000FFFF
51
52
53struct ChipInfo {
54	uint16		chipID;			// PCI device id of the chip
55	ChipType	chipType;		// assigned chip type identifier
56	const char*	chipName;		// user recognizable name for chip
57								//   (must be < 32 chars)
58};
59
60
61// Names for chip types.
62
63static char sRage128_GL[]		 = "RAGE 128 GL";
64static char sRage128_VR[]		 = "RAGE 128 VR";
65static char sRage128_Pro_GL[]	 = "RAGE 128 PRO GL";
66static char sRage128_Pro_VR[]	 = "RAGE 128 PRO VR";
67static char sRage128_Pro_Ultra[] = "RAGE 128 PRO Ultra";
68
69// This table maps a PCI device ID to a chip type identifier and the chip name.
70// The table is split into two groups of chips, the Mach64 and Rage128 chips,
71// with each group ordered by the chip ID.
72
73static const ChipInfo chipTable[] = {
74	{ 0x4742, MACH64_264GTPRO,		"3D RAGE PRO, AGP"		},		// GB
75	{ 0x4744, MACH64_264GTPRO,		"3D RAGE PRO, AGP"		},		// GD
76	{ 0x4749, MACH64_264GTPRO,		"3D RAGE PRO, PCI"		},		// GI
77	{ 0x474C, MACH64_264XL,			"3D RAGE XC, PCI"		},		// GL
78	{ 0x474D, MACH64_264XL,			"3D RAGE XL, AGP"		},		// GM
79	{ 0x474E, MACH64_264XL,			"3D RAGE XC, AGP"		},		// GN
80	{ 0x474F, MACH64_264XL,			"3D RAGE XL, PCI"		},		// GO
81	{ 0x4750, MACH64_264GTPRO,		"3D RAGE PRO, PCI"		},		// GP
82	{ 0x4751, MACH64_264GTPRO,		"3D RAGE PRO, PCI"		},		// GQ
83	{ 0x4752, MACH64_264XL,			"3D RAGE XL, PCI"		},		// GR
84	{ 0x4753, MACH64_264XL,			"3D RAGE XC, PCI"		},		// GS
85	{ 0x4754, MACH64_264GT,			"3D RAGE II"			},		// GT
86	{ 0x4755, MACH64_264GTDVD,		"3D RAGE II+"			},		// GU
87	{ 0x4756, MACH64_264GT2C,		"3D RAGE IIC, PCI"		},		// GV
88	{ 0x4757, MACH64_264GT2C,		"3D RAGE IIC, AGP"		},		// GW
89	{ 0x4759, MACH64_264GT2C,		"3D RAGE IIC, PCI"		},		// GY
90	{ 0x475A, MACH64_264GT2C,		"3D RAGE IIC, AGP"		},		// GZ
91	{ 0x4C42, MACH64_264LTPRO,		"3D RAGE LT PRO, AGP"	},		// LB
92	{ 0x4C44, MACH64_264LTPRO,		"3D RAGE LT PRO, AGP"	},		// LD
93	{ 0x4C47, MACH64_264LT,			"3D RAGE LT"			},		// LG
94	{ 0x4C49, MACH64_264LTPRO,		"3D RAGE LT PRO, PCI"	},		// LI
95	{ 0x4C4D, MACH64_MOBILITY,		"3D RAGE Mobility, AGP"	},		// LM
96	{ 0x4C4E, MACH64_MOBILITY,		"3D RAGE Mobility, AGP"	},		// LN
97	{ 0x4C50, MACH64_264LTPRO,		"3D RAGE LT PRO, PCI"	},		// LP
98	{ 0x4C51, MACH64_264LTPRO,		"3D RAGE LT PRO, PCI"	},		// LQ
99	{ 0x4C52, MACH64_MOBILITY,		"3D RAGE Mobility, PCI"	},		// LR
100	{ 0x4C53, MACH64_MOBILITY,		"3D RAGE Mobility, PCI"	},		// LS
101	{ 0x5654, MACH64_264VT,			"264VT2"				},		// VT
102	{ 0x5655, MACH64_264VT3,		"264VT3"				},		// VU
103	{ 0x5656, MACH64_264VT4,		"264VT4"				},		// VV
104
105	{ 0x4C45, RAGE128_MOBILITY,		"RAGE 128 Mobility 3"	},		// LE
106	{ 0x4C46, RAGE128_MOBILITY,		"RAGE 128 Mobility 3"	},		// LF
107	{ 0x4D46, RAGE128_MOBILITY,		"RAGE 128 Mobility 4"	},		// MF
108	{ 0x4D4C, RAGE128_MOBILITY,		"RAGE 128 Mobility 4"	},		// ML
109	{ 0x5041, RAGE128_PRO_GL,		sRage128_Pro_GL			},		// PA
110	{ 0x5042, RAGE128_PRO_GL,		sRage128_Pro_GL			},		// PB
111	{ 0x5043, RAGE128_PRO_GL,		sRage128_Pro_GL			},		// PC
112	{ 0x5044, RAGE128_PRO_GL,		sRage128_Pro_GL			},		// PD
113	{ 0x5045, RAGE128_PRO_GL,		sRage128_Pro_GL			},		// PE
114	{ 0x5046, RAGE128_PRO_GL,		sRage128_Pro_GL			},		// PF
115	{ 0x5047, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PG
116	{ 0x5048, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PH
117	{ 0x5049, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PI
118	{ 0x504A, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PJ
119	{ 0x504B, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PK
120	{ 0x504C, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PL
121	{ 0x504D, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PM
122	{ 0x504E, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PN
123	{ 0x504F, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PO
124	{ 0x5050, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PP
125	{ 0x5051, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PQ
126	{ 0x5052, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PR
127	{ 0x5053, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PS
128	{ 0x5054, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PT
129	{ 0x5055, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PU
130	{ 0x5056, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PV
131	{ 0x5057, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PW
132	{ 0x5058, RAGE128_PRO_VR,		sRage128_Pro_VR			},		// PX
133	{ 0x5245, RAGE128_GL,			sRage128_GL				},		// RE
134	{ 0x5246, RAGE128_GL,			sRage128_GL				},		// RF
135	{ 0x5247, RAGE128_GL,			sRage128_GL				},		// RG
136	{ 0x524B, RAGE128_VR,			sRage128_VR				},		// RK
137	{ 0x524C, RAGE128_VR,			sRage128_VR				},		// RL
138	{ 0x5345, RAGE128_VR,			sRage128_VR				},		// SE
139	{ 0x5346, RAGE128_VR,			sRage128_VR				},		// SF
140	{ 0x5347, RAGE128_VR,			sRage128_VR				},		// SG
141	{ 0x5348, RAGE128_VR,			sRage128_VR				},		// SH
142	{ 0x534B, RAGE128_GL,			sRage128_GL				},		// SK
143	{ 0x534C, RAGE128_GL,			sRage128_GL				},		// SL
144	{ 0x534D, RAGE128_GL,			sRage128_GL				},		// SM
145	{ 0x534E, RAGE128_GL,			sRage128_GL				},		// SN
146	{ 0x5446, RAGE128_PRO_ULTRA,	sRage128_Pro_Ultra		},		// TF
147	{ 0x544C, RAGE128_PRO_ULTRA,	sRage128_Pro_Ultra		},		// TL
148	{ 0x5452, RAGE128_PRO_ULTRA,	sRage128_Pro_Ultra		},		// TR
149	{ 0x5453, RAGE128_PRO_ULTRA,	sRage128_Pro_Ultra		},		// TS
150	{ 0x5454, RAGE128_PRO_ULTRA,	sRage128_Pro_Ultra		},		// TT
151	{ 0x5455, RAGE128_PRO_ULTRA,	sRage128_Pro_Ultra		},		// TU
152	{ 0,	  ATI_NONE,				NULL }
153};
154
155
156struct DeviceInfo {
157	uint32			openCount;		// count of how many times device has been opened
158	int32			flags;
159	area_id 		sharedArea;		// area shared between driver and all accelerants
160	SharedInfo* 	sharedInfo;		// pointer to shared info area memory
161	vuint8*	 		regs;			// pointer to memory mapped registers
162	const ChipInfo*	pChipInfo;		// info about the selected chip
163	pci_info		pciInfo;		// copy of pci info for this device
164	char			name[B_OS_NAME_LENGTH]; // name of device
165};
166
167
168static Benaphore		gLock;
169static DeviceInfo		gDeviceInfo[MAX_DEVICES];
170static char*			gDeviceNames[MAX_DEVICES + 1];
171static pci_module_info*	gPCI;
172
173
174// Prototypes for device hook functions.
175
176static status_t device_open(const char* name, uint32 flags, void** cookie);
177static status_t device_close(void* dev);
178static status_t device_free(void* dev);
179static status_t device_read(void* dev, off_t pos, void* buf, size_t* len);
180static status_t device_write(void* dev, off_t pos, const void* buf, size_t* len);
181static status_t device_ioctl(void* dev, uint32 msg, void* buf, size_t len);
182
183static device_hooks gDeviceHooks =
184{
185	device_open,
186	device_close,
187	device_free,
188	device_ioctl,
189	device_read,
190	device_write,
191	NULL,
192	NULL,
193	NULL,
194	NULL
195};
196
197
198
199static inline uint32
200GetPCI(pci_info& info, uint8 offset, uint8 size)
201{
202	return gPCI->read_pci_config(info.bus, info.device, info.function, offset,
203		size);
204}
205
206
207static inline void
208SetPCI(pci_info& info, uint8 offset, uint8 size, uint32 value)
209{
210	gPCI->write_pci_config(info.bus, info.device, info.function, offset, size,
211		value);
212}
213
214
215// Functions for dealing with Vertical Blanking Interrupts.  Currently, I do
216// not know the commands to handle these operations;  thus, these functions
217// currently do nothing.
218
219static bool
220InterruptIsVBI()
221{
222	// return true only if a vertical blanking interrupt has occured
223	return false;
224}
225
226
227static void
228ClearVBI()
229{
230}
231
232static void
233EnableVBI()
234{
235}
236
237static void
238DisableVBI()
239{
240}
241
242
243
244static status_t
245GetEdidFromBIOS(edid1_raw& edidRaw)
246{
247	// Get the EDID info from the video BIOS, and return B_OK if successful.
248
249#define ADDRESS_SEGMENT(address) ((addr_t)(address) >> 4)
250#define ADDRESS_OFFSET(address) ((addr_t)(address) & 0xf)
251
252	bios_module_info* biosModule;
253	status_t status = get_module(B_BIOS_MODULE_NAME, (module_info**)&biosModule);
254	if (status != B_OK) {
255		TRACE("GetEdidFromBIOS(): failed to get BIOS module: 0x%" B_PRIx32 "\n",
256			status);
257		return status;
258	}
259
260	bios_state* state;
261	status = biosModule->prepare(&state);
262	if (status != B_OK) {
263		TRACE("GetEdidFromBIOS(): bios_prepare() failed: 0x%" B_PRIx32 "\n",
264			status);
265		put_module(B_BIOS_MODULE_NAME);
266		return status;
267	}
268
269	bios_regs regs = {};
270	regs.eax = 0x4f15;
271	regs.ebx = 0;			// 0 = report DDC service
272	regs.ecx = 0;
273	regs.es = 0;
274	regs.edi = 0;
275
276	status = biosModule->interrupt(state, 0x10, &regs);
277	if (status == B_OK) {
278		// AH contains the error code, and AL determines whether or not the
279		// function is supported.
280		if (regs.eax != 0x4f)
281			status = B_NOT_SUPPORTED;
282
283		// Test if DDC is supported by the monitor.
284		if ((regs.ebx & 3) == 0)
285			status = B_NOT_SUPPORTED;
286	}
287
288	if (status == B_OK) {
289		edid1_raw* edid = (edid1_raw*)biosModule->allocate_mem(state,
290			sizeof(edid1_raw));
291		if (edid == NULL) {
292			status = B_NO_MEMORY;
293			goto out;
294		}
295
296		regs.eax = 0x4f15;
297		regs.ebx = 1;		// 1 = read EDID
298		regs.ecx = 0;
299		regs.edx = 0;
300		regs.es  = ADDRESS_SEGMENT(edid);
301		regs.edi = ADDRESS_OFFSET(edid);
302
303		status = biosModule->interrupt(state, 0x10, &regs);
304		if (status == B_OK) {
305			if (regs.eax != 0x4f) {
306				status = B_NOT_SUPPORTED;
307			} else {
308				// Copy the EDID info to the caller's location, and compute the
309				// checksum of the EDID info while copying.
310
311				uint8 sum = 0;
312				uint8 allOr = 0;
313				uint8* dest = (uint8*)&edidRaw;
314				uint8* src = (uint8*)edid;
315
316				for (uint32 j = 0; j < sizeof(edidRaw); j++) {
317					sum += *src;
318					allOr |= *src;
319					*dest++ = *src++;
320				}
321
322				if (allOr == 0) {
323					TRACE("GetEdidFromBIOS(); EDID info contains only zeros\n");
324					status = B_ERROR;
325				} else if (sum != 0) {
326					TRACE("GetEdidFromBIOS(); Checksum error in EDID info\n");
327					status = B_ERROR;
328				}
329			}
330		}
331	}
332
333out:
334	biosModule->finish(state);
335	put_module(B_BIOS_MODULE_NAME);
336	return status;
337}
338
339
340static status_t
341SetVesaDisplayMode(uint16 mode)
342{
343	// Set the VESA display mode, and return B_OK if successful.
344
345#define SET_MODE_MASK				0x01ff
346#define SET_MODE_LINEAR_BUFFER		(1 << 14)
347
348	bios_module_info* biosModule;
349	status_t status = get_module(B_BIOS_MODULE_NAME, (module_info**)&biosModule);
350	if (status != B_OK) {
351		TRACE("SetVesaDisplayMode(0x%x): failed to get BIOS module: 0x%" B_PRIx32
352			"\n", mode, status);
353		return status;
354	}
355
356	bios_state* state;
357	status = biosModule->prepare(&state);
358	if (status != B_OK) {
359		TRACE("SetVesaDisplayMode(0x%x): bios_prepare() failed: 0x%" B_PRIx32
360			"\n", mode, status);
361		put_module(B_BIOS_MODULE_NAME);
362		return status;
363	}
364
365	bios_regs regs = {};
366	regs.eax = 0x4f02;
367	regs.ebx = (mode & SET_MODE_MASK) | SET_MODE_LINEAR_BUFFER;
368
369	status = biosModule->interrupt(state, 0x10, &regs);
370	if (status != B_OK) {
371		TRACE("SetVesaDisplayMode(0x%x): BIOS interrupt failed\n", mode);
372	}
373
374	if (status == B_OK && (regs.eax & 0xffff) != 0x4f) {
375		TRACE("SetVesaDisplayMode(0x%x): BIOS returned 0x%04" B_PRIx32 "\n",
376			mode, regs.eax & 0xffff);
377		status = B_ERROR;
378	}
379
380	biosModule->finish(state);
381	put_module(B_BIOS_MODULE_NAME);
382	return status;
383}
384
385
386
387// Macros for accessing BIOS info.
388
389#define BIOS8(v)  (romAddr[v])
390#define BIOS16(v) (romAddr[v] | \
391				  (romAddr[(v) + 1] << 8))
392#define BIOS32(v) (romAddr[v] | \
393				  (romAddr[(v) + 1] << 8) | \
394				  (romAddr[(v) + 2] << 16) | \
395				  (romAddr[(v) + 3] << 24))
396
397
398static status_t
399Mach64_GetBiosParameters(DeviceInfo& di, uint8& clockType)
400{
401	// Get some clock parameters from the video BIOS, and if Mobility chip,
402	// also get the LCD panel width & height.
403
404	// In case mapping the ROM area fails or other error occurs, set default
405	// values for the parameters which will be obtained from the BIOS ROM.
406
407	clockType = M64_CLOCK_INTERNAL;
408
409	SharedInfo& si = *(di.sharedInfo);
410	M64_Params& params = si.m64Params;
411	params.clockNumberToProgram = 3;
412
413	si.panelX = 0;
414	si.panelY = 0;
415
416	// Map the ROM area.  The Mach64 chips do not assign a ROM address in the
417	// PCI info;  thus, access the ROM via the ISA legacy memory map.
418
419	uint8* romAddr;
420	area_id romArea = map_physical_memory("ATI Mach64 ROM",
421		0x000c0000,
422		M64_BIOS_SIZE,
423		B_ANY_KERNEL_ADDRESS,
424		B_READ_AREA,
425		(void**)&(romAddr));
426
427	if (romArea < 0) {
428		TRACE("Mach64_GetBiosParameters(), ROM mapping error: %ld\n", romArea);
429		return romArea;		// ROM mapping failed; return error code
430	}
431
432	// Check if we have the BIOS signature (might fail on laptops..).
433
434	if (BIOS8(0) != 0x55 || BIOS8(1) != 0xaa) {
435		TRACE("Mach64_GetBiosParameters(), ROM does not contain BIOS signature\n");
436		delete_area(romArea);
437		return B_ERROR;
438	}
439
440	// Get clock info from BIOS.
441
442	uint32 romTable = BIOS16(0x48);
443	uint32 clockTable = BIOS16(romTable + 16);
444	clockType = BIOS8(clockTable);
445	params.clockNumberToProgram = BIOS8(clockTable + 6);
446	params.maxPixelClock = BIOS16(clockTable + 4) * 10;
447	params.refFreq = BIOS16(clockTable + 8);
448	params.refDivider = BIOS16(clockTable + 10);
449
450	// If Mobility chip, get the LCD panel width & height.
451
452	if (si.chipType == MACH64_MOBILITY) {
453		uint32 lcdTable = BIOS16(0x78);
454		if (BIOS32(lcdTable) == 0x544d5224) {	// is LCD table signature correct?
455			uint32 lcdPanelInfo = BIOS16(lcdTable + 10);
456			si.panelX = BIOS16(lcdPanelInfo + 25);
457			si.panelY = BIOS16(lcdPanelInfo + 27);
458			TRACE("Mobility LCD Panel size: %dx%d\n", si.panelX, si.panelY);
459		} else {
460			TRACE("Mobility LCD table signature 0x%x in BIOS is incorrect\n",
461				 BIOS32(lcdTable));
462		}
463	}
464
465	delete_area(romArea);
466
467	return B_OK;
468}
469
470
471
472static status_t
473Rage128_GetBiosParameters(DeviceInfo& di)
474{
475	// Get the PLL parameters from the video BIOS, and if Mobility chips, also
476	// get the LCD panel width & height and a few other related parameters.
477
478	// In case mapping the ROM area fails or other error occurs, set default
479	// values for the parameters which will be obtained from the BIOS ROM.
480	// The default PLL parameters values probably will not work for all chips.
481	// For example, reference freq can be 29.50MHz, 28.63MHz, or 14.32MHz.
482
483	SharedInfo& si = *(di.sharedInfo);
484	R128_PLLParams& pll = si.r128PLLParams;
485	pll.reference_freq = 2950;
486	pll.reference_div = 65;
487	pll.min_pll_freq = 12500;
488	pll.max_pll_freq = 25000;
489	pll.xclk = 10300;
490
491	si.panelX = 0;
492	si.panelY = 0;
493	si.panelPowerDelay = 1;
494
495	// Map the ROM area.  The Rage128 chips do not assign a ROM address in the
496	// PCI info;  thus, access the ROM via the ISA legacy memory map.
497
498	uint8* romAddr;
499	area_id romArea = map_physical_memory("ATI Rage128 ROM",
500		0x000c0000,
501		R128_BIOS_SIZE,
502		B_ANY_KERNEL_ADDRESS,
503		B_READ_AREA,
504		(void**)&(romAddr));
505
506	if (romArea < 0) {
507		TRACE("Rage128_GetBiosParameters(), ROM mapping error: %ld\n", romArea);
508		return romArea;		// ROM mapping failed; return error code
509	}
510
511	// Check if we got the BIOS signature (might fail on laptops..).
512
513	if (BIOS8(0) != 0x55 || BIOS8(1) != 0xaa) {
514		TRACE("Rage128_GetBiosParameters(), ROM does not contain BIOS signature\n");
515		delete_area(romArea);
516		return B_ERROR;
517	}
518
519	// Get the PLL values from the mapped ROM area.
520
521	uint16 biosHeader = BIOS16(0x48);
522	uint16 pllInfoBlock = BIOS16(biosHeader + 0x30);
523
524	pll.reference_freq = BIOS16(pllInfoBlock + 0x0e);
525	pll.reference_div = BIOS16(pllInfoBlock + 0x10);
526	pll.min_pll_freq = BIOS32(pllInfoBlock + 0x12);
527	pll.max_pll_freq = BIOS32(pllInfoBlock + 0x16);
528	pll.xclk = BIOS16(pllInfoBlock + 0x08);
529
530	TRACE("PLL parameters: rf=%d rd=%d min=%ld max=%ld; xclk=%d\n",
531		pll.reference_freq, pll.reference_div, pll.min_pll_freq,
532		pll.max_pll_freq, pll.xclk);
533
534	// If Mobility chip, get the LCD panel width & height and a few other
535	// related parameters.
536
537	if (si.chipType == RAGE128_MOBILITY) {
538		// There should be direct access to the start of the FP info table, but
539		// until we find out where that offset is stored, we must search for
540		// the ATI signature string: "M3      ".
541
542		int i;
543		for (i = 4; i < R128_BIOS_SIZE - 8; i++) {
544			if (BIOS8(i) == 'M' &&
545					BIOS8(i + 1) == '3' &&
546					BIOS8(i + 2) == ' ' &&
547					BIOS8(i + 3) == ' ' &&
548					BIOS8(i + 4) == ' ' &&
549					BIOS8(i + 5) == ' ' &&
550					BIOS8(i + 6) == ' ' &&
551					BIOS8(i + 7) == ' ') {
552				int fpHeader = i - 2;
553
554				// Assume that only one panel is attached and supported.
555
556				for (i = fpHeader + 20; i < fpHeader + 84; i += 2) {
557					if (BIOS16(i) != 0) {
558						int fpStart = BIOS16(i);
559						si.panelX = BIOS16(fpStart + 25);
560						si.panelY = BIOS16(fpStart + 27);
561						si.panelPowerDelay = BIOS8(fpStart + 56);
562						TRACE("LCD Panel size: %dx%d  Panel type: 0x%x   power delay: %d\n",
563							si.panelX, si.panelY, BIOS16(fpStart + 29),
564							si.panelPowerDelay);
565						break;
566					}
567				}
568
569				break;
570			}
571		}
572	}
573
574	delete_area(romArea);
575
576	return B_OK;
577}
578
579
580static status_t
581MapDevice(DeviceInfo& di)
582{
583	SharedInfo& si = *(di.sharedInfo);
584	pci_info& pciInfo = di.pciInfo;
585
586	// Enable memory mapped IO and bus master.
587
588	SetPCI(pciInfo, PCI_command, 2, GetPCI(pciInfo, PCI_command, 2)
589		| PCI_command_io | PCI_command_memory | PCI_command_master);
590
591	// Map the video memory.
592
593	phys_addr_t videoRamAddr = pciInfo.u.h0.base_registers[0];
594	uint32 videoRamSize = pciInfo.u.h0.base_register_sizes[0];
595	si.videoMemPCI = videoRamAddr;
596	char frameBufferAreaName[] = "ATI frame buffer";
597
598	si.videoMemArea = map_physical_memory(
599		frameBufferAreaName,
600		videoRamAddr,
601		videoRamSize,
602		B_ANY_KERNEL_BLOCK_ADDRESS | B_MTR_WC,
603		B_READ_AREA + B_WRITE_AREA,
604		(void**)&(si.videoMemAddr));
605
606	if (si.videoMemArea < 0) {
607		// Try to map this time without write combining.
608		si.videoMemArea = map_physical_memory(
609			frameBufferAreaName,
610			videoRamAddr,
611			videoRamSize,
612			B_ANY_KERNEL_BLOCK_ADDRESS,
613			B_READ_AREA + B_WRITE_AREA,
614			(void**)&(si.videoMemAddr));
615	}
616
617	if (si.videoMemArea < 0)
618		return si.videoMemArea;
619
620	// Map the MMIO register area.
621
622	phys_addr_t regsBase = pciInfo.u.h0.base_registers[2];
623	uint32 regAreaSize = pciInfo.u.h0.base_register_sizes[2];
624
625	// If the register area address or size is not in the PCI info, it should
626	// be at the end of the video memory.  Check if it is there.
627
628	if (MACH64_FAMILY(si.chipType) && (regsBase == 0 || regAreaSize == 0)) {
629		uint32 regsOffset = 0x7ff000;	// offset to regs area in video memory
630		uint32 regs = uint32(si.videoMemAddr) + regsOffset;
631		uint32 chipInfo = *((vuint32*)(regs + M64_CONFIG_CHIP_ID));
632
633		if (si.deviceID != (chipInfo & M64_CFG_CHIP_TYPE)) {
634			// Register area not found;  delete any other areas that were
635			// created.
636			delete_area(si.videoMemArea);
637			si.videoMemArea = -1;
638			TRACE("Mach64 register area not found\n");
639			return B_ERROR;
640		}
641
642		// Adjust params for creating register area below.
643
644		regsBase = videoRamAddr + regsOffset;
645		regAreaSize = 0x1000;
646		TRACE("Register address is at end of frame buffer memory at 0x%lx\n",
647			uint32(regsBase));
648	}
649
650	si.regsArea = map_physical_memory("ATI mmio registers",
651		regsBase,
652		regAreaSize,
653		B_ANY_KERNEL_ADDRESS,
654		0,		// neither read nor write, to hide it from user space apps
655		(void**)&di.regs);
656
657	// If there was an error, delete other areas.
658	if (si.regsArea < 0) {
659		delete_area(si.videoMemArea);
660		si.videoMemArea = -1;
661	}
662
663	return si.regsArea;
664}
665
666
667static void
668UnmapDevice(DeviceInfo& di)
669{
670	SharedInfo& si = *(di.sharedInfo);
671
672	if (si.regsArea >= 0)
673		delete_area(si.regsArea);
674	if (si.videoMemArea >= 0)
675		delete_area(si.videoMemArea);
676
677	si.regsArea = si.videoMemArea = -1;
678	si.videoMemAddr = (addr_t)NULL;
679	di.regs = NULL;
680}
681
682
683static int32
684InterruptHandler(void* data)
685{
686	int32 handled = B_UNHANDLED_INTERRUPT;
687	DeviceInfo& di = *((DeviceInfo*)data);
688	int32* flags = &(di.flags);
689
690	// Is someone already handling an interrupt for this device?
691	if (atomic_or(flags, SKD_HANDLER_INSTALLED) & SKD_HANDLER_INSTALLED)
692		return B_UNHANDLED_INTERRUPT;
693
694	if (InterruptIsVBI()) {	// was interrupt a VBI?
695		ClearVBI();			// clear interrupt
696
697		handled = B_HANDLED_INTERRUPT;
698
699		// Release vertical blanking semaphore.
700		sem_id& sem = di.sharedInfo->vertBlankSem;
701
702		if (sem >= 0) {
703			int32 blocked;
704			if ((get_sem_count(sem, &blocked) == B_OK) && (blocked < 0)) {
705				release_sem_etc(sem, -blocked, B_DO_NOT_RESCHEDULE);
706				handled = B_INVOKE_SCHEDULER;
707			}
708		}
709	}
710
711	atomic_and(flags, ~SKD_HANDLER_INSTALLED);	// note we're not in handler anymore
712
713	return handled;
714}
715
716
717static void
718InitInterruptHandler(DeviceInfo& di)
719{
720	SharedInfo& si = *(di.sharedInfo);
721
722	DisableVBI();					// disable & clear any pending interrupts
723	si.bInterruptAssigned = false;	// indicate interrupt not assigned yet
724
725	// Create a semaphore for vertical blank management.
726	si.vertBlankSem = create_sem(0, di.name);
727	if (si.vertBlankSem < 0)
728		return;
729
730	// Change the owner of the semaphores to the calling team (usually the
731	// app_server).  This is required because apps can't aquire kernel
732	// semaphores.
733
734	thread_id threadID = find_thread(NULL);
735	thread_info threadInfo;
736	status_t status = get_thread_info(threadID, &threadInfo);
737	if (status == B_OK)
738		status = set_sem_owner(si.vertBlankSem, threadInfo.team);
739
740	// If there is a valid interrupt assigned, set up interrupts.
741
742	if (status == B_OK && di.pciInfo.u.h0.interrupt_pin != 0x00
743		&& di.pciInfo.u.h0.interrupt_line != 0xff) {
744		// We have a interrupt line to use.
745
746		status = install_io_interrupt_handler(di.pciInfo.u.h0.interrupt_line,
747			InterruptHandler, (void*)(&di), 0);
748
749		if (status == B_OK)
750			si.bInterruptAssigned = true;	// we can use interrupt related functions
751	}
752
753	if (status != B_OK) {
754		// Interrupt does not exist; thus delete semaphore as it won't be used.
755		delete_sem(si.vertBlankSem);
756		si.vertBlankSem = -1;
757	}
758}
759
760
761static status_t
762InitDevice(DeviceInfo& di)
763{
764	// Perform initialization and mapping of the device, and return B_OK if
765	// sucessful;  else, return error code.
766
767	// Get the table of VESA modes that the chip supports.  Note that we will
768	// need this table only for chips that are currently connected to a laptop
769	// display or a monitor connected via a DVI interface.
770
771	size_t vesaModeTableSize = 0;
772	VesaMode* vesaModes = (VesaMode*)get_boot_item(VESA_MODES_BOOT_INFO,
773		&vesaModeTableSize);
774
775	size_t sharedSize = (sizeof(SharedInfo) + 7) & ~7;
776
777	// Create the area for shared info with NO user-space read or write
778	// permissions, to prevent accidental damage.
779
780	di.sharedArea = create_area("ATI shared info",
781		(void**) &(di.sharedInfo),
782		B_ANY_KERNEL_ADDRESS,
783		ROUND_TO_PAGE_SIZE(sharedSize + vesaModeTableSize),
784		B_FULL_LOCK, 0);
785	if (di.sharedArea < 0)
786		return di.sharedArea;	// return error code
787
788	SharedInfo& si = *(di.sharedInfo);
789
790	memset(&si, 0, sharedSize);
791
792	if (vesaModes != NULL) {
793		si.vesaModeTableOffset = sharedSize;
794		si.vesaModeCount = vesaModeTableSize / sizeof(VesaMode);
795
796		memcpy((uint8*)&si + si.vesaModeTableOffset, vesaModes,
797			vesaModeTableSize);
798	}
799
800	pci_info& pciInfo = di.pciInfo;
801
802	si.vendorID = pciInfo.vendor_id;
803	si.deviceID = pciInfo.device_id;
804	si.revision = pciInfo.revision;
805	si.chipType = di.pChipInfo->chipType;
806	strcpy(si.chipName, di.pChipInfo->chipName);
807
808	TRACE("Chip revision: 0x%x\n", si.revision);
809
810	// 264GT has two chip versions.  If version is non-zero, chip is 264GTB.
811
812	if (si.chipType == MACH64_264GT && si.revision & 0x7)
813		si.chipType = MACH64_264GTB;
814
815	// 264VT has two chip versions.  If version is non-zero, chip is 264VTB.
816
817	if (si.chipType == MACH64_264VT && si.revision & 0x7)
818		si.chipType = MACH64_264VTB;
819
820	status_t status = MapDevice(di);
821
822	// If device mapped without any error, get the bios parameters from the
823	// chip's BIOS ROM.
824
825	if (status >= 0) {
826		if (MACH64_FAMILY(si.chipType)) {
827			uint8 clockType;
828			Mach64_GetBiosParameters(di, clockType);
829
830			// All chips supported by this driver should have an internal clock.
831			// If the clock is not an internal clock, the video chip is not
832			// supported.
833
834			if (clockType != M64_CLOCK_INTERNAL) {
835				TRACE("Video chip clock type %d not supported\n", clockType);
836				status = B_UNSUPPORTED;
837			}
838		}
839		else if (RAGE128_FAMILY(si.chipType))
840			Rage128_GetBiosParameters(di);
841	}
842
843	if (status < 0) {
844		delete_area(di.sharedArea);
845		di.sharedArea = -1;
846		di.sharedInfo = NULL;
847		return status;		// return error code
848	}
849
850	InitInterruptHandler(di);
851
852	TRACE("Interrupt assigned:  %s\n", si.bInterruptAssigned ? "yes" : "no");
853	return B_OK;
854}
855
856
857static const ChipInfo*
858GetNextSupportedDevice(uint32& pciIndex, pci_info& pciInfo)
859{
860	// Search the PCI devices for a device that is supported by this driver.
861	// The search starts at the device specified by argument pciIndex, and
862	// continues until a supported device is found or there are no more devices
863	// to examine.  Argument pciIndex is incremented after each device is
864	// examined.
865
866	// If a supported device is found, return a pointer to the struct containing
867	// the chip info; else return NULL.
868
869	while (gPCI->get_nth_pci_info(pciIndex, &pciInfo) == B_OK) {
870
871		if (pciInfo.vendor_id == VENDOR_ID) {
872
873			// Search the table of supported devices to find a chip/device that
874			// matches device ID of the current PCI device.
875
876			const ChipInfo* pDevice = chipTable;
877
878			while (pDevice->chipID != 0) {	// end of table?
879				if (pDevice->chipID == pciInfo.device_id) {
880					// Matching device/chip found.  If chip is 264VT, reject it
881					// if its version is zero since the mode can not be set on
882					// that chip.
883
884					if (pDevice->chipType == MACH64_264VT
885							&& (pciInfo.revision & 0x7) == 0)
886						break;
887
888					return pDevice;		// matching device/chip found
889				}
890
891				pDevice++;
892			}
893		}
894
895		pciIndex++;
896	}
897
898	return NULL;		// no supported device found
899}
900
901
902
903//	#pragma mark - Kernel Interface
904
905
906status_t
907init_hardware(void)
908{
909	// Return B_OK if a device supported by this driver is found; otherwise,
910	// return B_ERROR so the driver will be unloaded.
911
912	if (get_module(B_PCI_MODULE_NAME, (module_info**)&gPCI) != B_OK)
913		return B_ERROR;		// unable to access PCI bus
914
915	// Check pci devices for a device supported by this driver.
916
917	uint32 pciIndex = 0;
918	pci_info pciInfo;
919	const ChipInfo* pDevice = GetNextSupportedDevice(pciIndex, pciInfo);
920
921	TRACE("init_hardware() - %s\n",
922		pDevice == NULL ? "no supported devices" : "device supported");
923
924	put_module(B_PCI_MODULE_NAME);		// put away the module manager
925
926	return (pDevice == NULL ? B_ERROR : B_OK);
927}
928
929
930status_t
931init_driver(void)
932{
933	// Get handle for the pci bus.
934
935	if (get_module(B_PCI_MODULE_NAME, (module_info**)&gPCI) != B_OK)
936		return B_ERROR;
937
938	status_t status = gLock.Init("ATI driver lock");
939	if (status < B_OK)
940		return status;
941
942	// Get info about all the devices supported by this driver.
943
944	uint32 pciIndex = 0;
945	uint32 count = 0;
946
947	while (count < MAX_DEVICES) {
948		DeviceInfo& di = gDeviceInfo[count];
949
950		const ChipInfo* pDevice = GetNextSupportedDevice(pciIndex, di.pciInfo);
951		if (pDevice == NULL)
952			break;			// all supported devices have been obtained
953
954		// Compose device name.
955		sprintf(di.name, "graphics/" DEVICE_FORMAT,
956				  di.pciInfo.vendor_id, di.pciInfo.device_id,
957				  di.pciInfo.bus, di.pciInfo.device, di.pciInfo.function);
958		TRACE("init_driver() match found; name: %s\n", di.name);
959
960		gDeviceNames[count] = di.name;
961		di.openCount = 0;		// mark driver as available for R/W open
962		di.sharedArea = -1;		// indicate shared area not yet created
963		di.sharedInfo = NULL;
964		di.pChipInfo = pDevice;
965		count++;
966		pciIndex++;
967	}
968
969	gDeviceNames[count] = NULL;	// terminate list with null pointer
970
971	TRACE("init_driver() %ld supported devices\n", count);
972
973	return B_OK;
974}
975
976
977void
978uninit_driver(void)
979{
980	// Free the driver data.
981
982	gLock.Delete();
983	put_module(B_PCI_MODULE_NAME);	// put the pci module away
984}
985
986
987const char**
988publish_devices(void)
989{
990	return (const char**)gDeviceNames;	// return list of supported devices
991}
992
993
994device_hooks*
995find_device(const char* name)
996{
997	int i = 0;
998	while (gDeviceNames[i] != NULL) {
999		if (strcmp(name, gDeviceNames[i]) == 0)
1000			return &gDeviceHooks;
1001		i++;
1002	}
1003
1004	return NULL;
1005}
1006
1007
1008
1009//	#pragma mark - Device Hooks
1010
1011
1012static status_t
1013device_open(const char* name, uint32 /*flags*/, void** cookie)
1014{
1015	status_t status = B_OK;
1016
1017	TRACE("device_open() - name: %s\n", name);
1018
1019	// Find the device name in the list of devices.
1020
1021	int32 i = 0;
1022	while (gDeviceNames[i] != NULL && (strcmp(name, gDeviceNames[i]) != 0))
1023		i++;
1024
1025	if (gDeviceNames[i] == NULL)
1026		return B_BAD_VALUE;		// device name not found in list of devices
1027
1028	DeviceInfo& di = gDeviceInfo[i];
1029
1030	gLock.Acquire();	// make sure no one else has write access to common data
1031
1032	if (di.openCount == 0)
1033		status = InitDevice(di);
1034
1035	gLock.Release();
1036
1037	if (status == B_OK) {
1038		di.openCount++;		// mark device open
1039		*cookie = &di;		// send cookie to opener
1040	}
1041
1042	TRACE("device_open() returning 0x%lx,  open count: %ld\n", status,
1043		di.openCount);
1044	return status;
1045}
1046
1047
1048static status_t
1049device_read(void* dev, off_t pos, void* buf, size_t* len)
1050{
1051	// Following 3 lines of code are here to eliminate "unused parameter"
1052	// warnings.
1053	(void)dev;
1054	(void)pos;
1055	(void)buf;
1056
1057	*len = 0;
1058	return B_NOT_ALLOWED;
1059}
1060
1061
1062static status_t
1063device_write(void* dev, off_t pos, const void* buf, size_t* len)
1064{
1065	// Following 3 lines of code are here to eliminate "unused parameter"
1066	// warnings.
1067	(void)dev;
1068	(void)pos;
1069	(void)buf;
1070
1071	*len = 0;
1072	return B_NOT_ALLOWED;
1073}
1074
1075
1076static status_t
1077device_close(void* dev)
1078{
1079	(void)dev;		// avoid compiler warning for unused arg
1080
1081	return B_NO_ERROR;
1082}
1083
1084
1085static status_t
1086device_free(void* dev)
1087{
1088	DeviceInfo& di = *((DeviceInfo*)dev);
1089	SharedInfo& si = *(di.sharedInfo);
1090	pci_info& pciInfo = di.pciInfo;
1091
1092	TRACE("enter device_free()\n");
1093
1094	gLock.Acquire();		// lock driver
1095
1096	// If opened multiple times, merely decrement the open count and exit.
1097
1098	if (di.openCount <= 1) {
1099		DisableVBI();		// disable & clear any pending interrupts
1100
1101		if (si.bInterruptAssigned) {
1102			remove_io_interrupt_handler(pciInfo.u.h0.interrupt_line,
1103				InterruptHandler, &di);
1104		}
1105
1106		// Delete the semaphores, ignoring any errors because the owning team
1107		// may have died.
1108		if (si.vertBlankSem >= 0)
1109			delete_sem(si.vertBlankSem);
1110		si.vertBlankSem = -1;
1111
1112		UnmapDevice(di);	// free regs and frame buffer areas
1113
1114		delete_area(di.sharedArea);
1115		di.sharedArea = -1;
1116		di.sharedInfo = NULL;
1117	}
1118
1119	if (di.openCount > 0)
1120		di.openCount--;		// mark device available
1121
1122	gLock.Release();	// unlock driver
1123
1124	TRACE("exit device_free() openCount: %ld\n", di.openCount);
1125	return B_OK;
1126}
1127
1128
1129static status_t
1130device_ioctl(void* dev, uint32 msg, void* buffer, size_t bufferLength)
1131{
1132	DeviceInfo& di = *((DeviceInfo*)dev);
1133
1134//	TRACE("device_ioctl(); ioctl: %lu, buffer: 0x%08lx, bufLen: %lu\n", msg,
1135//		(uint32)buffer, bufferLength);
1136
1137	switch (msg) {
1138		case B_GET_ACCELERANT_SIGNATURE:
1139			strcpy((char*)buffer, ATI_ACCELERANT_NAME);
1140			return B_OK;
1141
1142		case ATI_DEVICE_NAME:
1143			strncpy((char*)buffer, di.name, B_OS_NAME_LENGTH);
1144			((char*)buffer)[B_OS_NAME_LENGTH -1] = '\0';
1145			return B_OK;
1146
1147		case ATI_GET_SHARED_DATA:
1148			if (bufferLength != sizeof(area_id))
1149				return B_BAD_DATA;
1150
1151			*((area_id*)buffer) = di.sharedArea;
1152			return B_OK;
1153
1154		case ATI_GET_EDID:
1155		{
1156			if (bufferLength != sizeof(edid1_raw))
1157				return B_BAD_DATA;
1158
1159			edid1_raw rawEdid;
1160			status_t status = GetEdidFromBIOS(rawEdid);
1161			if (status == B_OK)
1162				user_memcpy((edid1_raw*)buffer, &rawEdid, sizeof(rawEdid));
1163			return status;
1164		}
1165
1166		case ATI_SET_VESA_DISPLAY_MODE:
1167			if (bufferLength != sizeof(uint16))
1168				return B_BAD_DATA;
1169
1170			return SetVesaDisplayMode(*((uint16*)buffer));
1171
1172		case ATI_RUN_INTERRUPTS:
1173			if (bufferLength != sizeof(bool))
1174				return B_BAD_DATA;
1175
1176			if (*((bool*)buffer))
1177				EnableVBI();
1178			else
1179				DisableVBI();
1180
1181			return B_OK;
1182	}
1183
1184	return B_DEV_INVALID_IOCTL;
1185}
1186