/******************************************************************************
 *                                                                            *
 * 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$
 */


#include "tffsdrv.h"

#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0))

#include "tffs2lnx.h"
#include "flbase.h"



MODULE_AUTHOR("M-Systems");
MODULE_DESCRIPTION("TrueFFS driver");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE(TFFS_SUPPORTED_DEVICE);



/* 
 * module parameters
 */

/* major device # to use */
int tffs_major = 100;
module_param(tffs_major, int, S_IRUGO);
MODULE_PARM_DESC(tffs_major, "major device number, zero to use dynamic.");

/* priority of driver's I/O threads */
static int tffs_prio = 0;    /* max -20, min 19 */
module_param(tffs_prio, int, (S_IRUGO | S_IWUSR));
MODULE_PARM_DESC(tffs_prio,"priority of DiskOnChip I/O thread.");

/* interrupt line that DiskOnChip's IREQ is connected to */
int tffs_irq = TFFS_IRQ;
module_param(tffs_irq, int, S_IRUGO);
MODULE_PARM_DESC(tffs_irq, "Interrupt line DiskOnChip's IREQ is connected to.");

/* DMA mode. Allowed modes are:
 *      0 (don't use DMA)
 *      1 (use s/w DMA in read operations only; uses intermediate DMA buffer)
 *      2 (use s/w DMA in write operations only; uses intermediate DMA buffer)
 *      3 (combined 1 and 2)
 *      5 (use s/w DMA for direct transfers from user source buffers)
 *      6 (use s/w DMA for direct transfers to user dest. buffers)
 *      7 (combined 5 and 6)
 * Default is don't use DMA.
 */
int tffs_dma_mode = 0;
module_param(tffs_dma_mode, int, S_IRUGO);
MODULE_PARM_DESC(tffs_dma_mode, "DMA mode (0, 1, 2, 3, 5, 6 or 7).");

/* Automatic Deep PowerDown mode. Allowed modes are 0 (default; disabled),
 * or 1 (enabled). When enabled, Automatic Deep PowerDown mode will cause
 * DiskOnChip driver to power down DiskOnChip after completion of every 
 * read/write operation, and power it up again before starting the next one.
 */
int tffs_auto_dpd = FL_OFF;
module_param(tffs_auto_dpd, int, S_IRUGO);
MODULE_PARM_DESC(tffs_auto_dpd, "Powerdown DiskOnChip after every operation (1), or don't (0).");

/* Upon completion of every read/write access, DiskOnChip H3 devices
 * immediately switch from the normal mode into the idle mode, and stay
 * in the idle mode for 'DOCH_DPD_DEFAULT_DPD_TIMEOUT' milliseconds before
 * switching into deep-power-down mode.
 */
int tffs_dpd_timeout = 1;
module_param(tffs_dpd_timeout, int, S_IRUGO);
MODULE_PARM_DESC(tffs_dpd_timeout, "Time (in milliseconds) before DiskOnChip automatically powers itself down.");

/* Read data from DiskOnChip into scatter/gather buffer, then scatter it to
 * destination buffers. Allowed values are TRUE (scatter data) or FALSE (don't).
 */
int tffs_sg_read = TRUE;
module_param(tffs_sg_read, int, S_IRUGO);
MODULE_PARM_DESC(tffs_sg_read, "Use scatter/gather during read operations.");

/* Gather data from source buffers into scatter/gather buffer before writing
 * it to DiskOnChip. Allowed values are TRUE (gather data) or FALSE (don't).
 */
int tffs_sg_write = TRUE;
module_param(tffs_sg_write, int, S_IRUGO);
MODULE_PARM_DESC(tffs_sg_write, "Use scatter/gather during write operations.");

/* size of scatter/gather buffer in bytes; must be multiple of PAGE_SIZE */
int tffs_sg_bufsize = (16 * PAGE_SIZE);
module_param(tffs_sg_bufsize, int, S_IRUGO);
MODULE_PARM_DESC(tffs_sg_bufsize, "Size of scatter/gather buffer, in bytes.");




/*
 * macros
 */
#ifndef _MIN
#  define _MIN(a,b)  ((a) < (b) ? (a) : (b))
#endif




/*
 * types
 */
struct scatter_t      /* scatter buffer for READ requests */
{
    char         * buf;                   /* starting address                  */
    char         * pcurrent;
    unsigned int   size;                  /* size of buffer in bytes           */
    unsigned int   remaining_bytes;
    sector_t       start_sector;          /* starting disk sector #            */
    unsigned int   sectors;               /* remaining sectors in this request */
};

struct gather_t       /* gather buffer for WRITE requests */
{
    char         * buf;                   /* starting address              */
    char         * free;                  /* free part fo the buffer       */
    unsigned int   size;                  /* size of buffer in bytes       */
    unsigned int   free_bytes;            /* remaining free space in bytes */
    sector_t       start_sector;          /* starting disk sector #        */
};




/*
 * global vars
 */
int  write_requests = 0;




/*
 * static routines
 */
static int  /* __init */ __tffs_module_init (void);
static void /* __init */ init_socket (SocketInfo *psoc);
static void /* __init */ init_disk (DeviceInfo *pdisk);
static void /* __exit */ release_socket (SocketInfo *psoc);
static void /* __exit */ release_disk (DeviceInfo * pdisk);
static void cleanup (int STEP);

static void disk_request_queue_handler (request_queue_t *q);
static int  socket_io_thread (void *arg);
static int  requests_to_do (SocketInfo *psoc);
static void do_requests_list (SocketInfo *psoc);
static int  do_write_request (struct request *r);
static int  do_read_request (struct request *r);
static int  rw_bio_no_sg (struct bio *bio, DeviceInfo *pdisk, int rw);
static int  write_bio (struct bio *bio, struct gather_t *gather, DeviceInfo *pdisk);
static int  read_bio (struct bio *bio, struct scatter_t *scatter, DeviceInfo *pdisk);

static int  disk_open (struct inode *inode, struct file *filp);
static int  disk_close (struct inode *inode, struct file *filp);
static int  disk_ioctl (struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg);

static irqreturn_t  interrupt_handler (int irq, void *psoc, struct pt_regs *regs);

#ifdef CONFIG_PROC_FS
  static int /* __init */ procfs_register (DeviceInfo *pdisk);
  static int /* __exit */ procfs_unregister (DeviceInfo *pdisk);
  static int procfs_write (struct file* file, const char* buffer, unsigned long count, void* data);
  static int procfs_read (char* buffer, char** start, off_t offset, int length, int* eof, void* data);
#endif




/*
 * static vars
 */
static struct semaphore  open_close_mutex;  /* used to serialize disk open/close calls */

static char  tffs_str[] = TFFS_DEVICE_NAME;

static struct block_device_operations  tffs_bdev_ops =
{
    .open    = disk_open,
    .release = disk_close,
    .ioctl   = disk_ioctl,
    .owner   = THIS_MODULE
};

