/* ---------------------------------------------------------------------------
 * FAT_intern.h                                                 (C)ChaN, 2008
 * ---------------------------------------------------------------------------
 * Micro-key bv
 * Industrieweg 28, 9804 TG Noordhorn
 * Postbus 92, 9800 AB Zuidhorn
 * The Netherlands
 * Tel: +31 594 503020
 * Fax: +31 594 505825
 * Email: support@microkey.nl  
 * Web: www.microkey.nl
 * ---------------------------------------------------------------------------
 * Description: FatFs - FAT file system module include file  R0.06
 * 
 * FatFs module is an experimenal project to implement FAT file system to
 * cheap microcontrollers. This is a free software and is opened for education,
 * research and development under license policy of following trems.
 * 
 * Copyright (C) 2008, ChaN, all right reserved.
 * 
 * The FatFs module is a free software and there is no warranty.
 * You can use, modify and/or redistribute it for personal, non-profit or
 * commercial use without any restriction under your responsibility.
 * Redistributions of source code must retain the above copyright notice.
 * ---------------------------------------------------------------------------
 */
/* ---------------------------------------------------------------------------
 * Version(s):  0.2, Aug 11, 2008, MMi
 *                  Edited to fit into LAN_2636 Project
 *                   
 *              0.1, 2008 ChanN
 *                  Creation
 * ---------------------------------------------------------------------------
 */
#ifndef FAT_INTERN_H_
#define FAT_INTERN_H_   

/* ---------------------------------------------------------------------------
 * System include files.
 * ---------------------------------------------------------------------------
 */
#include "LPC23xx.h"
#include "types.h"

/* ---------------------------------------------------------------------------
 * Application include files.
 * ---------------------------------------------------------------------------
 */

/* ---------------------------------------------------------------------------
 * Constant and macro definitions.
 * ---------------------------------------------------------------------------
 */
/* The _MCU_ENDIAN defines which access method is used to the FAT structure.
 * 1: Enable word access.                                                  
 * 2: Disable word access and use byte-by-byte access instead.             
 */
#define _MCU_ENDIAN         2

/* Setting _FS_READONLY to 1 defines read only configuration. This removes  
 * writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename,
 * f_truncate and useless f_getfree.
 */
#define _FS_READONLY        0

/* _FS_MINIMIZE option defines minimization level to remove some functions.
 * 0: Full function.
 * 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and  f_rename
 * are  removed.
 * 2: f_opendir and f_readdir are removed in addition to level 1.
 * 3: f_lseek is removed in addition to level 2. */
#define _FS_MINIMIZE        0

/* To enable string functions, set _USE_STRFUNC to 1 or 2.                  */
#define _USE_STRFUNC        0

/* When _USE_MKFS is set to 1 and _FS_READONLY is set to 0, f_mkfs function is
 * enabled. 
 */
#define _USE_MKFS           0

/* Number of logical drives to use. This affects the size of internal table.*/
#define _DRIVES             2

/* When _MULTI_PARTITION is set to 0, each logical drive is bound to same
 * physical drive number and can mount only 1st primaly partition. When it is
 * set to 1, each logical drive can mount a partition listed in Drives[]. 
 */
#define _MULTI_PARTITION    0

/* To enable FSInfo support on FAT32 volume, set _USE_FSINFO to 1.          */
#define _USE_FSINFO	        0

/* When _USE_SJIS is set to 1, Shift-JIS code transparency is enabled, 
 * otherwise only US-ASCII(7bit) code can be accepted as file/directory name.
 */
#define _USE_SJIS           1

/* When _USE_NTFLAG is set to 1, upper/lower case of the file name is enabled.
 * Note that the files are always accessed in case insensitive.
 */
#define _USE_NTFLAG         1


/* Definitions corresponds to multiple sector size                          */
#define S_MAX_SIZ   512U            /* Do not change */
#if S_MAX_SIZ > 512U
#define SS(fs)  ((fs)->s_size)
#else
#define SS(fs)  512U
#endif

/* Definitions corresponds to multi partition                               */
#if _MULTI_PARTITION != 0               /* Multiple partition cfg           */
#define LD2PD(drv) (Drives[drv].pd)     /* Get physical drive number        */
#define LD2PT(drv) (Drives[drv].pt)     /* Get partition number             */
#else                                   /* Single partition cfg             */
#define LD2PD(drv) (drv)                /* Physical drive number is equal   */
                                        /* to logical drive number          */
#define LD2PT(drv) 0                    /* Always mounts the 1st partition  */
#endif

