/******************************************************************************
 *                                                                            *
 * Project: DOC Driver for Linux 2.6 Block device driver for mDOC H3  family  *
 * of devices under Linux kernel 2.6.                                         *
 *                                                                            *
 *   Version: 1.0                                                             *
 *   Email questions to: oemsupport@sandisk.com                               *
 *   Copyright (C) SanDisk IL Ltd. 1995 - 2007                                *
 *   SanDisk IL Ltd., 7 Atir Yeda Street, Kfar Saba 44425, Israel             *
 *                                                                            *
 ******************************************************************************
 *                                                                            *
 * 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 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, which is set forth in the readme.txt file.                   *
 * 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., 51 *
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA                    *
 *                                                                            *
 * This License does not grant you any right to use the trademarks, service   *
 * marks or logos of SanDisk IL Ltd. or SanDisk Corporation.                  *
 * Subject to the foregoing, SanDisk IL Ltd., for itself and on behalf of its *
 * licensors, hereby reserves all intellectual property rights in the program,*
 * except for the rights expressly granted in this License.                   *
 *                                                                            *
 ******************************************************************************/

/*
 * $Log$
 */



/*
 * includes
 */

#include "tffsdrv.h"
#include "flbase.h"
#include "doch_sys.h"
#include "hib.h"


#ifdef TFFS_MESSAGES_ENABLED
int fl_debug = FL_DEBUG_DEF;
module_param(fl_debug, int, (S_IRUGO | S_IWUSR));
MODULE_PARM_DESC(fl_debug,"Print TrueFFS debug messages [0-7].");
#endif

/* For portability reasons, Linux drivers should use macros readXXX/writeXXX
 * when reading/writing hardware registers and transferring data from
 * devices. Command line parameter "tffs_memcpy=<1|2|3>" allows DiskOnChip
 * driver to use memcpy() library routine instead, which often greatly
 * improves driver's 'read' performance.
 *
 *     insmod tffs.o tffs_memcpy=1
 */
int tffs_memcpy = 0;
module_param(tffs_memcpy, int, S_IRUGO);
MODULE_PARM_DESC(tffs_memcpy, "Use memcpy() for DiskOnChip data transfers.");


/* Command line parameter "tffs_addr=<physical_address>" allows user to tell
 * DiskOnChip driver where to look for DiskOnChip. For example, to instruct
 * driver to probe for DiskOnChip at physical address 0x14000000:
 *
 *     insmod tffs.o tffs_addr=0x14000000
 */
ulong tffs_addr[FL_SOCKETS] = { TFFS_PHYS_ADDR };
static int __fl_sockets = FL_SOCKETS;  /* just for module_param_array() below */
#if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9))
  module_param_array(tffs_addr, ulong, __fl_sockets, S_IRUGO);
#else
  module_param_array(tffs_addr, ulong, &__fl_sockets, S_IRUGO);
#endif
MODULE_PARM_DESC(tffs_addr,"Physical address of DiskOnChip.");

/* Command line parameter "tffs_skip_sleeps=<num>" instructs DiskOnChip driver
 * how often it should yield CPU during DiskOnChip 'write' operations. The
 * higher the <num>, the less frequently driver yield CPU, thus increasing
 * it's 'write' performance, but also increasing it's load on CPU. 
 *
 *     insmod tffs.o tffs_skip_sleep=3
 */
int tffs_skip_sleeps = 5;
module_param(tffs_skip_sleeps, int, (S_IRUGO | S_IWUSR));
MODULE_PARM_DESC(tffs_skip_sleeps,"How often to yield CPU during write operations.");


unsigned int profiling[10] = {0};



/*
 * static routines
 */
static void TffsMapMem (SocketInfo *psoc, unsigned long phys_addr, unsigned long length);
static void TffsUnmapMem (SocketInfo *psoc);
static void irq_wait_timed_out (unsigned long arg);



/*
 * static vars
 */

/* semaphore used by TrueFFS: one per socket, plus one for dochVol.mutex */
static struct semaphore  sems [FL_SOCKETS + 1];

/* next TrueFFS semaphore to allocate (0..FL_SOCKETS-1) */
static int  total_sems = 0;




/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       T f f s M a p M e m                             *
 *                                                                       *
 * Allocate physical memory region, and map it into kernel's address     *
 * space.                                                                *
 *                                                                       *
 * Parameters:                                                           *
 *      psoc          socket pointer                                     *
 *      phys_addr     starting address of physical memory region         *
 *      length        length (in bytes) of this physical memory region   *
 *                                                                       *
 *-----------------------------------------------------------------------*/