/* for tracking enabled/disabled state of IRQ that DiskOnChip is connected to */
static spinlock_t __irq_lock = SPIN_LOCK_UNLOCKED;
#if defined(CONFIG_ARCH_OMAP24XX) || defined(CONFIG_ARCH_MAINSTONE) || defined(CONFIG_MACH_MAINSTONE)
  static int __irq_enabled = TRUE;
#else
  static int __irq_enabled = FALSE;
#endif




/*******************************************************************************
 *                                                                             *
 *                     t f f s _ m o d u l e _ i n i t                         *
 *                                                                             *
 *  Module initialization routine.                                             *
 *                                                                             *
 *  Parameters: none                                                           *
 *                                                                             *
 *  Returns: zero if success, otherwise standard negative error code           *
 *                                                                             *
 *******************************************************************************/

int  /* __init */ tffs_module_init (void)
{
# ifdef TRACE32   /* needed for section relocation in TRACE32 */
    extern int       trace32_data;
    extern int       trace32_bss;
    extern const int trace32_rodata;
    printk ("\n\nTRACE32 section relocation: .data=0x%lx .bss=0x%lx .rodata=0x%lx\n\n",
               (long)(&trace32_data), (long)(&trace32_bss), (long)(&trace32_rodata));
# endif

    return __tffs_module_init();
}

module_init(tffs_module_init);




/*******************************************************************************
 *                                                                             *
 *                     t f f s _ m o d u l e _ e x i t                         *
 *                                                                             *
 *  Module cleanup and routine; called when module is unloaded.                *
 *                                                                             *
 *  Parameters: none                                                           *
 *                                                                             *
 *******************************************************************************/

void /* __exit */ tffs_module_exit (void)
{
    cleanup (100);
}

module_exit(tffs_module_exit);




/*******************************************************************************
 *                                                                             *
 *                    _ _ t f f s _ m o d u l e _ i n i t                      *
 *                                                                             *
 *  Initialize DiskOnChip driver.                                              *
 *                                                                             *
 *  Parameters: none                                                           *
 *                                                                             *
 *  Returns: zero if success, otherwise standard negative error code           *
 *                                                                             *
 *******************************************************************************/
static
int /* __init */ __tffs_module_init (void)
{
    int  STEP, iSoc, tmp;

    STEP = 0;

    PrintkInfo ("mDOC driver %s.%d", TrueFFSVersion, TFFS_DRV_VER);

    memset (tffsInfo.sockets, 0, sizeof(tffsInfo.sockets));

    for (iSoc = 0; iSoc < FL_SOCKETS; iSoc++)
    {
        init_completion (&tffsInfo.sockets[iSoc].wait_for_irq); /* sema_init (&tffsInfo.sockets[iSoc].sleep_sem, 0); */

        init_waitqueue_head (&tffsInfo.sockets[iSoc].waitQueueHead);
    }

    STEP++;  /* 1 */

    /* if requested, install handler for DiskOnChip interrupts */
    if (tffs_irq >= 0)
    {
        if( request_irq(tffs_irq, interrupt_handler, 0 /* SA_INTERRUPT */,
                                        tffs_str, &tffsInfo.sockets[0]) == 0 )
        {
            tffs_irq_disable (TRUE);

            PrintkInfo ("use IRQ %d", tffs_irq);
        }
        else /* can't install interrupt handler, won't use IRQ */
        { 
            PrintkWarning ("failed to get IRQ %d", tffs_irq);
            tffs_irq = -1;
        }
    }
    else { PrintkInfo ("will not use IRQ"); }

    STEP++;  /* 2 */

    /* Find all DiskOnChip sockets, find out how many disks are on
     * each socket, and abs.mount each disk.
     */
    if( TffsInit() <= 0 )
    {
        PrintkError ("No DiskOnChips found");
        return -ENODEV;
    }

    STEP++;  /* 3 */

    if (tffs_irq >= 0)
    {
        /* enable interrupt generation in DiskOnChip */
        TffsEnableIRQ (&tffsInfo.sockets[0]);
    }

    STEP++;  /* 4 */

    /* Register our major device # (or accept dynamically allocated
     * major #).
     */
    if ((tmp = register_blkdev(tffs_major, tffs_str)) < 0)
    {
        PrintkError ("Can't get major %d", tffs_major);
        cleanup (STEP);
        return -EBUSY;
    }
    if (tffs_major == 0)  /* we asked for dynamic major #, and we got it */
        tffs_major = tmp;
    PrintkInfo ("use major device number %d", tffs_major);

    STEP++; /* 5 */

#ifdef CONFIG_PROC_FS
    if ((tffsInfo.pProcDir = proc_mkdir(tffs_str, NULL)) == NULL)
        { PrintkWarning ("Can't create /proc/%s", tffs_str); }
#endif

    STEP++; /* 6 */

    /* initialize Open/Close mutex in "available" state */
    sema_init (&open_close_mutex, 1);

    /* init sockets */
    for (iSoc = 0; iSoc < FL_SOCKETS; iSoc++)
        init_socket (&tffsInfo.sockets[iSoc]);

    STEP++; /* 7 */

#ifdef CONFIG_PM
    tffs_pm_init ();   /* register with Power Manager */
#endif

    STEP++; /* 8 */

    return 0;
}




/*******************************************************************************
 *                                                                             *
 *                         i n i t _ s o c k e t                               *
 *                                                                             *
 *  Initialize socket's I/O thread and all socket's disks.                     *
 *                                                                             *
 *  Parameters:                                                                *
 *        psoc      pointer to socket being initialized                        *
 *                                                                             *
 *******************************************************************************/
static 
void /* __init */ init_socket ( SocketInfo * psoc )
{
    int  iDisk;

    if (psoc->fFound == 0)
        return;

    init_completion (&psoc->wait_for_io_thread); /* sema_init (&psoc->threadSemaphore, 0); */

    /* Tell I/O thread to wake us up once it gets up and running */
    psoc->io_thread_state = 2;

    /* start socket's I/O thread */
    kernel_thread (socket_io_thread, (void *)psoc, 0);

    /* wait until socket's I/O thread is up and running */
    wait_for_completion (&psoc->wait_for_io_thread); /* down_interruptible (&psoc->threadSemaphore); */

    /* socket's I/O thread has been started, and is currently waiting for
     * I/O requests to be posted to psoc->waitQueueHead.
     */
    for (iDisk = 0; iDisk < psoc->wDevices; iDisk++)
        init_disk (&psoc->pDevices[iDisk]);
}




/*******************************************************************************
 *                                                                             *
 *                         i n i t _ d i s k                                   *
 *                                                                             *
 *  Initialize individual disk.  s).                                           *
 *                                                                             *
 *  Parameters:                                                                *
 *        pdisk     pointer to disk                                            *
 *                                                                             *
 *******************************************************************************/
