/*
 *  Linux PCI - SD host driver
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

#ident "$Id: sd-pci.c,v 1.3 2006/01/12 01:53:57 gbarnard Exp $"

#include <linux/config.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <linux/wait.h>

#include "../include/sd.h"
#include "../include/sd_pci.h"
#include "../include/sd_host.h"
#include "../include/sd_debug.h"

#define SDH_MODULE_NAME		"SD_PCI_HOST"

#define ARASAN_PCI_VENDORID	0x1095
#define ARASAN_PCI_DEVICEID	0x0670

static struct pci_dev *pcidev = NULL;

static struct pci_device_id sdh_pci_tbl[] = 
{
	{ ARASAN_PCI_VENDORID, ARASAN_PCI_DEVICEID, PCI_ANY_ID, PCI_ANY_ID, },
	{ 0, }
};

u32 (*sdpci_irq_callback)(void *arg);
u32 baseaddr[SDHOST_MAX_SLOTS];

MODULE_DEVICE_TABLE(pci, sdh_pci_tbl);

/*
 * Comment out following line to remove debug code.
 */
#define DEBUG 0

#ifdef DEBUG

static struct _command_decode {
    int  command;
    char *command_name;
} command_decode[] = {
    { PCI_COMMAND_IO, "PCI_COMMAND_IO" },
    { PCI_COMMAND_MEMORY, "PCI_COMMAND_MEMORY" },
    { PCI_COMMAND_MASTER, "PCI_COMMAND_MASTER" },
    { PCI_COMMAND_SPECIAL, "PCI_COMMAND_SPECIAL" },
    { PCI_COMMAND_INVALIDATE, "PCI_COMMAND_INVALIDATE" },
    { PCI_COMMAND_VGA_PALETTE, "PCI_COMMAND_VGA_PALETTE" },
    { PCI_COMMAND_PARITY, "PCI_COMMAND_PARITY" },
    { PCI_COMMAND_WAIT, "PCI_COMMAND_WAIT" },
    { PCI_COMMAND_SERR, "PCI_COMMAND_SERR" },
    { PCI_COMMAND_FAST_BACK, "PCI_COMMAND_FAST_BACK" },
    { PCI_COMMAND_INTX_DISABLE, "PCI_COMMAND_INTX_DISABLE" },
};

static struct _status_decode {
    status_t status;
    char     *status_string;
} status_decode[] = {
    { st_illegal, "st_illegal" },
    { st_success, "st_success" },
    { st_fail_bad_op, "st_fail_bad_op" },
    { st_fail_no_ops, "st_fail_no_ops" },
    { st_fail_no_slots, "st_fail_no_slots" },
    { st_fail_bad_slot_count, "st_fail_bad_slot_count" },
    { st_fail_no_sdh, "st_fail_no_sdh" },
    { st_fail_bad_slot_window, "st_fail_bad_slot_window" },
};

char *
decode_status (status_t status)
{
    int i;

    for (i = 0; 
         i < (sizeof (status_decode) / sizeof (struct _status_decode));
         i++) {
        if (status == status_decode[i].status) {
            return (status_decode[i].status_string);
        }
    }

    return "unknown";
}

void
pci_decode_command (u16 command)
{
    int i;

    for (i = 0; 
         i < (sizeof (command_decode) / sizeof (struct _command_decode));
         i++) {
        if (command & command_decode[i].command) {
            printk (KERN_INFO "%s: %s\n",
                    __FUNCTION__, command_decode[i].command_name);
        }
    }
}

void
pci_dev_dump (struct pci_dev *pcidev)
{
    u8 latency = 0;
    u16 command = 0;
    u32 pci_id = 0, pci_subsys_id = 0, pci_class_rev = 0;

    if (!pcidev) {
        printk (KERN_CRIT "%s: can't dump non-existent device\n",
                __FUNCTION__);
    }

    pci_read_config_byte(pcidev, PCI_LATENCY_TIMER, &latency);
    pci_read_config_dword(pcidev, PCI_VENDOR_ID, &pci_id);
    pci_read_config_dword(pcidev, PCI_SUBSYSTEM_ID, &pci_subsys_id);
    pci_read_config_dword(pcidev, PCI_REVISION_ID, &pci_class_rev);
    pci_read_config_word(pcidev, PCI_COMMAND, &command);

    printk (KERN_INFO "%s: Latency 0x%x Vendor 0x%x Subsys 0x%x Revision 0x%x\n",
            __FUNCTION__, latency, pci_id, pci_subsys_id, pci_class_rev);
    printk (KERN_INFO "%s: Command 0x%x\n",
            __FUNCTION__, command);

    pci_decode_command (command);
}