static
void  TffsMapMem ( SocketInfo    * psoc,
                   unsigned long   phys_addr,
                   unsigned long   length )
{
    struct resource * rs;

    /* no memory region has been obtained yet */
    psoc->fMemRequested = 0;
    psoc->dwPhysAddr    = 0;
    psoc->dwMappedLen   = 0;
    psoc->dwVirtAddr    = 0;

    /* request physical memory region that DiskOnChip resides in */
    if ((rs = request_mem_region(phys_addr, length, "tffs")) != NULL)
    {
        /* map this physical memory region to kernel's virtual addr. space */
        if ((psoc->dwVirtAddr = (ulong)ioremap_nocache(phys_addr, length)) != 0)
        {
            psoc->fMemRequested = 1;
            psoc->dwPhysAddr    = phys_addr;
            psoc->dwMappedLen   = length;
        }
        else
        {
            PrintkDebug("ioremap_nocache(0x%lx,0x%lx) failed", phys_addr, length);
            release_mem_region (phys_addr, length);
        }
    }
    else
        { PrintkDebug("request_mem_region(0x%lx,0x%lx) failed", phys_addr, length); }
}




/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       T f f s U n m a p M e m                         *
 *                                                                       *
 * Unmap and free memory region previously allocated by TffsMapMem().    *
 *                                                                       *
 * Parameters:                                                           *
 *      psoc          socket pointer                                     *
 *                                                                       *
 *-----------------------------------------------------------------------*/
static
void  TffsUnmapMem ( SocketInfo * psoc )
{
    if (psoc->dwVirtAddr != 0)
        iounmap ((void *)psoc->dwVirtAddr);

    if (psoc->fMemRequested == 1)
        release_mem_region (psoc->dwPhysAddr, psoc->dwMappedLen);

    psoc->fMemRequested = 0;
    psoc->dwPhysAddr    = 0;
    psoc->dwMappedLen   = 0;
    psoc->dwVirtAddr    = 0;
}




void * TffsMalloc (unsigned long size)
{
    return vmalloc (size + 4);
}




void  TffsFree (void * vptr)
{
    vfree (vptr);
}