static 
void /* __init */ init_disk ( DeviceInfo * pdisk )
{
    struct gendisk * gd;
    int              max_partitions;

    /* nobody has opened this disk yet */
    pdisk->in_use = 0;

#ifdef TFFS_STATISTIC
    memset (&pdisk->stat, 0, sizeof(pdisk->stat));
#endif

#ifdef CONFIG_PROC_FS
    procfs_register (pdisk);
#endif

    /* allocate request queue for this disk */
    spin_lock_init (&pdisk->rq_lock);

    pdisk->rq = blk_init_queue (disk_request_queue_handler, &pdisk->rq_lock);
    if (pdisk->rq == NULL)
    {
        PrintkError ("blk_init_queue() failed for disk 0x%x", pdisk->bHandle);
        return;
    }
    else
        pdisk->rq->queuedata = pdisk;

    /* Maximum number of file system partitions that we allow
     * on the disk (this doesn't include "raw" disk).
     */
    max_partitions = ((1 << DEV2PART_SHIFT) - 1);

    /* allocate struct gendisk for this disk */
    if ((gd = alloc_disk(max_partitions)) == NULL)
    {
        /* return previously allocated request queue to the system */
        blk_cleanup_queue (pdisk->rq);
        pdisk->rq = NULL;

        PrintkError ("alloc_disk() failed for disk 0x%x", pdisk->bHandle);
        return;
    }
    else
        pdisk->gd = gd;

    gd->major        = tffs_major;
    gd->first_minor  = (pdisk->diskNo * (max_partitions + 1/*"raw" disk entry*/)); 
    gd->fops         = &tffs_bdev_ops;
    gd->queue        = pdisk->rq;
    gd->private_data = pdisk;

    /* name this disk */
    snprintf (gd->disk_name, sizeof(gd->disk_name), "%s%c", 
                        tffs_str, ('a' + (char)(pdisk->diskNo)));

    /* specify disk's capacity in 512-byte sectors */
    set_capacity (gd, pdisk->dwSize);

    /* Tell kernel about this disk. Before add_disk() returns,
     * kernel will attempt to read Master Boot Record and parse
     * partition table(s) on this disk; it will post I/O requests
     * to pdisk->rq, and call disk_request_queue_handler()
     * to handle these request.
     */
    add_disk (gd);
}




/*******************************************************************************
 *                                                                             *
 *                              c l e a n u p                                  *
 *                                                                             *
 *  Free all data structures alocated during driver's startup.                 *
 *                                                                             *
 *  Parameters:                                                                *
 *       STEP            specifies which resources to free                     *
 *                                                                             *
 *  Returns: void                                                              *
 *                                                                             *
 *******************************************************************************/
static 
void  cleanup ( int STEP )
{
    int iSoc;

    if (STEP >= 8)
    { 
#ifdef CONFIG_PM
        tffs_pm_exit ();    /* unregister from Power Manager */
#endif
    }

    if (STEP >= 7)
    { 
        /* For every socket, flush all socket's disks, and sleep until socket's
         * I/O thread handled all outstanding I/O requests and exited.
         */
        for (iSoc = 0; iSoc < FL_SOCKETS; iSoc++)
        {
            if (tffsInfo.sockets[iSoc].fFound != 0)
                release_socket (&tffsInfo.sockets[iSoc]);
        }
    }

    if (STEP >= 6)
    {
#ifdef CONFIG_PROC_FS
        remove_proc_entry (tffs_str, NULL);
        tffsInfo.pProcDir = NULL;
#endif
    }

    if (STEP >= 5)
    { 
        unregister_blkdev (tffs_major, tffs_str);
    }

    if (STEP >= 4)
    {
        /* disable_irq (tffs_irq); */

        /* We should tell DiskOnChip to disable interrupt generation, but
         * unfortunately TrueFFS currently doesn't provide API for that.
         */
    }

    if (STEP >= 3)
    {
        /* For all disks of all DiskOnChip sockets, write Quick Mount
         * records to them, abs.unmount them, and shut down TrueFFS.
         */
        TffsCleanup ();
    }

    if (STEP >= 2)
    {
        /* if previously installed, remove DiskOnChip interrupt handler */
        if (tffs_irq >= 0)
            free_irq (tffs_irq, &tffsInfo.sockets[0]);
    }
}




/*******************************************************************************
 *                                                                             *
 *                      r e l e a s e _ s o c k e t                            *
 *                                                                             *
 *  Release DiskOnChip socket.                                                 *
 *                                                                             *
 *  Parameters:                                                                *
 *        psoc      pointer to socket being released                           *
 *                                                                             *
 *  Returns: void                                                              *
 *                                                                             *
 *******************************************************************************/
static 
void /* __exit */ release_socket ( SocketInfo * psoc )
{
    int iDisk;

    if (psoc->fFound == 0)
        return;

    /* Release all socket's disks; this involves flushing all partitions
     * on all these disks.
     */
    for (iDisk = 0; iDisk < psoc->wDevices; iDisk++)
        release_disk (&psoc->pDevices[iDisk]);

    if (psoc->io_thread_state == 1)  /* I/O thread is running */
    {
        init_completion (&psoc->wait_for_io_thread);

        /* Tell I/O thread to complete handling of all outstanding I/O requests,
         * wake us up, and exit.
         */
        psoc->io_thread_state = 2;

        /* in case socket's I/O thread is currently sleeping, wake it up */
        wake_up (&psoc->waitQueueHead);

        /* now wait for I/O thread to exit */
        wait_for_completion (&psoc->wait_for_io_thread); /* down_interruptible (&psoc->threadSemaphore); */
    }
}




/*******************************************************************************
 *                                                                             *
 *                      r e l e a s e _ d i s k                                *
 *                                                                             *
 *  Release disk.                                                              *
 *                                                                             *
 *  Parameters:                                                                *
 *        pdisk      pointer to disk being released                            *
 *                                                                             *
 *  Returns: void                                                              *
 *                                                                             *
 *******************************************************************************/
static
void /* __exit */ release_disk (DeviceInfo * pdisk)
{
    if (pdisk->gd != NULL)
    {
        del_gendisk (pdisk->gd);
        pdisk->gd = NULL;
    }

    if (pdisk->rq != NULL)
    {
        blk_cleanup_queue (pdisk->rq);
        pdisk->rq = NULL;
    }

#ifdef CONFIG_PROC_FS
    procfs_unregister (pdisk);
#endif
}




/*******************************************************************************
 *                                                                             *
 *                             d i s k _ o p e n                               *
 *                                                                             *
 *  Open disk (i.e. block_device_operations.open()).                           *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       inode          inode pointer                                          *
 *       filp           file pointer                                           *
 *                                                                             *
 *  Returns: zero if success, otherwise negative error code                    *
 *                                                                             *
 *******************************************************************************/