#endif /* DEBUG */

/* 
 * assign_base_address()
 * 
 * Returns: 
 * Memory/IO region of requested BAR, 0 if not valid
 * (0 is not valid PCI address on the ARM development system)
 * Input valid pci_cfg_address and BAR number 0,1, or 2.
 * 
 */
static u32 assign_base_address(int bar_no)
{
	u32 pci_io_start, pci_io_length;
    u32* ioaddr;
      
	/* if it does not exist return 0 */
	if (!pcidev) 
	{ 
		return 0;
	}
	
	pci_io_start = pci_resource_start(pcidev, bar_no);
	pci_io_length = pci_resource_len(pcidev, bar_no);
	ioaddr = ioremap_nocache(pci_io_start, pci_io_length);
	
    printk (KERN_INFO "%s: pci_io_start 0x%x pci_io_length 0x%x\n",
            __FUNCTION__, pci_io_start, pci_io_length);
	printk (KERN_INFO  "%s: host->ioaddr[%d] = 0x%x\n",  
            __FUNCTION__, bar_no, (u32)ioaddr);
       
	return (u32)ioaddr;
}

/* 
 * sdpci_base_address()
 * 
 * Returns: 
 * Memory/IO region of requested BAR, 0 if not valid
 * (0 is not valid PCI address on the ARM development system)
 * Input valid pci_cfg_address and BAR number 0,1, or 2.
 * 
 */
unsigned int sdpci_base_address(int bar_no)
{ 
	return baseaddr[bar_no];
}

u16
READ_HOST_U16(u32 base, u16 reg)
{
    u16 ret;

    ret = readw((void __iomem *)base + reg);

    // printk (KERN_INFO  "%s: reg 0x%x ==> 0x%x\n", __FUNCTION__, reg, ret);

    return ret;
}

void 
WRITE_HOST_U16(u32 base, u16 reg, u16 val)
{
    writew(val, (void __iomem *)base + reg);
}

static irqreturn_t 
sdpci_irq(int irq, void *devid, struct pt_regs *regs)
{    
	/* Read All Slot(s) Common Interrupt Status HOSTREG_SLOTINTRS=0xFC*/
	u16 global_stat = 0;
	if (baseaddr[0])
    	global_stat = READ_HOST_U16(baseaddr[0], HOSTREG_SLOTINTRS);
    
    /* If IRQ from SD Host handle */
    if (global_stat)
    {
		#if 0
  		/* debug */
    	printk (KERN_INFO  "%s: global irq = 0x%x\n", __FUNCTION__,global_stat);
  		printk (KERN_INFO  "%s: norm int status = 0x%x\n", __FUNCTION__,
  			READ_HOST_U16(baseaddr[0], HOSTREG_NORMINTRSTAT) );
  		/* debug end */
    		#endif

  		if (sdpci_irq_callback) 
  		{
  			sdpci_irq_callback(baseaddr[0]);	
  		}
  		else
  		{
	  		/* should not be active, disable and clear */
	  		WRITE_HOST_U16(baseaddr[0], HOSTREG_NORINTRSGEN, 0x00);
	  		WRITE_HOST_U16(baseaddr[1], HOSTREG_NORINTRSGEN, 0x00);
	 		WRITE_HOST_U16(baseaddr[0], HOSTREG_NORMINTRSTAT, 0x1FF);
	  		WRITE_HOST_U16(baseaddr[0], HOSTREG_ERRINTRSTAT, 0x1FF);
	 		WRITE_HOST_U16(baseaddr[1], HOSTREG_NORMINTRSTAT, 0x1FF);
	  		WRITE_HOST_U16(baseaddr[1], HOSTREG_ERRINTRSTAT, 0x1FF);
  		}    		
   		return IRQ_HANDLED; /* if IRQ from our device */  		
    }

	return IRQ_NONE; /* for shared devices, if irq not from this device */
}


/*
 * Returns number of sd-card slots connected to sd-host controller (arasan) 
 * 
 */
u8 sdpci_slot_count(void)
{
	u8 Data_Byte;
	pci_read_config_byte(pcidev, SD_PCI_SLOT_INFO, &Data_Byte);
    Data_Byte = ((Data_Byte & 0x70)>>4)+1;
    return Data_Byte;
}

/*
 * sdpci_probe()
 * 
 * Linux calls during init.
 */