int LnxTffsPrint(const char *fmt, ...)
{
	va_list args;
	char buf[1024];			/* hopefully enough, kernel/printk.c thinks so */
	int i;

	va_start(args, fmt);
	i = vsprintf(buf, fmt, args);
	va_end(args);
	buf[i] = '\0';

	while(i>0)
	{
		if(buf[i-1]==0xd || buf[i-1]==0xa)
		{
			buf[--i]=0;
		}
		else
			break;
	}
	printk(KERN_ERR TFFS_DEVICE_NAME": %s\n",buf);
	return i;
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       t f f s _ r e a d w                             *
 *                                                                       *
 * This routine transfers data from RAM to DiskOnChip device in cases    *
 * when DMA is not used.                                                 *
 *                                                                       *
 * Parameters:                                                           *
 *      io_vaddr      virtual address of DiskOnChip's data port          *
 *      vbuf          buffer to transfer data from                       *
 *      words         number of 16-bit short words to transfer           *
 *                                                                       *
 *-----------------------------------------------------------------------*/

void tffs_readw ( unsigned long io_vaddr, short * vbuf, int words )
{
    if (tffs_memcpy & 1) /* use memcpy() to transfer data; might not work ! */
    {
        register char * p = (char *) vbuf;
        register int    n;

        for (words <<= 1; words > 0; words -= n, p += n)
        {
            /* DiskOnChip's I/O register is aliased across 1024-bytes region */
            n = ((words <= 1024) ? words : 1024);
            memcpy (p, (void *)io_vaddr, n);
        }  
    }
    else /* standard Linux case: use __raw_readw for portability */
    {
        while (words--)
            *vbuf++ = __raw_readw (io_vaddr);
    }
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       t f f s _ w r i t e w                           *
 *                                                                       *
 * This routine transfers data from DiskOnChip device to RAM in cases    *
 * when DMA is not used.                                                 *
 *                                                                       *
 * Parameters:                                                           *
 *      io_vaddr      virtual address of DiskOnChip's data port          *
 *      vbuf          buffer to transfer data to                         *
 *      words         number of 16-bit short words to transfer           *
 *                                                                       *
 *-----------------------------------------------------------------------*/

void tffs_writew ( unsigned long io_vaddr, short * vbuf, int words )
{
    if (tffs_memcpy & 2)  /* use memcpy() to transfer data; might not work ! */
    {
        register char * p = (char *) vbuf;
        register int    n;

        for (words <<= 1; words > 0; words -= n, p += n)
        {
            /* DiskOnChip's I/O register is aliased across 1024-bytes region */
            n = ((words <= 1024) ? words : 1024);
            memcpy ((void *)io_vaddr, p, n);
        }
    }
    else /* standard Linux case: use __raw_writew for portability */
    {
        while (words--)
        {
            __raw_writew (*vbuf, io_vaddr);
            vbuf++;
        }
    }
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       d o c h b l k _ r e a d                         *
 *                                                                       *
 * This routine transfers data from DiskOnChip H3 device to RAM.         *
 *                                                                       *
 * Parameters:                                                           *
 *      vbuf          buffer to transfer data to                         *
 *      sectors       number of 512-byte sectors to transfer             *
 *                                                                       *
 *-----------------------------------------------------------------------*/

int dochblk_read (void * vbuf, unsigned int sectors)
{
    flReadEvenNumberOfBytes ((DOCHFlash), DOCH_DATA_PORT_AREA, vbuf, ((sectors) << 9));
    return 0;
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       d o c h b l k _ w r i t e                       *
 *                                                                       *
 * This routine transfers data from RAM to DiskOnChip H3 device.         *
 *                                                                       *
 * Parameters:                                                           *
 *      vbuf          buffer to transfer data from                       *
 *      sectors       number of 512-byte sectors to transfer             *
 *                                                                       *
 *-----------------------------------------------------------------------*/

int dochblk_write (void * vbuf, unsigned int sectors)
{
    flWriteEvenNumberOfBytes ((DOCHFlash), DOCH_DATA_PORT_AREA, vbuf, ((sectors) << 9));
    return 0;
}




void  flSysfunInit ( void )
{
    register int   iSoc;
    unsigned long  win_size;  /* size of DiskOnChip window in bytes */

    total_sems = 0;

    /* DiskOnChip H3 devices can be configured to use 8-, 32- or 128-KByte
     * window; we assume the worst case here (128-KB).
     */
    win_size = DOCH_MEM_WIN_SIZE_128KB /* or DOCH_MEM_WIN_SIZE_8KB */; 

    for (iSoc = 0; iSoc < FL_SOCKETS; iSoc++)
        TffsMapMem (&tffsInfo.sockets[iSoc], tffs_addr[iSoc], win_size);

    /* We are not doing 'resume' after previous power 'suspend', but rather
     * a full scale board initialization, hence FALSE flag below.
     */
    if( tffsarch_init(FALSE) == 0 )
        PrintkWarning("tffsarch_init error");
}



void  LnxSysfunRelease ( void )
{
    int i;

    for (i = 0; i < FL_SOCKETS; i++)
        TffsUnmapMem (&tffsInfo.sockets[i]);

    total_sems = 0;

    TffsHWRelease ();
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       f l C r e a t e M u t e x                       *
 *                                                                       *
 * Create mutex.                   .                                     *
 *                                                                       *
 * Parameters:                                                           *
 *      mutex         ID of newly created sempahore will be stored here  *
 *                                                                       *
 * Returns:                                                              *
 *      flOK if successful otherwise respective error code               *
 *                                                                       *
 *-----------------------------------------------------------------------*/

FLStatus  flCreateMutex (FLMutex * mutex)
{
    if (total_sems >= (sizeof(sems) / sizeof(sems[0])))
    {
        PrintkError("flCreateMutex: error creating mutex");
        return flNotEnoughMemory;
    }

    /* initialize next available semaphore to 'available' state */
    sema_init (&sems[total_sems], 1);

    *mutex = (FLMutex) total_sems++;

    return flOK;
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       f l T a k e M u t e x                           *
 *                                                                       *
 * Called to aquire the mutex.                                           *
 *                                                                       *
 * Parameters:                                                           *
 *      mutex           identifies mutex to release                      *
 *                                                                       *
 * Returns:                                                              *
 *      always TRUE                                                      *
 *                                                                       *
 *-----------------------------------------------------------------------*/

FLBoolean  flTakeMutex (FLMutex * mutex)
{
    register struct semaphore * psem = &sems[ (int)(*mutex) ];

    /* put caller to sleep until semaphore is available */
    if( down_interruptible(psem) != 0 )
    {
        /* Semaphore still isn't available - down_interruptible() returned
         * because caller was waken up by signal. We must abort TrueFFS call.
         */
        return FALSE;
    }

    /* semaphore has been taken; TrueFFS call can proceed now */
    return TRUE;
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       f l F r e e M u t e x                           *
 *                                                                       *
 * Called to release the mutex.                                          *
 *                                                                       *
 * Parameters:                                                           *
 *      mutex           identifies mutex to release                      *
 *                                                                       *
 *-----------------------------------------------------------------------*/

void  flFreeMutex (FLMutex * mutex)
{
    register struct semaphore * psem = &sems[ (int)(*mutex) ];

    /* release semaphore */
    up (psem);
}



/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       f l D e l e t e M u t e x                       *
 *                                                                       *
 * Called to destroy the mutex and free all associated resources.        *
 *                                                                       *
 * Parameters:                                                           *
 *      mutex           identifies mutex to destroy                      *
 *                                                                       *
 *-----------------------------------------------------------------------*/

void  flDeleteMutex (FLMutex * mutex)
{
    /* just in case some thread(s) are still sleeping on this semaphore */
    flFreeMutex (mutex);
}




/*-----------------------------------------------------------------------*
 *                                                                       *
 *                       f l B u i l d G e o m e t r y                   *
 *                                                                       *
 * This routine calculates cylinder/head/sector geometry based on the    *
 * number of sectors on the disk.                                        *
 *                                                                       *
 * Parameters:                                                           *
 *      sectors         total sectors on disk                            *
 *      cyl             pointer to number of cylinders                   *
 *      heads           pointer to number of heads                       *
 *      sec_per_track   pointer to number of sectors per track           *
 *      oldFormat       ignored                                          *
 *      wirHandle       ignored                                          *
 *                                                                       *
 *-----------------------------------------------------------------------*/

void flBuildGeometry ( unsigned long   sectors, 
                       unsigned long * cyl,
                       unsigned long * heads,
                       unsigned long * sec_per_track,
                       unsigned char   oldFormat,
                       unsigned short  wIrHandle )
{
    DeviceInfo  * pdisk;
    register int  i;

    for (i = 0; i < (sizeof(tffsInfo.ppDevices) / sizeof(tffsInfo.ppDevices[0])); i++)
    {
        if ((pdisk = tffsInfo.ppDevices[i]) == NULL)
            return;

        /* The 'wIrHandle' argument is the internal TrueFFS handle which is
         * different from TrueFFS handle stored in DeviceInfo.bHandle, and
         * passed to TrueFFS API routines. 
         */
        if (pdisk->dwSize == sectors) /* was (pdisk->bHandle == wIrHandle) */
        {
            if (cyl           != NULL) *cyl           = pdisk->wCyl;
            if (heads         != NULL) *heads         = pdisk->bHead;
            if (sec_per_track != NULL) *sec_per_track = pdisk->bSect;

            return;
        }
    }
}




/*-----------------------------------------------------------------------*
 *                                                                       *
 *                 i r q _ w a i t _ t i m e d _ o u t                   *
 *                                                                       *
 * This routine is called when DiskOnChip interrupt gets lost, and       *
 * watchdog timer gets activated. It prevents driver from hanging up in  *
 * such cases by posting a semaphore that socket's I/O thread is waiting *
 * for.                                                                  *
 *                                                                       *
 * Parameters:                                                           *
 *      arg           pointer to semaphore                               *
 *                                                                       *
 *-----------------------------------------------------------------------*/

static
void irq_wait_timed_out ( unsigned long arg )
{
    profiling[5]++;

    /* Since this routine is running, it means that DiskOnChip interrupt
     * got lost (or delayed for too long). To prevent socket's I/O thread
     * from hanging up, we wake up I/O thread here.
     */
    complete ((struct completion *)arg); /* up ((struct semaphore *)arg); */
}




/*-----------------------------------------------------------------------*
 *                                                                       *
 *                     f l _ t f f s _ s l e e p                         *
 *                                                                       *
 * This routine is called right after starting flash 'write' or 'erase'  *
 * operation on DiskOnChip. These operations usually take around 700     *
 * ('write') or 3000 ('erase') microseconds to complete. This routine    *
 * might yield the CPU and cause task switch.                            *
 *                                                                       *
 * Parameters:                                                           *
 *      handle        TrueFFS handle (only lower 4 bits are used)        *
 *      microseconds  expected average duration of flash operation       *
 *                                                                       *
 *-----------------------------------------------------------------------*/

void  fl_tffs_sleep ( unsigned int   handle, 
                      unsigned long  microseconds )
{
#ifdef TFFS_USE_SLEEP

    int socNo = (int)(handle & 0xf);  /* extract socket # from TrueFFS handle */

    static int _counter = 0;

    if (tffsInfo.sockets[socNo].io_thread_state != 1)
    {
        /* DiskOnChip driver is being uninstalled, or power-suspended, or is
         * power-resuming. In either of these cases, we want to process all
         * outstanding I/O requests as quickly as possible; therefore we
         * will not sleep.
         */
        return;
    }

    if (tffs_irq < 0)  /* DiskOnChip R/B interrupts are not used */
    {
        if (++_counter > tffs_skip_sleeps)
        {
            /* Once in a while (once in 'tffs_skip_sleeps' calls to this routine)
             * we yield CPU and put DiskOnChip driver to sleep, to give chance
             * to other tasks to run. Note that this negatively impacts
             * DiskOnChip's 'write' performance.
             */
            unsigned long jiffies_to_sleep = (HZ * microseconds) / 1000000;
#if 0
            if (jiffies_to_sleep == 0)
                jiffies_to_sleep = 1;
#endif
            /* yield CPU and sleep */
            set_current_state (TASK_INTERRUPTIBLE);
            schedule_timeout (jiffies_to_sleep);

            _counter = 0;
        }
        else
        {
            /* TrueFFS will busy-poll DiskOnChip's status register to
             * detect completion of flash 'write' and 'erase' operations. This
             * improves DiskOnChip's 'write' performance, but also ties up CPU
             * for extensive periods of time.
             */
            return;
        }
    }
    else    /* yield CPU and sleep until waken up by DiskOnChip interrupt */
    {
        struct timer_list watchdog_timer;

        profiling[0]++;

        /* To guard ourselves against stray DiskOnChip interrupts,
         * we clear tffsInfo.sockets[socNo].wait_for_irq
         * before enabling IRQ that DiskOnChip is nonnected to
         */
        init_completion (&tffsInfo.sockets[socNo].wait_for_irq); /* sema_init (&tffsInfo.sockets[socNo].sleep_sem, 0); */

        tffs_irq_enable (TRUE);

        /* To guard ourselves against the case when DiskOnChip interrupt
         * will not be generated for some reason, or will get lost, we
         * set watchdog timer to wake us up after 30 milliseconds.
         */
        init_timer (&watchdog_timer);
        watchdog_timer.function = irq_wait_timed_out;
        watchdog_timer.data     = (unsigned long) &tffsInfo.sockets[socNo].wait_for_irq /* &tffsInfo.sockets[socNo].sleep_sem */ ;
        watchdog_timer.expires  = jiffies + ((30 * HZ) / 1000);
        add_timer (&watchdog_timer);

        /* sleep until DiskOnChip interrupt or watchdog timer wakes us up */
        wait_for_completion (&tffsInfo.sockets[socNo].wait_for_irq); /* down_interruptible (&tffsInfo.sockets[socNo].sleep_sem); */

        tffs_irq_disable (TRUE);

        /* no longer need watchdog timer */
        del_timer_sync (&watchdog_timer);
    }
#endif /* TFFS_USE_SLEEP */
}




/*-----------------------------------------------------------------------*
 *                                                                       *
 *                          d o c h _ s l e e p                          *
 *                                                                       *
 * This routine is called numerous times during DiskOnChip H3 'write'    *
 * operations.                                                           *
 *                                                                       *
 * Parameters:                                                           *
 *      sock          socket # (zero-based)                              *
 *      microseconds  expected average duration of flash operation       *
 *                                                                       *
 *-----------------------------------------------------------------------*/

void doch_sleep ( unsigned int  soc,
                  unsigned long microseconds )
{
    extern int   write_requests;
    static int __write_requests = 0;
   
    /* If DiskOnChip IRQ is enabled, or if 'tffs_skip_sleeps' set to yeild
     * CPU often, we yield CPU.
     */ 
    if (tffs_irq >= 0)
    {
        fl_tffs_sleep (soc, microseconds);
    }
    else                 
    {
        /* DiskOnChip IRQ is disabled. We yield CPU according to
         * 'tffs_skip_sleep' setting, making sure that we do yield CPU
         * at least once per I/O 'write' request.
         */
        if ((tffs_skip_sleeps >= 100) || (write_requests != __write_requests))
        {
            fl_tffs_sleep (soc, microseconds);
        }
        __write_requests = write_requests;
    }
}