static
int  disk_open ( struct inode * inode, 
                 struct file  * filp )
{
    int              rc    = 0;          /* assume success */
    struct gendisk * gd    = inode->i_bdev->bd_disk;
    DeviceInfo     * pdisk = (DeviceInfo *) gd->private_data;

    if (pdisk == NULL)
        return -ENODEV;

    /* one Open/Close at a time */
    if( down_interruptible(&open_close_mutex) != 0 )
        return -ERESTARTSYS;   /* wait was interrupted by signal */

    /* can't open write-protected disk for writing */
    if (filp->f_mode & O_RDWR)
    {
#ifndef TFFS_RO
        if( TffsIsWriteProtected(pdisk) )
#endif
        { 
            rc = -EROFS;   goto quit;
        }
    }

    if (pdisk->in_use == 0)
    {
        if( TffsOpenDevice(pdisk) == 0 )
        {
            PrintkError("Open() failed on %s(0x%x)", gd->disk_name, pdisk->bHandle);

            rc = -ENODEV;  goto quit;
        }
    }

    /* success opening this disk */
    filp->private_data = pdisk;

    /* one more user for this device, as well as for DiskOnChip driver */
    pdisk->in_use++;

 quit:

    /* allow other Open/Close calls to proceed */
    up (&open_close_mutex);

    return rc;
}




/*******************************************************************************
 *                                                                             *
 *                            d i s k _ c l o s e                              *
 *                                                                             *
 *  Release disk (i.e. block_device_operations.release()).                     *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       inode          inode pointer                                          *
 *       filp           file pointer (could be NULL)                           *
 *                                                                             *
 *  Returns: zero if success, otherwise negative error code                    *
 *                                                                             *
 *******************************************************************************/
static
int  disk_close ( struct inode * inode, 
                  struct file  * filp )
{
    struct gendisk * gd    = inode->i_bdev->bd_disk;
    DeviceInfo     * pdisk = (DeviceInfo *) gd->private_data;

    /* one Open/Close at a time */
    if( down_interruptible(&open_close_mutex) != 0 )
        return -ERESTARTSYS;   /* wait was interrupted by signal */

    if (--pdisk->in_use == 0)  /* last user had just closed this disk */
    {
        if( TffsCloseDevice(pdisk) == 0 )
        { 
            PrintkDebug("Release() failed on %s(0x%x)", gd->disk_name, pdisk->bHandle);
        }
    }

    /* allow other Open/Close calls to proceed */
    up (&open_close_mutex);

    return 0;
}




/*******************************************************************************
 *                                                                             *
 *                             d i s k _ i o c t l                             *
 *                                                                             *
 *  Handle IOCTLs to disk (i.e. device_operations.ioctl()).                    *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       inode          inode pointer                                          *
 *       filp           file pointer (could be NULL)                           *
 *       cmd            IOCTL command                                          *
 *       arg            argument to IOCTL command                              *
 *                                                                             *
 *  Returns: zero if success, otherwise negative error code                    *
 *                                                                             *
 *******************************************************************************/
static 
int disk_ioctl ( struct inode * inode,
                 struct file  * filp,
                 unsigned int   cmd,
                 unsigned long  arg )
{
    struct gendisk * gd    = inode->i_bdev->bd_disk;
    DeviceInfo     * pdisk = (DeviceInfo *) gd->private_data;
    int              rc    = -ENOTTY;

    /* sanity check */
    if ((filp != NULL) && (filp->private_data != pdisk))
        return -ENODEV;

    if (cmd >= SIOCDEVPRIVATE) /* driver specific (TrueFFS) IOCTL code */
    {
        rc = TffsIoctl (pdisk, (cmd - SIOCDEVPRIVATE), arg);

        if (rc < 0)
            PrintkError("ioctl=0x%x error=0x%x on %s", cmd, rc, gd->disk_name);

        if (rc == 1)   /* unrecognized TrueFFS IOCTL code */
            rc = -ENOTTY;
    }
    else   /* standard Linux IOCTL code */
    {
        switch (cmd)
        {
            case HDIO_GETGEO:
            {
                struct hd_geometry geo;

                geo.heads     = pdisk->bHead;
                geo.sectors   = pdisk->bSect;
                geo.cylinders = pdisk->wCyl;
                geo.start     = get_start_sect (inode->i_bdev);

                if ((void *)arg == NULL)
                    { rc = -EINVAL;  break; }

                if( !access_ok(VERIFY_WRITE, (void *)arg, sizeof(geo)))
                    { rc = -EFAULT;  break; }

                if( copy_to_user((void *)arg, &geo, sizeof(geo)) != 0 )
                    { rc = -EFAULT;  break; }

                rc = 0;   /* success */
            }
            break;

            default:      /* unknown Linux IOCTL code */
            {
                PrintkError("unknown ioctl=0x%x on %s", cmd, gd->disk_name);
            }
        }
    }

    return rc;
}




/*******************************************************************************
 *                                                                             *
 *                     i n t e r r u p t _ h a n d l e r                       *
 *                                                                             *
 *  DiskOnChip interupt handler.                                               *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       irq            not used                                               *
 *       psoc           socket pointer                                         *
 *       regs           not used                                               *
 *                                                                             *
 *  Returns: always IRQ_HANDLED                                                *
 *                                                                             *
 *******************************************************************************/
static 
irqreturn_t  interrupt_handler ( int              irq,    /* not used */
                                 void           * psoc, 
                                 struct pt_regs * regs )  /* not used */
{
    tffs_irq_disable (FALSE);

    profiling[1]++;

    /* wake up socket's I/O thread */
    complete (&((SocketInfo *)psoc)->wait_for_irq); /* up (&((SocketInfo *)psoc)->sleep_sem); */
    return IRQ_HANDLED;
}




/*******************************************************************************
 *                                                                             *
 *                     t f f s _i r q _ e n a b l e                            *
 *                                                                             *
 *  Enable IRQ that DiskOnChip is connected to.                                *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       lock           if TRUE, use __irq_lock; otherwise don't               *
 *                                                                             *
 *******************************************************************************/
void tffs_irq_enable (int lock)
{
    unsigned long flags;

    if (lock == TRUE)
        spin_lock_irqsave (&__irq_lock, flags);

    if (__irq_enabled == FALSE)
    {
        __irq_enabled = TRUE;

        enable_irq (tffs_irq);

#ifdef CONFIG_ARCH_OMAP24XX
        omap24xx_enable_gpio_irq (tffs_irq, TRUE);
#endif
    }

    if (lock == TRUE)
        spin_unlock_irqrestore (&__irq_lock, flags);
}



/*******************************************************************************
 *                                                                             *
 *                     t f f s _i r q _ d i s a b l e                          *
 *                                                                             *
 *  Disable IRQ that DiskOnChip is connected to.                               *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       lock           if TRUE, use __irq_lock; otherwise don't               *
 *                                                                             *
 *******************************************************************************/
