/** @par LICENCE
* @verbatim
Copyright (C) 2009  ADDI-DATA GmbH for the source code of this module.

ADDI-DATA GmbH
Airpark Business Center
Airport Boulevard B210
77836 Rheinmuenster
Germany
Tel: +49(0)7229/1847-0
Fax: +49(0)7229/1847-200
http://www.addi-data-com
info@addi-data.com

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 shoud find the complete GPL in the COPYING file accompanying
this source code.
* @endverbatim
*/

#include "apci3120-private.h"
#include "vtable.h"

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
#include <linux/sysfs.h>
#endif

MODULE_LICENSE("GPL");
MODULE_AUTHOR("ADDI-DATA GmbH <info@addi-data.com>");
MODULE_DESCRIPTION("APCI-3120 IOCTL driver");

EXPORT_SYMBOL(APCI3120_get_lock);

EXPORT_NO_SYMBOLS;

/*
 * __devinit / __devexit / __devinitdata / __devexit_p() were section markers
 * removed in kernel 3.8. Define them as empty for newer kernels so the
 * existing source code compiles unchanged.
 */
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,8,0)
	#ifndef __devinit
		#define __devinit
		#define __devexit
		#define __devinitdata
		#define __devexit_p(x) (x)
	#endif
#endif

//------------------------------------------------------------------------------
spinlock_t * APCI3120_get_lock(struct pci_dev *pdev)
{
	return &(APCI3120_PRIVDATA(pdev)->lock);
}
//------------------------------------------------------------------------------
atomic_t apci3120_count = ATOMIC_INIT(0);
unsigned int apci3120_majornumber = 0;

//------------------------------------------------------------------------------
static int __devinit apci3120_probe_one(struct pci_dev *dev,const struct pci_device_id *ent);
static void __devexit apci3120_remove_one(struct pci_dev *dev);

//------------------------------------------------------------------------------
/** The ID table is an array of struct pci_device_id ending with a all-zero entry.
Each entry consists of:

- vendor, device	Vendor and device ID to match (or PCI_ANY_ID)
- subvendor,	Subsystem vendor and device ID to match (or PCI_ANY_ID)
- subdevice class,		Device class to match. The class_mask tells which bits
- class_mask	of the class are honored during the comparison.
- driver_data	Data private to the driver.
*/

static struct pci_device_id apci3120_pci_tbl[] __devinitdata =
{
	#include "devices.ids"
	{ 0 },	/* terminate list */
};

MODULE_DEVICE_TABLE (pci, apci3120_pci_tbl);

//----------------------------------------------------------------------------------------------------------------------
static struct pci_driver apci3120_pci_driver = {
		.name		= __DRIVER_NAME,
		.probe		= apci3120_probe_one,
		.remove		= __devexit_p(apci3120_remove_one),
		.id_table	= apci3120_pci_tbl,
};
//------------------------------------------------------------------------------
static struct file_operations apci3120_fops =
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,36)
		.ioctl          = apci3120_ioctl_lookup,
#else
		.unlocked_ioctl = apci3120_ioctl_lookup,
#endif
		.open		= apci3120_open_lookup,
		.release	= apci3120_release_lookup,
		/*
		 * If using signal to inform user mode,
		 * uncomment following line:
		 */
		//.fasync		= apci3120_fasync_lookup,
};

//------------------------------------------------------------------------------

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
static struct class * apci3120_class = NULL;
#endif

//------------------------------------------------------------------------------
/** when module is unloaded, stop all board activities (cf interrupt)*/
static void apci3120_stop_board(struct pci_dev * pdev)
{
	// FILL THE BLANK
}
//------------------------------------------------------------------------------
static void compute_base_io(struct pci_dev *pdev)
{
	switch(pdev->device)
	{
	case APCI3120_BOARD_DEVICE_ID:
		APCI3120_PRIVDATA(pdev)->base_io = GET_BAR1(pdev);
		break;
	case APCIE3120_BOARD_DEVICE_ID:
		APCI3120_PRIVDATA(pdev)->base_io = GET_BAR2(pdev) + 0x40; /* for APCI Express, offset 0x40 in BAR 2 */
		break;
	default:
		BUG();
	}
}
//-------------------------------------------------------------------
/** event: a new card is detected.
*
* Historically - in former ADDI-DATA drivers - data about a board has been stored
* in a static structure.
* This led to huge duplication of information since most of these information
* are already present in the pci_dev struct.
*
* Now we manipulate this standard structure provided by the OS and we attach
* private data using the field driver_data, if necessary.
*
*  */
static int __devinit apci3120_probe_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
	{
		int ret = pci_enable_device(pdev);
		if (ret)
		{
			printk(KERN_ERR "%s: pci_enable_device failed\n",__DRIVER_NAME);
			return ret;
		}
	}

	// needed to enable PCI DMA
	pci_set_master(pdev);

