/** @page main.c
* @brief Body of the driver
* @author Sylvain NAHAS, Julien KRAUTH
* @verbatim
  +-----------------------------------------------------------------------+
  | (C) ADDI-DATA GmbH          Dieselstrasse 3      D-77833 Ottersweier  |
  +-----------------------------------------------------------------------+
  | Tel : +49 (0) 7223/9493-0     | email    : info@addi-data.com         |
  | Fax : +49 (0) 7223/9493-92    | Internet : http://www.addi-data.com   |
  +-----------------------------------------------------------------------+
  | Project   : API APCIE1564      | Compiler : GCC                        |
  | Modulname : APCIE1564.C        | Version  : 2.96 (SuSE 7.1 - 2.2.18)   |
  | Version   : 01.00.01          |                                       |
  +-------------------------------+---------------------------------------+
  | Author    : STOLZ, Eric       | Date     : 21.10.2001                 |
  +-----------------------------------------------------------------------+
  |                   Description : APCIE1564 main module                  |
  +-----------------------------------------------------------------------+
  |                             UPDATE'S                                  |
  +-----------------------------------------------------------------------+
  |   Date   |   Author  |          Description of updates                |
  +----------+-----------+------------------------------------------------+
  | 29.09.04 | J. Krauth | - Correction from read 1 digital input         |
  |          |           | - Changes in APCIE1564_release and fops struct  |
  +-----------------------------------------------------------------------+
* @endverbatim
*/


/** @par LICENCE
* @verbatim
 Copyright (C) 2004,2005  ADDI-DATA GmbH for the source code and the documentation.

        ADDI-DATA GmbH
        Dieselstrasse 3
        D-77833 Ottersweier
        Tel: +19(0)7223/9493-0
        Fax: +49(0)7223/9493-92
        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 "apcie1564-private.h"
#include "knowndev.h"

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


//BEGIN JK 06.12.2004: Module informatIon
MODULE_LICENSE("GPL");
MODULE_AUTHOR("ADDI-DATA GmbH <info@addi-data.com>");
MODULE_DESCRIPTION("APCI-1564 IOCTL driver");

EXPORT_SYMBOL(APCIE1564_Read32DigitalInput);
EXPORT_SYMBOL(APCIE1564_InitAndStartDigitalInputInterrupt);
EXPORT_SYMBOL(APCIE1564_ClearAndStopDigitalInputInterrupt);
EXPORT_SYMBOL(APCIE1564_GetDigitalInputInterruptConfig);
EXPORT_SYMBOL(APCIE1564_Set32DigitalOutputOn);
EXPORT_SYMBOL(APCIE1564_Set32DigitalOutputOff);
EXPORT_SYMBOL(APCIE1564_SetOutputMemoryOn);
EXPORT_SYMBOL(APCIE1564_SetOutputMemoryOff);
EXPORT_SYMBOL(APCIE1564_CounterInitAndStart);
EXPORT_SYMBOL(APCIE1564_ReadCounterValue);
EXPORT_SYMBOL(APCIE1564_CounterStop);
EXPORT_SYMBOL(APCIE1564_CounterTrigger);
EXPORT_SYMBOL(APCIE1564_CounterGetStatus);
EXPORT_SYMBOL(APCIE1564_CounterGetConfigRegister);
EXPORT_SYMBOL(APCIE1564_CounterReset);
EXPORT_SYMBOL(APCIE1564_SetInterruptCallback);
EXPORT_SYMBOL(APCIE1564_ClearInterruptCallback);
EXPORT_SYMBOL(APCIE1564_get_lock);

EXPORT_NO_SYMBOLS;

#ifndef __devinit
#define __devinit
#define __devexit
#define __devinitdata
#define __devexit_p
#endif

//------------------------------------------------------------------------------
spinlock_t * APCIE1564_get_lock(struct pci_dev *pdev)
{
        return &(APCIE1564_PRIVDATA(pdev)->lock);
}
//------------------------------------------------------------------------------

atomic_t apcie1564_count = ATOMIC_INIT(0);
unsigned int apcie1564_majornumber = 0;

//------------------------------------------------------------------------------
static int __devinit apcie1564_probe_one(struct pci_dev *dev,const struct pci_device_id *ent);
static void __devexit apcie1564_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 apcie1564_pci_tbl[] __devinitdata = {
	#include "devices.ids"
	{ 0 },	/* terminate list */
};

MODULE_DEVICE_TABLE (pci, apcie1564_pci_tbl);

//----------------------------------------------------------------------------------------------------------------------
static struct pci_driver apcie1564_pci_driver = {
	.name		= __DRIVER_NAME,
	.probe		= apcie1564_probe_one,
	.remove		= __devexit_p(apcie1564_remove_one),
	.id_table	= apcie1564_pci_tbl,
};
//----------------------------------------------------------------------------------------------------------------------


/* Prototypes of the used functions
 */
int APCIE1564_open   (struct inode *inode, struct file *filp);
int APCIE1564_release(struct inode *inode, struct file *filp);
int APCIE1564_ioctl  (struct        inode *inode,
                     struct        file *filp,
		     unsigned int  cmd,
		     unsigned long arg);



//------------------------------------------------------------------------------
static struct file_operations apcie1564_fops =
{
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,36)

        .ioctl                          = apcie1564_ioctl_lookup,
   #else
        .unlocked_ioctl         = apcie1564_ioctl_lookup,
   #endif
	.open		= apcie1564_open_lookup,
	.release	= apcie1564_release_lookup,
};

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

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