void tffs_irq_disable (int lock)
{
    unsigned long flags;

    if (lock == TRUE)
        spin_lock_irqsave (&__irq_lock, flags);

    if (__irq_enabled == TRUE)
    {
        __irq_enabled = FALSE;

#ifdef CONFIG_ARCH_OMAP24XX
        omap24xx_enable_gpio_irq (tffs_irq, FALSE);
#endif

        disable_irq (tffs_irq);
    }

    if (lock == TRUE)
        spin_unlock_irqrestore (&__irq_lock, flags);
}




/*******************************************************************************
 *                                                                             *
 *              d i s k _ r e q u e s t _ q u e u e _ h a n d l e r            *
 *                                                                             *
 *  This routine implements request handling function for per-disk request     *
 *  queue. It's called by generic_unplug_device (drivers/block/ll_rw_block.c)  *
 *  with request queue's lock held, and both hardware and software interrupts  *
 *  disabled (so it must be fast).                                             *
 *                                                                             *
 *  Parameters:                                                                *
 *      q           disk's request queue                                       *
 *                                                                             *
 *******************************************************************************/
static
void  disk_request_queue_handler (request_queue_t * q)
{
    struct request * r;
    SocketInfo     * psoc;
    DeviceInfo     * pdisk;
    int              lock_taken = FALSE;

    /* we run with hardware and software interrupts disabled */

    while ((r = elv_next_request(q)) != NULL)
    {
        /* take this request off disk's request queue */
        blkdev_dequeue_request (r);

        if (lock_taken == FALSE)
        {
            pdisk = r->rq_disk->private_data;
            psoc  = pdisk->pSocket;

            spin_lock (&psoc->request_list_lock);
            lock_taken = TRUE;
        }

        /* Append this request to socket's request list. Socket's
         * I/O thread will take it from there, handle it, and cycle
         * it back to this queue.
         */
        list_add_tail (&r->queuelist, &psoc->requestsList);
    }

    if (lock_taken == TRUE)
    {
        spin_unlock (&psoc->request_list_lock);

        /* in case socket's I/O thread is currently sleeping, wake it up */
        wake_up (&psoc->waitQueueHead);
    }
}




/*******************************************************************************
 *                                                                             *
 *                         s o c k e t _ i o _ t h r e a d                     *
 *                                                                             *
 *  This routine implements per-socket I/O thread. It runs as a kernel thread, *
 *  and processes I/O requests that disk_request_queue_handler() put to        *
 *  socket's request list. This routine can (and often does) sleep.            *
 *                                                                             *
 *  Parameters:                                                                *
 *      arg         socket pointer                                             *
 *                                                                             *
 *******************************************************************************/
static
int socket_io_thread (void * arg) 
{
    SocketInfo * psoc = (SocketInfo *) arg;
    char         name[32];

    current->flags |= (PF_MEMALLOC | PF_NOFREEZE);

    sprintf (name, "%s%c", tffs_str, '0' + (char)psoc->bHandle);
    daemonize (name);

    /* we don't want to receive any signals */
    spin_lock_irq (&current->sighand->siglock);
    sigfillset (&current->blocked);
    recalc_sigpending ();
    spin_unlock_irq (&current->sighand->siglock);

    /* adjist thread's priority if necessary */
    if (tffs_prio != 0)
        set_user_nice (current, tffs_prio);

    /* initially socket's request list is empty */
    spin_lock_init (&psoc->request_list_lock);
    INIT_LIST_HEAD (&psoc->requestsList);

    /* If somebody is waiting for socket's I/O thread to start up and 
     * get ready for processing I/O requests, let them know that we did.
     */
    if (psoc->io_thread_state == 2)
        complete (&psoc->wait_for_io_thread); /* up (&psoc->threadSemaphore); */

    /* socket's I/O thread is ready to receive I/O requests */
    psoc->io_thread_state = 1;

    while (psoc->io_thread_state == 1)
    {
        /* wait 5 clock ticks for I/O requests to arrive */
        wait_event_interruptible_timeout (psoc->waitQueueHead, requests_to_do(psoc), 5);

        /* handle all I/O requests (if any) in socket's request ist */
        do_requests_list (psoc);
    }

    /* If somebody is waiting for socket's I/O thread to terminate, 
     * let them know that it did.
     */
    if (psoc->io_thread_state == 2)
        complete (&psoc->wait_for_io_thread); /* up (&psoc->threadSemaphore); */

    /* socket's I/O thread terminated */
    psoc->io_thread_state = 0;

    return 0;
}




/*******************************************************************************
 *                                                                             *
 *                      d o _ r e q u e s t s _ l i s t                        *
 *                                                                             *
 *  This routine handles all requests in socket's request list.                *
 *                                                                             *
 *  Parameters:                                                                *
 *      psoc        socket pointer                                             *
 *                                                                             *
 *******************************************************************************/
static
void  do_requests_list ( SocketInfo * psoc )
{
    struct request * r;
    struct gendisk * gd;
    DeviceInfo     * pdisk;
    unsigned long    flags;

    /* lock socket's request list */
    spin_lock_irqsave (&psoc->request_list_lock, flags);

    /* if socket's request list isn't empty, process all requests there */
    while( !(list_empty(&psoc->requestsList)) )
    {
        /* take next request off socket's request list */
        r = list_entry_rq (psoc->requestsList.next);
        list_del_init (&r->queuelist);

        /* unlock socket's request list */
        spin_unlock_irqrestore (&psoc->request_list_lock, flags);

        /* Mark all non-filesystem request, and those filesystem requests
         * that don't pass sanity check, as not-uptodate (i.e. failed).
         */
        if( !blk_fs_request(r)                                ||
            ((gd = r->rq_disk) == NULL)                       ||
            ((pdisk = gd->private_data) == NULL)              ||
            (pdisk->gd != gd)                                 ||
            (r->sector + r->nr_sectors > pdisk->dwSize)
          )
        {
            end_that_request_first (r, /* failed */ 0, r->hard_cur_sectors);
        }
        else  /* legitimate filesystem request; handle it */
        {
            if (rq_data_dir(r) == WRITE)
            {
                write_requests++;

                do_write_request (r);
            }
            else  /* READ request */
            {
                do_read_request (r);
            }
        }

        /* mark this request as done */
        spin_lock_irqsave (&pdisk->rq_lock, flags);      /* spin_lock (&pdisk->rq_lock);   */

#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16))
        end_that_request_last (r, /* success */ 1);
#else
        end_that_request_last (r);
#endif

        spin_unlock_irqrestore (&pdisk->rq_lock, flags); /* spin_unlock (&pdisk->rq_lock); */

        /* lock socket's request list */
        spin_lock_irqsave (&psoc->request_list_lock, flags);
    }

    /* unlock socket's request list */
    spin_unlock_irqrestore (&psoc->request_list_lock, flags);
}




