/* NVClock 0.8 - OpenSolaris overclocker for NVIDIA cards
 *
 * Site: http://nvclock.sourceforge.net
 *
 * Solaris Backend: Copyright 2009 Bernd Markgraf <markgraf@med.ovgu.de>
 * Copyright(C) 2001-2009 Roderick Colenbrander
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/mman.h>
#include <pciaccess.h>
#include <sys/pci.h>

#include "backend.h"

#define SIZE 255
#define DEBUG 0

NVClock nvclock;
NVCard *nv_card = NULL;

static int probe_devices();

int init_nvclock()
{
	/* Check if the user is root */
	if(getuid() != 0 && geteuid() != 0)
	{
		set_error(NV_ERR_NOT_ENOUGH_PERMISSIONS);
		return 0;
	}

	/* Detect all nvidia cards; this needs to be done before creating directory and config file as that code needs card access */
	if(!probe_devices())
	{
		/* probe_devices takes care of the error as it isn't certain it failed because of there are no nvidia cards */
		return 0;
	}

	if(!open_config())
		return 0;

	return 1;
}

static int probe_devices()
{
	struct pci_device *pcidev;
	struct pci_id_match *patterns;
	struct pci_device_iterator *iter;

	int counter=0;

	pcidev=calloc(1, sizeof(struct pci_device));
	patterns=calloc(1,sizeof(struct pci_id_match));
  
	patterns->vendor_id=PCI_VENDOR_ID_NVIDIA;
	patterns->device_class=PCI_CLASS_VGA<<16;
	patterns->device_id=PCI_MATCH_ANY;
	patterns->subdevice_id=PCI_MATCH_ANY;
	patterns->subvendor_id=PCI_MATCH_ANY;
	patterns->device_class_mask=PCI_MATCH_ANY;
  
	pci_system_init();
	iter = pci_id_match_iterator_create(patterns);
	while (( pcidev = pci_device_next( iter )) != NULL )
	{
#if DEBUG
		printf("count %d, vend 0x%x, dev 0x%x, class 0x%x\n",counter,pcidev->vendor_id,pcidev->device_id,pcidev->device_class>>16);
#endif
		nvclock.card[counter].device_id=pcidev->device_id;
		nvclock.card[counter].dev_name= "/dev/xsvc";
		nvclock.card[counter].card_name = (char*)get_card_name(nvclock.card[counter].device_id, &nvclock.card[counter].gpu);
		nvclock.card[counter].arch = get_gpu_arch(nvclock.card[counter].device_id);
		nvclock.card[counter].number = counter;
		nvclock.card[counter].state = 0;
		nvclock.card[counter].devbusfn = PCI_GET_DEVBUSFN(pcidev->dev, pcidev->bus, pcidev->func);
		pci_device_probe( pcidev );
#if DEBUG
		int i;
		for ( i = 0 ; i < 6 ; i++ ) 
		{
			if ( pcidev->regions[i].base_addr != 0 ) 
			{
				printf( "  BASE%u     0x%08x  addr 0x%08x  %s",
					i,
					0,
					(intptr_t) pcidev->regions[i].base_addr,
					(pcidev->regions[i].is_IO) ? "I/O" : "MEM" );

				if ( ! pcidev->regions[i].is_IO )
				{
					if ( pcidev->regions[i].is_prefetchable )
					{
						printf( " PREFETCHABLE" );
					}
				}
			
				printf( "\n" );
			}
		}
#endif
		nvclock.card[counter].reg_address=pcidev->regions[0].base_addr;
		counter++;
	}

	nvclock.num_cards = counter;

	pci_system_cleanup();

	return 1;
}

int32_t pciReadLong(unsigned short devbusfn, long offset)
{
	struct pci_device *pcidev;
	int32_t data;

	pci_system_init();
	pcidev=pci_device_find_by_slot(0,PCI_GET_BUS(devbusfn),PCI_GET_DEVICE(devbusfn),PCI_GET_FUNCTION(devbusfn));
#if DEBUG
	printf("pciReadLong vend 0x%x, dev 0x%x, class 0x%x\n",pcidev->vendor_id,pcidev->device_id,pcidev->device_class>>16);
#endif

	pci_device_cfg_read_u32(pcidev,&data,offset);

	pci_system_cleanup();
	return data;
}


/* -------- mmap on devices -------- */
/* This piece of code is from nvtv a linux program for tvout */
/* The author of nvtv got this from xfree86's os-support/linux/lnx_video.c */
/* and he modified it a little  */
void *map_dev_mem (dev_handle_t *dev, unsigned long Base, unsigned long Size)
{
	void *base;
	int mapflags = MAP_SHARED;
	unsigned long realBase, alignOff;

	realBase = Base & ~(getpagesize() - 1);
	alignOff = Base - realBase;

	base = mmap((caddr_t)0, Size + alignOff, PROT_READ|PROT_WRITE, mapflags, dev->fd, (off_t)realBase);
	return (void *) ((char *)base + alignOff);
}

void unmap_dev_mem (unsigned long Base, unsigned long Size)
{
	unsigned long alignOff = Base - (Base & ~(getpagesize() - 1));
	munmap((caddr_t)(Base - alignOff), (Size + alignOff));
	nv_card->mem_mapped = 0;
}

/* Retrieve a handle to /dev/mem or /dev/nvidiaX */
dev_handle_t* open_dev(const char *dev_name)
{
	dev_handle_t *dev;
	int fd;

	if( (fd = open(dev_name, O_RDWR)) == -1 )
	{
		char err[80];
		sprintf(err, "Can't open %s", dev_name);
		set_error_str(err);
		return NULL;
	}

	dev = (dev_handle_t*)calloc(1, sizeof(dev_handle_t));
	dev->fd = fd;
	return dev;
}

/* Close the devide handle */
void close_dev(dev_handle_t *dev)
{
	if(!dev)
		return;

	close(dev->fd);
	free(dev);
}
