1/*
2	Copyright 1999, Be Incorporated.   All Rights Reserved.
3	This file may be used under the terms of the Be Sample Code License.
4
5	Other authors:
6	Mark Watson;
7	Rudolf Cornelissen 3/2002-4/2006.
8*/
9
10/* standard kernel driver stuff */
11#include <KernelExport.h>
12#include <ISA.h>
13#include <PCI.h>
14#include <OS.h>
15#include <directories.h>
16#include <driver_settings.h>
17#include <malloc.h>
18#include <stdlib.h> // for strtoXX
19#include "AGP.h"
20
21/* this is for the standardized portion of the driver API */
22/* currently only one operation is defined: B_GET_ACCELERANT_SIGNATURE */
23#include <graphic_driver.h>
24
25/* this is for sprintf() */
26#include <stdio.h>
27
28/* this is for string compares */
29#include <string.h>
30
31/* The private interface between the accelerant and the kernel driver. */
32#include "DriverInterface.h"
33#include "macros.h"
34
35#define get_pci(o, s) (*pci_bus->read_pci_config)(pcii->bus, pcii->device, pcii->function, (o), (s))
36#define set_pci(o, s, v) (*pci_bus->write_pci_config)(pcii->bus, pcii->device, pcii->function, (o), (s), (v))
37
38#define MAX_DEVICES	  8
39
40#define DEVICE_FORMAT "%04x_%04x_%02x%02x%02x" // apsed
41
42/* Tell the kernel what revision of the driver API we support */
43int32	api_version = B_CUR_DRIVER_API_VERSION; // apsed, was 2, is 2 in R5
44
45/* these structures are private to the kernel driver */
46typedef struct device_info device_info;
47
48typedef struct {
49	timer		te;				/* timer entry for add_timer() */
50	device_info	*di;			/* pointer to the owning device */
51	bigtime_t	when_target;	/* when we're supposed to wake up */
52} timer_info;
53
54struct device_info {
55	uint32		is_open;			/* a count of how many times the devices has been opened */
56	area_id		shared_area;		/* the area shared between the driver and all of the accelerants */
57	shared_info	*si;				/* a pointer to the shared area, for convenience */
58	vuint32		*regs;				/* kernel's pointer to memory mapped registers */
59	pci_info	pcii;					/* a convenience copy of the pci info for this device */
60	char		name[B_OS_NAME_LENGTH];	/* where we keep the name of the device for publishing and comparing */
61};
62
63typedef struct {
64	uint32		count;				/* number of devices actually found */
65	benaphore	kernel;				/* for serializing opens/closes */
66	char		*device_names[MAX_DEVICES+1];	/* device name pointer storage */
67	device_info	di[MAX_DEVICES];	/* device specific stuff */
68} DeviceData;
69
70/* prototypes for our private functions */
71static status_t open_hook (const char* name, uint32 flags, void** cookie);
72static status_t close_hook (void* dev);
73static status_t free_hook (void* dev);
74static status_t read_hook (void* dev, off_t pos, void* buf, size_t* len);
75static status_t write_hook (void* dev, off_t pos, const void* buf, size_t* len);
76static status_t control_hook (void* dev, uint32 msg, void *buf, size_t len);
77static status_t map_device(device_info *di);
78static void unmap_device(device_info *di);
79static void probe_devices(void);
80static int32 eng_interrupt(void *data);
81
82static DeviceData		*pd;
83static isa_module_info	*isa_bus = NULL;
84static pci_module_info	*pci_bus = NULL;
85static agp_gart_module_info *agp_bus = NULL;
86static device_hooks graphics_device_hooks = {
87	open_hook,
88	close_hook,
89	free_hook,
90	control_hook,
91	read_hook,
92	write_hook,
93	NULL,
94	NULL,
95	NULL,
96	NULL
97};
98
99#define VENDOR_ID_VIA	0x1106 /* Via */
100
101static uint16 via_device_list[] = {
102	0x3022, /* CLE266 Unichrome Pro (CLE3022) */
103	0x3108, /* K8M800 Unichrome Pro (unknown chiptype) */
104	0x3122, /* CLE266 Unichrome Pro (CLE3122) */
105	0x3205, /* KM400 Unichrome (VT3205) */
106//	0x3344, /* P4M800 Pro (VT3344) */
107	0x7205, /* KM400 Unichrome (VT7205) */
108	0
109};
110
111static struct {
112	uint16	vendor;
113	uint16	*devices;
114} SupportedDevices[] = {
115	{VENDOR_ID_VIA, via_device_list},
116	{0x0000, NULL}
117};
118
119static settings current_settings = { // see comments in skel.settings
120	// for driver
121	DRIVER_PREFIX ".accelerant",
122	false,      // dumprom
123	// for accelerant
124	0x00000000, // logmask
125	0,          // memory
126	true,       // usebios
127	true,       // hardcursor
128	false,		// switchhead
129	false,		// force_pci
130	false,		// unhide_fw
131	true,		// pgm_panel
132};
133
134static void dumprom (void *rom, uint32 size)
135{
136	int fd;
137	uint32 cnt;
138
139	fd = open (kUserDirectory "/" DRIVER_PREFIX ".rom",
140		O_WRONLY | O_CREAT, 0666);
141	if (fd < 0) return;
142
143	/* apparantly max. 32kb may be written at once;
144	 * the ROM size is a multiple of that anyway. */
145	for (cnt = 0; (cnt < size); cnt += 32768)
146		write (fd, ((void *)(((uint8 *)rom) + cnt)), 32768);
147	close (fd);
148}
149
150/* return 1 if vblank interrupt has occured */
151static int caused_vbi(vuint32 * regs)
152{
153//	return (ENG_REG32(RG32_CRTC_INTS) & 0x00000001);
154return 0;
155}
156
157/* clear the vblank interrupt */
158static void clear_vbi(vuint32 * regs)
159{
160//	ENG_REG32(RG32_CRTC_INTS) = 0x00000001;
161}
162
163static void enable_vbi(vuint32 * regs)
164{
165	/* clear the vblank interrupt */
166//	ENG_REG32(RG32_CRTC_INTS) = 0x00000001;
167	/* enable nVidia interrupt source vblank */
168//	ENG_REG32(RG32_CRTC_INTE) |= 0x00000001;
169	/* enable nVidia interrupt system hardware (b0-1) */
170//	ENG_REG32(RG32_MAIN_INTE) = 0x00000001;
171}
172
173static void disable_vbi(vuint32 * regs)
174{
175	/* disable nVidia interrupt source vblank */
176//	ENG_REG32(RG32_CRTC_INTE) &= 0xfffffffe;
177	/* clear the vblank interrupt */
178//	ENG_REG32(RG32_CRTC_INTS) = 0x00000001;
179	/* disable nVidia interrupt system hardware (b0-1) */
180//	ENG_REG32(RG32_MAIN_INTE) = 0x00000000;
181}
182
183/*
184	init_hardware() - Returns B_OK if one is
185	found, otherwise returns B_ERROR so the driver will be unloaded.
186*/
187status_t
188init_hardware(void) {
189	long		pci_index = 0;
190	pci_info	pcii;
191	bool		found_one = false;
192
193	/* choke if we can't find the PCI bus */
194	if (get_module(B_PCI_MODULE_NAME, (module_info **)&pci_bus) != B_OK)
195		return B_ERROR;
196
197	/* choke if we can't find the ISA bus */
198	if (get_module(B_ISA_MODULE_NAME, (module_info **)&isa_bus) != B_OK)
199	{
200		put_module(B_PCI_MODULE_NAME);
201		return B_ERROR;
202	}
203
204	/* while there are more pci devices */
205	while ((*pci_bus->get_nth_pci_info)(pci_index, &pcii) == B_NO_ERROR) {
206		int vendor = 0;
207
208		/* if we match a supported vendor */
209		while (SupportedDevices[vendor].vendor) {
210			if (SupportedDevices[vendor].vendor == pcii.vendor_id) {
211				uint16 *devices = SupportedDevices[vendor].devices;
212				/* while there are more supported devices */
213				while (*devices) {
214					/* if we match a supported device */
215					if (*devices == pcii.device_id ) {
216
217						found_one = true;
218						goto done;
219					}
220					/* next supported device */
221					devices++;
222				}
223			}
224			vendor++;
225		}
226		/* next pci_info struct, please */
227		pci_index++;
228	}
229
230done:
231	/* put away the module manager */
232	put_module(B_PCI_MODULE_NAME);
233	return (found_one ? B_OK : B_ERROR);
234}
235
236status_t
237init_driver(void) {
238	void *settings_handle;
239
240	// get driver/accelerant settings, apsed
241	settings_handle  = load_driver_settings (DRIVER_PREFIX ".settings");
242	if (settings_handle != NULL) {
243		const char *item;
244		char       *end;
245		uint32      value;
246
247		// for driver
248		item = get_driver_parameter (settings_handle, "accelerant", "", "");
249		if ((strlen (item) > 0) && (strlen (item) < sizeof (current_settings.accelerant) - 1)) {
250			strcpy (current_settings.accelerant, item);
251		}
252		current_settings.dumprom = get_driver_boolean_parameter (settings_handle, "dumprom", false, false);
253
254		// for accelerant
255		item = get_driver_parameter (settings_handle, "logmask", "0x00000000", "0x00000000");
256		value = strtoul (item, &end, 0);
257		if (*end == '\0') current_settings.logmask = value;
258
259		item = get_driver_parameter (settings_handle, "memory", "0", "0");
260		value = strtoul (item, &end, 0);
261		if (*end == '\0') current_settings.memory = value;
262
263		current_settings.hardcursor = get_driver_boolean_parameter (settings_handle, "hardcursor", false, false);
264		current_settings.usebios = get_driver_boolean_parameter (settings_handle, "usebios", false, false);
265		current_settings.switchhead = get_driver_boolean_parameter (settings_handle, "switchhead", false, false);
266		current_settings.force_pci = get_driver_boolean_parameter (settings_handle, "force_pci", false, false);
267		current_settings.unhide_fw = get_driver_boolean_parameter (settings_handle, "unhide_fw", false, false);
268		current_settings.pgm_panel = get_driver_boolean_parameter (settings_handle, "pgm_panel", false, false);
269
270		unload_driver_settings (settings_handle);
271	}
272
273	/* get a handle for the pci bus */
274	if (get_module(B_PCI_MODULE_NAME, (module_info **)&pci_bus) != B_OK)
275		return B_ERROR;
276
277	/* get a handle for the isa bus */
278	if (get_module(B_ISA_MODULE_NAME, (module_info **)&isa_bus) != B_OK)
279	{
280		put_module(B_PCI_MODULE_NAME);
281		return B_ERROR;
282	}
283
284	/* get a handle for the agp bus if it exists */
285	get_module(B_AGP_GART_MODULE_NAME, (module_info **)&agp_bus);
286
287	/* driver private data */
288	pd = (DeviceData *)calloc(1, sizeof(DeviceData));
289	if (!pd) {
290		if (agp_bus)
291			put_module(B_AGP_GART_MODULE_NAME);
292		put_module(B_ISA_MODULE_NAME);
293		put_module(B_PCI_MODULE_NAME);
294		return B_ERROR;
295	}
296	/* initialize the benaphore */
297	INIT_BEN(pd->kernel);
298	/* find all of our supported devices */
299	probe_devices();
300	return B_OK;
301}
302
303const char **
304publish_devices(void) {
305	/* return the list of supported devices */
306	return (const char **)pd->device_names;
307}
308
309device_hooks *
310find_device(const char *name) {
311	int index = 0;
312	while (pd->device_names[index]) {
313		if (strcmp(name, pd->device_names[index]) == 0)
314			return &graphics_device_hooks;
315		index++;
316	}
317	return NULL;
318
319}
320
321void uninit_driver(void) {
322
323	/* free the driver data */
324	DELETE_BEN(pd->kernel);
325	free(pd);
326	pd = NULL;
327
328	/* put the pci module away */
329	put_module(B_PCI_MODULE_NAME);
330	put_module(B_ISA_MODULE_NAME);
331
332	/* put the agp module away if it's there */
333	if (agp_bus)
334		put_module(B_AGP_GART_MODULE_NAME);
335}
336
337static status_t map_device(device_info *di)
338{
339	char buffer[B_OS_NAME_LENGTH]; /*memory for device name*/
340	shared_info *si = di->si;
341	uint32	tmpUlong;
342	pci_info *pcii = &(di->pcii);
343	system_info sysinfo;
344
345	/*storage for the physical to virtual table (used for dma buffer)*/
346//	physical_entry physical_memory[2];
347//	#define G400_DMA_BUFFER_SIZE 1024*1024
348
349	/* variables for making copy of ROM */
350	uint8* rom_temp;
351	area_id rom_area;
352
353	/* Nvidia cards have registers in [0] and framebuffer in [1] */
354	int registers = 1;
355	int frame_buffer = 0;
356//	int pseudo_dma = 2;
357
358	/* enable memory mapped IO, disable VGA I/O - this is defined in the PCI standard */
359	tmpUlong = get_pci(PCI_command, 2);
360	/* enable PCI access */
361	tmpUlong |= PCI_command_memory;
362	/* enable busmastering */
363	tmpUlong |= PCI_command_master;
364	/* disable ISA I/O access */
365	tmpUlong &= ~PCI_command_io;
366	set_pci(PCI_command, 2, tmpUlong);
367
368 	/*work out which version of BeOS is running*/
369 	get_system_info(&sysinfo);
370 	if (0)//sysinfo.kernel_build_date[0]=='J')/*FIXME - better ID version*/
371 	{
372 		si->use_clone_bugfix = 1;
373 	}
374 	else
375 	{
376 		si->use_clone_bugfix = 0;
377 	}
378
379	/* work out a name for the register mapping */
380	sprintf(buffer, DEVICE_FORMAT " regs",
381		di->pcii.vendor_id, di->pcii.device_id,
382		di->pcii.bus, di->pcii.device, di->pcii.function);
383
384	/* get a virtual memory address for the registers*/
385	si->regs_area = map_physical_memory(
386		buffer,
387		/* WARNING: Nvidia needs to map regs as viewed from PCI space! */
388		di->pcii.u.h0.base_registers_pci[registers],
389		di->pcii.u.h0.base_register_sizes[registers],
390		B_ANY_KERNEL_ADDRESS,
391 		(si->use_clone_bugfix ? B_READ_AREA|B_WRITE_AREA : 0),
392		(void **)&(di->regs));
393 	si->clone_bugfix_regs = (uint32 *) di->regs;
394
395	/* if mapping registers to vmem failed then pass on error */
396	if (si->regs_area < 0) return si->regs_area;
397
398	/* work out a name for the ROM mapping*/
399	sprintf(buffer, DEVICE_FORMAT " rom",
400		di->pcii.vendor_id, di->pcii.device_id,
401		di->pcii.bus, di->pcii.device, di->pcii.function);
402
403	/* disable ROM shadowing, we want the guaranteed exact contents of the chip */
404	/* warning:
405	 * don't touch: (confirmed) NV04, NV05, NV05-M64, NV11 all shutoff otherwise.
406	 * NV18, NV28 and NV34 keep working.
407	 * confirmed NV28 and NV34 to use upper part of shadowed ROM for scratch purposes,
408	 * however the actual ROM content (so the used part) is intact (confirmed). */
409	//set_pci(ENCFG_ROMSHADOW, 4, 0);
410
411	/* get ROM memory mapped base adress - this is defined in the PCI standard */
412	tmpUlong = get_pci(PCI_rom_base, 4);
413	if (tmpUlong)
414	{
415		/* ROM was assigned an adress, so enable ROM decoding - see PCI standard */
416		tmpUlong |= 0x00000001;
417		set_pci(PCI_rom_base, 4, tmpUlong);
418
419		rom_area = map_physical_memory(
420			buffer,
421			(void *)di->pcii.u.h0.rom_base_pci,
422			di->pcii.u.h0.rom_size,
423			B_ANY_KERNEL_ADDRESS,
424			B_READ_AREA,
425			(void **)&(rom_temp)
426		);
427
428		/* check if we got the BIOS signature (might fail on laptops..) */
429		if (rom_temp[0]!=0x55 || rom_temp[1]!=0xaa)
430		{
431			/* apparantly no ROM is mapped here */
432			delete_area(rom_area);
433			rom_area = -1;
434			/* force using ISA legacy map as fall-back */
435			tmpUlong = 0x00000000;
436		}
437	}
438
439	if (!tmpUlong)
440	{
441		/* ROM was not assigned an adress, fetch it from ISA legacy memory map! */
442		rom_area = map_physical_memory(
443			buffer,
444			(void *)0x000c0000,
445			65536,
446			B_ANY_KERNEL_ADDRESS,
447			B_READ_AREA,
448			(void **)&(rom_temp)
449		);
450	}
451
452	/* if mapping ROM to vmem failed then clean up and pass on error */
453	if (rom_area < 0) {
454		delete_area(si->regs_area);
455		si->regs_area = -1;
456		return rom_area;
457	}
458
459	/* dump ROM to file if selected in skel.settings
460	 * (ROM always fits in 64Kb: checked TNT1 - FX5950) */
461	if (current_settings.dumprom) dumprom (rom_temp, 65536);
462	/* make a copy of ROM for future reference */
463	memcpy (si->rom_mirror, rom_temp, 65536);
464
465	/* disable ROM decoding - this is defined in the PCI standard, and delete the area */
466	tmpUlong = get_pci(PCI_rom_base, 4);
467	tmpUlong &= 0xfffffffe;
468	set_pci(PCI_rom_base, 4, tmpUlong);
469	delete_area(rom_area);
470
471	/* work out a name for the framebuffer mapping*/
472	sprintf(buffer, DEVICE_FORMAT " framebuffer",
473		di->pcii.vendor_id, di->pcii.device_id,
474		di->pcii.bus, di->pcii.device, di->pcii.function);
475
476	/* map the framebuffer into vmem, using Write Combining*/
477	si->fb_area = map_physical_memory(
478		buffer,
479		/* WARNING: Nvidia needs to map framebuffer as viewed from PCI space! */
480		(void *) di->pcii.u.h0.base_registers_pci[frame_buffer],
481		di->pcii.u.h0.base_register_sizes[frame_buffer],
482		B_ANY_KERNEL_BLOCK_ADDRESS | B_MTR_WC,
483		B_READ_AREA + B_WRITE_AREA,
484		&(si->framebuffer));
485
486	/*if failed with write combining try again without*/
487	if (si->fb_area < 0) {
488		si->fb_area = map_physical_memory(
489			buffer,
490			/* WARNING: Nvidia needs to map framebuffer as viewed from PCI space! */
491			(void *) di->pcii.u.h0.base_registers_pci[frame_buffer],
492			di->pcii.u.h0.base_register_sizes[frame_buffer],
493			B_ANY_KERNEL_BLOCK_ADDRESS,
494			B_READ_AREA + B_WRITE_AREA,
495			&(si->framebuffer));
496	}
497
498	/* if there was an error, delete our other areas and pass on error*/
499	if (si->fb_area < 0)
500	{
501		delete_area(si->regs_area);
502		si->regs_area = -1;
503		return si->fb_area;
504	}
505//fixme: retest for card coldstart and PCI/virt_mem mapping!!
506	/* remember the DMA address of the frame buffer for BDirectWindow?? purposes */
507	si->framebuffer_pci = (void *) di->pcii.u.h0.base_registers_pci[frame_buffer];
508
509	// remember settings for use here and in accelerant
510	si->settings = current_settings;
511
512	/* in any case, return the result */
513	return si->fb_area;
514}
515
516static void unmap_device(device_info *di) {
517	shared_info *si = di->si;
518	uint32	tmpUlong;
519	pci_info *pcii = &(di->pcii);
520
521	/* disable memory mapped IO */
522	tmpUlong = get_pci(PCI_command, 4);
523	tmpUlong &= 0xfffffffc;
524	set_pci(PCI_command, 4, tmpUlong);
525	/* delete the areas */
526	if (si->regs_area >= 0) delete_area(si->regs_area);
527	if (si->fb_area >= 0) delete_area(si->fb_area);
528	si->regs_area = si->fb_area = -1;
529	si->framebuffer = NULL;
530	di->regs = NULL;
531}
532
533static void probe_devices(void) {
534	uint32 pci_index = 0;
535	uint32 count = 0;
536	device_info *di = pd->di;
537
538	/* while there are more pci devices */
539	while ((count < MAX_DEVICES) && ((*pci_bus->get_nth_pci_info)(pci_index, &(di->pcii)) == B_NO_ERROR)) {
540		int vendor = 0;
541
542		/* if we match a supported vendor */
543		while (SupportedDevices[vendor].vendor) {
544			if (SupportedDevices[vendor].vendor == di->pcii.vendor_id) {
545				uint16 *devices = SupportedDevices[vendor].devices;
546				/* while there are more supported devices */
547				while (*devices) {
548					/* if we match a supported device */
549					if (*devices == di->pcii.device_id ) {
550						/* publish the device name */
551						sprintf(di->name, "graphics/" DEVICE_FORMAT,
552							di->pcii.vendor_id, di->pcii.device_id,
553							di->pcii.bus, di->pcii.device, di->pcii.function);
554
555						/* remember the name */
556						pd->device_names[count] = di->name;
557						/* mark the driver as available for R/W open */
558						di->is_open = 0;
559						/* mark areas as not yet created */
560						di->shared_area = -1;
561						/* mark pointer to shared data as invalid */
562						di->si = NULL;
563						/* inc pointer to device info */
564						di++;
565						/* inc count */
566						count++;
567						/* break out of these while loops */
568						goto next_device;
569					}
570					/* next supported device */
571					devices++;
572				}
573			}
574			vendor++;
575		}
576next_device:
577		/* next pci_info struct, please */
578		pci_index++;
579	}
580	/* propagate count */
581	pd->count = count;
582	/* terminate list of device names with a null pointer */
583	pd->device_names[pd->count] = NULL;
584}
585
586static uint32 thread_interrupt_work(int32 *flags, vuint32 *regs, shared_info *si) {
587	uint32 handled = B_HANDLED_INTERRUPT;
588	/* release the vblank semaphore */
589	if (si->vblank >= 0) {
590		int32 blocked;
591		if ((get_sem_count(si->vblank, &blocked) == B_OK) && (blocked < 0)) {
592			release_sem_etc(si->vblank, -blocked, B_DO_NOT_RESCHEDULE);
593			handled = B_INVOKE_SCHEDULER;
594		}
595	}
596	return handled;
597}
598
599static int32
600eng_interrupt(void *data)
601{
602	int32 handled = B_UNHANDLED_INTERRUPT;
603	device_info *di = (device_info *)data;
604	shared_info *si = di->si;
605	int32 *flags = &(si->flags);
606	vuint32 *regs;
607
608	/* is someone already handling an interrupt for this device? */
609	if (atomic_or(flags, SKD_HANDLER_INSTALLED) & SKD_HANDLER_INSTALLED) {
610		goto exit0;
611	}
612	/* get regs */
613	regs = di->regs;
614
615	/* was it a VBI? */
616	if (caused_vbi(regs)) {
617		/*clear the interrupt*/
618		clear_vbi(regs);
619		/*release the semaphore*/
620		handled = thread_interrupt_work(flags, regs, si);
621	}
622
623	/* note that we're not in the handler any more */
624	atomic_and(flags, ~SKD_HANDLER_INSTALLED);
625
626exit0:
627	return handled;
628}
629
630static status_t open_hook (const char* name, uint32 flags, void** cookie) {
631	int32 index = 0;
632	device_info *di;
633	shared_info *si;
634	thread_id	thid;
635	thread_info	thinfo;
636	status_t	result = B_OK;
637	vuint32		*regs;
638	char shared_name[B_OS_NAME_LENGTH];
639
640	/* find the device name in the list of devices */
641	/* we're never passed a name we didn't publish */
642	while (pd->device_names[index] && (strcmp(name, pd->device_names[index]) != 0)) index++;
643
644	/* for convienience */
645	di = &(pd->di[index]);
646
647	/* make sure no one else has write access to the common data */
648	AQUIRE_BEN(pd->kernel);
649
650	/* if it's already open for writing */
651	if (di->is_open) {
652		/* mark it open another time */
653		goto mark_as_open;
654	}
655	/* create the shared area */
656	sprintf(shared_name, DEVICE_FORMAT " shared",
657		di->pcii.vendor_id, di->pcii.device_id,
658		di->pcii.bus, di->pcii.device, di->pcii.function);
659	/* create this area with NO user-space read or write permissions, to prevent accidental dammage */
660	di->shared_area = create_area(shared_name, (void **)&(di->si), B_ANY_KERNEL_ADDRESS, ((sizeof(shared_info) + (B_PAGE_SIZE - 1)) & ~(B_PAGE_SIZE - 1)), B_FULL_LOCK, 0);
661	if (di->shared_area < 0) {
662		/* return the error */
663		result = di->shared_area;
664		goto done;
665	}
666
667	/* save a few dereferences */
668	si = di->si;
669
670	/* save the vendor and device IDs */
671	si->vendor_id = di->pcii.vendor_id;
672	si->device_id = di->pcii.device_id;
673	si->revision = di->pcii.revision;
674	si->bus = di->pcii.bus;
675	si->device = di->pcii.device;
676	si->function = di->pcii.function;
677
678	/* device at bus #0, device #0, function #0 holds byte value at byte-index 0xf6 */
679	si->ps.chip_rev = ((*pci_bus->read_pci_config)(0, 0, 0, 0xf6, 1));
680
681	/* map the device */
682	result = map_device(di);
683	if (result < 0) goto free_shared;
684	result = B_OK;
685
686	/* create a semaphore for vertical blank management */
687	si->vblank = create_sem(0, di->name);
688	if (si->vblank < 0) {
689		result = si->vblank;
690		goto unmap;
691	}
692
693	/* change the owner of the semaphores to the opener's team */
694	/* this is required because apps can't aquire kernel semaphores */
695	thid = find_thread(NULL);
696	get_thread_info(thid, &thinfo);
697	set_sem_owner(si->vblank, thinfo.team);
698
699	/* assign local regs pointer for SAMPLExx() macros */
700	regs = di->regs;
701
702	/* disable and clear any pending interrupts */
703	disable_vbi(regs);
704
705	/* If there is a valid interrupt line assigned then set up interrupts */
706	if ((di->pcii.u.h0.interrupt_pin == 0x00) ||
707	    (di->pcii.u.h0.interrupt_line == 0xff) || /* no IRQ assigned */
708	    (di->pcii.u.h0.interrupt_line <= 0x02))   /* system IRQ assigned */
709	{
710		/* we are aborting! */
711		/* Note: the R4 graphics driver kit lacks this statement!! */
712		result = B_ERROR;
713		/* interrupt does not exist so exit without installing our handler */
714		goto delete_the_sem;
715	}
716	else
717	{
718		/* otherwise install our interrupt handler */
719		result = install_io_interrupt_handler(di->pcii.u.h0.interrupt_line, eng_interrupt, (void *)di, 0);
720		/* bail if we couldn't install the handler */
721		if (result != B_OK) goto delete_the_sem;
722	}
723
724mark_as_open:
725	/* mark the device open */
726	di->is_open++;
727
728	/* send the cookie to the opener */
729	*cookie = di;
730
731	goto done;
732
733
734delete_the_sem:
735	delete_sem(si->vblank);
736
737unmap:
738	unmap_device(di);
739
740free_shared:
741	/* clean up our shared area */
742	delete_area(di->shared_area);
743	di->shared_area = -1;
744	di->si = NULL;
745
746done:
747	/* end of critical section */
748	RELEASE_BEN(pd->kernel);
749
750	/* all done, return the status */
751	return result;
752}
753
754/* ----------
755	read_hook - does nothing, gracefully
756----- */
757static status_t
758read_hook (void* dev, off_t pos, void* buf, size_t* len)
759{
760	*len = 0;
761	return B_NOT_ALLOWED;
762}
763
764/* ----------
765	write_hook - does nothing, gracefully
766----- */
767static status_t
768write_hook (void* dev, off_t pos, const void* buf, size_t* len)
769{
770	*len = 0;
771	return B_NOT_ALLOWED;
772}
773
774/* ----------
775	close_hook - does nothing, gracefully
776----- */
777static status_t
778close_hook (void* dev)
779{
780	/* we don't do anything on close: there might be dup'd fd */
781	return B_NO_ERROR;
782}
783
784/* -----------
785	free_hook - close down the device
786----------- */
787static status_t
788free_hook (void* dev) {
789	device_info *di = (device_info *)dev;
790	shared_info	*si = di->si;
791	vuint32 *regs = di->regs;
792
793	/* lock the driver */
794	AQUIRE_BEN(pd->kernel);
795
796	/* if opened multiple times, decrement the open count and exit */
797	if (di->is_open > 1)
798		goto unlock_and_exit;
799
800	/* disable and clear any pending interrupts */
801	disable_vbi(regs);
802
803	/* remove interrupt handler */
804	remove_io_interrupt_handler(di->pcii.u.h0.interrupt_line, eng_interrupt, di);
805
806	/* delete the semaphores, ignoring any errors ('cause the owning team may have died on us) */
807	delete_sem(si->vblank);
808	si->vblank = -1;
809
810	/* free regs and framebuffer areas */
811	unmap_device(di);
812
813	/* clean up our shared area */
814	delete_area(di->shared_area);
815	di->shared_area = -1;
816	di->si = NULL;
817
818unlock_and_exit:
819	/* mark the device available */
820	di->is_open--;
821	/* unlock the driver */
822	RELEASE_BEN(pd->kernel);
823	/* all done */
824	return B_OK;
825}
826
827/* -----------
828	control_hook - where the real work is done
829----------- */
830static status_t
831control_hook (void* dev, uint32 msg, void *buf, size_t len) {
832	device_info *di = (device_info *)dev;
833	status_t result = B_DEV_INVALID_IOCTL;
834	uint32 tmpUlong;
835
836	switch (msg) {
837		/* the only PUBLIC ioctl */
838		case B_GET_ACCELERANT_SIGNATURE: {
839			char *sig = (char *)buf;
840			strcpy(sig, current_settings.accelerant);
841			result = B_OK;
842		} break;
843
844		/* PRIVATE ioctl from here on */
845		case ENG_GET_PRIVATE_DATA: {
846			eng_get_private_data *gpd = (eng_get_private_data *)buf;
847			if (gpd->magic == VIA_PRIVATE_DATA_MAGIC) {
848				gpd->shared_info_area = di->shared_area;
849				result = B_OK;
850			}
851		} break;
852		case ENG_GET_PCI: {
853			eng_get_set_pci *gsp = (eng_get_set_pci *)buf;
854			if (gsp->magic == VIA_PRIVATE_DATA_MAGIC) {
855				pci_info *pcii = &(di->pcii);
856				gsp->value = get_pci(gsp->offset, gsp->size);
857				result = B_OK;
858			}
859		} break;
860		case ENG_SET_PCI: {
861			eng_get_set_pci *gsp = (eng_get_set_pci *)buf;
862			if (gsp->magic == VIA_PRIVATE_DATA_MAGIC) {
863				pci_info *pcii = &(di->pcii);
864				set_pci(gsp->offset, gsp->size, gsp->value);
865				result = B_OK;
866			}
867		} break;
868		case ENG_DEVICE_NAME: { // apsed
869			eng_device_name *dn = (eng_device_name *)buf;
870			if (dn->magic == VIA_PRIVATE_DATA_MAGIC) {
871				strcpy(dn->name, di->name);
872				result = B_OK;
873			}
874		} break;
875		case ENG_RUN_INTERRUPTS: {
876			eng_set_bool_state *ri = (eng_set_bool_state *)buf;
877			if (ri->magic == VIA_PRIVATE_DATA_MAGIC) {
878				vuint32 *regs = di->regs;
879				if (ri->do_it) {
880					enable_vbi(regs);
881				} else {
882					disable_vbi(regs);
883				}
884				result = B_OK;
885			}
886		} break;
887		case ENG_GET_NTH_AGP_INFO: {
888			eng_nth_agp_info *nai = (eng_nth_agp_info *)buf;
889			if (nai->magic == VIA_PRIVATE_DATA_MAGIC) {
890				nai->exist = false;
891				nai->agp_bus = false;
892				if (agp_bus) {
893					nai->agp_bus = true;
894					if ((*agp_bus->get_nth_agp_info)(nai->index, &(nai->agpi)) == B_NO_ERROR) {
895						nai->exist = true;
896					}
897				}
898				result = B_OK;
899			}
900		} break;
901		case ENG_ENABLE_AGP: {
902			eng_cmd_agp *nca = (eng_cmd_agp *)buf;
903			if (nca->magic == VIA_PRIVATE_DATA_MAGIC) {
904				if (agp_bus) {
905					nca->agp_bus = true;
906					nca->cmd = agp_bus->set_agp_mode(nca->cmd);
907				} else {
908					nca->agp_bus = false;
909					nca->cmd = 0;
910				}
911				result = B_OK;
912			}
913		} break;
914		case ENG_ISA_OUT: {
915			eng_in_out_isa *io_isa = (eng_in_out_isa *)buf;
916			if (io_isa->magic == VIA_PRIVATE_DATA_MAGIC) {
917				pci_info *pcii = &(di->pcii);
918
919				/* lock the driver:
920				 * no other graphics card may have ISA I/O enabled when we enter */
921				AQUIRE_BEN(pd->kernel);
922
923				/* enable ISA I/O access */
924				tmpUlong = get_pci(PCI_command, 2);
925				tmpUlong |= PCI_command_io;
926				set_pci(PCI_command, 2, tmpUlong);
927
928				if (io_isa->size == 1)
929  					isa_bus->write_io_8(io_isa->adress, (uint8)io_isa->data);
930   				else
931   					isa_bus->write_io_16(io_isa->adress, io_isa->data);
932  				result = B_OK;
933
934				/* disable ISA I/O access */
935				tmpUlong = get_pci(PCI_command, 2);
936				tmpUlong &= ~PCI_command_io;
937				set_pci(PCI_command, 2, tmpUlong);
938
939				/* end of critical section */
940				RELEASE_BEN(pd->kernel);
941   			}
942		} break;
943		case ENG_ISA_IN: {
944			eng_in_out_isa *io_isa = (eng_in_out_isa *)buf;
945			if (io_isa->magic == VIA_PRIVATE_DATA_MAGIC) {
946				pci_info *pcii = &(di->pcii);
947
948				/* lock the driver:
949				 * no other graphics card may have ISA I/O enabled when we enter */
950				AQUIRE_BEN(pd->kernel);
951
952				/* enable ISA I/O access */
953				tmpUlong = get_pci(PCI_command, 2);
954				tmpUlong |= PCI_command_io;
955				set_pci(PCI_command, 2, tmpUlong);
956
957				if (io_isa->size == 1)
958	   				io_isa->data = isa_bus->read_io_8(io_isa->adress);
959	   			else
960	   				io_isa->data = isa_bus->read_io_16(io_isa->adress);
961   				result = B_OK;
962
963				/* disable ISA I/O access */
964				tmpUlong = get_pci(PCI_command, 2);
965				tmpUlong &= ~PCI_command_io;
966				set_pci(PCI_command, 2, tmpUlong);
967
968				/* end of critical section */
969				RELEASE_BEN(pd->kernel);
970   			}
971		} break;
972	}
973	return result;
974}
975