/* String functions enabled                                                 */
#if _USE_STRFUNC
#define feof(fp) ((fp)->fptr == (fp)->fsize)
#define EOF -1
int fputc (int, FIL*);                  /* Put a character to the file      */
int fputs (const char*, FIL*);          /* Put a string to the file         */
int fprintf (FIL*, const char*, ...);   /* Put a formatted string to file   */
char* fgets (char*, int, FIL*);         /* Get a string from the file       */
#endif

/* File access control and file status flags                                */
#define FA_OPEN_EXISTING    0x00        /* Open file. Fails if not exist    */
#define FA_READ             0x01        /* Allow reading access             */
#if _FS_READONLY == 0                   /* En-/disable writing functions    */
#define FA_WRITE            0x02        /* Allow writing access             */
#define FA_CREATE_NEW       0x04        /* Create file. Fails if exists     */
#define FA_CREATE_ALWAYS    0x08        /* Create file, overwrites if exists*/
#define FA_OPEN_ALWAYS      0x10        /* Open file, create if not exists  */
#define FA__WRITTEN         0x20        /* "FileChanged" Flag (internal use)*/
#define FA__DIRTY           0x40        
#endif
#define FA__ERROR           0x80        /* ERROR Flag                       */

/* FAT sub types                                                            */
#define FS_FAT12            1
#define FS_FAT16            2
#define FS_FAT32            3

/* File attribute bits for directory entry                                  */
#define AR_RDO              0x01        /* Read only                        */
#define AR_HID              0x02        /* Hidden                           */
#define AR_SYS              0x04        /* System                           */
#define AR_VOL              0x08        /* Volume label                     */
#define AR_LFN              0x0F        /* LFN entry                        */
#define AR_DIR              0x10        /* Directory                        */
#define AR_ARC              0x20        /* Archive                          */

/* Offset of FAT structure members                                          */
#define BS_jmpBoot          0           /* Jump Statement                   */  
#define BS_OEMName          3           /* OEM Name                         */
#define BPB_BytsPerSec      11          /* Bytes per Sector                 */
#define BPB_SecPerClus      13          /* Sectors per Cluster              */
#define BPB_RsvdSecCnt      14          /* Number of reserved Sectors       */
#define BPB_NumFATs         16          /* Number of FATs                   */
#define BPB_RootEntCnt      17          /* Number of Root entries           */
#define BPB_TotSec16        19          /* Number of total Sectors (FAT16)  */
#define BPB_Media           21          /* Media Descriptor (unnecessary)   */
#define BPB_FATSz16         22          /* Number of Sectors per FAT        */
#define BPB_SecPerTrk       24          /* Sectors per Track                */
#define BPB_NumHeads        26          /* Number of writing-heads          */
#define BPB_HiddSec         28          /* Number of hidden Sectors         */
#define BPB_TotSec32        32          /* Number of total Sectors (FAT32)  */
#define BS_55AA             510         /* MBR ending structure "55AA"      */

/* Offset of additional FAT12/FAT16 Descriptors                             */
#define BS_DrvNum           36          /* Physical BIOS Drive number       */
#define BS_BootSig          38          /* Extended Boot Signature          */
#define BS_VolID            39          /* Volume ID                        */
#define BS_VolLab           43          /* Volume Label (not necessary)     */
#define BS_FilSysType       54          /* Filesystem Type                  */

/* Offset of additional FAT32 Descriptors                                   */
#define BPB_FATSz32         36          /* Number of Sectors per FAT        */
#define BPB_ExtFlags        40          /* Extended FAT Flags               */
#define BPB_FSVer           42          /* FAT32 Version (usually:0x0000)   */
#define BPB_RootClus        44          /* Rootcluster number               */
#define BPB_FSInfo          48          /* FS Information Sector (usually 1)*/
#define BPB_BkBootSec       50          /* Sectornumber of Bootsector copy  */
#define BS_DrvNum32         64          /* Physical BIOS Drive number       */  
#define BS_BootSig32        66          /* Extended Boot Signature          */
#define BS_VolID32          67          /* Volume ID                        */
#define BS_VolLab32         71          /* Volume Label (unused)            */
#define BS_FilSysType32     82          /* FAT Version (always FAT32)       */

/* Offset of additional File System Information                             */
#define FSI_LeadSig         0
#define FSI_StrucSig        484
#define FSI_Free_Count      488
#define FSI_Nxt_Free        492

#define MBR_Table           446

