xref: /haiku/src/add-ons/kernel/drivers/graphics/ati/driver.cpp (revision 68ea01249e1e2088933cb12f9c28d4e5c5d1c9ef)
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 
43 int32 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 
53 struct 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 
63 static char sRage128_GL[]		 = "RAGE 128 GL";
64 static char sRage128_VR[]		 = "RAGE 128 VR";
65 static char sRage128_Pro_GL[]	 = "RAGE 128 PRO GL";
66 static char sRage128_Pro_VR[]	 = "RAGE 128 PRO VR";
67 static 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 
73 static 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 
156 struct 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 
168 static Benaphore		gLock;
169 static DeviceInfo		gDeviceInfo[MAX_DEVICES];
170 static char*			gDeviceNames[MAX_DEVICES + 1];
171 static pci_module_info*	gPCI;
172 
173 
174 // Prototypes for device hook functions.
175 
176 static status_t device_open(const char* name, uint32 flags, void** cookie);
177 static status_t device_close(void* dev);
178 static status_t device_free(void* dev);
179 static status_t device_read(void* dev, off_t pos, void* buf, size_t* len);
180 static status_t device_write(void* dev, off_t pos, const void* buf, size_t* len);
181 static status_t device_ioctl(void* dev, uint32 msg, void* buf, size_t len);
182 
183 static 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 
199 static inline uint32
200 GetPCI(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 
207 static inline void
208 SetPCI(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 
219 static bool
220 InterruptIsVBI()
221 {
222 	// return true only if a vertical blanking interrupt has occured
223 	return false;
224 }
225 
226 
227 static void
228 ClearVBI()
229 {
230 }
231 
232 static void
233 EnableVBI()
234 {
235 }
236 
237 static void
238 DisableVBI()
239 {
240 }
241 
242 
243 
244 static status_t
245 GetEdidFromBIOS(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 
333 out:
334 	biosModule->finish(state);
335 	put_module(B_BIOS_MODULE_NAME);
336 	return status;
337 }
338 
339 
340 static status_t
341 SetVesaDisplayMode(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 
398 static status_t
399 Mach64_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 
472 static status_t
473 Rage128_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 
580 static status_t
581 MapDevice(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 		B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA | B_CLONEABLE_AREA,
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 
667 static void
668 UnmapDevice(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 
683 static int32
684 InterruptHandler(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 
717 static void
718 InitInterruptHandler(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 
761 static status_t
762 InitDevice(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,
785 		B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA | B_CLONEABLE_AREA);
786 	if (di.sharedArea < 0)
787 		return di.sharedArea;	// return error code
788 
789 	SharedInfo& si = *(di.sharedInfo);
790 
791 	memset(&si, 0, sharedSize);
792 
793 	if (vesaModes != NULL) {
794 		si.vesaModeTableOffset = sharedSize;
795 		si.vesaModeCount = vesaModeTableSize / sizeof(VesaMode);
796 
797 		memcpy((uint8*)&si + si.vesaModeTableOffset, vesaModes,
798 			vesaModeTableSize);
799 	}
800 
801 	pci_info& pciInfo = di.pciInfo;
802 
803 	si.vendorID = pciInfo.vendor_id;
804 	si.deviceID = pciInfo.device_id;
805 	si.revision = pciInfo.revision;
806 	si.chipType = di.pChipInfo->chipType;
807 	strcpy(si.chipName, di.pChipInfo->chipName);
808 
809 	TRACE("Chip revision: 0x%x\n", si.revision);
810 
811 	// 264GT has two chip versions.  If version is non-zero, chip is 264GTB.
812 
813 	if (si.chipType == MACH64_264GT && si.revision & 0x7)
814 		si.chipType = MACH64_264GTB;
815 
816 	// 264VT has two chip versions.  If version is non-zero, chip is 264VTB.
817 
818 	if (si.chipType == MACH64_264VT && si.revision & 0x7)
819 		si.chipType = MACH64_264VTB;
820 
821 	status_t status = MapDevice(di);
822 
823 	// If device mapped without any error, get the bios parameters from the
824 	// chip's BIOS ROM.
825 
826 	if (status >= 0) {
827 		if (MACH64_FAMILY(si.chipType)) {
828 			uint8 clockType;
829 			Mach64_GetBiosParameters(di, clockType);
830 
831 			// All chips supported by this driver should have an internal clock.
832 			// If the clock is not an internal clock, the video chip is not
833 			// supported.
834 
835 			if (clockType != M64_CLOCK_INTERNAL) {
836 				TRACE("Video chip clock type %d not supported\n", clockType);
837 				status = B_UNSUPPORTED;
838 			}
839 		}
840 		else if (RAGE128_FAMILY(si.chipType))
841 			Rage128_GetBiosParameters(di);
842 	}
843 
844 	if (status < 0) {
845 		delete_area(di.sharedArea);
846 		di.sharedArea = -1;
847 		di.sharedInfo = NULL;
848 		return status;		// return error code
849 	}
850 
851 	InitInterruptHandler(di);
852 
853 	TRACE("Interrupt assigned:  %s\n", si.bInterruptAssigned ? "yes" : "no");
854 	return B_OK;
855 }
856 
857 
858 static const ChipInfo*
859 GetNextSupportedDevice(uint32& pciIndex, pci_info& pciInfo)
860 {
861 	// Search the PCI devices for a device that is supported by this driver.
862 	// The search starts at the device specified by argument pciIndex, and
863 	// continues until a supported device is found or there are no more devices
864 	// to examine.  Argument pciIndex is incremented after each device is
865 	// examined.
866 
867 	// If a supported device is found, return a pointer to the struct containing
868 	// the chip info; else return NULL.
869 
870 	while (gPCI->get_nth_pci_info(pciIndex, &pciInfo) == B_OK) {
871 
872 		if (pciInfo.vendor_id == VENDOR_ID) {
873 
874 			// Search the table of supported devices to find a chip/device that
875 			// matches device ID of the current PCI device.
876 
877 			const ChipInfo* pDevice = chipTable;
878 
879 			while (pDevice->chipID != 0) {	// end of table?
880 				if (pDevice->chipID == pciInfo.device_id) {
881 					// Matching device/chip found.  If chip is 264VT, reject it
882 					// if its version is zero since the mode can not be set on
883 					// that chip.
884 
885 					if (pDevice->chipType == MACH64_264VT
886 							&& (pciInfo.revision & 0x7) == 0)
887 						break;
888 
889 					return pDevice;		// matching device/chip found
890 				}
891 
892 				pDevice++;
893 			}
894 		}
895 
896 		pciIndex++;
897 	}
898 
899 	return NULL;		// no supported device found
900 }
901 
902 
903 
904 //	#pragma mark - Kernel Interface
905 
906 
907 status_t
908 init_hardware(void)
909 {
910 	// Return B_OK if a device supported by this driver is found; otherwise,
911 	// return B_ERROR so the driver will be unloaded.
912 
913 	if (get_module(B_PCI_MODULE_NAME, (module_info**)&gPCI) != B_OK)
914 		return B_ERROR;		// unable to access PCI bus
915 
916 	// Check pci devices for a device supported by this driver.
917 
918 	uint32 pciIndex = 0;
919 	pci_info pciInfo;
920 	const ChipInfo* pDevice = GetNextSupportedDevice(pciIndex, pciInfo);
921 
922 	TRACE("init_hardware() - %s\n",
923 		pDevice == NULL ? "no supported devices" : "device supported");
924 
925 	put_module(B_PCI_MODULE_NAME);		// put away the module manager
926 
927 	return (pDevice == NULL ? B_ERROR : B_OK);
928 }
929 
930 
931 status_t
932 init_driver(void)
933 {
934 	// Get handle for the pci bus.
935 
936 	if (get_module(B_PCI_MODULE_NAME, (module_info**)&gPCI) != B_OK)
937 		return B_ERROR;
938 
939 	status_t status = gLock.Init("ATI driver lock");
940 	if (status < B_OK)
941 		return status;
942 
943 	// Get info about all the devices supported by this driver.
944 
945 	uint32 pciIndex = 0;
946 	uint32 count = 0;
947 
948 	while (count < MAX_DEVICES) {
949 		DeviceInfo& di = gDeviceInfo[count];
950 
951 		const ChipInfo* pDevice = GetNextSupportedDevice(pciIndex, di.pciInfo);
952 		if (pDevice == NULL)
953 			break;			// all supported devices have been obtained
954 
955 		// Compose device name.
956 		sprintf(di.name, "graphics/" DEVICE_FORMAT,
957 				  di.pciInfo.vendor_id, di.pciInfo.device_id,
958 				  di.pciInfo.bus, di.pciInfo.device, di.pciInfo.function);
959 		TRACE("init_driver() match found; name: %s\n", di.name);
960 
961 		gDeviceNames[count] = di.name;
962 		di.openCount = 0;		// mark driver as available for R/W open
963 		di.sharedArea = -1;		// indicate shared area not yet created
964 		di.sharedInfo = NULL;
965 		di.pChipInfo = pDevice;
966 		count++;
967 		pciIndex++;
968 	}
969 
970 	gDeviceNames[count] = NULL;	// terminate list with null pointer
971 
972 	TRACE("init_driver() %ld supported devices\n", count);
973 
974 	return B_OK;
975 }
976 
977 
978 void
979 uninit_driver(void)
980 {
981 	// Free the driver data.
982 
983 	gLock.Delete();
984 	put_module(B_PCI_MODULE_NAME);	// put the pci module away
985 }
986 
987 
988 const char**
989 publish_devices(void)
990 {
991 	return (const char**)gDeviceNames;	// return list of supported devices
992 }
993 
994 
995 device_hooks*
996 find_device(const char* name)
997 {
998 	int i = 0;
999 	while (gDeviceNames[i] != NULL) {
1000 		if (strcmp(name, gDeviceNames[i]) == 0)
1001 			return &gDeviceHooks;
1002 		i++;
1003 	}
1004 
1005 	return NULL;
1006 }
1007 
1008 
1009 
1010 //	#pragma mark - Device Hooks
1011 
1012 
1013 static status_t
1014 device_open(const char* name, uint32 /*flags*/, void** cookie)
1015 {
1016 	status_t status = B_OK;
1017 
1018 	TRACE("device_open() - name: %s\n", name);
1019 
1020 	// Find the device name in the list of devices.
1021 
1022 	int32 i = 0;
1023 	while (gDeviceNames[i] != NULL && (strcmp(name, gDeviceNames[i]) != 0))
1024 		i++;
1025 
1026 	if (gDeviceNames[i] == NULL)
1027 		return B_BAD_VALUE;		// device name not found in list of devices
1028 
1029 	DeviceInfo& di = gDeviceInfo[i];
1030 
1031 	gLock.Acquire();	// make sure no one else has write access to common data
1032 
1033 	if (di.openCount == 0)
1034 		status = InitDevice(di);
1035 
1036 	gLock.Release();
1037 
1038 	if (status == B_OK) {
1039 		di.openCount++;		// mark device open
1040 		*cookie = &di;		// send cookie to opener
1041 	}
1042 
1043 	TRACE("device_open() returning 0x%lx,  open count: %ld\n", status,
1044 		di.openCount);
1045 	return status;
1046 }
1047 
1048 
1049 static status_t
1050 device_read(void* dev, off_t pos, void* buf, size_t* len)
1051 {
1052 	// Following 3 lines of code are here to eliminate "unused parameter"
1053 	// warnings.
1054 	(void)dev;
1055 	(void)pos;
1056 	(void)buf;
1057 
1058 	*len = 0;
1059 	return B_NOT_ALLOWED;
1060 }
1061 
1062 
1063 static status_t
1064 device_write(void* dev, off_t pos, const void* buf, size_t* len)
1065 {
1066 	// Following 3 lines of code are here to eliminate "unused parameter"
1067 	// warnings.
1068 	(void)dev;
1069 	(void)pos;
1070 	(void)buf;
1071 
1072 	*len = 0;
1073 	return B_NOT_ALLOWED;
1074 }
1075 
1076 
1077 static status_t
1078 device_close(void* dev)
1079 {
1080 	(void)dev;		// avoid compiler warning for unused arg
1081 
1082 	return B_NO_ERROR;
1083 }
1084 
1085 
1086 static status_t
1087 device_free(void* dev)
1088 {
1089 	DeviceInfo& di = *((DeviceInfo*)dev);
1090 	SharedInfo& si = *(di.sharedInfo);
1091 	pci_info& pciInfo = di.pciInfo;
1092 
1093 	TRACE("enter device_free()\n");
1094 
1095 	gLock.Acquire();		// lock driver
1096 
1097 	// If opened multiple times, merely decrement the open count and exit.
1098 
1099 	if (di.openCount <= 1) {
1100 		DisableVBI();		// disable & clear any pending interrupts
1101 
1102 		if (si.bInterruptAssigned) {
1103 			remove_io_interrupt_handler(pciInfo.u.h0.interrupt_line,
1104 				InterruptHandler, &di);
1105 		}
1106 
1107 		// Delete the semaphores, ignoring any errors because the owning team
1108 		// may have died.
1109 		if (si.vertBlankSem >= 0)
1110 			delete_sem(si.vertBlankSem);
1111 		si.vertBlankSem = -1;
1112 
1113 		UnmapDevice(di);	// free regs and frame buffer areas
1114 
1115 		delete_area(di.sharedArea);
1116 		di.sharedArea = -1;
1117 		di.sharedInfo = NULL;
1118 	}
1119 
1120 	if (di.openCount > 0)
1121 		di.openCount--;		// mark device available
1122 
1123 	gLock.Release();	// unlock driver
1124 
1125 	TRACE("exit device_free() openCount: %ld\n", di.openCount);
1126 	return B_OK;
1127 }
1128 
1129 
1130 static status_t
1131 device_ioctl(void* dev, uint32 msg, void* buffer, size_t bufferLength)
1132 {
1133 	DeviceInfo& di = *((DeviceInfo*)dev);
1134 
1135 //	TRACE("device_ioctl(); ioctl: %lu, buffer: 0x%08lx, bufLen: %lu\n", msg,
1136 //		(uint32)buffer, bufferLength);
1137 
1138 	switch (msg) {
1139 		case B_GET_ACCELERANT_SIGNATURE:
1140 			strcpy((char*)buffer, ATI_ACCELERANT_NAME);
1141 			return B_OK;
1142 
1143 		case ATI_DEVICE_NAME:
1144 			strncpy((char*)buffer, di.name, B_OS_NAME_LENGTH);
1145 			((char*)buffer)[B_OS_NAME_LENGTH -1] = '\0';
1146 			return B_OK;
1147 
1148 		case ATI_GET_SHARED_DATA:
1149 			if (bufferLength != sizeof(area_id))
1150 				return B_BAD_DATA;
1151 
1152 			*((area_id*)buffer) = di.sharedArea;
1153 			return B_OK;
1154 
1155 		case ATI_GET_EDID:
1156 		{
1157 			if (bufferLength != sizeof(edid1_raw))
1158 				return B_BAD_DATA;
1159 
1160 			edid1_raw rawEdid;
1161 			status_t status = GetEdidFromBIOS(rawEdid);
1162 			if (status == B_OK)
1163 				user_memcpy((edid1_raw*)buffer, &rawEdid, sizeof(rawEdid));
1164 			return status;
1165 		}
1166 
1167 		case ATI_SET_VESA_DISPLAY_MODE:
1168 			if (bufferLength != sizeof(uint16))
1169 				return B_BAD_DATA;
1170 
1171 			return SetVesaDisplayMode(*((uint16*)buffer));
1172 
1173 		case ATI_RUN_INTERRUPTS:
1174 			if (bufferLength != sizeof(bool))
1175 				return B_BAD_DATA;
1176 
1177 			if (*((bool*)buffer))
1178 				EnableVBI();
1179 			else
1180 				DisableVBI();
1181 
1182 			return B_OK;
1183 	}
1184 
1185 	return B_DEV_INVALID_IOCTL;
1186 }
1187