#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,13,0)
	/* explicitly request a 32-bit DMA mask (mandatory on modern kernels with IOMMU) */
	if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
	{
		printk(KERN_ERR "%s: dma_set_mask_and_coherent failed\n",__DRIVER_NAME);
		return -ENODEV;
	}
#endif

	/* 2.4 only : check_region is deprecated in 2.6 */
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
	/* check if BAR 0 is free */
	if ( check_region(pdev->resource[0].start, pci_resource_len(pdev,0)) )
	{
		printk(KERN_WARNING "%s: BAR 0 (%lX) is already in use\n",__DRIVER_NAME,pdev->resource[0].start);
		return -EBUSY;
	}
	/* check if BAR 1 is free */
	if ( check_region(pdev->resource[1].start, pci_resource_len(pdev,1)) )
	{
		printk(KERN_WARNING "%s: BAR 1 (%lX) is already in use\n",__DRIVER_NAME,pdev->resource[1].start);
		return -EBUSY;
	}
	/* check if BAR 2 is free */
	if ( check_region(pdev->resource[2].start, pci_resource_len(pdev,2)) )
	{
		printk(KERN_WARNING "%s: BAR 2 (%lX) is already in use\n",__DRIVER_NAME,pdev->resource[2].start);
		return -EBUSY;
	}
#endif // 2.4

	/* allocate a new data structure containing board private data */
	{
		struct apci3120_str_BoardInformations * newboard_data = NULL;
		newboard_data = kmalloc( sizeof( struct apci3120_str_BoardInformations) , GFP_ATOMIC);
		if (!newboard_data)
		{
			printk(KERN_CRIT "Can't allocate memory for new board %s\n",pci_name(pdev));
			return -ENOMEM;
		}
		apci3120_init_priv_data(newboard_data);
		pci_set_drvdata(pdev,newboard_data);
	}

	/* lock BAR IO ports ressources */
	{
		int ret = pci_request_regions(pdev,__DRIVER_NAME);
		if (ret)
		{
			printk(KERN_ERR "%s: pci_request_regions failed\n",__DRIVER_NAME);
			/* free all allocated ressources here*/
			kfree(APCI3120_PRIVDATA(pdev));
			return ret;
		}
	}

	/* dependaing of the board type, compute the base I/O address */
	compute_base_io(pdev);

	/*
	 * The registration of the interruption is now done by ioctl command
	//register interrupt
	if ( apci3120_register_interrupt(pdev) )
	{
		// failed, clean previously allocated resources
		printk(KERN_ERR "Failed to register the interruption \n");
	 	kfree(APCI3120_PRIVDATA(pdev));
	 	pci_release_regions(pdev);
	}
	*/

	{
		/* increase the global board count */
		atomic_inc(&apci3120_count);
		printk(KERN_INFO "%s: board %s managed (minor number will be %d) \n",__DRIVER_NAME, pci_name(pdev), atomic_read(&apci3120_count)-1);
	}

	/* create /proc entry */
	apci3120_proc_create_device(pdev, atomic_read(&apci3120_count)-1);

	/* add to the list of known device */
	apci3120_known_dev_append(pdev);

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
	while(1)
	{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
		struct class_device *cdev;
#else
		struct device *cdev;
#endif

		int minor = (atomic_read(&apci3120_count)-1);

        /* don't execute if class not exists */
        if (IS_ERR(apci3120_class))
                break;

#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
		cdev = class_device_create (apci3120_class, NULL, MKDEV(apci3120_majornumber, minor), NULL, "%s_%d", __DRIVER_NAME, minor);
#elseif LINUX_VERSION_CODE < KERNEL_VERSION(2,6,27)
		cdev = device_create (apci3120_class, NULL, MKDEV(apci3120_majornumber, minor), "%s_%d", __DRIVER_NAME, minor);
#else
		cdev = device_create (apci3120_class, NULL, MKDEV(apci3120_majornumber, minor), NULL, "%s_%d", __DRIVER_NAME, minor);
#endif

		if (IS_ERR(cdev))
		{
			printk (KERN_WARNING "%s: class_device_create error\n", __DRIVER_NAME);
		}
		break;
	}