/*******************************************************************************
 *                                                                             *
 *                       d o _ w r i t e _ r e q u e s t                       *
 *                                                                             *
 *  This routine handles single WRITE request.                                 *
 *                                                                             *
 *  Parameters:                                                                *
 *      psoc        socket pointer                                             *
 *                                                                             *
 *  Returns:                                                                   *
 *      zero if I/O error was encountered, otherwise '1'.                      *
 *                                                                             *
 *******************************************************************************/
static
int  do_write_request ( struct request  * r )
{
    DeviceInfo     * pdisk = (DeviceInfo *) r->rq_disk->private_data;
    struct bio     * bio;
    struct gather_t  gather;
    unsigned long    total_sectors = r->nr_sectors;
    int              success = 1;

    /* in case we are going to use gather buffer, mark it as empty */
    if ((tffs_sg_bufsize > 0) && (tffs_sg_write != FALSE))
    {
        gather.buf          = 
        gather.free         = pdisk->pSocket->pCache;
        gather.size         =
        gather.free_bytes   = tffs_sg_bufsize;

        /* first disk sector # for this request */
        gather.start_sector = r->sector;
    }

    /* do all bio's of this request */
    rq_for_each_bio (bio, r)
    {
        if( write_bio(bio, &gather, pdisk) < 0)
            success = 0;     /* I/O error */
    }

    /* flush remaining data (if any) from gather buffer to disk */    
    if ((tffs_sg_bufsize > 0) && (tffs_sg_write != FALSE)
                              && (gather.free > gather.buf))
    {
        int ns = ((gather.free - gather.buf) >> 9); /* remaining sectors in buf */

        if( TffsWrite (pdisk, gather.buf, gather.start_sector, ns) == 0 )
            success = 0;    /* I/O error */
    }

    /* Note that if we encountered I/O error in the middle of 
     * request processing, we mark the entire request as failed.
     * Not very smart but hopefully will do for now ...
     */
    end_that_request_first (r, success, total_sectors);

    return success;
}




/*******************************************************************************
 *                                                                             *
 *                       d o _ r e a d  _ r e q u e s t                        *
 *                                                                             *
 *  This routine handles single READ request.                                  *
 *                                                                             *
 *  Parameters:                                                                *
 *      psoc        socket pointer                                             *
 *                                                                             *
 *  Returns:                                                                   *
 *      zero if I/O error was encountered, otherwise '1'.                      *
 *                                                                             *
 *******************************************************************************/
static
int  do_read_request ( struct request  * r )
{
    DeviceInfo      * pdisk = (DeviceInfo *) r->rq_disk->private_data;
    struct bio      * bio;
    struct scatter_t  scatter;
    unsigned long     total_sectors = r->nr_sectors;
    int               success = 1;

    /* read in data from disk into scatter buffer */
    if ((tffs_sg_bufsize > 0) && (tffs_sg_read != FALSE))
    {
        int  ns = _MIN(r->nr_sectors, (tffs_sg_bufsize >> 9));

        scatter.buf  = pdisk->pSocket->pCache;
        scatter.size = tffs_sg_bufsize;

        if( TffsRead (pdisk, scatter.buf, r->sector, ns) == 0 )
        {
            success = 0;   /* I/O error */
            goto out;
        }

        scatter.pcurrent        = scatter.buf;
        scatter.remaining_bytes = (ns << 9);
        scatter.sectors         = r->nr_sectors - ns;
        scatter.start_sector    = r->sector + ns;
    }

    /* do all bio's of this request */
    rq_for_each_bio (bio, r)
    {
        if( read_bio(bio, &scatter, pdisk) < 0)
            success = 0;    /* I/O error */
    }

out:

    /* Note that if we encountered I/O error in the middle of 
     * request processing, we mark the entire request as failed.
     * Not very smart but hopefully will do for now ...
     */
    end_that_request_first (r, success, total_sectors);

    return success;
}




/*******************************************************************************
 *                                                                             *
 *                             w r i t e _ b i o                               *
 *                                                                             *
 *  This routine handles single 'struct bio' WRITE operation using gather      *
 *  buffer.                                                                    *
 *                                                                             *
 *  Parameters:                                                                *
 *      bio          pointer to 'struct bio' to WRITE                          *
 *      gather       pointer to gather buffer                                  *
 *      pdisk        disk pointer                                              *
 *                                                                             *
 *  Returns:                                                                   *
 *      zero if success otherwise -EIO negative error code                     *
 *                                                                             *
 *******************************************************************************/
static
int  write_bio ( struct bio      * bio, 
                 struct gather_t * gather, 
                 DeviceInfo      * pdisk )
{
    struct bio_vec * bv;
    int              i, rc = 0;

    if ((tffs_sg_bufsize == 0) || (tffs_sg_write == FALSE))
    {
        /* we don't use gather buffer; do one I/O segment at a time */
        rc = rw_bio_no_sg (bio, pdisk, WRITE);
    }
    else /* use gather buffer */
    {
        bio_for_each_segment (bv, bio, i)
        {
            unsigned int   n  = bv->bv_len; /* bytes in this I/O segment */
            char         * p;

            /* If segment's page resides in high memory, map it into
             * kernel's address space temporarily.
             */
            if (PageHighMem(bv->bv_page))
                p = kmap (bv->bv_page) + bv->bv_offset;
            else  /* segment's page resides in low memory */
                p = page_address (bv->bv_page) + bv->bv_offset;

            for (; n >= gather->free_bytes; )
            {
                /* This I/O segment won't fit into the remaining space in
                 * gather buffer. Copy the part that does fit into gather
                 * buffer (making it full), then flush entire gather buffer
                 * to disk.
                 */
                if (gather->free_bytes > 0)
                {
                    memcpy (gather->free, p, gather->free_bytes);

                    p += gather->free_bytes;
                    n -= gather->free_bytes;
                }

                /* flush entire gather buffer to disk */
                if( TffsWrite (pdisk, gather->buf, gather->start_sector,
                                                     (gather->size >> 9)) == 0 )
                    rc = -EIO;    /* I/O error */

                /* gather buffer is empty */
                gather->free          = gather->buf;
                gather->free_bytes    = gather->size;
                gather->start_sector += (gather->size >> 9);
            }

            /* remaining part of this segment fits into gather buffer */
            if (n > 0)
            {
                memcpy (gather->free, p, n);

                gather->free       += n;
                gather->free_bytes -= n;
            }

            /* If segment's page resides in high memory, cancel
             * previously established mapping.
             */
            if (PageHighMem(bv->bv_page))
                kunmap (bv->bv_page);
        }
    }

    return rc;
}