/* Offset of directory or file information in RootDirectory entries         */ 
#define DIR_Name            0           /* Entry name (8B Name 3B Extension)*/
#define DIR_Attr            11          /* Attributes                       */
#define DIR_NTres           12          /* Used by NT                       */ 
#define DIR_CrtTime         14          /* Creation Time                    */
#define DIR_CrtDate         16          /* Creation Date                    */
#define DIR_FstClusHI       20          /* First Cluster (High Bytes)       */
#define DIR_WrtTime         22          /* Last written Time                */
#define DIR_WrtDate         24          /* Last written Date                */        
#define DIR_FstClusLO       26          /* First Cluster (Low Bytes)        */
#define DIR_FileSize        28          /* File Size                        */


/* Multi-byte word access macros                                            */
#if _MCU_ENDIAN == 1                    /* Use word access                  */
#define LD_WORD(ptr)        (UINT16)(*(UINT16*)(UINT8*)(ptr))
#define LD_DWORD(ptr)       (UINT32)(*(UINT32*)(UINT8*)(ptr))
#define ST_WORD(ptr,val)    *(UINT16*)(UINT8*)(ptr)=(UINT16)(val)
#define ST_DWORD(ptr,val)   *(UINT32*)(UINT8*)(ptr)=(UINT32)(val)
#elif _MCU_ENDIAN == 2                  /* Use byte-by-byte access          */
#define LD_WORD(ptr)        (UINT16)(((UINT16)*(volatile UINT8*)((ptr)+1)<<8)|(UINT16)*(volatile UINT8*)(ptr))
#define LD_DWORD(ptr)       (UINT32)(((UINT32)*(volatile UINT8*)((ptr)+3)<<24)|((UINT32)*(volatile UINT8*)((ptr)+2)<<16)|((UINT16)*(volatile UINT8*)((ptr)+1)<<8)|*(volatile UINT8*)(ptr))
#define ST_WORD(ptr,val)    *(volatile UINT8*)(ptr)=(UINT8)(val); *(volatile UINT8*)((ptr)+1)=(UINT8)((UINT16)(val)>>8)
#define ST_DWORD(ptr,val)   *(volatile UINT8*)(ptr)=(UINT8)(val); *(volatile UINT8*)((ptr)+1)=(UINT8)((UINT16)(val)>>8); *(volatile UINT8*)((ptr)+2)=(UINT8)((UINT32)(val)>>16); *(volatile UINT8*)((ptr)+3)=(UINT8)((UINT32)(val)>>24)
#else
#error Do not forget to set _MCU_ENDIAN properly!
#endif
/* ---------------------------------------------------------------------------
 * Type definitions.
 * ---------------------------------------------------------------------------
 */

/* File system object structure                                             */
typedef struct _FATFS
    {
        UINT16 id;                      /* File system mount ID             */
        UINT16 n_rootdir;               /* Number of root directory entries */
        UINT32 winsect;                 /* Current sector in the win[]      */
        UINT32 sects_fat;               /* Sectors per FAT                  */
        UINT32 max_clust;               /* Maximum number of cluster + 1    */
        UINT32 fatbase;                 /* FAT start sector                 */
        UINT32 dirbase;                 /* RootDir start sector             */
                                        /* (cluster number for FAT32)       */
        UINT32 database;                /* Data start sector                */
#if !_FS_READONLY
        UINT32 last_clust;              /* Last allocated cluster           */
        UINT32 free_clust;              /* Number of free clusters          */
#if _USE_FSINFO
        UINT32 fsi_sector;              /* Fsinfo sector                    */
        UINT8 fsi_flag;                 /* fsinfo dirty flag                */
                                        /* (1:must be written back)         */
        UINT8 pad2;
#endif
#endif
        UINT8 fs_type;                  /* FAT sub type                     */
        UINT8 csize;                    /* Number of sectors per cluster    */
#if S_MAX_SIZ > 512U
        UINT16 s_size;                  /* Sector size                      */
#endif
        UINT8 n_fats;                   /* Number of FAT copies             */
        UINT8 drive;                    /* Physical drive number            */
        UINT8 winflag;                  /* win[] dirty flag                 */
                                        /* (1:must be written back)         */
        UINT8 pad1;
        UINT8 win[S_MAX_SIZ];           /* Disk access window for FAT       */
    } FATFS;
    
/* Directory object structure                                               */
typedef struct _DIR
    {
        UINT16 id;                      /* Owner file system mount ID       */
        UINT16 index;                   /* Current index                    */
        FATFS* fs;                      /* Pointer to file system object    */
        UINT32 sclust;                  /* Start cluster                    */
        UINT32 clust;                   /* Current cluster                  */
        UINT32 sect;                    /* Current sector                   */
    } DIR;
    