static int __devinit 
sdpci_probe(struct pci_dev *pcidev, const struct pci_device_id *id)
{
    int ret = 0;
    int i,slots;

	printk (KERN_INFO  "%s: entered\n", __FUNCTION__);
	
	/* Gather information required by serial module */
	slots = sdpci_slot_count();
	printk (KERN_INFO "Number Of Slots=%d\n",slots);
	for (i=0; i<slots; i++)
	{
		baseaddr[i] = assign_base_address(i);
	}
	
	//printk (KERN_INFO "SLOT IRQ=%x",READ_HOST_U16(baseaddr[0], HOSTREG_SLOTINTRS));

	/* SA_INTERRUPT: fast interrupt executed with all other interrupts disabled */
	/* SA_SHIRQ: sharing required by PCI */
    ret = request_irq(pcidev->irq, sdpci_irq, SA_INTERRUPT|SA_SHIRQ,
                "SDPCI", pcidev);
    if (ret) {
        printk (KERN_INFO  "%s: Can't initilize IRQ Ret code: %X\n", 
               __FUNCTION__, ret);
    }
    return ret;
}

/*
 * sdpci_remove()
 * Linux calls when pcidev struct is being removed, or driver unloading
 */
static void 
sdpci_remove(struct pci_dev *pcidev)
{
	printk (KERN_INFO  "%s: free called \n", __FUNCTION__);

    //disable_irq(pcidev->irq); /* seems to disable interrupt for all cards on same pci irq */
	free_irq(pcidev->irq, pcidev);
    pci_release_regions(pcidev);
	pci_disable_device(pcidev);
}


static struct pci_driver sdha_driver = {
	.name		 = SDH_MODULE_NAME,
	.id_table	 = sdh_pci_tbl,
	.probe		 = sdpci_probe,
	.remove		 = sdpci_remove,
};

/*
 * sdpci_init()
 * 
 * Called when module loaded
 */
static int 
__devinit sdpci_init(void)
{
    int	status = 0;
    u8	data_byte;
    u16	data_half;
    sdpci_irq_callback = NULL;

    printk (KERN_INFO  "%s: Init Module\n", __FUNCTION__);

	if (!(pcidev = pci_find_device (ARASAN_PCI_VENDORID, 
                                    ARASAN_PCI_DEVICEID, pcidev))) {
        printk (KERN_INFO  "%s: cannot find PCI card\n",
                __FUNCTION__);
		return(0);
	}
	
	printk (KERN_INFO  "%s: Arasan PCI card found\n", __FUNCTION__);

	status = pci_enable_device(pcidev);
	if (status) {
		printk (KERN_INFO  "%s Cannot enable PCI device error %d, aborting.\n",
               __FUNCTION__, status);
		return status;
	}
 
	pci_set_master(pcidev);
	
    /* Set latency timer. */
    data_byte = 0x04;

    pci_write_config_byte(pcidev, PCI_LATENCY_TIMER, data_byte);

    /* Ensure PCI command includes parity */
    pci_read_config_word(pcidev, PCI_COMMAND, &data_half);

    data_half |= PCI_COMMAND_PARITY;
    pci_write_config_word(pcidev, PCI_COMMAND, data_half);

 	status = pci_request_regions(pcidev, SDH_MODULE_NAME);
    if (status) {
        printk (KERN_INFO  "%s Cannot obtain PCI region error %d, aborting.\n",
               __FUNCTION__, status);
        pci_disable_device(pcidev);
        return status;
    }

	/* calls sdpci_probe */
    status = pci_register_driver(&sdha_driver);
	printk (KERN_INFO  "%s pci_register_driver = %d\n",
       __FUNCTION__, status);
	       
	#ifdef DEBUG
	    pci_dev_dump (pcidev);
	#endif /* DEBUG */

    return status;
}

/*
 * sdpci_exit()
 *  then calls remove ...
 */
static void __devexit sdpci_exit(void)
{
	printk (KERN_INFO  "%s called\n",__FUNCTION__);

	//free_irq(pcidev->irq, pcidev);	       
	pci_unregister_driver(&sdha_driver);
	
}

/* --- ---- Interface Functions ---- --- */
void sdpci_attach_irq(void* irq_function)
{
	printk (KERN_INFO  "%s irq()=%x\n",__FUNCTION__,(u32)irq_function);
	sdpci_irq_callback = irq_function;
}


// --- The following represent all that we require from PCI ---
EXPORT_SYMBOL(sdpci_slot_count);	// for number of slots
EXPORT_SYMBOL(sdpci_base_address);		// for base addresses
EXPORT_SYMBOL(sdpci_attach_irq);		// for irq

module_init(sdpci_init);
module_exit(sdpci_exit);

MODULE_DESCRIPTION("SD PCI Host Device Driver");
MODULE_AUTHOR ("Developer , info@broadon.com");
//MODULE_LICENSE("Proprietory");
MODULE_LICENSE("GPL");