/*******************************************************************************
 *                                                                             *
 *                             r e a d  _ b i o                                *
 *                                                                             *
 *  This routine handles single 'struct bio' READ operation using scatter      *
 *  buffer.                                                                    *
 *                                                                             *
 *  Parameters:                                                                *
 *      bio          pointer to 'struct bio' to WRITE                          *
 *      scatter      pointer to scatter buffer                                 *
 *      pdisk        disk pointer                                              *
 *                                                                             *
 *  Returns:                                                                   *
 *      zero if success otherwise -EIO negative error code                     *
 *                                                                             *
 *******************************************************************************/
static
int  read_bio ( struct bio       * bio, 
                struct scatter_t * scatter, 
                DeviceInfo       * pdisk )
{
    struct bio_vec * bv;
    int              i, rc = 0;

    if ((tffs_sg_bufsize == 0) || (tffs_sg_read == FALSE))
    {
        /* we don't use scatter buffer; do one I/O segment at a time */
        rc = rw_bio_no_sg (bio, pdisk, READ);
    }
    else  /* use gather buffer */
    {
        bio_for_each_segment (bv, bio, i)
        {
            unsigned int   n  = bv->bv_len; /* bytes in this I/O segment */
            unsigned int   ns;
            char         * p;

            /* If segment's page resides in high memory, map it into
             * kernel's address space temporarily.
             */
            if (PageHighMem(bv->bv_page))
                p = kmap (bv->bv_page) + bv->bv_offset;
            else  /* segment's page resides in low memory */
                p = page_address (bv->bv_page) + bv->bv_offset;

            for (; n >= scatter->remaining_bytes; )
            {
                /* This I/O segment is larger then number of remaining bytes
                 * in scatter buffer. Copy all these remaining bytes (making
                 * scatter buffer empty), then re-fill scatter buffer from disk.
                 */
                if (scatter->remaining_bytes > 0)
                {
                    memcpy (p, scatter->pcurrent, scatter->remaining_bytes);

                    p += scatter->remaining_bytes;
                    n -= scatter->remaining_bytes;
                }

                /* scatter buffer is empty now */
                scatter->remaining_bytes = 0;
                scatter->pcurrent        = scatter->buf;

                /* end of this request ? */
                if ((ns = _MIN(scatter->sectors, (tffs_sg_bufsize >> 9))) == 0)
                    break;

                /* re-fill scatter buffer from disk */
                if( TffsRead (pdisk, scatter->buf, scatter->start_sector, ns) == 0 )
                    rc = -EIO;    /* I/O error */

                scatter->remaining_bytes  = (ns << 9);
                scatter->sectors         -= ns;
                scatter->start_sector    += ns;
            }

            /* Remaining part of this segment can be entirely taken
             * from the scatter buffer.
             */
            if (n > 0)
            {
                memcpy (p, scatter->pcurrent, n);

                scatter->pcurrent        += n;
                scatter->remaining_bytes -= n;
            }

            /* If segment's page resides in high memory, cancel
             * previously established mapping.
             */
            if (PageHighMem(bv->bv_page))
                kunmap (bv->bv_page);
        }
    }

    return rc;
}




/*******************************************************************************
 *                                                                             *
 *                       r w _ b i o _ n o _ s g                               *
 *                                                                             *
 *  This routine handles single 'struct bio' without using scatter/gather      *
 *  buffers. It issues TrueFFS I/O call for each segment of this 'struct bio'. *
 *                                                                             *
 *  Parameters:                                                                *
 *      bio          pointer to 'struct bio' to handle                         *
 *      pdisk        disk pointer                                              *
 *      rw           READ or WRITE                                             *
 *                                                                             *
 *  Returns:                                                                   *
 *      zero if success otherwise -EIO negative error code                     *
 *                                                                             *
 *******************************************************************************/
static
int  rw_bio_no_sg ( struct bio * bio, 
                    DeviceInfo * pdisk,
                    int          rw )
{
    sector_t         sector = bio->bi_sector;  /* starting disk sector for this bio */
    struct bio_vec * bv;
    char           * p;
    int              i, rc = 0;
    unsigned int     ns;

    bio_for_each_segment (bv, bio, i)
    {
        if ((ns = (bv->bv_len >> 9)) > 0)   /* sectors in this segment */
        {
            /* If segment's page resides in high memory, map it into
             * kernel's address space temporarily.
             */
            if (PageHighMem(bv->bv_page))
                p = kmap (bv->bv_page) + bv->bv_offset;
            else  /* segment's page resides in low memory */
                p = page_address (bv->bv_page) + bv->bv_offset;

            if (rw == READ)
            {
                if( TffsRead (pdisk, p, sector, ns) == 0 )
                    rc = -EIO;    /* I/O error */
            }
            else
            {
                if( TffsWrite (pdisk, p, sector, ns) == 0 )
                    rc = -EIO;    /* I/O error */
            }

            /* If segment's page resides in high memory, cancel
             * previously established mapping.
             */
            if (PageHighMem(bv->bv_page))
                kunmap (bv->bv_page);

            sector += ns;
        }
    }

    return rc;
}




/*******************************************************************************
 *                                                                             *
 *                         r e q u e s t s _ t o _ d o                         *
 *                                                                             *
 *  This routine checks if there are any requests in socket's request list.    *
 *                                                                             *
 *  Parameters:                                                                *
 *      psoc        socket pointer                                             *
 *                                                                             *
 *  Returns:                                                                   *
 *      FALSE if list is empty, otherwise TRUE                                 *
 *                                                                             *
 *******************************************************************************/
static
int  requests_to_do ( SocketInfo * psoc )
{
    unsigned long  flags;
    int            rc = FALSE;   /* assume list is empty */

    spin_lock_irqsave (&psoc->request_list_lock, flags);

    if( !list_empty(&psoc->requestsList) )
        rc = TRUE;

    spin_unlock_irqrestore (&psoc->request_list_lock, flags);

    return rc;
}



/*******************************************************************************
 *                                                                             *
 *                         t f f s _ s u s p e n d                             *
 *                                                                             *
 *  This routine is intended to be called by various Linux Power Managers to   *
 *  power down all DiskOnChip devices when system goes into powerdown mode.    *
 *                                                                             *
 *  Parameters:   none                                                         *
 *                                                                             *
 *  Returns: void                                                              *
 *                                                                             *
 *******************************************************************************/
void tffs_suspend (void)
{
    SocketInfo * psoc;
    int          i;

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

        if (psoc->fFound == 0)
            continue;

        init_completion (&psoc->wait_for_io_thread);

        /* Tell I/O thread to finish all outstanding I/O requests, wake
         * up us, and exit.
         */
        psoc->io_thread_state = 2;

        /* in case socket's I/O thread is currently sleeping, wake it up */
        wake_up (&psoc->waitQueueHead);

        /* wait for I/O thread to exit */
        wait_for_completion (&psoc->wait_for_io_thread); /* down_interruptible (&psoc->threadSemaphore); */

        /* tell TrueFFS to power down DiskOnChip */
        TffsSuspend (psoc);
    }

    /* disable DiskOnChip interrupts */
    if (tffs_irq >= 0)
    {
        tffs_irq_disable (TRUE);
    }
}




