/******************************************************************************/
/*                                                                            */
/*  Copyright (C), 1995-2007, SanDisk IL Ltd. All rights reserved.            */
/*                                                                            */
/*  Redistribution and use in source and binary forms, with or without        */
/*  modification, are permitted provided that the following conditions are    */
/*  met:                                                                      */
/*  1. Redistributions of source code must retain the above copyright notice, */
/*     this list of conditions and the following disclaimer.                  */
/*  2. Redistributions in binary form must reproduce the above copyright      */
/*     notice, this list of conditions and the following disclaimer in the    */
/*     documentation and/or other materials provided with the distribution.   */
/*  3. Neither the name of SanDisk IL nor the names of its contributors may be*/
/*     used to endorse or promote products derived from this software without */
/*     specific prior written permission.                                     */
/*                                                                            */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED */
/*  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR             */
/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      */
/*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,     */
/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  */
/*  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    */
/*  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    */
/*  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      */
/*  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              */
/*                                                                            */
/*  NOTWITHSTANDING ANYTHING STATED TO THE CONTRARY, SANDISK'S TOTAL LIABILITY*/
/*  ARISING OUT OF OR RELATED TO THE SOFTWARE OR ANY SUPPORT SERVICES         */
/*  PROVIDED WITH RESPECT THERETO SHALL NOT EXCEED $100.                      */
/*                                                                            */
/*  The laws of the State of California, United States of America, exclusive  */
/*  of conflict-of-laws provisions, shall govern this license in all respects.*/
/*  The the federal or state courts of competent jurisdiction in the State    */ 
/*  of California shall have exclusive jurisdiction with respect to all       */
/*  actions commenced in relation to the software. Licensee agrees not        */ 
/*  to export or re-export, directly or indirectly any technical data         */ 
/*  acquired from SanDisk or any products utilizing such data in violation    */
/*  of applicable export laws and regulations.                                */
/*                                                                            */
/******************************************************************************/
/*
 * $Log:   V:/PVCSDB/DiskOnChip/archives/Testing/TrueFFS 6.3/Drop 2.5/3/bddoc/src/fatfilt.c-arc  $
 * 
 *    Rev 1.10   Oct 22 2007 11:34:52   einat.avidan
 * update copyrights header
 * 
 *    Rev 1.9   Feb 28 2007 09:53:46   einat.avidan
 * No change
 * 
 *    Rev 1.8.1.1   Sep 11 2006 13:45:20   yaniv.iarovici
 * Legal header added
 * 
 *    Rev 1.8.1.0   Aug 08 2006 15:55:28   Polina.Marimont
 * DOC Driver 1.0 initial
 */

/*******************************************************************************
 *                                                                             * 
 *                                                                             * 
 *                         Module: FATFILT                                     * 
 *                                                                             * 
 *  This module implements installable FAT12/16 filters. It supports up to     *
 *  SOCKETS sockets, with up to FL_MAX_TL_PARTITIONS disks per socket.         * 
 *  Each disk can contain up to FL_MAX_PARTS_PER_DISK partitions on it, with   * 
 *  maximum depth of partition nesting in extended partitions equal to         * 
 *  MAX_PARTITION_DEPTH.                                                       *
 *                                                                             * 
 *  In order for this module to work, disks must be abs.mounted rather then    * 
 *  mounted. In latter case, this module won't detect any of disk's            * 
 *  partitions, and won't install FAT filters.                                 * 
 *                                                                             * 
 *  This module uses more then 512 bytes of stack space in case if MALLOC is   * 
 *  not enabled.                                                               * 
 *                                                                             * 
 *******************************************************************************/

/* 
 * Includes
 */

#include "fatfilt.h"
#include "blockdev.h"
#include "defs.h"


#if defined(FL_ABS_READ_WRITE) && !defined(FL_READ_ONLY)



/*
 * Module configuration
 */

#define  FL_INCLUDE_FAT_MONITOR  /* undefine it to remove FAT filter code */
#undef   FL_INCLUDE_FAT32        /* define after support for FAT32 is added */
#define  FL_DEL_SECTOR_SETS      /* undefine to delete single cluster at a time */
#undef   FL_DEL_SECTOR_STATS     /* gather sector deletion statistics */



/*
 * Defines
 */

/* extract pointer to user's buffer from IOreq */

#ifdef SCATTER_GATHER
#define  FLBUF(ioreq,i)  (*((FLSByte FAR1 **)((ioreq)->irData) + (int)(i)))
#else
#define  FLBUF(ioreq,i)  ((FLSByte FAR1 *)(ioreq->irData) + (FL_SECTOR_SIZE * ((int)(i))))
#endif

/* extract socket# and disk# from TFFS handle */

#define  H2S(handle)     (((int)(handle)) & 0xf)
#define  H2D(handle)     ((((int)(handle)) >> 4) & 0xf)

/* construct TFFS handle from socket# and disk# */

#define  SD2H(socNo,diskNo)  ((int)((((diskNo) & 0xf) << 4) | ((socNo) & 0xf)))

/* unformatted ("raw") disk partition */

#define  FL_RAW_PART  (-1)



/*
 * Global vars
 */

#ifdef FL_DEL_SECTOR_SETS
FLBoolean del_sect_sets = TRUE;  /* try to delete sectors in larger sets */
#endif




/*
 * Local routines 
 */

static FLStatus   reset (void);
static FLStatus   discardDisk (int handle);
static FLStatus   newDisk (int handle);
static FLStatus   parseDisk (int handle);
static FLStatus   discardDiskParts (FLffDisk *pd);
static FLStatus   addDiskPart (FLffDisk *pd, int partNo);
static FLStatus   addNewDiskPart (FLffDisk *pd);
static FLBoolean  isPartTableWrite (FLffDisk *pd, IOreq FAR2 *ioreq);
static FLStatus   isExtPartPresent (FLSByte FAR1 *buf, SectorNo *nextExtPartSec);
static FLBoolean  isBPBchanged (FLffVol *pv, FLSByte FAR1 *buf);


#ifdef FL_INCLUDE_FAT_MONITOR

static FLStatus   partEnableFF (FLffVol* pv);
static FLStatus   partFreeDelClusters (FLffVol *pv, SectorNo secNo, 
                                       FLSByte FAR1 *newFAT, IOreq *ioreq_delete);

#endif




/*
 * Local data
 */

/* module reset flag */

static FLBoolean  resetDone = FALSE; 

/* disks (BDTL partitions in OSAK terminology) */

static FLffDisk*  ffDisk[FL_SOCKETS][FL_MAX_TL_PARTITIONS] = { { NULL } };


#ifndef FL_MALLOC

/*          
 *        WARNING: Large static arrays ! 
 *
 *  sizeof(ffAllDisks[x][y])    is 64 bytes. 
 *  sizeof(ffAllParts[x][y][z]) is 40 bytes.
 *
 */

static FLffDisk ffAllDisks[FL_SOCKETS][FL_MAX_TL_PARTITIONS];
static FLffVol  ffAllParts[FL_SOCKETS][FL_MAX_TL_PARTITIONS][FL_MAX_PARTS_PER_DISK];

#endif /* FL_MALLOC */