#endif

	return 0;
}


//------------------------------------------------------------------------------
/** This function registers the driver with register_chrdev.
*
* @todo For kernel 2.6, use udev
*  */

static int apci3120_register(void)
{

	//Registration of driver
	apci3120_majornumber = register_chrdev(0, __DRIVER_NAME, &apci3120_fops);

	if (apci3120_majornumber < 0)
	{
		printk (KERN_ERR "%s: register_chrdev returned %d ... aborting\n",__DRIVER_NAME,apci3120_majornumber);
		return -ENODEV;
	}
	return 0;
}

//------------------------------------------------------------------------------
/** Called when module loads. */
static int __init apci3120_init(void)
{

	apci3120_init_vtable(apci3120_vtable);

	if( apci3120_register() )
	{
		return -ENODEV;
	}

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
	apci3120_class = ADDI_CLASS_CREATE(THIS_MODULE, __DRIVER_NAME);
	if (IS_ERR(apci3120_class))
	{
		printk (KERN_WARNING "%s: class_create error\n",__DRIVER_NAME );
	}
#endif

	/* registred, now create root /proc entry */
	apci3120_proc_init();

	printk(KERN_INFO "%s: loaded\n",__DRIVER_NAME);

	/* now, subscribe to PCI bus subsystem  */
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18)
	/** @note The module will load anyway even if the call to pci_module_init() fails */
	if ( pci_module_init (&apci3120_pci_driver) != 0)
#else
		if ( pci_register_driver (&apci3120_pci_driver) != 0)
#endif
		{
			printk("%s: no device found\n",__DRIVER_NAME);
			apci3120_pci_driver.name = "";
		}

	return 0;
}

//-------------------------------------------------------------------
/** event: a card is removed (also called when module is unloaded) */
static void __devexit apci3120_remove_one(struct pci_dev *dev)
{

	/* stop board activities */
	apci3120_stop_board(dev);

	/* register interrupt */
	apci3120_deregister_interrupt(dev);

	/* do OS-dependant thing we don't really want to know of :) */
	pci_disable_device(dev);

	/* deallocate BAR IO Ports ressources */
	pci_release_regions(dev);

	/* delete associated /proc entry */
	apci3120_proc_release_device(dev);

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
	while(1)
	{
		int minor = (atomic_read(&apci3120_count)-1);

		/* don't execute if class not exists */
		if(IS_ERR(apci3120_class))
				break;

#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
		class_device_destroy (apci3120_class, MKDEV(apci3120_majornumber, minor));
#else
		device_destroy (apci3120_class, MKDEV(apci3120_majornumber, minor));
#endif

		break;
	}
#endif

	/* decrement global board count*/
	atomic_dec(&apci3120_count);

	/* remove from the list of known devices */
	apci3120_known_dev_remove(dev);

	/* free private device data*/
	if (APCI3120_PRIVDATA(dev))
		kfree(APCI3120_PRIVDATA(dev));
	printk("%s: board %s unloaded \n",__DRIVER_NAME,pci_name(dev));

}

//------------------------------------------------------------------------------
/** This function unregisters the driver with unregister_chrdev.
*
* @todo For kernel 2.6, use udev
*  */

static void apci3120_unregister(void)
{
	unregister_chrdev(apci3120_majornumber, __DRIVER_NAME);
}

//-------------------------------------------------------------------
/** Called when module is unloaded. */
static void __exit apci3120_exit(void)
{

	/* unsubscribe to PCI bus subsystem */
	if (apci3120_pci_driver.name[0])
	{
		pci_unregister_driver (&apci3120_pci_driver);
	}

	/* unsubscribe to /dev VFS */
	apci3120_unregister();

	/* delete /proc root */
	apci3120_proc_release();

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
	class_destroy (apci3120_class);
#endif
}
//------------------------------------------------------------------------------
module_exit(apci3120_exit);
module_init(apci3120_init);