/*******************************************************************************
 *                                                                             *
 *                         t f f s _ r e s u m e                               *
 *                                                                             *
 *  This routine is intended to be called by various Linux Power Managers to   *
 *  power up all DiskOnChip devices when system comes up from powerdown mode.  *
 *                                                                             *
 *  Parameters:   none                                                         *
 *                                                                             *
 *  Returns: void                                                              *
 *                                                                             *
 *******************************************************************************/
void tffs_resume (void)
{
    SocketInfo * psoc;
    int          i;

    /* We are doing 'resume' after previous power 'suspend', not 
     * full scale board initialization, hence TRUE flag below.
     */
    tffsarch_init (TRUE);

    /* enable DiskOnChip interrupts */
    if (tffs_irq >= 0)
    {
        tffs_irq_enable (TRUE);
    }

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

        if (psoc->fFound == 0)
            continue;

        /* Tell TrueFFS to power up DiskOnChip. This call takes around 20
         * milliseconds (DiskOnChip driver will not yield CPU during this time).
         */
        TffsResume (psoc);

        /* restore multi-sector poleld I/O mode in DiskOnChip h3 devices */
        TffsSetPIO (psoc);

        init_completion (&psoc->wait_for_io_thread);

        /* tell I/O thread to wake us up once it gets running */
        psoc->io_thread_state = 2;

        /* start I/O thread */
        kernel_thread (socket_io_thread, (void *)psoc, 0);

        /* wait for I/O thread to get running */
        wait_for_completion (&psoc->wait_for_io_thread); /* down_interruptible (&psoc->threadSemaphore); */
    }
}




#ifdef CONFIG_PROC_FS

/*******************************************************************************
 *                                                                             *
 *                     p r o c f s _ r e g i s t e r                           *
 *                                                                             *
 *  Create disk's entry in /proc/<module-name>.                                *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       pdisk          disk pointer                                           *
 *                                                                             *
 *  Returns: zero if success otherwise negative error code.                    *
 *                                                                             *
 *******************************************************************************/
static
int  /* __init */ procfs_register ( DeviceInfo * pdisk )
{
    char name[] = "a";

    name[0] += (char)(pdisk->diskNo);

    if ((pdisk->pProcFile = create_proc_entry(name, 0, tffsInfo.pProcDir)) == NULL)
    { 
        PrintkWarning("Can't create /proc/tffs/%s", name);
        return -EBUSY;
    }

    pdisk->pProcFile->read_proc  = procfs_read;
    pdisk->pProcFile->write_proc = procfs_write;
    pdisk->pProcFile->data       = pdisk;

    return 0;
}




/*******************************************************************************
 *                                                                             *
 *                     p r o c f s _ u n r e g i s t e r                       *
 *                                                                             *
 *  Delete disk's entry in /proc/<module-name>.                                *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       pdisk          disk pointer                                           *
 *                                                                             *
 *  Returns: always zero (success).                                            *
 *                                                                             *
 *******************************************************************************/
static
int  /* __exit */ procfs_unregister ( DeviceInfo * pdisk )
{
    char name[] = "a";

    name[0] += (char)(pdisk->diskNo);

    remove_proc_entry (name, tffsInfo.pProcDir);
    pdisk->pProcFile = NULL;

    return 0;
}




/*******************************************************************************
 *                                                                             *
 *                     p r o c f s _ w r i t e                                 *
 *                                                                             *
 *  Called when disk's entry in /proc/<module-name> is wriiten to.             *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       file          not used                                                *
 *       buffer        not used                                                *
 *       count         not used                                                *
 *       data          disk pointer                                            *
 *                                                                             *
 *  Returns: always zero (success).                                            *
 *                                                                             *
 *******************************************************************************/
static
int  procfs_write ( struct file * file,
                    const char  * buffer,
                    unsigned long count,
                    void        * data )
{
# ifdef TFFS_STATISTIC
    DeviceInfo * pdisk = (DeviceInfo *)data;

    memset (&pdisk->stat, 0, sizeof(pdisk->stat));
# endif

    return count;
}




/*******************************************************************************
 *                                                                             *
 *                     p r o c f s _ r e a d                                   *
 *                                                                             *
 *  Called when disk's entry in /proc/<module-name> is read from.              *
 *                                                                             *
 *  Parameters:                                                                *
 *                                                                             *
 *       buf           buffer to put data to                                   *
 *       start         not used                                                *
 *       offset        not used                                                *
 *       length        not used                                                *
 *       eof           End-of-File indicator                                   *
 *       data          disk pointer                                            *
 *                                                                             *
 *  Returns: number of characters written to buffer 'buf'                      *
 *                                                                             *
 *******************************************************************************/
static 
int  procfs_read ( char *  buf,
                   char ** start,
                   off_t   offset,
                   int     length,
                   int  *  eof,
                   void *  data )
{
    char * p = buf;
    int    i;

# ifdef TFFS_STATISTIC

    {   DeviceInfo    * pdisk = (DeviceInfo *)data;
        TffsStatistic * stat  = &pdisk->stat;

        p += sprintf (p, "flAbsRead calls %ld\n", stat->dwAbsRead);
        p += sprintf (p, "total %ld read requests (%ld by disk_request_queue_handler)\n",
                               stat->dwReadReq, stat->dwReadReqNoThread);
        p += sprintf (p, "total %ld sectors read (aligned %ld, unaligned %ld)\n",
                               stat->dwAbsReadSec, stat->dwAlReadSec, stat->dwUnalReadSec);
        p += sprintf (p, "read shared sectors: aligned %ld, unaligned %ld\n",
                               stat->dwAlReadShared, stat->dwUnalReadShared);

        p += sprintf (p,"flAbsWrite calls %ld\n", stat->dwAbsWrite);
        p += sprintf (p, "total %ld write requests\n", stat->dwWriteReq);
        p += sprintf (p,"total %ld sectors written (aligned %ld, unaligned %ld)\n",
                               stat->dwAbsWriteSec, stat->dwAlWriteSec, stat->dwUnalWriteSec);
        p += sprintf (p,"written shared sectors: aligned %ld, unaligned %ld\n",
                               stat->dwAlWriteShared, stat->dwUnalWriteShared);
    }

# endif /* TFFS_STATISTIC */

    p += sprintf (p, "profiling:");
    for (i = 0; i < 10; i++)
        p += sprintf (p, " %d", profiling[i]);
    p += sprintf (p, "\n");

    *eof = 1;

    return (p - buf);
}

#endif /* CONFIG_PROC_FS */

#endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,0)) */