/* File object structure                                                    */
typedef struct _FIL
    {
        UINT16 id;                      /* Owner file system mount ID       */
        UINT8 flag;                     /* File status flags                */
        UINT8 csect;                    /* Sector address in the cluster    */
        FATFS* fs;                      /* Pointer to file system object    */
        UINT32 fptr;                    /* File Read/Write pointer          */
        UINT32 fsize;                   /* File size                        */
        UINT32 org_clust;               /* File start cluster               */
        UINT32 curr_clust;              /* Current cluster                  */
        UINT32 curr_sect;               /* Current sector                   */
#if _FS_READONLY == 0
        UINT32 dir_sect;                /* Sector containing directory entry*/
        pUINT8 dir_ptr;                 /* Pointer to dir entry in window   */
#endif
        UINT8 buffer[S_MAX_SIZ];        /* File Read/Write buffer           */
    } FIL;
    
/* File status structure                                                    */
typedef struct _FILINFO
    {
        UINT32 fsize;                   /* Size                             */
        UINT16 fdate;                   /* Date                             */
        UINT16 ftime;                   /* Time                             */
        UINT8 fattrib;                  /* Attribute                        */
        char fname[8+1+3+1];            /* Name (8.3 format)                */
    } FILINFO;

/* File function return code (FRESULT)                                      */
typedef enum
    {
        FR_OK = 0,                      /* 0 - Operation Suceeded           */
        FR_NOT_READY,                   /* 1 - Device not ready             */
        FR_NO_FILE,                     /* 2 - No file available            */
        FR_NO_PATH,                     /* 3 - No path available            */
        FR_INVALID_NAME,                /* 4 - Invalid file or dir name     */
        FR_INVALID_DRIVE,               /* 5 - Invalid drive number         */
        FR_DENIED,                      /* 6 - Access denied                */
        FR_EXIST,                       /* 7 - File or dir already exists   */
        FR_RW_ERROR,                    /* 8 - Read or Write Error          */
        FR_WRITE_PROTECTED,             /* 9 - Device is write-protected    */
        FR_NOT_ENABLED,                 /* 10 - Device/function not enabled */
        FR_NO_FILESYSTEM,               /* 11 - No filesystem available     */
        FR_INVALID_OBJECT,              /* 12 - Invalid object reference    */
        FR_MKFS_ABORTED                 /* 13 - MKFS function aborted       */
    } FRESULT;
    

/* Definitions corresponds to multi partition                               */
#if _MULTI_PARTITION != 0               /* Multiple partition cfg           */
typedef struct _PARTITION
    {
        UINT8 pd;                       /* Physical drive # (0-255)         */
        UINT8 pt;                       /* Partition # (0-3)                */
    } PARTITION;
extern
const PARTITION Drives[];               /* Logical drive number to physical */
#endif
/* ---------------------------------------------------------------------------
 * Variable declarations.
 * ---------------------------------------------------------------------------
 */

/* ---------------------------------------------------------------------------
 * Function declarations.
 * ---------------------------------------------------------------------------
 */

BOOLEAN move_window (FATFS *fs, UINT32 sector);

#if !_FS_READONLY
FRESULT sync (FATFS *fs);
#endif

UINT32 get_cluster (FATFS *fs, UINT32 clust);

#if !_FS_READONLY
BOOLEAN put_cluster(FATFS *fs, UINT32 clust, UINT32 val);
#endif 


#if !_FS_READONLY
BOOLEAN remove_chain (FATFS *fs, UINT32 clust);
#endif

#if !_FS_READONLY
UINT32 create_chain (FATFS *fs, UINT32 clust);
#endif 

UINT32 clust2sect(FATFS *fs, UINT32 clust);
BOOLEAN next_dir_entry(DIR *dj);

#if _FS_MINIMIZE <= 1
void get_fileinfo (FILINFO *finfo, const UINT8 *dir);
#endif 

char make_dirfile(const char **path, char *dirname);
FRESULT trace_path (DIR *dj, char *fn, const char *path, UINT8 **dir);

#if !_FS_READONLY
FRESULT reserve_direntry (DIR *dj, UINT8 **dir); 
#endif

UINT8 check_fs (FATFS *fs, UINT32 sect);

FRESULT auto_mount (const char **path, FATFS **rfs, UINT8 chk_wp);

FRESULT validate (const FATFS *fs, UINT16 id);




#endif