//-------------------------------------------------------------------
/** called when 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 the apcie1564_str_BoardInformations contains a field "dev", a pointer to
 * the OS PCI device structure.
 *
 *  */
static int __devinit apcie1564_probe_one(struct pci_dev *dev, const struct pci_device_id *ent)
{
	{
    	int ret = pci_enable_device(dev);
        if (ret)
        {
        	printk(KERN_ERR "%s: pci_enable_device failed\n",__DRIVER_NAME);
            return ret;
		}
	}

	/* 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(dev->resource[0].start, 512) )
	{
		printk(KERN_WARNING "%s: BAR 0 (%lX) is already in use\n",__DRIVER_NAME,dev->resource[0].start);
		return -EBUSY;
	}
	/* check if BAR 1 is free */
	if ( check_region(dev->resource[1].start, 256) )
	{
		printk(KERN_WARNING "%s: BAR 1 (%lX) is already in use\n",__DRIVER_NAME,dev->resource[1].start);
		return -EBUSY;
	}
	/* check if BAR 2 is free */
	if ( check_region(dev->resource[2].start, 16) )
	{
		printk(KERN_WARNING "%s: BAR 2 (%lX) is already in use\n",__DRIVER_NAME,dev->resource[2].start);
		return -EBUSY;
	}
	/* check if BAR 3 is free */
	if ( check_region(dev->resource[3].start, 256) )
	{
		printk(KERN_WARNING "%s: BAR 2 (%lX) is already in use\n",__DRIVER_NAME,dev->resource[2].start);
		return -EBUSY;
	}
	#endif // 2.4

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

		/* link standard data structure to the board's private one */
		pci_set_drvdata (dev, newboard_data);

		apcie1564_init_priv_data(newboard_data);
	}

	/* register interrupt */
	if ( apcie1564_register_interrupt(dev) )
	{
		/* failed, clean previously allocated resources */
	 	kfree(APCIE1564_PRIVDATA(dev));
	 	pci_release_regions(dev);
	}

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

	/* allocate BAR 0 to 3 memory regions */
	{
		int ret = pci_request_regions(dev,__DRIVER_NAME);
        if (ret)
        {
        	printk(KERN_ERR "%s: pci_request_regions failed\n",__DRIVER_NAME);
            /* free all allocated ressources here*/
            apcie1564_deregister_interrupt(dev);
            kfree(APCIE1564_PRIVDATA(dev));
            return ret;
		}
	}

	/* create */
	apcie1564_proc_create_device(dev, atomic_read(&apcie1564_count)-1);

	apcie1564_known_dev_append(dev);

	#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(&apcie1564_count)-1);

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

	#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
		cdev = class_device_create (apcie1564_class, NULL, MKDEV(apcie1564_majornumber, minor), NULL, "%s_%d", __DRIVER_NAME, minor);
	#elif LINUX_VERSION_CODE < KERNEL_VERSION(2,6,27)
		cdev = device_create (apcie1564_class, NULL, MKDEV(apcie1564_majornumber, minor), "%s_%d", __DRIVER_NAME, minor);
	#else
		cdev = device_create (apcie1564_class, NULL, MKDEV(apcie1564_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 apcie1564_register(void)
{

	//Registration of driver
	apcie1564_majornumber = register_chrdev(0, __DRIVER_NAME, &apcie1564_fops);

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

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

	/* 2.4 only : check_region is deprecated in 2.6 */
	#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
		/* Detection if an PCI Bus is present */
		if(!pci_present())
		{
			printk(KERN_WARNING "%s: NO PCI BUS.\n", __DRIVER_NAME);
			return -ENODEV;
		}
	#endif // 2.4

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

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

	/* registred, now create root /proc entry */
	apcie1564_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 (&apcie1564_pci_driver) != 0)
#else
	if ( pci_register_driver (&apcie1564_pci_driver) != 0)
#endif
	{
		printk("%s: no device found\n",__DRIVER_NAME);
		apcie1564_pci_driver.name = "";
	}



	return 0;
}
//------------------------------------------------------------------------------
/** when module is unloaded, stop all board activities (cf interrupt)*/
static void apcie1564_stop_board(struct pci_dev * pdev)
{
	APCIE1564_ClearAndStopDigitalInputInterrupt (pdev);
	APCIE1564_CounterStop(pdev,0);
	APCIE1564_CounterStop(pdev,1);
	APCIE1564_CounterStop(pdev,2);
}
//-------------------------------------------------------------------
/** a card is removed */
static void __devexit apcie1564_remove_one(struct pci_dev *dev)
{
	/* stop board activities */
	apcie1564_stop_board(dev);

	/* deregister interrupt */
	apcie1564_deregister_interrupt(dev);

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

	/* deallocate BAR 0 to 2 memory regions */
	pci_release_regions(dev);

	/* free private device data */
	kfree(APCIE1564_PRIVDATA(dev));

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

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

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

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

	break;
	}
#endif

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

	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 apcie1564_unregister(void)
{
	unregister_chrdev(apcie1564_majornumber, __DRIVER_NAME);
}

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

	/* Cleans the module from the kernel */
	if (apcie1564_pci_driver.name[0])
	{
		pci_unregister_driver (&apcie1564_pci_driver);
	}

	apcie1564_unregister();
	apcie1564_proc_release();

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)
	class_destroy (apcie1564_class);
#endif
}
//------------------------------------------------------------------------------
module_exit(apcie1564_exit);
module_init(apcie1564_init);