static const FLSByte zeroes[FL_SECTOR_SIZE] = {0};

#if (defined(FL_DEL_SECTOR_SETS) && defined(FL_DEL_SECTOR_STATS))
static FLDword del_sect_stats[16] = {0};   /* sector deletion statistics */
#endif




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                    d i s c a r d D i s k P a r t s                          *
 *                                                                             * 
 *  Discard all the partition info (if any) associated with particular disk.   * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      pd                 : disk (BDTL volume)                                * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      Always flOK.                                                           * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  discardDiskParts ( FLffDisk * pd )
{
    register int  i;

    if (pd != NULL) {

        for (i = 0; i < FL_MAX_PARTS_PER_DISK; i++) {

#ifdef FL_MALLOC

            if (pd->part[i] != NULL) {

                FL_FREE(pd->part[i]);
            }
#endif

            pd->part[i] = NULL;
        }

        pd->parts = 0;
    }

    return flOK;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                      a d d D i s k P a r t                                  *
 *                                                                             * 
 *  If there is partition record #partNo associated with the disk, discard     * 
 *  this info. Attach new partition record #partNo.                            * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      pd                 : disk (BDTL volume)                                * 
 *      partNo             : partition (0 ... FL_MAX_PARTS_PER_DISK-1)         * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK if success, otherwise respective error code                       * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  addDiskPart ( FLffDisk * pd, 
                               int        partNo )
{
    FLffVol  * pv;    
    FLStatus   status;
    int        socNo, diskNo;

    /* arg. sanity check */

    if ((pd == NULL) || (partNo >= FL_MAX_PARTS_PER_DISK))
        return flBadDriveHandle;

    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(pd->handle);
    diskNo = H2D(pd->handle);
 
    if ((socNo >= FL_SOCKETS) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    status = flNotEnoughMemory;

#ifdef FL_MALLOC
    pv = (FLffVol *)FL_MALLOC( sizeof(FLffVol) );
#else
    pv = &ffAllParts[socNo][diskNo][partNo];
#endif

    if (pv != NULL) {

        /* initialize fields in struct FLffDisk to safe values */
 
        pv->handle         = pd->handle; 
        pv->type           = FL_RAW_PART;
        pv->flags          = 0;          
        pv->ffEnabled      = FALSE;                  /* turn off FAT minitor */
        pv->sectors        = (SectorNo) 0;
        pv->firstFATsecNo  = (SectorNo) -1;          /* none */
        pv->lastFATsecNo   = pv->firstFATsecNo;      /* none */
        pv->firstDataSecNo = (SectorNo) 0;
        pv->clusterSize    = (unsigned) 0;

#ifdef FL_MALLOC
        if( pd->part[partNo] != NULL ) {

           FL_FREE(pd->part[partNo]);
           pd->part[partNo] = NULL;
        }
#endif
        pd->part[partNo] = pv;

        status = flOK;
    }

    return status;    
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                    a d d N e w D i s k P a r t                              *
 *                                                                             * 
 *  Add one more partition record to the disk.                                 * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      pd                 : disk (BDTL volume)                                * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK if success, otherwise respective error code                       * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  addNewDiskPart ( FLffDisk * pd )
{
    if (pd->parts < FL_MAX_PARTS_PER_DISK) {

        checkStatus( addDiskPart (pd, pd->parts) );
        pd->parts++;
    }

    return flOK;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                       d i s c a r d D i s k                                 *
 *                                                                             * 
 *  Remove disk record (with all the associated partition records).            * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      handle             : TFFS handle                                       * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK if success, otherwise respective error code                       * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  discardDisk ( int  handle )
{
    int  socNo, diskNo;

    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(handle);
    diskNo = H2D(handle);
 
    if ((socNo >= FL_SOCKETS) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    if( ffDisk[socNo][diskNo] != NULL ) {

    /* discard associated partition info */

    (void) discardDiskParts( ffDisk[socNo][diskNo] );

#ifdef FL_MALLOC

        /* release disk's scratch buffer */
 
        if( (ffDisk[socNo][diskNo])->buf != NULL) {

            FL_FREE( (ffDisk[socNo][diskNo])->buf );
            (ffDisk[socNo][diskNo])->buf = NULL;
        }

        FL_FREE( ffDisk[socNo][diskNo] );
#endif

        ffDisk[socNo][diskNo] = NULL;
    }

    return flOK;    
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                           n e w D i s k                                     *
 *                                                                             * 
 *  Discard existing disk record (if any), and create new one.                 * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      handle             : TFFS handle                                       * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK if success, otherwise respective error code                       * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  newDisk ( int  handle )
{
    int        socNo, diskNo;
    int        i;
    FLffDisk * pd;

    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(handle);
    diskNo = H2D(handle);
 
    if ((socNo >= FL_SOCKETS) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    /* discard current disk and associated partition info (if any) */

    checkStatus( discardDisk(handle) );

#ifdef FL_MALLOC

    pd = (FLffDisk *) FL_MALLOC( sizeof(FLffDisk) );

    if (pd == NULL)
        return flNotEnoughMemory;

    /* allocate and attach disk's scratch buffer */

    pd->buf = (FLSByte *)FL_MALLOC( FL_SECTOR_SIZE );

    if (pd->buf == NULL) {

        FL_FREE (pd);
        pd = NULL;
        return flNotEnoughMemory;
    }

#else /* !FL_MALLOC */

    pd = &ffAllDisks[socNo][diskNo];

#endif /* FL_MALLOC */


    pd->handle  = handle;
    pd->ffstate = flStateNotInitialized;

    /* don't know partition layout yet */

    pd->parts   = 0;
    for (i = 0; i < FL_MAX_PARTS_PER_DISK; i++)
        pd->part[i] = NULL;

    /* watch Master Boot Record for update */

    pd->secToWatch = (SectorNo) 0;

    ffDisk[socNo][diskNo] = pd;

    return flOK;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                   i s P a r t T a b l e W r i t e                           *
 *                                                                             * 
 *  Check if any of the sectors specified by 'ioreq' points to Master Boot     * 
 *  Record or next extended partition in the extended partitions list.         * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      pd                 : pointer to disk structure                         * 
 *      ioreq              : standard I/O request                              * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      TRUE if write to MBR or extended partition list is detected, otherwise * 
 *      FALSE                                                                  * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLBoolean isPartTableWrite ( FLffDisk   * pd, 
                                    IOreq FAR2 * ioreq )
{
    register FLSDword  i;

    if (pd != NULL) {

        for (i = (FLSDword)0; i < ioreq->irSectorCount; i++) {

            if( (ioreq->irSectorNo + i) == (FLSDword)pd->secToWatch )
                return TRUE;
        }
    }

    return FALSE;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                   i s E x t P a r t P r e s e n t                           *
 *                                                                             * 
 *  Check if extended partition persent in the partition table. If it is,      * 
 *  calculate the sector # where next partition table will be written to.      * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      buf                : partition table                                   * 
 *      nextExtPartSec  : sector where next partition table will be written to * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK on success, otherwise error code                                  * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  isExtPartPresent ( FLSByte FAR1 * buf, 
                                    SectorNo  * nextExtPartSec )
{
    Partition FAR1 * p;
    register int     i;
  
    /* does it look like partition table ? */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    if (LE2(((PartitionTable FAR1 *) buf)->signature) != PARTITION_SIGNATURE)
#else
    if (FL_GET_LE2(buf, FL_PARTITION_TABLE_SIGNATURE_OFFSET) != PARTITION_SIGNATURE)
#endif
        return flBadFormat;

    /* if extended. part. present, get sector# that will contain next part. in list */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    p = &( ((PartitionTable FAR1 *) buf)->ptEntry[0] );
#else
    p = (Partition *) &FL_REF_1(buf, FL_PARTITION_TABLE_PT_ENTRY_OFFSET );
#endif

    for (i = 0;  i < FL_PART_TBL_ENTRIES;  i++) {

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
        if (p->type == EX_PARTIT) {
            *nextExtPartSec = (SectorNo) UNAL4( p[i].startingSectorOfPartition );
#else
        if (FL_REF_1(p, FL_PARTITION_TYPE_OFFSET) == EX_PARTIT) {
            *nextExtPartSec = (SectorNo) FL_GET_UNAL4(p, i* FL_PARTITION_SIZE + FL_PARTITION_STARTING_SECTOR_OF_PARTITION_OFFSET );
#endif
            return flOK;
        }
    }

    /* no extended partition found */

    return flFileNotFound;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                         i s B P B c h a n g e d                             *
 *                                                                             * 
 *  Check if critical fields in partition's boot sector have been changed.     * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      pv                 : disk partition (filesystem volume)                * 
 *      buf                : new contents of partition's boot sector           * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      TRUE if critical fields in BPB have been changed, otherwise FALSE      * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLBoolean  isBPBchanged ( FLffVol * pv, FLSByte FAR1 * buf )
{
    BPB FAR1 * bpb;
    SectorNo   sectors;
    SectorNo   firstFATsecNo;
    SectorNo   lastFATsecNo;
    SectorNo   rootDirSecNo;
    SectorNo   rootDirSectors;
    SectorNo   sectorsPerFAT;
    SectorNo   firstDataSecNo;

    /* if FAT monitor already inactive on this partition, do nothing and return */

    if (pv->ffEnabled == FALSE)
        return FALSE;

    /* we only handle 512-byte sectors */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    bpb = &( ((DOSBootSector FAR1 *) buf)->bpb );

    if( UNAL2(bpb->bytesPerSector) != FL_SECTOR_SIZE )
        return TRUE;

    /* check if 'number of sectors in partition' has been changed */ 
 
    sectors = UNAL2( bpb->totalSectorsInVolumeDOS3 );

    if (sectors == (SectorNo)0)
        sectors = (SectorNo) LE4( bpb->totalSectorsInVolume );
#else
    bpb = (BPB FAR1 *) buf;

    if( FL_GET_UNAL2(bpb, FL_BPB_BYTES_PER_SECTOR_OFFSET) != FL_SECTOR_SIZE )
        return TRUE;

    /* check if 'number of sectors in partition' has been changed */ 
 
    sectors = FL_GET_UNAL2(bpb, FL_BPB_TOTAL_SECTORS_IN_VOL_DOS3_OFFSET );

    if (sectors == (SectorNo)0)
        sectors = (SectorNo) FL_GET_LE4(bpb, FL_BPB_TOTAL_SECTORS_IN_VOL_OFFSET );
#endif

    if (sectors != pv->sectors)
        return TRUE;

    /* check if 'FAT's starting sector #' has been changed */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    firstFATsecNo = pv->startSecNo + (SectorNo)( LE2(bpb->reservedSectors) );
#else
    firstFATsecNo = pv->startSecNo + (SectorNo)( FL_GET_LE2(bpb, FL_BPB_RESERVED_SECTORS_OFFSET) );
#endif

    if (firstFATsecNo != pv->firstFATsecNo)
        return TRUE;

    /* check if 'FAT's ending sector #' has been changed */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    sectorsPerFAT = (SectorNo) LE2( bpb->sectorsPerFAT );
#else
    sectorsPerFAT = (SectorNo) FL_GET_LE2(bpb, FL_BPB_SECTORS_PER_FAT_OFFSET );
#endif

    lastFATsecNo  = firstFATsecNo + sectorsPerFAT - (SectorNo)1;

    if (lastFATsecNo != pv->lastFATsecNo)
        return TRUE;

    /* check if 'first data sector #' has been changed */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    rootDirSecNo = firstFATsecNo + (sectorsPerFAT * bpb->noOfFATS);

    rootDirSectors = (SectorNo)1 + (SectorNo)
        (((UNAL2(bpb->rootDirectoryEntries) * DIRECTORY_ENTRY_SIZE) - 1) / FL_SECTOR_SIZE);
#else
    rootDirSecNo = firstFATsecNo + (sectorsPerFAT * FL_REF_1(bpb, FL_BPB_NO_OF_FATS_OFFSET));

    rootDirSectors = (SectorNo)1 + (SectorNo)
        (((FL_GET_UNAL2(bpb, FL_BPB_ROOT_DIR_ENTRIES_OFFSET) * DIRECTORY_ENTRY_SIZE) - 1) / FL_SECTOR_SIZE);
#endif

    firstDataSecNo = rootDirSecNo + rootDirSectors;

    if (firstDataSecNo != pv->firstDataSecNo)
        return TRUE;

    /* check if cluster size has been changed */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    if (pv->clusterSize != bpb->sectorsPerCluster)
#else
    if (pv->clusterSize != FL_REF_1(bpb, FL_BPB_SECTORS_PER_CLUSTER_OFFSET))
#endif
        return TRUE;

    return FALSE;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                           r e s e t                                         *
 *                                                                             * 
 *  Resets this software module to it's initial state upon boot.               * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *    none                                                                     * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK in case of success, otherwise respective error code               * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  reset (void)
{
    int iSoc, iDisk;

    for (iSoc = 0; iSoc < FL_SOCKETS; iSoc++) {

        /* discard existing disk structures for that socket */

        for (iDisk = 0; iDisk < FL_MAX_TL_PARTITIONS; iDisk++)
        (void) discardDisk( SD2H(iSoc, iDisk) );

        /* pre-allocate disk structure for first disk of every socket */

        checkStatus( newDisk(SD2H(iSoc, 0)) );
    }

    resetDone = TRUE;

    return flOK;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                          p a r s e D i s k                                  *
 *                                                                             * 
 *  Read partition table(s), install and enable FAT filters on all FAT12/16    * 
 *  partitions.                                                                * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *    handle         : TFFS handle                                             * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK on success, otherwise error code                                  * 
 *                                                                             * 
 *  NOTE:  This routine uses disk's scratch buffer.                            * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  parseDisk ( int handle )
{
    int          socNo, diskNo;
    SectorNo     extPartStartSec, sec;
    int          i, depth;
    int          type;
    FLffDisk   * pd;
    FLffVol    * pv;
    Partition  * pp;
    IOreq        ioreq;

#ifdef  FL_MALLOC
    FLSByte       * buf;
#else
    FLSByte         buf[FL_SECTOR_SIZE];
#endif

    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(handle);
    diskNo = H2D(handle);
 
    if ((socNo >= ((int) noOfSockets)) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    /* if disk structure hasn't been allocated yet, do it now */

    if (ffDisk[socNo][diskNo] == NULL)
        checkStatus( newDisk(handle) );

    pd = ffDisk[socNo][diskNo];
    
#ifdef  FL_MALLOC

    /* make sure scratch buffer is available */

    if (pd->buf == NULL)
        return flBufferingError;

    buf = pd->buf;

#endif /* FL_MALLOC */ 
 
    /* discard obsolete disk's partition info */

    (void) discardDiskParts (pd);

    /* read Master Boot Record */

    ioreq.irHandle      = handle;
    ioreq.irSectorNo    = (SectorNo) 0;
    ioreq.irSectorCount = (SectorNo) 1;
    ioreq.irData        = (void FAR1 *) buf;
    checkStatus( flAbsRead(&ioreq) );

    /* is it MBR indeed ? */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    if (LE2(((PartitionTable *) buf)->signature) != PARTITION_SIGNATURE)
#else
    if (FL_GET_LE2(buf, FL_PARTITION_TABLE_SIGNATURE_OFFSET) != PARTITION_SIGNATURE)
#endif
        return flPartitionNotFound;                         

    /* do primary partitions only (we will do extended partitions later) */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    pp = &( ((PartitionTable *) buf)->ptEntry[0] );
#else
    pp = (Partition *) &FL_REF_1(buf, FL_PARTITION_TABLE_PT_ENTRY_OFFSET );
#endif

    for (i = 0; i < FL_PART_TBL_ENTRIES; i++, pp++) {
#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    	FLByte ppType = pp->type;
#else
    	FLByte ppType = FL_REF_1(pp, FL_PARTITION_TYPE_OFFSET);
#endif

        if( ppType == ((FLSByte)0) )          /* skip empty slot */
            continue;

        if( ppType == ((FLSByte)EX_PARTIT) )  /* skip extended partition */
        continue;

    /* primary partition found (not necessarily FAT12/16) */

        if( addNewDiskPart(pd) != flOK )
        break;

        pv = pd->part[pd->parts - 1];

        /* remember partition's type, and where it starts */

        pv->type       = (int) ppType;
        
#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
        pv->startSecNo = (SectorNo) UNAL4( pp->startingSectorOfPartition );
#else
        pv->startSecNo = (SectorNo) FL_GET_UNAL4(pp, FL_PARTITION_STARTING_SECTOR_OF_PARTITION_OFFSET );
#endif
    } 

    /* do extended partitions in depth */

    for (i = 0; i < FL_PART_TBL_ENTRIES; i++) {

        /* re-read Master Boot Record */

        ioreq.irHandle      = handle;
        ioreq.irSectorNo    = (SectorNo) 0;
        ioreq.irSectorCount = (SectorNo) 1;
        ioreq.irData        = (void FAR1 *) buf;
        checkStatus( flAbsRead(&ioreq) );

        /* is it MBR indeed ? */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
        if (LE2(((PartitionTable *) buf)->signature) != PARTITION_SIGNATURE)
#else
        if (FL_GET_LE2(buf, FL_PARTITION_TABLE_SIGNATURE_OFFSET) != PARTITION_SIGNATURE)
#endif
            return flOK;

        /* pick up next extended partition in MBR */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
        pp = &( ((PartitionTable *) buf)->ptEntry[i] );

        if( pp->type == ((FLSByte)EX_PARTIT) ) {

            /* remember where extended partition starts */

            extPartStartSec = (SectorNo) UNAL4( pp->startingSectorOfPartition );   
#else
        pp = (Partition *)&FL_REF_1(buf, FL_PARTITION_TABLE_PT_ENTRY_OFFSET + FL_PARTITION_SIZE*i);

        if( FL_REF_1(pp, FL_PARTITION_TYPE_OFFSET) == ((FLSByte)EX_PARTIT) ) {

            /* remember where extended partition starts */

            extPartStartSec = (SectorNo) FL_GET_UNAL4(pp, FL_PARTITION_STARTING_SECTOR_OF_PARTITION_OFFSET );
#endif

            /* follow the list of partition tables */

            sec = extPartStartSec;

            for (depth = 0;  depth < FL_MAX_PARTITION_DEPTH;  depth++) {

                /* read next partition table in the list */

                ioreq.irHandle      = handle;
                ioreq.irSectorNo    = sec;
                ioreq.irSectorCount = (SectorNo) 1;
                ioreq.irData        = (void FAR1 *) buf;
                checkStatus( flAbsRead(&ioreq) );

                /* is it valid partition table ? */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
                if (LE2(((PartitionTable *) buf)->signature) != PARTITION_SIGNATURE)
#else
                if (FL_GET_LE2(buf, FL_PARTITION_TABLE_SIGNATURE_OFFSET) != PARTITION_SIGNATURE)
#endif
                    break;

                /* if 1st entry is zero, it's the end of part. table list */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
                pp = &( ((PartitionTable *) buf)->ptEntry[0] );
                if( pp->type == ((FLSByte)0) )
#else
                pp = (Partition *) &FL_REF_1(buf, FL_PARTITION_TABLE_PT_ENTRY_OFFSET );
                if( FL_REF_1(pp, FL_PARTITION_TYPE_OFFSET) == ((FLSByte)0) )
#endif                
                    break;

                /* Take this partition. Remember it's type, and where it starts */

                if( addNewDiskPart(pd) != flOK )
                break;

                pv = pd->part[pd->parts - 1];

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
                pv->type       = (int) pp->type;
                pv->startSecNo = 
                    (SectorNo) UNAL4( pp->startingSectorOfPartition) + sec;
#else
                pv->type       = (int) FL_REF_1(pp, FL_PARTITION_TYPE_OFFSET);
                pv->startSecNo = 
                    (SectorNo) FL_GET_UNAL4(pp, FL_PARTITION_STARTING_SECTOR_OF_PARTITION_OFFSET) + sec;
#endif

                /* 2nd entry must be extended partition */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
                pp = &( ((PartitionTable *) buf)->ptEntry[1] );
                if( pp->type != ((FLSByte)EX_PARTIT) )
#else
                pp = (Partition *) &FL_REF_1(buf, FL_PARTITION_TABLE_PT_ENTRY_OFFSET + FL_PARTITION_SIZE );
                if( FL_REF_1(pp, FL_PARTITION_TYPE_OFFSET) != ((FLSByte)EX_PARTIT) )
#endif
                    break;

                /* sector where next part. table in the list resides */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
                sec = extPartStartSec + 
                      (SectorNo) UNAL4( pp->startingSectorOfPartition );
#else
                sec = extPartStartSec + 
                      (SectorNo) FL_GET_UNAL4(pp, FL_PARTITION_STARTING_SECTOR_OF_PARTITION_OFFSET );
#endif

            }   /* for(depth) */
        }
    }   /* for(i) */ 

#ifdef FL_INCLUDE_FAT_MONITOR

    /* turn on FAT filters on FAT12/16 partition(s) */

    if (pd->parts > 0) {

        for (i = 0;  i < pd->parts;  i++) {

            pv   = pd->part[i];
            type = pv->type;

            /*
             *  WARNING : Routine partEnableFF() uses disk's scratch buffer !
             */

        if((type == FAT12_PARTIT) || (type == FAT16_PARTIT) || (type == DOS4_PARTIT))
                partEnableFF (pv);
    }
    }

#endif /* FL_INCLUDE_FAT_MONITOR */

    /* watch for MBR (sector #0) update */

    pd->secToWatch = (SectorNo) 0;

    pd->ffstate    = flStateInitialized;

    return flOK;
}




#ifdef FL_INCLUDE_FAT_MONITOR

/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                     p a r t E n a b l e F F                                 *
 *                                                                             * 
 *  Installs and enables FAT filter on partition.                              * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *    pv            : disk partition (filesystem volume)                       * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK on success, otherwise error code                                  * 
 *                                                                             * 
 *  NOTE:  This routine uses disk's scratch buffer.                            * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  partEnableFF ( FLffVol * pv )
{
    int        socNo, diskNo;
    FLffDisk * pd;
    BPB      * bpb;
    SectorNo   sectors;
    SectorNo   reservedSectors;
    SectorNo   rootDirSecNo;
    SectorNo   rootDirSectors;
    SectorNo   sectorsPerFAT;
    SectorNo   rootDirEntries;
    unsigned   maxCluster;
    int        partNo;
    IOreq      ioreq;

#ifdef  FL_MALLOC
    FLSByte     * buf;
#else
    FLSByte       buf[FL_SECTOR_SIZE];
#endif

    DBG_PRINT_FLOW(FLZONE_FS,"Debug: (partEnableFF) checking FAT type.\r\n");

    /* arg. sanity check */

    if (pv == NULL)
        return flBadDriveHandle;
 
    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(pv->handle);
    diskNo = H2D(pv->handle);
 
    if ((socNo >= ((int) noOfSockets)) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    /* check if 'pv' belongs to this disk */

    pd = ffDisk[socNo][diskNo];

    if (pd == NULL)
        return flBadDriveHandle;

    for (partNo = 0; partNo < pd->parts; partNo++) {

        if (pd->part[partNo] == pv)
        break;
    }

    if (partNo >= pd->parts)
        return flBadDriveHandle;

#ifdef  FL_MALLOC

    /* make sure scratch buffer is available */

    if (pd->buf == NULL)
        return flBufferingError;

    buf = pd->buf;
 
#endif /* FL_MALLOC */ 

    /* make sure FAT filter is off on this partition */

    pv->ffEnabled       = FALSE;

    pv->firstFATsecNo   = (SectorNo) -1;
    pv->lastFATsecNo    = pv->firstFATsecNo;
    pv->clusterSize     = (unsigned) 0;

    /* read BPB */

    ioreq.irHandle      = pv->handle;
    ioreq.irSectorNo    = pv->startSecNo;
    ioreq.irSectorCount = (SectorNo) 1;
    ioreq.irData        = (void FAR1 *) buf;
    checkStatus( flAbsRead(&ioreq) );

    /* Does it look like DOS bootsector ? */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED

    bpb = &( ((DOSBootSector *) buf)->bpb );

    if( !((bpb->jumpInstruction[0] == 0xe9) 
            || 
         ((bpb->jumpInstruction[0] == 0xeb) && (bpb->jumpInstruction[2] == 0x90)))) {
#else

    bpb = (BPB *) buf;
    
    if( !((FL_REF_1(bpb, FL_BPB_JUMP_INSTRUCTION_OFFSET) == 0xe9) 
            || 
         ((FL_REF_1(bpb, FL_BPB_JUMP_INSTRUCTION_OFFSET) == 0xeb) && (FL_REF_1(bpb, FL_BPB_JUMP_INSTRUCTION_OFFSET + 2) == 0x90)))) {
#endif
        return flNonFATformat;
    }

    /* Do we handle this sector size ? */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    if (UNAL2(bpb->bytesPerSector) != FL_SECTOR_SIZE)
#else
    if (FL_GET_UNAL2(bpb, FL_BPB_BYTES_PER_SECTOR_OFFSET) != FL_SECTOR_SIZE)
#endif
        return flFormatNotSupported;

    /* 
     * Is it a bogus BPB (leftover from previous disk partitioning) ? 
     * Check that there is no overlap with next partition (if one exists).
     */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    sectors = UNAL2(bpb->totalSectorsInVolumeDOS3);

    if (sectors == (SectorNo)0)
        sectors = (SectorNo) LE4(bpb->totalSectorsInVolume);
#else
    sectors = FL_GET_UNAL2(bpb, FL_BPB_TOTAL_SECTORS_IN_VOL_DOS3_OFFSET);

    if (sectors == (SectorNo)0)
        sectors = (SectorNo) FL_GET_LE4(bpb, FL_BPB_TOTAL_SECTORS_IN_VOL_OFFSET);
#endif

    if ((partNo+1 < pd->parts) && (pd->part[partNo+1] != NULL)) {

        if( sectors > (pd->part[partNo+1])->startSecNo - pv->startSecNo )
            return flNonFATformat;
    }

    /* number of sectors in partition as reported by BPB */

    pv->sectors = sectors;

    /* get number of reserved sectors from BPB, and check it's sanity */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    reservedSectors = (SectorNo) LE2(bpb->reservedSectors);
#else
    reservedSectors = (SectorNo) FL_GET_LE2(bpb, FL_BPB_RESERVED_SECTORS_OFFSET);
#endif

    switch( (int)reservedSectors ) {

        case 32:      /* always the case with FAT 32 */

#ifndef FL_INCLUDE_FAT32

            DBG_PRINT_FLOW(FLZONE_FS,"Debug: (partEnableFF) FAT32 detected.\r\n");
            return flFormatNotSupported;
#endif

        case 1:       /* must always be the case for FAT 12 and FAT16 */
        default:

            break;
    }

    /* get location and size of the first FAT copy */

    pv->firstFATsecNo = pv->startSecNo + reservedSectors;

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    sectorsPerFAT = (SectorNo) LE2(bpb->sectorsPerFAT);
#else
    sectorsPerFAT = (SectorNo) FL_GET_LE2(bpb, FL_BPB_SECTORS_PER_FAT_OFFSET);
#endif

#ifndef FL_INCLUDE_FAT32

    if (sectorsPerFAT == 0) {        /* always the case with FAT32 */

        DBG_PRINT_FLOW(FLZONE_FS,"Debug: (partEnableFF) FAT32 detected.\r\n");
        return flFormatNotSupported;
    }

#endif

    pv->lastFATsecNo = pv->firstFATsecNo + sectorsPerFAT - (SectorNo)1;

    /* get location and size of root directory */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    rootDirSecNo = pv->firstFATsecNo + (sectorsPerFAT * bpb->noOfFATS);

    rootDirEntries = (SectorNo) UNAL2(bpb->rootDirectoryEntries);
#else
    rootDirSecNo = pv->firstFATsecNo + (sectorsPerFAT * (FL_REF_1(bpb, FL_BPB_NO_OF_FATS_OFFSET)));

    rootDirEntries = (SectorNo) FL_GET_UNAL2(bpb, FL_BPB_ROOT_DIR_ENTRIES_OFFSET);
#endif

    switch (rootDirEntries) {

#ifndef FL_INCLUDE_FAT32

        case 0:            /* always the case with FAT32 */

            DBG_PRINT_FLOW(FLZONE_FS,"Debug: (partEnableFF) FAT32 detected.\r\n");
            return flFormatNotSupported;
#endif
    
        default:

            if( ((rootDirEntries * DIRECTORY_ENTRY_SIZE) % FL_SECTOR_SIZE) != 0 )
                return flNonFATformat;
            break;
    }

    rootDirSectors = (SectorNo)(((rootDirEntries * DIRECTORY_ENTRY_SIZE) - 1) / FL_SECTOR_SIZE) +
                             (SectorNo)1;

    /* get location of data area */

    pv->firstDataSecNo = rootDirSecNo + rootDirSectors;

    /* get size of FAT cluster in sectors, and check it's sanity */

#ifndef FL_NO_PACKED_STRUCTS_SUPPORTED
    pv->clusterSize = bpb->sectorsPerCluster;
#else
    pv->clusterSize = FL_REF_1(bpb, FL_BPB_SECTORS_PER_CLUSTER_OFFSET);
#endif

    switch( (int)pv->clusterSize ) {

        case 1: case 2: case 4: case 8: case 16: case 32: case 64: case 128:  
            break;

        default:
            return flNonFATformat;
    }

    if ((pv->clusterSize << FL_SECTOR_SIZE_BITS) > (32768 /*(32 * 1024)*/))
        return flFormatNotSupported;

    /* sanity check */

    if( (pv->lastFATsecNo   < pv->firstFATsecNo)  ||
        (pv->firstDataSecNo <= pv->lastFATsecNo)  ||  
        (pv->sectors        < pv->firstDataSecNo) )
        return flNonFATformat;


    /* decide which type of FAT is it */

    maxCluster         = (unsigned)1 + (unsigned) 
        ((pv->sectors - (pv->firstDataSecNo - pv->startSecNo)) / pv->clusterSize);

    if (maxCluster < 4085) {

        pv->flags |= VOLUME_12BIT_FAT;    /* 12-bit FAT */

#ifndef FS_FAT_12BIT

        DBG_PRINT_ERR(FLZONE_FS,"ERROR - FS_FAT_12BIT must be defined.\r\n");
        return flFormatNotSupported;

#else

        DBG_PRINT_FLOW(FLZONE_FS,"Debug: (partEnableFF) FAT12 detected.\r\n");

#endif /* FS_FAT_12BIT */
    }
    else {

        DBG_PRINT_FLOW(FLZONE_FS,"Debug: (partEnableFF) FAT16 detected.\r\n");
    }

    /* turn on FAT filter on this partition */

    pv->ffEnabled = TRUE;

    return flOK;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                   p a r t F r e e D e l C l u s t e r s                     *
 *                                                                             * 
 *  Compare the new contents of the specified FAT sector against the old       * 
 *  one on the disk. If any freed clusters are found, issue 'sector delete'    * 
 *  calls for all sectors that are occupied by these freed clusters.           * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      pv              : disk partition (filesystem volume)                   * 
 *      secNo           : abs. sector # of the FAT sector                      * 
 *      newFAT          : new contents of this FAT sector                      * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK on success, otherwise error code                                  * 
 *                                                                             * 
 *  NOTE:  This routine uses disk's scratch buffer.                            * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

static FLStatus  partFreeDelClusters ( FLffVol      * pv,
                                       SectorNo       secNo,
                                       FLSByte FAR1 * newFAT,
                                       IOreq        * ioreq_delete )
{
    FLffDisk * pd;
    int        socNo, diskNo;
    FLWord     oldFATentry, newFATentry;
    SectorNo   iSec;
    unsigned   firstCluster;
    IOreq      ioreq;
    int        offset;
    int        iPart;

#ifdef FS_FAT_12BIT
    int        halfBytes;
#endif

#ifdef  FL_MALLOC
    FLSByte     * oldFAT;
#else
    FLSByte       oldFAT[FL_SECTOR_SIZE];
#endif

    /* arg. sanity check */

    if (pv == NULL)
        return flBadDriveHandle;
 
    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(pv->handle);
    diskNo = H2D(pv->handle);
 
    if ((socNo >= ((int) noOfSockets)) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    /* check if 'pv' belongs to this disk */

    pd = ffDisk[socNo][diskNo];

    if (pd == NULL)
        return flBadDriveHandle;

    for (iPart = 0; iPart < pd->parts; iPart++) {

        if (pd->part[iPart] == pv)
            break;
    }

    if (iPart >= pd->parts)
        return flBadDriveHandle;

#ifdef  FL_MALLOC

    /* make sure scratch buffer is available */

    if (pd->buf == NULL)
        return flBufferingError;

    oldFAT = pd->buf;
 
#endif /* FL_MALLOC */

    /* read in the FAT sector from the disk */

    ioreq.irHandle      = pv->handle;
    ioreq.irSectorNo    = secNo;
    ioreq.irSectorCount = 1;
    ioreq.irData        = (void FAR1 *) oldFAT;
    checkStatus( flAbsRead(&ioreq) );

#ifdef FS_FAT_12BIT

    /* size of FAT entry in half-bytes */

    halfBytes = ((pv->flags & VOLUME_12BIT_FAT) ? 3 : 4);

    /* starting cluster */

    if (halfBytes == 3) {

        firstCluster = 
            ((((unsigned)(secNo - pv->firstFATsecNo)) * (2 * FL_SECTOR_SIZE)) + 2) / 3;
    }
    else {

        firstCluster = ((unsigned)(secNo - pv->firstFATsecNo)) * (FL_SECTOR_SIZE / 2);
    }

    /* starting data sector */

    iSec = (((SectorNo)firstCluster - 2) * pv->clusterSize) + pv->firstDataSecNo;

    offset = (firstCluster * ((unsigned) halfBytes)) & ((2 * FL_SECTOR_SIZE) - 1);

    /* 
     *  Find if any clusters were logically deleted, and if so, delete them.
     *
     *  NOTE: We are skipping over 12-bit FAT entries which span more than
     *        one sector.
     */

    for (; offset < ((2 * FL_SECTOR_SIZE) - 2); 
               offset += halfBytes, iSec += pv->clusterSize) {

        oldFATentry = UNAL2( *(Unaligned FAR0 *)(oldFAT + (offset / 2)) );
        newFATentry = UNAL2( *(Unaligned FAR1 *)(newFAT + (offset / 2)) );

        if (offset & 1) {
            oldFATentry >>= 4;
            newFATentry >>= 4;
        }
        else { 
            if (halfBytes == 3) {
                oldFATentry &= 0xfff;
                newFATentry &= 0xfff;
            }
        }

#else /* !FS_FAT_12BIT */

    firstCluster = ((unsigned) (secNo - pv->firstFATsecNo) * (FL_SECTOR_SIZE / 2));
    iSec  = pv->firstDataSecNo + 
            (((SectorNo)(firstCluster - (unsigned)2)) * pv->clusterSize);

    /* Find if any clusters were logically deleted, and if so, delete them */

    for (offset = 0;  offset < FL_SECTOR_SIZE;  offset += 2, iSec += pv->clusterSize) {

        oldFATentry = LE2( *(LEushort FAR0 *)(oldFAT + offset) );
        newFATentry = LE2( *(LEushort FAR1 *)(newFAT + offset) );

#endif /* FS_FAT_12BIT */

        if ((oldFATentry != FAT_FREE) && (newFATentry == FAT_FREE)) {

#ifdef FL_DEL_SECTOR_SETS

            if (del_sect_sets == TRUE) {

                /* Rather then deleting this cluster's sectors immediately, we try to 
                 * accumulate as many consecutive clusters as only possible before 
                 * calling flAbsDelete(). The hope here is that the underlaying
                 * TL will be able to handle deletion of larger sets of
                 * consecutive sectors more efficiently. 
                 */

                if ((SectorNo)(ioreq_delete->irSectorNo + ioreq_delete->irSectorCount) == iSec) {

                    ioreq_delete->irSectorCount += pv->clusterSize;
                }
                else {

                    if (ioreq_delete->irSectorNo != (SectorNo)(-1)) {

#ifdef FL_DEL_SECTOR_STATS
                        {  register int x = -1, S = (int)(ioreq_delete->irSectorCount);
                           while (S != 0) { x++;  S >>= 1; }
                           if ((x >= 0) && (x < (sizeof(del_sect_stats)/sizeof(del_sect_stats[0])))) { del_sect_stats[x]++; }
                        }
#endif
                        flAbsDelete (ioreq_delete);
                    }

                    ioreq_delete->irSectorNo    = iSec;
                    ioreq_delete->irSectorCount = pv->clusterSize;
                }
            }
            else

#endif /* FL_DEL_SECTOR_SETS */

            {   /* delete one FAT cluster at a time */

                ioreq_delete->irHandle      = pv->handle;
                ioreq_delete->irSectorNo    = iSec;
                ioreq_delete->irSectorCount = pv->clusterSize;
                flAbsDelete (ioreq_delete);
            }
        }
    }

    return flOK;
}

#endif /* FL_INCLUDE_FAT_MONITOR */




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                   f f C h e c k B e f o r e W r i t e                       *
 *                                                                             *
 *  Catch all the FAT updates. Detect disk partitioning operation, track it    *
 *  to completion, re-read partition tables, and re-install FAT filters on     *
 *  all FAT12/16 partitions.                                                   *
 *                                                                             *
 *  Parameters:                                                                *
 *      ioreq              : standard I/O request to be checked                *
 *                                                                             *
 *  Returns:                                                                   *
 *      flOK on success, otherwise error code                                  *
 *                                                                             *
 * --------------------------------------------------------------------------- */

FLStatus  ffCheckBeforeWrite ( IOreq FAR2 * ioreq )
{
    int            socNo, diskNo;
    FLffDisk     * pd;
    FLffVol      * pv;
    FLSDword       iSec;
    int            iPart;
    IOreq          ioreq2;
    FLSByte FAR1 * usrBuf;

    /* if module hasn't been reset yet, do it now */

    if (resetDone == FALSE)
        (void) reset();

    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(ioreq->irHandle);
    diskNo = H2D(ioreq->irHandle);
 
    if ((socNo >= ((int) noOfSockets)) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    /* if disk structure hasn't been allocated yet, do it now */

    if (ffDisk[socNo][diskNo] == NULL)
        checkStatus( newDisk((int)ioreq->irHandle) );

    pd = ffDisk[socNo][diskNo];

    /* read partition table(s) and install FAT filters is needed */

    if (pd->ffstate == flStateNotInitialized)
        checkStatus( parseDisk((int)ioreq->irHandle) );

    /* catch writes to MBR, and track the whole disk partitioning operations */

    while( isPartTableWrite(pd, ioreq) == TRUE ) {

        /* disk re-partitioning is in progress */

        if( pd->secToWatch == (SectorNo)0 ) {

            /* it's write to MBR, so trash BPBs in all disk's partitions */

            if (pd->parts > 0) {

                for (iPart = 0;  iPart < pd->parts;  iPart++) {

                    ioreq2.irHandle      = ioreq->irHandle;
                    ioreq2.irSectorNo    = (pd->part[iPart])->startSecNo;
                    ioreq2.irSectorCount = (SectorNo) 1;
                    ioreq2.irData        = (void FAR1 *) zeroes;
                    (void) flAbsWrite(&ioreq2);
                }
            }
        }

        /* keep FAT filters disabled while disk partitioning is in progress */

        pd->ffstate = flStateInitInProgress;

        /* partition table which is about to be written to disk */

        usrBuf = FLBUF( ioreq, (pd->secToWatch - ioreq->irSectorNo) );

        switch( isExtPartPresent(usrBuf, &(pd->secToWatch)) ) {

            case flOK: 

                /* 
                 * Found valid partition table with extended partition.
                 * The pd->secToWatch has been updated to point to the
                 * sector where next partition table will be written to. 
                 */
                continue;

            case flFileNotFound:

                /* 
                 * Valid partition table, but no extended partition in it. 
                 * Partitioning has been completed. Set pd->ffstate to 
                 * 'flStateNotInitialized' to initiate parsing of partition
                 * table(s) and FAT filter installation next time this routine
                 * is called. 
                 */

                pd->ffstate = flStateNotInitialized;
                break;

            case flBadFormat:
            default:

                /* No valid partition table. */

                break;
        }

        return flOK;
    }

#ifdef FL_INCLUDE_FAT_MONITOR

    /* check for FAT update */

    if (pd->ffstate == flStateInitialized) {

#ifdef FL_DEL_SECTOR_SETS

        if (del_sect_sets == TRUE) {

            ioreq2.irHandle      = ioreq->irHandle;
            ioreq2.irSectorNo    = (FLSDword)(-1);
            ioreq2.irSectorCount = 0;
        }
#endif

        /* NOTE: We can handle 'write' request that spans disk partition boundaries */

        for (iSec = ioreq->irSectorNo; 
             iSec < (ioreq->irSectorNo + ioreq->irSectorCount); iSec++) {

            for (iPart = 0; iPart < pd->parts; iPart++) {

                pv = pd->part[iPart];

                /* we monitor only FAT12/16 partitions */

                if ((pv->type != FAT12_PARTIT) && (pv->type != FAT16_PARTIT) && 
                                                  (pv->type != DOS4_PARTIT))
                    continue;

                /* FAT filters can be disabled on individual partitions */

                if (pv->ffEnabled != TRUE)
                    continue;

                if (iSec == (FLSDword)pv->startSecNo) {

                    /* partition's boot sector is being updated */

                    usrBuf = FLBUF( ioreq, (iSec - ioreq->irSectorNo) );

                    if( isBPBchanged(pv, usrBuf) == TRUE ) {

                        /* 
                         * Critical fields in partition's boot sector have been changed.
                         * Turn off FAT monitor on this partition.
                         */

                        pv->ffEnabled = FALSE;

                        DBG_PRINT_FLOW(FLZONE_FS,"Debug: (ffCheckBeforeWrite) BPB update detected.\r\n");
                        continue;
                    }
                }

                if ((iSec >= (FLSDword)pv->firstFATsecNo) && (iSec <= (FLSDword)pv->lastFATsecNo)) {

                    /* 
                     * Compare new and old contents of FAT sectors(s). If freed
                     * sectors are detected, add then to ioreq2.
                     */

                    usrBuf = FLBUF( ioreq, (iSec - ioreq->irSectorNo) );

                    checkStatus( partFreeDelClusters(pv, iSec, usrBuf, &ioreq2) ); 
                }
            }      /* for(iPart) */
        }          /* for(iSec) */

#ifdef FL_DEL_SECTOR_SETS

        if ((del_sect_sets == TRUE) && (ioreq2.irSectorNo != (SectorNo)(-1))) {

#ifdef FL_DEL_SECTOR_STATS
            {  register int x = -1, S = (int)(ioreq2.irSectorCount);
               while (S != 0) { x++;  S >>= 1; }
               if ((x >= 0) && (x < (sizeof(del_sect_stats)/sizeof(del_sect_stats[0])))) { del_sect_stats[x]++; }
            }
#endif
            flAbsDelete (&ioreq2);
        }

#endif /* FL_DEL_SECTOR_SETS */
    }

#endif /* FL_INCLUDE_FAT_MONITOR */

    return flOK;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                   f l f f C o n t r o l                                     *
 *                                                                             * 
 *  Enable/disable/install FAT filters. See comments inside the routine for    * 
 *  the list of supported operations.                                          * 
 *                                                                             * 
 *  Parameters:                                                                * 
 *      handle             : TFFS handle                                       * 
 *      partNo             : partition # (0 .. FL_MAX_PARTS_PER_DISK)          * 
 *      state              : see list of supported operations below            * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      flOK on success, otherwise error code                                  * 
 *                                                                             * 
 * --------------------------------------------------------------------------- *
 *                                                                             *
 *  The following FAT monitor control requests are supported:                  *
 *                                                                             *
 *      state  : flStateNotInitialized                                         *
 *      partNo : [0 ... pd->parts-1]                                           *
 *      action : turn off FAT monitor on specified partition                   *
 *                                                                             *
 *      state  : flStateNotInitialized                                         *
 *      partNo : < 0                                                           *
 *      action : turn off FAT monitor on all partitions                        *
 *                                                                             *
 *      state  : flStateInitialized                                            *
 *      partNo : [0 ... pd->parts-1]                                           *
 *      action : if FAT monitor has been installed on specified partition,     *
 *               turn it on                                                    *
 *                                                                             *
 *      state  : flStateInitInProgress                                         *
 *      partNo : ignored                                                       *
 *      action : re-read partition table(s), and install FAT filters on all    *
 *               partitions                                                    *
 *                                                                             *
 * --------------------------------------------------------------------------- */

FLStatus  flffControl ( int      handle,
                        int      partNo, 
                        FLState  state )
{
    int        socNo, diskNo;
    FLffDisk * pd;
    int        i;
    FLStatus   status;

    /* if module hasn't been reset yet, do it now */

    if (resetDone == FALSE)
        (void) reset();

    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(handle);
    diskNo = H2D(handle);
 
    if ((socNo >= ((int) noOfSockets)) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return flBadDriveHandle;

    /* if disk structure hasn't been allocated yet, do it now */

    if (ffDisk[socNo][diskNo] == NULL)
        checkStatus( newDisk(handle) );

    pd = ffDisk[socNo][diskNo];

    /* abort if disk re-partitioning is in progress */

    if (pd->ffstate == flStateInitInProgress)
        return flDriveNotReady;

    /* read partition table(s) and install FAT filters is needed */

    if (pd->ffstate == flStateNotInitialized) {

        if (state == flStateNotInitialized)
          return flOK;

        checkStatus( parseDisk(handle) );
    }

    /* check 'partNo' arguement for sanity */
 
    if ((partNo >= pd->parts) || (partNo >= FL_MAX_PARTS_PER_DISK))
        return flBadDriveHandle;

    /* do requested operation */

    status = flBadParameter;

    switch (state) {

        case flStateInitInProgress: 

            /* read partition table(s), install FAT filters on all partitions */

            pd->ffstate = flStateNotInitialized; 
            status = parseDisk(handle);
            break;

        case flStateNotInitialized:         

            /* turn off FAT monitor */

            if (partNo < 0) {                      /* all partitions */

                for (i = 0; i < FL_MAX_PARTS_PER_DISK; i++) {

                    if (pd->part[i] != NULL)
                        (pd->part[i])->ffEnabled = FALSE;
                }
            }
            else {                                 /* specified partition */

                if (pd->part[partNo] != NULL)
                    (pd->part[partNo])->ffEnabled = FALSE;
            }
            status = flOK;
            break;

#ifdef FL_INCLUDE_FAT_MONITOR

        case flStateInitialized:            

            /* turn on FAT monitor */

            if ((pd->ffstate == flStateInitialized) && (partNo >= 0)) {

                if (pd->part[partNo] != NULL) {

                    switch( (pd->part[partNo])->type ) {

                        case FAT12_PARTIT:
                        case FAT16_PARTIT:
                        case DOS4_PARTIT:
                            (pd->part[partNo])->ffEnabled = TRUE;
                            status = flOK;
                            break;

                        case FL_RAW_PART:
                            DBG_PRINT_ERR(FLZONE_FS,"ERROR - can't ctrl non-existent partition.\r\n");
                            break;

                        default:
                            DBG_PRINT_ERR(FLZONE_FS,"ERROR - can't ctrl non-FAT12/16 partition.\r\n");
                            break;
                    }
                }
            }
            break;

#endif /* FL_INCLUDE_FAT_MONITOR */

    }  /* switch(state) */ 

    return status;
}




/* --------------------------------------------------------------------------- *
 *                                                                             *
 *                   f l f f I n f o                                           *
 *                                                                             * 
 *  Obtain complete partition info for specified disk.                         *
 *                                                                             * 
 *  Parameters:                                                                * 
 *    handle         : TFFS handle                                             * 
 *                                                                             * 
 *  Returns:                                                                   * 
 *      NULL if error, otherwise pointer to partitioning info                  * 
 *                                                                             * 
 * --------------------------------------------------------------------------- */

FLffDisk * flffInfo ( int  handle )
{
    int        socNo, diskNo;
    FLffDisk * pd;

    /* if module hasn't been reset yet, do it now */

    if (resetDone == FALSE)
        (void) reset();

    /* break TFFS handle into socket# and disk#, and do sanity check */

    socNo  = H2S(handle);
    diskNo = H2D(handle);
 
    if ((socNo >= ((int) noOfSockets)) || (diskNo >= FL_MAX_TL_PARTITIONS))
        return NULL;

    /* if disk structure hasn't been allocated yet, do it now */

    if (ffDisk[socNo][diskNo] == NULL) {

        if( newDisk(handle) != flOK )
        return NULL;
    }

    pd = ffDisk[socNo][diskNo];

    /* read partition table(s) and install FAT filters is needed */

    if (pd->ffstate == flStateNotInitialized) {

        if( parseDisk(handle) != flOK )
            return NULL;
    }

    return pd;
}



#endif /* FL_ABS_READ_WRITE && FL_READ_ONLY */


