/*----------------------------------------------------------------------------/\r
-/ FatFs - Generic FAT Filesystem Module R0.13b /\r
+/ FatFs - Generic FAT Filesystem Module R0.15 w/patch1 /\r
/-----------------------------------------------------------------------------/\r
/\r
-/ Copyright (C) 2018, ChaN, all right reserved.\r
+/ Copyright (C) 2022, ChaN, all right reserved.\r
/\r
/ FatFs module is an open source software. Redistribution and use of FatFs in\r
/ source and binary forms, with or without modification, are permitted provided\r
/----------------------------------------------------------------------------*/\r
\r
\r
+#include <string.h>\r
#include "ff.h" /* Declarations of FatFs API */\r
#include "diskio.h" /* Declarations of device I/O functions */\r
\r
\r
---------------------------------------------------------------------------*/\r
\r
-#if FF_DEFINED != 63463 /* Revision ID */\r
+#if FF_DEFINED != 80286 /* Revision ID */\r
#error Wrong include file (ff.h).\r
#endif\r
\r
\r
+/* Limits and boundaries */\r
+#define MAX_DIR 0x200000 /* Max size of FAT directory */\r
+#define MAX_DIR_EX 0x10000000 /* Max size of exFAT directory */\r
+#define MAX_FAT12 0xFF5 /* Max FAT12 clusters (differs from specs, but right for real DOS/Windows behavior) */\r
+#define MAX_FAT16 0xFFF5 /* Max FAT16 clusters (differs from specs, but right for real DOS/Windows behavior) */\r
+#define MAX_FAT32 0x0FFFFFF5 /* Max FAT32 clusters (not specified, practical limit) */\r
+#define MAX_EXFAT 0x7FFFFFFD /* Max exFAT clusters (differs from specs, implementation limit) */\r
+\r
+\r
/* Character code support macros */\r
#define IsUpper(c) ((c) >= 'A' && (c) <= 'Z')\r
#define IsLower(c) ((c) >= 'a' && (c) <= 'z')\r
#define IsDigit(c) ((c) >= '0' && (c) <= '9')\r
+#define IsSeparator(c) ((c) == '/' || (c) == '\\')\r
+#define IsTerminator(c) ((UINT)(c) < (FF_USE_LFN ? ' ' : '!'))\r
#define IsSurrogate(c) ((c) >= 0xD800 && (c) <= 0xDFFF)\r
#define IsSurrogateH(c) ((c) >= 0xD800 && (c) <= 0xDBFF)\r
#define IsSurrogateL(c) ((c) >= 0xDC00 && (c) <= 0xDFFF)\r
\r
\r
-/* Additional file attribute bits for internal use */\r
-#define AM_VOL 0x08 /* Volume label */\r
-#define AM_LFN 0x0F /* LFN entry */\r
-#define AM_MASK 0x3F /* Mask of defined bits */\r
-\r
-\r
/* Additional file access control and file status flags for internal use */\r
#define FA_SEEKEND 0x20 /* Seek to end of the file on file open */\r
#define FA_MODIFIED 0x40 /* File has been modified */\r
#define FA_DIRTY 0x80 /* FIL.buf[] needs to be written-back */\r
\r
\r
+/* Additional file attribute bits for internal use */\r
+#define AM_VOL 0x08 /* Volume label */\r
+#define AM_LFN 0x0F /* LFN entry */\r
+#define AM_MASK 0x3F /* Mask of defined bits in FAT */\r
+#define AM_MASKX 0x37 /* Mask of defined bits in exFAT */\r
+\r
+\r
/* Name status flags in fn[11] */\r
#define NSFLAG 11 /* Index of the name status byte */\r
#define NS_LOSS 0x01 /* Out of 8.3 format */\r
#define NS_NONAME 0x80 /* Not followed */\r
\r
\r
-/* Limits and boundaries */\r
-#define MAX_DIR 0x200000 /* Max size of FAT directory */\r
-#define MAX_DIR_EX 0x10000000 /* Max size of exFAT directory */\r
-#define MAX_FAT12 0xFF5 /* Max FAT12 clusters (differs from specs, but right for real DOS/Windows behavior) */\r
-#define MAX_FAT16 0xFFF5 /* Max FAT16 clusters (differs from specs, but right for real DOS/Windows behavior) */\r
-#define MAX_FAT32 0x0FFFFFF5 /* Max FAT32 clusters (not specified, practical limit) */\r
-#define MAX_EXFAT 0x7FFFFFFD /* Max exFAT clusters (differs from specs, implementation limit) */\r
+/* exFAT directory entry types */\r
+#define ET_BITMAP 0x81 /* Allocation bitmap */\r
+#define ET_UPCASE 0x82 /* Up-case table */\r
+#define ET_VLABEL 0x83 /* Volume label */\r
+#define ET_FILEDIR 0x85 /* File and directory */\r
+#define ET_STREAM 0xC0 /* Stream extension */\r
+#define ET_FILENAME 0xC1 /* Name extension */\r
\r
\r
/* FatFs refers the FAT structure as simple byte array instead of structure member\r
#define PTE_StLba 8 /* MBR PTE: Start in LBA */\r
#define PTE_SizLba 12 /* MBR PTE: Size in LBA */\r
\r
+#define GPTH_Sign 0 /* GPT HDR: Signature (8-byte) */\r
+#define GPTH_Rev 8 /* GPT HDR: Revision (DWORD) */\r
+#define GPTH_Size 12 /* GPT HDR: Header size (DWORD) */\r
+#define GPTH_Bcc 16 /* GPT HDR: Header BCC (DWORD) */\r
+#define GPTH_CurLba 24 /* GPT HDR: This header LBA (QWORD) */\r
+#define GPTH_BakLba 32 /* GPT HDR: Another header LBA (QWORD) */\r
+#define GPTH_FstLba 40 /* GPT HDR: First LBA for partition data (QWORD) */\r
+#define GPTH_LstLba 48 /* GPT HDR: Last LBA for partition data (QWORD) */\r
+#define GPTH_DskGuid 56 /* GPT HDR: Disk GUID (16-byte) */\r
+#define GPTH_PtOfs 72 /* GPT HDR: Partition table LBA (QWORD) */\r
+#define GPTH_PtNum 80 /* GPT HDR: Number of table entries (DWORD) */\r
+#define GPTH_PteSize 84 /* GPT HDR: Size of table entry (DWORD) */\r
+#define GPTH_PtBcc 88 /* GPT HDR: Partition table BCC (DWORD) */\r
+#define SZ_GPTE 128 /* GPT PTE: Size of partition table entry */\r
+#define GPTE_PtGuid 0 /* GPT PTE: Partition type GUID (16-byte) */\r
+#define GPTE_UpGuid 16 /* GPT PTE: Partition unique GUID (16-byte) */\r
+#define GPTE_FstLba 32 /* GPT PTE: First LBA of partition (QWORD) */\r
+#define GPTE_LstLba 40 /* GPT PTE: Last LBA of partition (QWORD) */\r
+#define GPTE_Flags 48 /* GPT PTE: Partition flags (QWORD) */\r
+#define GPTE_Name 56 /* GPT PTE: Partition name */\r
+\r
\r
/* Post process on fatal error in the file operations */\r
#define ABORT(fs, res) { fp->err = (BYTE)(res); LEAVE_FF(fs, res); }\r
/* Re-entrancy related */\r
#if FF_FS_REENTRANT\r
#if FF_USE_LFN == 1\r
-#error Static LFN work area cannot be used at thread-safe configuration\r
+#error Static LFN work area cannot be used in thread-safe configuration\r
#endif\r
-#define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; }\r
+#define LEAVE_FF(fs, res) { unlock_volume(fs, res); return res; }\r
#else\r
#define LEAVE_FF(fs, res) return res\r
#endif\r
\r
\r
-/* Definitions of volume - physical location conversion */\r
+/* Definitions of logical drive - physical location conversion */\r
#if FF_MULTI_PARTITION\r
#define LD2PD(vol) VolToPart[vol].pd /* Get physical drive number */\r
-#define LD2PT(vol) VolToPart[vol].pt /* Get partition index */\r
+#define LD2PT(vol) VolToPart[vol].pt /* Get partition number (0:auto search, 1..:forced partition number) */\r
#else\r
-#define LD2PD(vol) (BYTE)(vol) /* Each logical drive is bound to the same physical drive number */\r
-#define LD2PT(vol) 0 /* Find first valid partition or in SFD */\r
+#define LD2PD(vol) (BYTE)(vol) /* Each logical drive is associated with the same physical drive number */\r
+#define LD2PT(vol) 0 /* Auto partition search */\r
#endif\r
\r
\r
\r
\r
/* File lock controls */\r
-#if FF_FS_LOCK != 0\r
+#if FF_FS_LOCK\r
#if FF_FS_READONLY\r
#error FF_FS_LOCK must be 0 at read-only configuration\r
#endif\r
typedef struct {\r
- FATFS *fs; /* Object ID 1, volume (NULL:blank entry) */\r
+ FATFS* fs; /* Object ID 1, volume (NULL:blank entry) */\r
DWORD clu; /* Object ID 2, containing directory (0:root) */\r
DWORD ofs; /* Object ID 3, offset in the directory */\r
- WORD ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */\r
+ UINT ctr; /* Object open counter, 0:none, 0x01..0xFF:read mode open count, 0x100:write mode */\r
} FILESEM;\r
#endif\r
\r
\r
\r
/* DBCS code range |----- 1st byte -----| |----------- 2nd byte -----------| */\r
+/* <------> <------> <------> <------> <------> */\r
#define TBL_DC932 {0x81, 0x9F, 0xE0, 0xFC, 0x40, 0x7E, 0x80, 0xFC, 0x00, 0x00}\r
#define TBL_DC936 {0x81, 0xFE, 0x00, 0x00, 0x40, 0x7E, 0x80, 0xFE, 0x00, 0x00}\r
#define TBL_DC949 {0x81, 0xFE, 0x00, 0x00, 0x41, 0x5A, 0x61, 0x7A, 0x81, 0xFE}\r
#if FF_VOLUMES < 1 || FF_VOLUMES > 10\r
#error Wrong FF_VOLUMES setting\r
#endif\r
-static FATFS* FatFs[FF_VOLUMES]; /* Pointer to the filesystem objects (logical drives) */\r
+static FATFS *FatFs[FF_VOLUMES]; /* Pointer to the filesystem objects (logical drives) */\r
static WORD Fsid; /* Filesystem mount ID */\r
\r
#if FF_FS_RPATH != 0\r
-static BYTE CurrVol; /* Current drive */\r
+static BYTE CurrVol; /* Current drive set by f_chdrive() */\r
#endif\r
\r
#if FF_FS_LOCK != 0\r
static FILESEM Files[FF_FS_LOCK]; /* Open object lock semaphores */\r
+#if FF_FS_REENTRANT\r
+static BYTE SysLock; /* System lock flag (0:no mutex, 1:unlocked, 2:locked) */\r
+#endif\r
#endif\r
\r
#if FF_STR_VOLUME_ID\r
#ifdef FF_VOLUME_STRS\r
-static const char* const VolumeStr[FF_VOLUMES] = {FF_VOLUME_STRS}; /* Pre-defined volume ID */\r
+static const char *const VolumeStr[FF_VOLUMES] = {FF_VOLUME_STRS}; /* Pre-defined volume ID */\r
+#endif\r
+#endif\r
+\r
+#if FF_LBA64\r
+#if FF_MIN_GPT > 0x100000000\r
+#error Wrong FF_MIN_GPT setting\r
#endif\r
+static const BYTE GUID_MS_Basic[16] = {0xA2,0xA0,0xD0,0xEB,0xE5,0xB9,0x33,0x44,0x87,0xC0,0x68,0xB6,0xB7,0x26,0x99,0xC7};\r
#endif\r
\r
\r
+\r
/*--------------------------------*/\r
/* LFN/Directory working buffer */\r
/*--------------------------------*/\r
/* Code conversion tables */\r
/*--------------------------------*/\r
\r
-#if FF_CODE_PAGE == 0 /* Run-time code page configuration */\r
+#if FF_CODE_PAGE == 0 /* Run-time code page configuration */\r
#define CODEPAGE CodePage\r
static WORD CodePage; /* Current code page */\r
-static const BYTE *ExCvt, *DbcTbl; /* Pointer to current SBCS up-case table and DBCS code range table below */\r
+static const BYTE* ExCvt; /* Ptr to SBCS up-case table Ct???[] (null:not used) */\r
+static const BYTE* DbcTbl; /* Ptr to DBCS code range table Dc???[] (null:not used) */\r
+\r
static const BYTE Ct437[] = TBL_CT437;\r
static const BYTE Ct720[] = TBL_CT720;\r
static const BYTE Ct737[] = TBL_CT737;\r
/* String functions */\r
/*-----------------------------------------------------------------------*/\r
\r
-/* Copy memory to memory */\r
-static void mem_cpy (void* dst, const void* src, UINT cnt)\r
-{\r
- BYTE *d = (BYTE*)dst;\r
- const BYTE *s = (const BYTE*)src;\r
-\r
- if (cnt != 0) {\r
- do {\r
- *d++ = *s++;\r
- } while (--cnt);\r
- }\r
-}\r
-\r
-\r
-/* Fill memory block */\r
-static void mem_set (void* dst, int val, UINT cnt)\r
-{\r
- BYTE *d = (BYTE*)dst;\r
-\r
- do {\r
- *d++ = (BYTE)val;\r
- } while (--cnt);\r
-}\r
-\r
-\r
-/* Compare memory block */\r
-static int mem_cmp (const void* dst, const void* src, UINT cnt) /* ZR:same, NZ:different */\r
-{\r
- const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;\r
- int r = 0;\r
-\r
- do {\r
- r = *d++ - *s++;\r
- } while (--cnt && r == 0);\r
-\r
- return r;\r
-}\r
-\r
-\r
-/* Check if chr is contained in the string */\r
-static int chk_chr (const char* str, int chr) /* NZ:contained, ZR:not contained */\r
-{\r
- while (*str && *str != chr) str++;\r
- return *str;\r
-}\r
-\r
-\r
-/* Test if the character is DBC 1st byte */\r
+/* Test if the byte is DBC 1st byte */\r
static int dbc_1st (BYTE c)\r
{\r
#if FF_CODE_PAGE == 0 /* Variable code page */\r
}\r
\r
\r
-/* Test if the character is DBC 2nd byte */\r
+/* Test if the byte is DBC 2nd byte */\r
static int dbc_2nd (BYTE c)\r
{\r
#if FF_CODE_PAGE == 0 /* Variable code page */\r
\r
#if FF_USE_LFN\r
\r
-/* Get a character from TCHAR string in defined API encodeing */\r
-static DWORD tchar2uni ( /* Returns character in UTF-16 encoding (>=0x10000 on double encoding unit, 0xFFFFFFFF on decode error) */\r
+/* Get a Unicode code point from the TCHAR string in defined API encodeing */\r
+static DWORD tchar2uni ( /* Returns a character in UTF-16 encoding (>=0x10000 on surrogate pair, 0xFFFFFFFF on decode error) */\r
const TCHAR** str /* Pointer to pointer to TCHAR string in configured encoding */\r
)\r
{\r
BYTE b;\r
int nf;\r
\r
- uc = (BYTE)*p++; /* Get a unit */\r
+ uc = (BYTE)*p++; /* Get an encoding unit */\r
if (uc & 0x80) { /* Multiple byte code? */\r
- if ((uc & 0xE0) == 0xC0) { /* 2-byte sequence? */\r
+ if ((uc & 0xE0) == 0xC0) { /* 2-byte sequence? */\r
uc &= 0x1F; nf = 1;\r
- } else {\r
- if ((uc & 0xF0) == 0xE0) { /* 3-byte sequence? */\r
- uc &= 0x0F; nf = 2;\r
- } else {\r
- if ((uc & 0xF8) == 0xF0) { /* 4-byte sequence? */\r
- uc &= 0x07; nf = 3;\r
- } else { /* Wrong sequence */\r
- return 0xFFFFFFFF;\r
- }\r
- }\r
+ } else if ((uc & 0xF0) == 0xE0) { /* 3-byte sequence? */\r
+ uc &= 0x0F; nf = 2;\r
+ } else if ((uc & 0xF8) == 0xF0) { /* 4-byte sequence? */\r
+ uc &= 0x07; nf = 3;\r
+ } else { /* Wrong sequence */\r
+ return 0xFFFFFFFF;\r
}\r
do { /* Get trailing bytes */\r
b = (BYTE)*p++;\r
\r
#elif FF_LFN_UNICODE == 3 /* UTF-32 input */\r
uc = (TCHAR)*p++; /* Get a unit */\r
- if (uc >= 0x110000) return 0xFFFFFFFF; /* Wrong code? */\r
+ if (uc >= 0x110000 || IsSurrogate(uc)) return 0xFFFFFFFF; /* Wrong code? */\r
if (uc >= 0x010000) uc = 0xD800DC00 | ((uc - 0x10000) << 6 & 0x3FF0000) | (uc & 0x3FF); /* Make a surrogate pair if needed */\r
\r
#else /* ANSI/OEM input */\r
}\r
\r
\r
-/* Output a TCHAR string in defined API encoding */\r
-static BYTE put_utf ( /* Returns number of encoding units written (0:buffer overflow or wrong encoding) */\r
- DWORD chr, /* UTF-16 encoded character (Double encoding unit char if >=0x10000) */\r
+/* Store a Unicode char in defined API encoding */\r
+static UINT put_utf ( /* Returns number of encoding units written (0:buffer overflow or wrong encoding) */\r
+ DWORD chr, /* UTF-16 encoded character (Surrogate pair if >=0x10000) */\r
TCHAR* buf, /* Output buffer */\r
UINT szb /* Size of the buffer */\r
)\r
/*-----------------------------------------------------------------------*/\r
/* Request/Release grant to access the volume */\r
/*-----------------------------------------------------------------------*/\r
-static int lock_fs ( /* 1:Ok, 0:timeout */\r
- FATFS* fs /* Filesystem object */\r
+\r
+static int lock_volume ( /* 1:Ok, 0:timeout */\r
+ FATFS* fs, /* Filesystem object to lock */\r
+ int syslock /* System lock required */\r
)\r
{\r
- return ff_req_grant(fs->sobj);\r
+ int rv;\r
+\r
+\r
+#if FF_FS_LOCK\r
+ rv = ff_mutex_take(fs->ldrv); /* Lock the volume */\r
+ if (rv && syslock) { /* System lock reqiered? */\r
+ rv = ff_mutex_take(FF_VOLUMES); /* Lock the system */\r
+ if (rv) {\r
+ SysLock = 2; /* System lock succeeded */\r
+ } else {\r
+ ff_mutex_give(fs->ldrv); /* Failed system lock */\r
+ }\r
+ }\r
+#else\r
+ rv = syslock ? ff_mutex_take(fs->ldrv) : ff_mutex_take(fs->ldrv); /* Lock the volume (this is to prevent compiler warning) */\r
+#endif\r
+ return rv;\r
}\r
\r
\r
-static void unlock_fs (\r
+static void unlock_volume (\r
FATFS* fs, /* Filesystem object */\r
FRESULT res /* Result code to be returned */\r
)\r
{\r
if (fs && res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_TIMEOUT) {\r
- ff_rel_grant(fs->sobj);\r
+#if FF_FS_LOCK\r
+ if (SysLock == 2) { /* Is the system locked? */\r
+ SysLock = 1;\r
+ ff_mutex_give(FF_VOLUMES);\r
+ }\r
+#endif\r
+ ff_mutex_give(fs->ldrv); /* Unlock the volume */\r
}\r
}\r
\r
\r
\r
\r
-#if FF_FS_LOCK != 0\r
+#if FF_FS_LOCK\r
/*-----------------------------------------------------------------------*/\r
-/* File lock control functions */\r
+/* File shareing control functions */\r
/*-----------------------------------------------------------------------*/\r
\r
-static FRESULT chk_lock ( /* Check if the file can be accessed */\r
+static FRESULT chk_share ( /* Check if the file can be accessed */\r
DIR* dp, /* Directory object pointing the file to be checked */\r
int acc /* Desired access type (0:Read mode open, 1:Write mode open, 2:Delete or rename) */\r
)\r
}\r
\r
\r
-static int enq_lock (void) /* Check if an entry is available for a new object */\r
+static int enq_share (void) /* Check if an entry is available for a new object */\r
{\r
UINT i;\r
\r
- for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ;\r
+ for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; /* Find a free entry */\r
return (i == FF_FS_LOCK) ? 0 : 1;\r
}\r
\r
\r
-static UINT inc_lock ( /* Increment object open counter and returns its index (0:Internal error) */\r
+static UINT inc_share ( /* Increment object open counter and returns its index (0:Internal error) */\r
DIR* dp, /* Directory object pointing the file to register or increment */\r
int acc /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */\r
)\r
\r
\r
for (i = 0; i < FF_FS_LOCK; i++) { /* Find the object */\r
- if (Files[i].fs == dp->obj.fs &&\r
- Files[i].clu == dp->obj.sclust &&\r
- Files[i].ofs == dp->dptr) break;\r
+ if (Files[i].fs == dp->obj.fs\r
+ && Files[i].clu == dp->obj.sclust\r
+ && Files[i].ofs == dp->dptr) break;\r
}\r
\r
- if (i == FF_FS_LOCK) { /* Not opened. Register it as new. */\r
- for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ;\r
+ if (i == FF_FS_LOCK) { /* Not opened. Register it as new. */\r
+ for (i = 0; i < FF_FS_LOCK && Files[i].fs; i++) ; /* Find a free entry */\r
if (i == FF_FS_LOCK) return 0; /* No free entry to register (int err) */\r
Files[i].fs = dp->obj.fs;\r
Files[i].clu = dp->obj.sclust;\r
}\r
\r
\r
-static FRESULT dec_lock ( /* Decrement object open counter */\r
+static FRESULT dec_share ( /* Decrement object open counter */\r
UINT i /* Semaphore index (1..) */\r
)\r
{\r
- WORD n;\r
+ UINT n;\r
FRESULT res;\r
\r
\r
if (--i < FF_FS_LOCK) { /* Index number origin from 0 */\r
n = Files[i].ctr;\r
- if (n == 0x100) n = 0; /* If write mode open, delete the entry */\r
- if (n > 0) n--; /* Decrement read mode open count */\r
+ if (n == 0x100) n = 0; /* If write mode open, delete the object semaphore */\r
+ if (n > 0) n--; /* Decrement read mode open count */\r
Files[i].ctr = n;\r
- if (n == 0) Files[i].fs = 0; /* Delete the entry if open count gets zero */\r
+ if (n == 0) { /* Delete the object semaphore if open count becomes zero */\r
+ Files[i].fs = 0; /* Free the entry <<<If this memory write operation is not in atomic, FF_FS_REENTRANT == 1 and FF_VOLUMES > 1, there is a potential error in this process >>> */\r
+ }\r
res = FR_OK;\r
} else {\r
- res = FR_INT_ERR; /* Invalid index nunber */\r
+ res = FR_INT_ERR; /* Invalid index number */\r
}\r
return res;\r
}\r
\r
\r
-static void clear_lock ( /* Clear lock entries of the volume */\r
- FATFS *fs\r
+static void clear_share ( /* Clear all lock entries of the volume */\r
+ FATFS* fs\r
)\r
{\r
UINT i;\r
}\r
}\r
\r
-#endif /* FF_FS_LOCK != 0 */\r
+#endif /* FF_FS_LOCK */\r
\r
\r
\r
FRESULT res = FR_OK;\r
\r
\r
- if (fs->wflag) { /* Is the disk access window dirty */\r
- if (disk_write(fs->pdrv, fs->win, fs->winsect, 1) == RES_OK) { /* Write back the window */\r
+ if (fs->wflag) { /* Is the disk access window dirty? */\r
+ if (disk_write(fs->pdrv, fs->win, fs->winsect, 1) == RES_OK) { /* Write it back into the volume */\r
fs->wflag = 0; /* Clear window dirty flag */\r
if (fs->winsect - fs->fatbase < fs->fsize) { /* Is it in the 1st FAT? */\r
if (fs->n_fats == 2) disk_write(fs->pdrv, fs->win, fs->winsect + fs->fsize, 1); /* Reflect it to 2nd FAT if needed */\r
\r
\r
static FRESULT move_window ( /* Returns FR_OK or FR_DISK_ERR */\r
- FATFS* fs, /* Filesystem object */\r
- DWORD sector /* Sector number to make appearance in the fs->win[] */\r
+ FATFS* fs, /* Filesystem object */\r
+ LBA_t sect /* Sector LBA to make appearance in the fs->win[] */\r
)\r
{\r
FRESULT res = FR_OK;\r
\r
\r
- if (sector != fs->winsect) { /* Window offset changed? */\r
+ if (sect != fs->winsect) { /* Window offset changed? */\r
#if !FF_FS_READONLY\r
- res = sync_window(fs); /* Write-back changes */\r
+ res = sync_window(fs); /* Flush the window */\r
#endif\r
if (res == FR_OK) { /* Fill sector window with new data */\r
- if (disk_read(fs->pdrv, fs->win, sector, 1) != RES_OK) {\r
- sector = 0xFFFFFFFF; /* Invalidate window if read data is not valid */\r
+ if (disk_read(fs->pdrv, fs->win, sect, 1) != RES_OK) {\r
+ sect = (LBA_t)0 - 1; /* Invalidate window if read data is not valid */\r
res = FR_DISK_ERR;\r
}\r
- fs->winsect = sector;\r
+ fs->winsect = sect;\r
}\r
}\r
return res;\r
if (res == FR_OK) {\r
if (fs->fs_type == FS_FAT32 && fs->fsi_flag == 1) { /* FAT32: Update FSInfo sector if needed */\r
/* Create FSInfo structure */\r
- mem_set(fs->win, 0, SS(fs));\r
- st_word(fs->win + BS_55AA, 0xAA55);\r
- st_dword(fs->win + FSI_LeadSig, 0x41615252);\r
- st_dword(fs->win + FSI_StrucSig, 0x61417272);\r
- st_dword(fs->win + FSI_Free_Count, fs->free_clst);\r
- st_dword(fs->win + FSI_Nxt_Free, fs->last_clst);\r
- /* Write it into the FSInfo sector */\r
- fs->winsect = fs->volbase + 1;\r
+ memset(fs->win, 0, sizeof fs->win);\r
+ st_word(fs->win + BS_55AA, 0xAA55); /* Boot signature */\r
+ st_dword(fs->win + FSI_LeadSig, 0x41615252); /* Leading signature */\r
+ st_dword(fs->win + FSI_StrucSig, 0x61417272); /* Structure signature */\r
+ st_dword(fs->win + FSI_Free_Count, fs->free_clst); /* Number of free clusters */\r
+ st_dword(fs->win + FSI_Nxt_Free, fs->last_clst); /* Last allocated culuster */\r
+ fs->winsect = fs->volbase + 1; /* Write it into the FSInfo sector (Next to VBR) */\r
disk_write(fs->pdrv, fs->win, fs->winsect, 1);\r
fs->fsi_flag = 0;\r
}\r
/* Get physical sector number from cluster number */\r
/*-----------------------------------------------------------------------*/\r
\r
-static DWORD clst2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */\r
+static LBA_t clst2sect ( /* !=0:Sector number, 0:Failed (invalid cluster#) */\r
FATFS* fs, /* Filesystem object */\r
DWORD clst /* Cluster# to be converted */\r
)\r
{\r
clst -= 2; /* Cluster number is origin from 2 */\r
if (clst >= fs->n_fatent - 2) return 0; /* Is it invalid cluster number? */\r
- return fs->database + fs->csize * clst; /* Start sector number of the cluster */\r
+ return fs->database + (LBA_t)fs->csize * clst; /* Start sector number of the cluster */\r
}\r
\r
\r
\r
\r
/*-----------------------------------------------------------------------*/\r
-/* FAT access - Read value of a FAT entry */\r
+/* FAT access - Read value of an FAT entry */\r
/*-----------------------------------------------------------------------*/\r
\r
static DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Internal error, 2..0x7FFFFFFF:Cluster status */\r
case FS_EXFAT :\r
if ((obj->objsize != 0 && obj->sclust != 0) || obj->stat == 0) { /* Object except root dir must have valid data length */\r
DWORD cofs = clst - obj->sclust; /* Offset from start cluster */\r
- DWORD clen = (DWORD)((obj->objsize - 1) / SS(fs)) / fs->csize; /* Number of clusters - 1 */\r
+ DWORD clen = (DWORD)((LBA_t)((obj->objsize - 1) / SS(fs)) / fs->csize); /* Number of clusters - 1 */\r
\r
if (obj->stat == 2 && cofs <= clen) { /* Is it a contiguous chain? */\r
val = (cofs == clen) ? 0x7FFFFFFF : clst + 1; /* No data on the FAT, generate the value */\r
break;\r
}\r
}\r
- /* go to default */\r
+ val = 1; /* Internal error */\r
+ break;\r
#endif\r
default:\r
val = 1; /* Internal error */\r
\r
#if !FF_FS_READONLY\r
/*-----------------------------------------------------------------------*/\r
-/* FAT access - Change value of a FAT entry */\r
+/* FAT access - Change value of an FAT entry */\r
/*-----------------------------------------------------------------------*/\r
\r
static FRESULT put_fat ( /* FR_OK(0):succeeded, !=0:error */\r
\r
if (clst >= 2 && clst < fs->n_fatent) { /* Check if in valid range */\r
switch (fs->fs_type) {\r
- case FS_FAT12 :\r
+ case FS_FAT12:\r
bc = (UINT)clst; bc += bc / 2; /* bc: byte offset of the entry */\r
res = move_window(fs, fs->fatbase + (bc / SS(fs)));\r
if (res != FR_OK) break;\r
p = fs->win + bc++ % SS(fs);\r
- *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; /* Put 1st byte */\r
+ *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; /* Update 1st byte */\r
fs->wflag = 1;\r
res = move_window(fs, fs->fatbase + (bc / SS(fs)));\r
if (res != FR_OK) break;\r
p = fs->win + bc % SS(fs);\r
- *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); /* Put 2nd byte */\r
+ *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); /* Update 2nd byte */\r
fs->wflag = 1;\r
break;\r
\r
- case FS_FAT16 :\r
+ case FS_FAT16:\r
res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));\r
if (res != FR_OK) break;\r
st_word(fs->win + clst * 2 % SS(fs), (WORD)val); /* Simple WORD array */\r
fs->wflag = 1;\r
break;\r
\r
- case FS_FAT32 :\r
+ case FS_FAT32:\r
#if FF_FS_EXFAT\r
- case FS_EXFAT :\r
+ case FS_EXFAT:\r
#endif\r
res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));\r
if (res != FR_OK) break;\r
if (clst >= fs->n_fatent - 2) clst = 0;\r
scl = val = clst; ctr = 0;\r
for (;;) {\r
- if (move_window(fs, fs->database + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF; /* (assuming bitmap is located top of the cluster heap) */\r
+ if (move_window(fs, fs->bitbase + val / 8 / SS(fs)) != FR_OK) return 0xFFFFFFFF;\r
i = val / 8 % SS(fs); bm = 1 << (val % 8);\r
do {\r
do {\r
{\r
BYTE bm;\r
UINT i;\r
- DWORD sect;\r
+ LBA_t sect;\r
\r
\r
clst -= 2; /* The first bit corresponds to cluster #2 */\r
- sect = fs->database + clst / 8 / SS(fs); /* Sector address (assuming bitmap is located top of the cluster heap) */\r
- i = clst / 8 % SS(fs); /* Byte offset in the sector */\r
- bm = 1 << (clst % 8); /* Bit mask in the byte */\r
+ sect = fs->bitbase + clst / 8 / SS(fs); /* Sector address */\r
+ i = clst / 8 % SS(fs); /* Byte offset in the sector */\r
+ bm = 1 << (clst % 8); /* Bit mask in the byte */\r
for (;;) {\r
if (move_window(fs, sect++) != FR_OK) return FR_DISK_ERR;\r
do {\r
static FRESULT remove_chain ( /* FR_OK(0):succeeded, !=0:error */\r
FFOBJID* obj, /* Corresponding object */\r
DWORD clst, /* Cluster to remove a chain from */\r
- DWORD pclst /* Previous cluster of clst (0:entire chain) */\r
+ DWORD pclst /* Previous cluster of clst (0 if entire chain) */\r
)\r
{\r
FRESULT res = FR_OK;\r
DWORD scl = clst, ecl = clst;\r
#endif\r
#if FF_USE_TRIM\r
- DWORD rt[2];\r
+ LBA_t rt[2];\r
#endif\r
\r
if (clst < 2 || clst >= fs->n_fatent) return FR_INT_ERR; /* Check if in valid range */\r
}\r
#endif\r
#if FF_USE_TRIM\r
- rt[0] = clst2sect(fs, scl); /* Start of data area freed */\r
- rt[1] = clst2sect(fs, ecl) + fs->csize - 1; /* End of data area freed */\r
- disk_ioctl(fs->pdrv, CTRL_TRIM, rt); /* Inform device the data in the block is no longer needed */\r
+ rt[0] = clst2sect(fs, scl); /* Start of data area to be freed */\r
+ rt[1] = clst2sect(fs, ecl) + fs->csize - 1; /* End of data area to be freed */\r
+ disk_ioctl(fs->pdrv, CTRL_TRIM, rt); /* Inform storage device that the data in the block may be erased */\r
#endif\r
scl = ecl = nxt;\r
}\r
FSIZE_t ofs /* File offset to be converted to cluster# */\r
)\r
{\r
- DWORD cl, ncl, *tbl;\r
+ DWORD cl, ncl;\r
+ DWORD *tbl;\r
FATFS *fs = fp->obj.fs;\r
\r
\r
DWORD clst /* Directory table to clear */\r
)\r
{\r
- DWORD sect;\r
+ LBA_t sect;\r
UINT n, szb;\r
BYTE *ibuf;\r
\r
if (sync_window(fs) != FR_OK) return FR_DISK_ERR; /* Flush disk access window */\r
sect = clst2sect(fs, clst); /* Top of the cluster */\r
fs->winsect = sect; /* Set window to top of the cluster */\r
- mem_set(fs->win, 0, SS(fs)); /* Clear window buffer */\r
+ memset(fs->win, 0, sizeof fs->win); /* Clear window buffer */\r
#if FF_USE_LFN == 3 /* Quick table clear by using multi-secter write */\r
/* Allocate a temporary buffer */\r
for (szb = ((DWORD)fs->csize * SS(fs) >= MAX_MALLOC) ? MAX_MALLOC : fs->csize * SS(fs), ibuf = 0; szb > SS(fs) && (ibuf = ff_memalloc(szb)) == 0; szb /= 2) ;\r
if (szb > SS(fs)) { /* Buffer allocated? */\r
- mem_set(ibuf, 0, szb);\r
+ memset(ibuf, 0, szb);\r
szb /= SS(fs); /* Bytes -> Sectors */\r
for (n = 0; n < fs->csize && disk_write(fs->pdrv, ibuf, sect + n, szb) == RES_OK; n += szb) ; /* Fill the cluster with 0 */\r
ff_memfree(ibuf);\r
dp->dptr = ofs; /* Set current offset */\r
clst = dp->obj.sclust; /* Table start cluster (0:root) */\r
if (clst == 0 && fs->fs_type >= FS_FAT32) { /* Replace cluster# 0 with root cluster# */\r
- clst = fs->dirbase;\r
+ clst = (DWORD)fs->dirbase;\r
if (FF_FS_EXFAT) dp->obj.stat = 0; /* exFAT: Root dir has an FAT chain */\r
}\r
\r
\r
static FRESULT dir_alloc ( /* FR_OK(0):succeeded, !=0:error */\r
DIR* dp, /* Pointer to the directory object */\r
- UINT nent /* Number of contiguous entries to allocate */\r
+ UINT n_ent /* Number of contiguous entries to allocate */\r
)\r
{\r
FRESULT res;\r
res = move_window(fs, dp->sect);\r
if (res != FR_OK) break;\r
#if FF_FS_EXFAT\r
- if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) {\r
+ if ((fs->fs_type == FS_EXFAT) ? (int)((dp->dir[XDIR_Type] & 0x80) == 0) : (int)(dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0)) { /* Is the entry free? */\r
#else\r
- if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) {\r
+ if (dp->dir[DIR_Name] == DDEM || dp->dir[DIR_Name] == 0) { /* Is the entry free? */\r
#endif\r
- if (++n == nent) break; /* A block of contiguous free entries is found */\r
+ if (++n == n_ent) break; /* Is a block of contiguous free entries found? */\r
} else {\r
- n = 0; /* Not a blank entry. Restart to search */\r
+ n = 0; /* Not a free entry, restart to search */\r
}\r
- res = dir_next(dp, 1);\r
- } while (res == FR_OK); /* Next entry with table stretch enabled */\r
+ res = dir_next(dp, 1); /* Next entry with table stretch enabled */\r
+ } while (res == FR_OK);\r
}\r
\r
if (res == FR_NO_FILE) res = FR_DENIED; /* No directory entry to allocate */\r
for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */\r
uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */\r
if (wc != 0) {\r
- if (i >= FF_MAX_LFN || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */\r
+ if (i >= FF_MAX_LFN + 1 || ff_wtoupper(uc) != ff_wtoupper(lfnbuf[i++])) { /* Compare it */\r
return 0; /* Not matched */\r
}\r
wc = uc;\r
for (wc = 1, s = 0; s < 13; s++) { /* Process all characters in the entry */\r
uc = ld_word(dir + LfnOfs[s]); /* Pick an LFN character */\r
if (wc != 0) {\r
- if (i >= FF_MAX_LFN) return 0; /* Buffer overflow? */\r
+ if (i >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */\r
lfnbuf[i++] = wc = uc; /* Store it */\r
} else {\r
if (uc != 0xFFFF) return 0; /* Check filler */\r
}\r
}\r
\r
- if (dir[LDIR_Ord] & LLEF) { /* Put terminator if it is the last LFN part */\r
- if (i >= FF_MAX_LFN) return 0; /* Buffer overflow? */\r
+ if (dir[LDIR_Ord] & LLEF && wc != 0) { /* Put terminator if it is the last LFN part and not terminated */\r
+ if (i >= FF_MAX_LFN + 1) return 0; /* Buffer overflow? */\r
lfnbuf[i] = 0;\r
}\r
\r
do {\r
if (wc != 0xFFFF) wc = lfn[i++]; /* Get an effective character */\r
st_word(dir + LfnOfs[s], wc); /* Put it */\r
- if (wc == 0) wc = 0xFFFF; /* Padding characters for left locations */\r
+ if (wc == 0) wc = 0xFFFF; /* Padding characters for following items */\r
} while (++s < 13);\r
if (wc == 0xFFFF || !lfn[i]) ord |= LLEF; /* Last LFN part is the start of LFN sequence */\r
dir[LDIR_Ord] = ord; /* Set the LFN order */\r
\r
static void gen_numname (\r
BYTE* dst, /* Pointer to the buffer to store numbered SFN */\r
- const BYTE* src, /* Pointer to SFN */\r
+ const BYTE* src, /* Pointer to SFN in directory form */\r
const WCHAR* lfn, /* Pointer to LFN */\r
UINT seq /* Sequence number */\r
)\r
BYTE ns[8], c;\r
UINT i, j;\r
WCHAR wc;\r
- DWORD sr;\r
+ DWORD sreg;\r
\r
\r
- mem_cpy(dst, src, 11);\r
+ memcpy(dst, src, 11); /* Prepare the SFN to be modified */\r
\r
if (seq > 5) { /* In case of many collisions, generate a hash number instead of sequential number */\r
- sr = seq;\r
+ sreg = seq;\r
while (*lfn) { /* Create a CRC as hash value */\r
wc = *lfn++;\r
for (i = 0; i < 16; i++) {\r
- sr = (sr << 1) + (wc & 1);\r
+ sreg = (sreg << 1) + (wc & 1);\r
wc >>= 1;\r
- if (sr & 0x10000) sr ^= 0x11021;\r
+ if (sreg & 0x10000) sreg ^= 0x11021;\r
}\r
}\r
- seq = (UINT)sr;\r
+ seq = (UINT)sreg;\r
}\r
\r
- /* itoa (hexdecimal) */\r
+ /* Make suffix (~ + hexadecimal) */\r
i = 7;\r
do {\r
- c = (BYTE)((seq % 16) + '0');\r
+ c = (BYTE)((seq % 16) + '0'); seq /= 16;\r
if (c > '9') c += 7;\r
ns[i--] = c;\r
- seq /= 16;\r
- } while (seq);\r
+ } while (i && seq);\r
ns[i] = '~';\r
\r
- /* Append the number to the SFN body */\r
- for (j = 0; j < i && dst[j] != ' '; j++) {\r
- if (dbc_1st(dst[j])) {\r
+ /* Append the suffix to the SFN body */\r
+ for (j = 0; j < i && dst[j] != ' '; j++) { /* Find the offset to append */\r
+ if (dbc_1st(dst[j])) { /* To avoid DBC break up */\r
if (j == i - 1) break;\r
j++;\r
}\r
}\r
- do {\r
+ do { /* Append the suffix */\r
dst[j++] = (i < 8) ? ns[i++] : ' ';\r
} while (j < 8);\r
}\r
#endif\r
\r
\r
-#if FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2\r
-/*------------------------------------------------------*/\r
-/* exFAT: Get object information from a directory block */\r
-/*------------------------------------------------------*/\r
\r
-static void get_xfileinfo (\r
- BYTE* dirb, /* Pointer to the direcotry entry block 85+C0+C1s */\r
- FILINFO* fno /* Buffer to store the extracted file information */\r
-)\r
-{\r
- WCHAR wc, hs;\r
- UINT di, si, nc;\r
-\r
- /* Get file name from the entry block */\r
- si = SZDIRE * 2; /* 1st C1 entry */\r
- nc = 0; hs = 0; di = 0;\r
- while (nc < dirb[XDIR_NumName]) {\r
- if (si >= MAXDIRB(FF_MAX_LFN)) { di = 0; break; } /* Truncated directory block? */\r
- if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */\r
- wc = ld_word(dirb + si); si += 2; nc++; /* Get a character */\r
- if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */\r
- hs = wc; continue; /* Get low surrogate */\r
- }\r
- wc = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */\r
- if (wc == 0) { di = 0; break; } /* Buffer overflow or wrong encoding? */\r
- di += wc;\r
- hs = 0;\r
- }\r
- if (hs != 0) di = 0; /* Broken surrogate pair? */\r
- if (di == 0) fno->fname[di++] = '?'; /* Inaccessible object name? */\r
- fno->fname[di] = 0; /* Terminate the name */\r
- fno->altname[0] = 0; /* exFAT does not support SFN */\r
-\r
- fno->fattrib = dirb[XDIR_Attr]; /* Attribute */\r
- fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(dirb + XDIR_FileSize); /* Size */\r
- fno->ftime = ld_word(dirb + XDIR_ModTime + 0); /* Time */\r
- fno->fdate = ld_word(dirb + XDIR_ModTime + 2); /* Date */\r
-}\r
-\r
-#endif /* FF_FS_MINIMIZE <= 1 || FF_FS_RPATH >= 2 */\r
-\r
-\r
-/*-----------------------------------*/\r
-/* exFAT: Get a directry entry block */\r
-/*-----------------------------------*/\r
+/*------------------------------------*/\r
+/* exFAT: Get a directory entry block */\r
+/*------------------------------------*/\r
\r
static FRESULT load_xdir ( /* FR_INT_ERR: invalid entry block */\r
- DIR* dp /* Reading direcotry object pointing top of the entry block to load */\r
+ DIR* dp /* Reading directory object pointing top of the entry block to load */\r
)\r
{\r
FRESULT res;\r
UINT i, sz_ent;\r
- BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory direcotry entry block 85+C0+C1s */\r
+ BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the on-memory directory entry block 85+C0+C1s */\r
\r
\r
- /* Load 85 entry */\r
+ /* Load file directory entry */\r
res = move_window(dp->obj.fs, dp->sect);\r
if (res != FR_OK) return res;\r
- if (dp->dir[XDIR_Type] != 0x85) return FR_INT_ERR; /* Invalid order */\r
- mem_cpy(dirb + 0 * SZDIRE, dp->dir, SZDIRE);\r
+ if (dp->dir[XDIR_Type] != ET_FILEDIR) return FR_INT_ERR; /* Invalid order */\r
+ memcpy(dirb + 0 * SZDIRE, dp->dir, SZDIRE);\r
sz_ent = (dirb[XDIR_NumSec] + 1) * SZDIRE;\r
if (sz_ent < 3 * SZDIRE || sz_ent > 19 * SZDIRE) return FR_INT_ERR;\r
\r
- /* Load C0 entry */\r
+ /* Load stream extension entry */\r
res = dir_next(dp, 0);\r
if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */\r
if (res != FR_OK) return res;\r
res = move_window(dp->obj.fs, dp->sect);\r
if (res != FR_OK) return res;\r
- if (dp->dir[XDIR_Type] != 0xC0) return FR_INT_ERR; /* Invalid order */\r
- mem_cpy(dirb + 1 * SZDIRE, dp->dir, SZDIRE);\r
+ if (dp->dir[XDIR_Type] != ET_STREAM) return FR_INT_ERR; /* Invalid order */\r
+ memcpy(dirb + 1 * SZDIRE, dp->dir, SZDIRE);\r
if (MAXDIRB(dirb[XDIR_NumName]) > sz_ent) return FR_INT_ERR;\r
\r
- /* Load C1 entries */\r
- i = 2 * SZDIRE; /* C1 offset to load */\r
+ /* Load file name entries */\r
+ i = 2 * SZDIRE; /* Name offset to load */\r
do {\r
res = dir_next(dp, 0);\r
if (res == FR_NO_FILE) res = FR_INT_ERR; /* It cannot be */\r
if (res != FR_OK) return res;\r
res = move_window(dp->obj.fs, dp->sect);\r
if (res != FR_OK) return res;\r
- if (dp->dir[XDIR_Type] != 0xC1) return FR_INT_ERR; /* Invalid order */\r
- if (i < MAXDIRB(FF_MAX_LFN)) mem_cpy(dirb + i, dp->dir, SZDIRE);\r
+ if (dp->dir[XDIR_Type] != ET_FILENAME) return FR_INT_ERR; /* Invalid order */\r
+ if (i < MAXDIRB(FF_MAX_LFN)) memcpy(dirb + i, dp->dir, SZDIRE);\r
} while ((i += SZDIRE) < sz_ent);\r
\r
/* Sanity check (do it for only accessible object) */\r
/*------------------------------------------------*/\r
\r
static FRESULT load_obj_xdir (\r
- DIR* dp, /* Blank directory object to be used to access containing direcotry */\r
+ DIR* dp, /* Blank directory object to be used to access containing directory */\r
const FFOBJID* obj /* Object with its containing directory information */\r
)\r
{\r
/*----------------------------------------*/\r
\r
static FRESULT store_xdir (\r
- DIR* dp /* Pointer to the direcotry object */\r
+ DIR* dp /* Pointer to the directory object */\r
)\r
{\r
FRESULT res;\r
UINT nent;\r
- BYTE* dirb = dp->obj.fs->dirbuf; /* Pointer to the direcotry entry block 85+C0+C1s */\r
+ BYTE *dirb = dp->obj.fs->dirbuf; /* Pointer to the directory entry block 85+C0+C1s */\r
\r
/* Create set sum */\r
st_word(dirb + XDIR_SetSum, xdir_sum(dirb));\r
nent = dirb[XDIR_NumSec] + 1;\r
\r
- /* Store the direcotry entry block to the directory */\r
+ /* Store the directory entry block to the directory */\r
res = dir_sdi(dp, dp->blk_ofs);\r
while (res == FR_OK) {\r
res = move_window(dp->obj.fs, dp->sect);\r
if (res != FR_OK) break;\r
- mem_cpy(dp->dir, dirb, SZDIRE);\r
+ memcpy(dp->dir, dirb, SZDIRE);\r
dp->obj.fs->wflag = 1;\r
if (--nent == 0) break;\r
dirb += SZDIRE;\r
\r
\r
/*-------------------------------------------*/\r
-/* exFAT: Create a new directory enrty block */\r
+/* exFAT: Create a new directory entry block */\r
/*-------------------------------------------*/\r
\r
static void create_xdir (\r
- BYTE* dirb, /* Pointer to the direcotry entry block buffer */\r
+ BYTE* dirb, /* Pointer to the directory entry block buffer */\r
const WCHAR* lfn /* Pointer to the object name */\r
)\r
{\r
WCHAR wc;\r
\r
\r
- /* Create 85,C0 entry */\r
- mem_set(dirb, 0, 2 * SZDIRE);\r
- dirb[0 * SZDIRE + XDIR_Type] = 0x85; /* 85 entry */\r
- dirb[1 * SZDIRE + XDIR_Type] = 0xC0; /* C0 entry */\r
+ /* Create file-directory and stream-extension entry */\r
+ memset(dirb, 0, 2 * SZDIRE);\r
+ dirb[0 * SZDIRE + XDIR_Type] = ET_FILEDIR;\r
+ dirb[1 * SZDIRE + XDIR_Type] = ET_STREAM;\r
\r
- /* Create C1 entries */\r
- i = SZDIRE * 2; /* Top of C1 entries */\r
+ /* Create file-name entries */\r
+ i = SZDIRE * 2; /* Top of file_name entries */\r
nlen = nc1 = 0; wc = 1;\r
do {\r
- dirb[i++] = 0xC1; dirb[i++] = 0; /* Entry type C1 */\r
+ dirb[i++] = ET_FILENAME; dirb[i++] = 0;\r
do { /* Fill name field */\r
if (wc != 0 && (wc = lfn[nlen]) != 0) nlen++; /* Get a character if exist */\r
- st_word(dirb + i, wc); /* Store it */\r
+ st_word(dirb + i, wc); /* Store it */\r
i += 2;\r
} while (i % SZDIRE != 0);\r
nc1++;\r
/* Read an object from the directory */\r
/*-----------------------------------------------------------------------*/\r
\r
-#define dir_read_file(dp) dir_read(dp, 0)\r
-#define dir_read_label(dp) dir_read(dp, 1)\r
+#define DIR_READ_FILE(dp) dir_read(dp, 0)\r
+#define DIR_READ_LABEL(dp) dir_read(dp, 1)\r
\r
static FRESULT dir_read (\r
DIR* dp, /* Pointer to the directory object */\r
{\r
FRESULT res = FR_NO_FILE;\r
FATFS *fs = dp->obj.fs;\r
- BYTE a, c;\r
+ BYTE attr, b;\r
#if FF_USE_LFN\r
BYTE ord = 0xFF, sum = 0xFF;\r
#endif\r
while (dp->sect) {\r
res = move_window(fs, dp->sect);\r
if (res != FR_OK) break;\r
- c = dp->dir[DIR_Name]; /* Test for the entry type */\r
- if (c == 0) {\r
+ b = dp->dir[DIR_Name]; /* Test for the entry type */\r
+ if (b == 0) {\r
res = FR_NO_FILE; break; /* Reached to end of the directory */\r
}\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */\r
if (FF_USE_LABEL && vol) {\r
- if (c == 0x83) break; /* Volume label entry? */\r
+ if (b == ET_VLABEL) break; /* Volume label entry? */\r
} else {\r
- if (c == 0x85) { /* Start of the file entry block? */\r
+ if (b == ET_FILEDIR) { /* Start of the file entry block? */\r
dp->blk_ofs = dp->dptr; /* Get location of the block */\r
res = load_xdir(dp); /* Load the entry block */\r
if (res == FR_OK) {\r
} else\r
#endif\r
{ /* On the FAT/FAT32 volume */\r
- dp->obj.attr = a = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */\r
+ dp->obj.attr = attr = dp->dir[DIR_Attr] & AM_MASK; /* Get attribute */\r
#if FF_USE_LFN /* LFN configuration */\r
- if (c == DDEM || c == '.' || (int)((a & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */\r
+ if (b == DDEM || b == '.' || (int)((attr & ~AM_ARC) == AM_VOL) != vol) { /* An entry without valid data */\r
ord = 0xFF;\r
} else {\r
- if (a == AM_LFN) { /* An LFN entry is found */\r
- if (c & LLEF) { /* Is it start of an LFN sequence? */\r
+ if (attr == AM_LFN) { /* An LFN entry is found */\r
+ if (b & LLEF) { /* Is it start of an LFN sequence? */\r
sum = dp->dir[LDIR_Chksum];\r
- c &= (BYTE)~LLEF; ord = c;\r
+ b &= (BYTE)~LLEF; ord = b;\r
dp->blk_ofs = dp->dptr;\r
}\r
/* Check LFN validity and capture it */\r
- ord = (c == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;\r
- } else { /* An SFN entry is found */\r
+ ord = (b == ord && sum == dp->dir[LDIR_Chksum] && pick_lfn(fs->lfnbuf, dp->dir)) ? ord - 1 : 0xFF;\r
+ } else { /* An SFN entry is found */\r
if (ord != 0 || sum != sum_sfn(dp->dir)) { /* Is there a valid LFN? */\r
- dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */\r
+ dp->blk_ofs = 0xFFFFFFFF; /* It has no LFN. */\r
}\r
break;\r
}\r
}\r
#else /* Non LFN configuration */\r
- if (c != DDEM && c != '.' && a != AM_LFN && (int)((a & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */\r
+ if (b != DDEM && b != '.' && attr != AM_LFN && (int)((attr & ~AM_ARC) == AM_VOL) == vol) { /* Is it a valid entry? */\r
break;\r
}\r
#endif\r
UINT di, ni;\r
WORD hash = xname_sum(fs->lfnbuf); /* Hash value of the name to find */\r
\r
- while ((res = dir_read_file(dp)) == FR_OK) { /* Read an item */\r
+ while ((res = DIR_READ_FILE(dp)) == FR_OK) { /* Read an item */\r
#if FF_MAX_LFN < 255\r
- if (fs->dirbuf[XDIR_NumName] > FF_MAX_LFN) continue; /* Skip comparison if inaccessible object name */\r
+ if (fs->dirbuf[XDIR_NumName] > FF_MAX_LFN) continue; /* Skip comparison if inaccessible object name */\r
#endif\r
if (ld_word(fs->dirbuf + XDIR_NameHash) != hash) continue; /* Skip comparison if hash mismatched */\r
for (nc = fs->dirbuf[XDIR_NumName], di = SZDIRE * 2, ni = 0; nc; nc--, di += 2, ni++) { /* Compare the name */\r
}\r
} else { /* An SFN entry is found */\r
if (ord == 0 && sum == sum_sfn(dp->dir)) break; /* LFN matched? */\r
- if (!(dp->fn[NSFLAG] & NS_LOSS) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */\r
+ if (!(dp->fn[NSFLAG] & NS_LOSS) && !memcmp(dp->dir, dp->fn, 11)) break; /* SFN matched? */\r
ord = 0xFF; dp->blk_ofs = 0xFFFFFFFF; /* Reset LFN sequence */\r
}\r
}\r
#else /* Non LFN configuration */\r
dp->obj.attr = dp->dir[DIR_Attr] & AM_MASK;\r
- if (!(dp->dir[DIR_Attr] & AM_VOL) && !mem_cmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */\r
+ if (!(dp->dir[DIR_Attr] & AM_VOL) && !memcmp(dp->dir, dp->fn, 11)) break; /* Is it a valid entry? */\r
#endif\r
res = dir_next(dp, 0); /* Next entry */\r
} while (res == FR_OK);\r
FRESULT res;\r
FATFS *fs = dp->obj.fs;\r
#if FF_USE_LFN /* LFN configuration */\r
- UINT n, nlen, nent;\r
+ UINT n, len, n_ent;\r
BYTE sn[12], sum;\r
\r
\r
if (dp->fn[NSFLAG] & (NS_DOT | NS_NONAME)) return FR_INVALID_NAME; /* Check name validity */\r
- for (nlen = 0; fs->lfnbuf[nlen]; nlen++) ; /* Get lfn length */\r
+ for (len = 0; fs->lfnbuf[len]; len++) ; /* Get lfn length */\r
\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */\r
- nent = (nlen + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */\r
- res = dir_alloc(dp, nent); /* Allocate entries */\r
+ n_ent = (len + 14) / 15 + 2; /* Number of entries to allocate (85+C0+C1s) */\r
+ res = dir_alloc(dp, n_ent); /* Allocate directory entries */\r
if (res != FR_OK) return res;\r
- dp->blk_ofs = dp->dptr - SZDIRE * (nent - 1); /* Set the allocated entry block offset */\r
+ dp->blk_ofs = dp->dptr - SZDIRE * (n_ent - 1); /* Set the allocated entry block offset */\r
\r
- if (dp->obj.stat & 4) { /* Has the directory been stretched? */\r
+ if (dp->obj.stat & 4) { /* Has the directory been stretched by new allocation? */\r
dp->obj.stat &= ~4;\r
res = fill_first_frag(&dp->obj); /* Fill the first fragment on the FAT if needed */\r
if (res != FR_OK) return res;\r
res = fill_last_frag(&dp->obj, dp->clust, 0xFFFFFFFF); /* Fill the last fragment on the FAT if needed */\r
if (res != FR_OK) return res;\r
- if (dp->obj.sclust != 0) { /* Is it a sub directory? */\r
+ if (dp->obj.sclust != 0) { /* Is it a sub-directory? */\r
DIR dj;\r
\r
res = load_obj_xdir(&dj, &dp->obj); /* Load the object status */\r
if (res != FR_OK) return res;\r
- dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */\r
- st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize); /* Update the allocation status */\r
+ dp->obj.objsize += (DWORD)fs->csize * SS(fs); /* Increase the directory size by cluster size */\r
+ st_qword(fs->dirbuf + XDIR_FileSize, dp->obj.objsize);\r
st_qword(fs->dirbuf + XDIR_ValidFileSize, dp->obj.objsize);\r
- fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1;\r
+ fs->dirbuf[XDIR_GenFlags] = dp->obj.stat | 1; /* Update the allocation status */\r
res = store_xdir(&dj); /* Store the object status */\r
if (res != FR_OK) return res;\r
}\r
}\r
#endif\r
/* On the FAT/FAT32 volume */\r
- mem_cpy(sn, dp->fn, 12);\r
+ memcpy(sn, dp->fn, 12);\r
if (sn[NSFLAG] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */\r
dp->fn[NSFLAG] = NS_NOLFN; /* Find only SFN */\r
for (n = 1; n < 100; n++) {\r
}\r
\r
/* Create an SFN with/without LFNs. */\r
- nent = (sn[NSFLAG] & NS_LFN) ? (nlen + 12) / 13 + 1 : 1; /* Number of entries to allocate */\r
- res = dir_alloc(dp, nent); /* Allocate entries */\r
- if (res == FR_OK && --nent) { /* Set LFN entry if needed */\r
- res = dir_sdi(dp, dp->dptr - nent * SZDIRE);\r
+ n_ent = (sn[NSFLAG] & NS_LFN) ? (len + 12) / 13 + 1 : 1; /* Number of entries to allocate */\r
+ res = dir_alloc(dp, n_ent); /* Allocate entries */\r
+ if (res == FR_OK && --n_ent) { /* Set LFN entry if needed */\r
+ res = dir_sdi(dp, dp->dptr - n_ent * SZDIRE);\r
if (res == FR_OK) {\r
sum = sum_sfn(dp->fn); /* Checksum value of the SFN tied to the LFN */\r
do { /* Store LFN entries in bottom first */\r
res = move_window(fs, dp->sect);\r
if (res != FR_OK) break;\r
- put_lfn(fs->lfnbuf, dp->dir, (BYTE)nent, sum);\r
+ put_lfn(fs->lfnbuf, dp->dir, (BYTE)n_ent, sum);\r
fs->wflag = 1;\r
res = dir_next(dp, 0); /* Next entry */\r
- } while (res == FR_OK && --nent);\r
+ } while (res == FR_OK && --n_ent);\r
}\r
}\r
\r
if (res == FR_OK) {\r
res = move_window(fs, dp->sect);\r
if (res == FR_OK) {\r
- mem_set(dp->dir, 0, SZDIRE); /* Clean the entry */\r
- mem_cpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */\r
+ memset(dp->dir, 0, SZDIRE); /* Clean the entry */\r
+ memcpy(dp->dir + DIR_Name, dp->fn, 11); /* Put SFN */\r
#if FF_USE_LFN\r
dp->dir[DIR_NTres] = dp->fn[NSFLAG] & (NS_BODY | NS_EXT); /* Put NT flag */\r
#endif\r
if (res != FR_OK) break;\r
if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) { /* On the exFAT volume */\r
dp->dir[XDIR_Type] &= 0x7F; /* Clear the entry InUse flag. */\r
- } else { /* On the FAT/FAT32 volume */\r
+ } else { /* On the FAT/FAT32 volume */\r
dp->dir[DIR_Name] = DDEM; /* Mark the entry 'deleted'. */\r
}\r
fs->wflag = 1;\r
{\r
UINT si, di;\r
#if FF_USE_LFN\r
+ BYTE lcf;\r
WCHAR wc, hs;\r
FATFS *fs = dp->obj.fs;\r
+ UINT nw;\r
#else\r
TCHAR c;\r
#endif\r
\r
#if FF_USE_LFN /* LFN configuration */\r
#if FF_FS_EXFAT\r
- if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */\r
- get_xfileinfo(fs->dirbuf, fno);\r
+ if (fs->fs_type == FS_EXFAT) { /* exFAT volume */\r
+ UINT nc = 0;\r
+\r
+ si = SZDIRE * 2; di = 0; /* 1st C1 entry in the entry block */\r
+ hs = 0;\r
+ while (nc < fs->dirbuf[XDIR_NumName]) {\r
+ if (si >= MAXDIRB(FF_MAX_LFN)) { /* Truncated directory block? */\r
+ di = 0; break;\r
+ }\r
+ if ((si % SZDIRE) == 0) si += 2; /* Skip entry type field */\r
+ wc = ld_word(fs->dirbuf + si); si += 2; nc++; /* Get a character */\r
+ if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */\r
+ hs = wc; continue; /* Get low surrogate */\r
+ }\r
+ nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */\r
+ if (nw == 0) { /* Buffer overflow or wrong char? */\r
+ di = 0; break;\r
+ }\r
+ di += nw;\r
+ hs = 0;\r
+ }\r
+ if (hs != 0) di = 0; /* Broken surrogate pair? */\r
+ if (di == 0) fno->fname[di++] = '\?'; /* Inaccessible object name? */\r
+ fno->fname[di] = 0; /* Terminate the name */\r
+ fno->altname[0] = 0; /* exFAT does not support SFN */\r
+\r
+ fno->fattrib = fs->dirbuf[XDIR_Attr] & AM_MASKX; /* Attribute */\r
+ fno->fsize = (fno->fattrib & AM_DIR) ? 0 : ld_qword(fs->dirbuf + XDIR_FileSize); /* Size */\r
+ fno->ftime = ld_word(fs->dirbuf + XDIR_ModTime + 0); /* Time */\r
+ fno->fdate = ld_word(fs->dirbuf + XDIR_ModTime + 2); /* Date */\r
return;\r
} else\r
#endif\r
- { /* On the FAT/FAT32 volume */\r
+ { /* FAT/FAT32 volume */\r
if (dp->blk_ofs != 0xFFFFFFFF) { /* Get LFN if available */\r
- si = di = hs = 0;\r
+ si = di = 0;\r
+ hs = 0;\r
while (fs->lfnbuf[si] != 0) {\r
wc = fs->lfnbuf[si++]; /* Get an LFN character (UTF-16) */\r
if (hs == 0 && IsSurrogate(wc)) { /* Is it a surrogate? */\r
hs = wc; continue; /* Get low surrogate */\r
}\r
- wc = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in UTF-16 or UTF-8 encoding */\r
- if (wc == 0) { di = 0; break; } /* Invalid char or buffer overflow? */\r
- di += wc;\r
+ nw = put_utf((DWORD)hs << 16 | wc, &fno->fname[di], FF_LFN_BUF - di); /* Store it in API encoding */\r
+ if (nw == 0) { /* Buffer overflow or wrong char? */\r
+ di = 0; break;\r
+ }\r
+ di += nw;\r
hs = 0;\r
}\r
if (hs != 0) di = 0; /* Broken surrogate pair? */\r
wc = wc << 8 | dp->dir[si++];\r
}\r
wc = ff_oem2uni(wc, CODEPAGE); /* ANSI/OEM -> Unicode */\r
- if (wc == 0) { di = 0; break; } /* Wrong char in the current code page? */\r
- wc = put_utf(wc, &fno->altname[di], FF_SFN_BUF - di); /* Store it in Unicode */\r
- if (wc == 0) { di = 0; break; } /* Buffer overflow? */\r
- di += wc;\r
+ if (wc == 0) { /* Wrong char in the current code page? */\r
+ di = 0; break;\r
+ }\r
+ nw = put_utf(wc, &fno->altname[di], FF_SFN_BUF - di); /* Store it in API encoding */\r
+ if (nw == 0) { /* Buffer overflow? */\r
+ di = 0; break;\r
+ }\r
+ di += nw;\r
#else /* ANSI/OEM output */\r
fno->altname[di++] = (TCHAR)wc; /* Store it without any conversion */\r
#endif\r
fno->altname[di] = 0; /* Terminate the SFN (null string means SFN is invalid) */\r
\r
if (fno->fname[0] == 0) { /* If LFN is invalid, altname[] needs to be copied to fname[] */\r
- if (di == 0) { /* If LFN and SFN both are invalid, this object is inaccesible */\r
- fno->fname[di++] = '?';\r
+ if (di == 0) { /* If LFN and SFN both are invalid, this object is inaccessible */\r
+ fno->fname[di++] = '\?';\r
} else {\r
- for (si = di = 0; fno->altname[si]; si++, di++) { /* Copy altname[] to fname[] with case information */\r
+ for (si = di = 0, lcf = NS_BODY; fno->altname[si]; si++, di++) { /* Copy altname[] to fname[] with case information */\r
wc = (WCHAR)fno->altname[si];\r
- if (IsUpper(wc) && (dp->dir[DIR_NTres] & ((si >= 9) ? NS_EXT : NS_BODY))) wc += 0x20;\r
+ if (wc == '.') lcf = NS_EXT;\r
+ if (IsUpper(wc) && (dp->dir[DIR_NTres] & lcf)) wc += 0x20;\r
fno->fname[di] = (TCHAR)wc;\r
}\r
}\r
if (si == 9) fno->fname[di++] = '.';/* Insert a . if extension is exist */\r
fno->fname[di++] = c;\r
}\r
- fno->fname[di] = 0;\r
+ fno->fname[di] = 0; /* Terminate the SFN */\r
#endif\r
\r
- fno->fattrib = dp->dir[DIR_Attr]; /* Attribute */\r
+ fno->fattrib = dp->dir[DIR_Attr] & AM_MASK; /* Attribute */\r
fno->fsize = ld_dword(dp->dir + DIR_FileSize); /* Size */\r
fno->ftime = ld_word(dp->dir + DIR_ModTime + 0); /* Time */\r
fno->fdate = ld_word(dp->dir + DIR_ModTime + 2); /* Date */\r
/* Pattern matching */\r
/*-----------------------------------------------------------------------*/\r
\r
-static DWORD get_achar ( /* Get a character and advances ptr */\r
+#define FIND_RECURS 4 /* Maximum number of wildcard terms in the pattern to limit recursion */\r
+\r
+\r
+static DWORD get_achar ( /* Get a character and advance ptr */\r
const TCHAR** ptr /* Pointer to pointer to the ANSI/OEM or Unicode string */\r
)\r
{\r
}\r
\r
\r
-static int pattern_matching ( /* 0:not matched, 1:matched */\r
+static int pattern_match ( /* 0:mismatched, 1:matched */\r
const TCHAR* pat, /* Matching pattern */\r
const TCHAR* nam, /* String to be tested */\r
- int skip, /* Number of pre-skip chars (number of ?s) */\r
- int inf /* Infinite search (* specified) */\r
+ UINT skip, /* Number of pre-skip chars (number of ?s, b8:infinite (* specified)) */\r
+ UINT recur /* Recursion count */\r
)\r
{\r
- const TCHAR *pp, *np;\r
- DWORD pc, nc;\r
- int nm, nx;\r
+ const TCHAR *pptr;\r
+ const TCHAR *nptr;\r
+ DWORD pchr, nchr;\r
+ UINT sk;\r
\r
\r
- while (skip--) { /* Pre-skip name chars */\r
+ while ((skip & 0xFF) != 0) { /* Pre-skip name chars */\r
if (!get_achar(&nam)) return 0; /* Branch mismatched if less name chars */\r
+ skip--;\r
}\r
- if (*pat == 0 && inf) return 1; /* (short circuit) */\r
+ if (*pat == 0 && skip) return 1; /* Matched? (short circuit) */\r
\r
do {\r
- pp = pat; np = nam; /* Top of pattern and name to match */\r
+ pptr = pat; nptr = nam; /* Top of pattern and name to match */\r
for (;;) {\r
- if (*pp == '?' || *pp == '*') { /* Wildcard? */\r
- nm = nx = 0;\r
- do { /* Analyze the wildcard block */\r
- if (*pp++ == '?') nm++; else nx = 1;\r
- } while (*pp == '?' || *pp == '*');\r
- if (pattern_matching(pp, np, nm, nx)) return 1; /* Test new branch (recurs upto number of wildcard blocks in the pattern) */\r
- nc = *np; break; /* Branch mismatched */\r
- }\r
- pc = get_achar(&pp); /* Get a pattern char */\r
- nc = get_achar(&np); /* Get a name char */\r
- if (pc != nc) break; /* Branch mismatched? */\r
- if (pc == 0) return 1; /* Branch matched? (matched at end of both strings) */\r
+ if (*pptr == '\?' || *pptr == '*') { /* Wildcard term? */\r
+ if (recur == 0) return 0; /* Too many wildcard terms? */\r
+ sk = 0;\r
+ do { /* Analyze the wildcard term */\r
+ if (*pptr++ == '\?') {\r
+ sk++;\r
+ } else {\r
+ sk |= 0x100;\r
+ }\r
+ } while (*pptr == '\?' || *pptr == '*');\r
+ if (pattern_match(pptr, nptr, sk, recur - 1)) return 1; /* Test new branch (recursive call) */\r
+ nchr = *nptr; break; /* Branch mismatched */\r
+ }\r
+ pchr = get_achar(&pptr); /* Get a pattern char */\r
+ nchr = get_achar(&nptr); /* Get a name char */\r
+ if (pchr != nchr) break; /* Branch mismatched? */\r
+ if (pchr == 0) return 1; /* Branch matched? (matched at end of both strings) */\r
}\r
get_achar(&nam); /* nam++ */\r
- } while (inf && nc); /* Retry until end of name if infinite search is specified */\r
+ } while (skip && nchr); /* Retry until end of name if infinite search is specified */\r
\r
return 0;\r
}\r
{\r
#if FF_USE_LFN /* LFN configuration */\r
BYTE b, cf;\r
- WCHAR wc, *lfn;\r
+ WCHAR wc;\r
+ WCHAR *lfn;\r
+ const TCHAR* p;\r
DWORD uc;\r
UINT i, ni, si, di;\r
- const TCHAR *p;\r
\r
\r
/* Create LFN into LFN working buffer */\r
if (uc == 0xFFFFFFFF) return FR_INVALID_NAME; /* Invalid code or UTF decode error */\r
if (uc >= 0x10000) lfn[di++] = (WCHAR)(uc >> 16); /* Store high surrogate if needed */\r
wc = (WCHAR)uc;\r
- if (wc < ' ' || wc == '/' || wc == '\\') break; /* Break if end of the path or a separator is found */\r
- if (wc < 0x80 && chk_chr("\"*:<>\?|\x7F", wc)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */\r
+ if (wc < ' ' || IsSeparator(wc)) break; /* Break if end of the path or a separator is found */\r
+ if (wc < 0x80 && strchr("*:<>|\"\?\x7F", (int)wc)) return FR_INVALID_NAME; /* Reject illegal characters for LFN */\r
if (di >= FF_MAX_LFN) return FR_INVALID_NAME; /* Reject too long name */\r
- lfn[di++] = wc; /* Store the Unicode character */\r
+ lfn[di++] = wc; /* Store the Unicode character */\r
}\r
- while (*p == '/' || *p == '\\') p++; /* Skip duplicated separators if exist */\r
- *path = p; /* Return pointer to the next segment */\r
- cf = (wc < ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */\r
+ if (wc < ' ') { /* Stopped at end of the path? */\r
+ cf = NS_LAST; /* Last segment */\r
+ } else { /* Stopped at a separator */\r
+ while (IsSeparator(*p)) p++; /* Skip duplicated separators if exist */\r
+ cf = 0; /* Next segment may follow */\r
+ if (IsTerminator(*p)) cf = NS_LAST; /* Ignore terminating separator */\r
+ }\r
+ *path = p; /* Return pointer to the next segment */\r
\r
#if FF_FS_RPATH != 0\r
if ((di == 1 && lfn[di - 1] == '.') ||\r
(di == 2 && lfn[di - 1] == '.' && lfn[di - 2] == '.')) { /* Is this segment a dot name? */\r
lfn[di] = 0;\r
- for (i = 0; i < 11; i++) { /* Create dot name for SFN entry */\r
+ for (i = 0; i < 11; i++) { /* Create dot name for SFN entry */\r
dp->fn[i] = (i < di) ? '.' : ' ';\r
}\r
- dp->fn[i] = cf | NS_DOT; /* This is a dot entry */\r
+ dp->fn[i] = cf | NS_DOT; /* This is a dot entry */\r
return FR_OK;\r
}\r
#endif\r
- while (di) { /* Snip off trailing spaces and dots if exist */\r
+ while (di) { /* Snip off trailing spaces and dots if exist */\r
wc = lfn[di - 1];\r
if (wc != ' ' && wc != '.') break;\r
di--;\r
if (si > 0 || lfn[si] == '.') cf |= NS_LOSS | NS_LFN; /* Is there any leading space or dot? */\r
while (di > 0 && lfn[di - 1] != '.') di--; /* Find last dot (di<=si: no extension) */\r
\r
- mem_set(dp->fn, ' ', 11);\r
+ memset(dp->fn, ' ', 11);\r
i = b = 0; ni = 8;\r
for (;;) {\r
wc = lfn[si++]; /* Get an LFN character */\r
continue;\r
}\r
\r
- if (wc >= 0x80) { /* Is this a non-ASCII character? */\r
+ if (wc >= 0x80) { /* Is this an extended character? */\r
cf |= NS_LFN; /* LFN entry needs to be created */\r
#if FF_CODE_PAGE == 0\r
- if (ExCvt) { /* At SBCS */\r
+ if (ExCvt) { /* In SBCS cfg */\r
wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */\r
if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */\r
- } else { /* At DBCS */\r
- wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Upper convert ==> ANSI/OEM code */\r
+ } else { /* In DBCS cfg */\r
+ wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */\r
}\r
-#elif FF_CODE_PAGE < 900 /* SBCS cfg */\r
+#elif FF_CODE_PAGE < 900 /* In SBCS cfg */\r
wc = ff_uni2oem(wc, CODEPAGE); /* Unicode ==> ANSI/OEM code */\r
if (wc & 0x80) wc = ExCvt[wc & 0x7F]; /* Convert extended character to upper (SBCS) */\r
-#else /* DBCS cfg */\r
- wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Upper convert ==> ANSI/OEM code */\r
+#else /* In DBCS cfg */\r
+ wc = ff_uni2oem(ff_wtoupper(wc), CODEPAGE); /* Unicode ==> Up-convert ==> ANSI/OEM code */\r
#endif\r
}\r
\r
}\r
dp->fn[i++] = (BYTE)(wc >> 8); /* Put 1st byte */\r
} else { /* SBC */\r
- if (wc == 0 || chk_chr("+,;=[]", wc)) { /* Replace illegal characters for SFN if needed */\r
+ if (wc == 0 || strchr("+,;=[]", (int)wc)) { /* Replace illegal characters for SFN */\r
wc = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */\r
} else {\r
if (IsUpper(wc)) { /* ASCII upper case? */\r
\r
\r
#else /* FF_USE_LFN : Non-LFN configuration */\r
- BYTE c, d, *sfn;\r
+ BYTE c, d;\r
+ BYTE *sfn;\r
UINT ni, si, i;\r
const char *p;\r
\r
/* Create file name in directory form */\r
p = *path; sfn = dp->fn;\r
- mem_set(sfn, ' ', 11);\r
+ memset(sfn, ' ', 11);\r
si = i = 0; ni = 8;\r
#if FF_FS_RPATH != 0\r
if (p[si] == '.') { /* Is this a dot entry? */\r
if (c != '.' || si >= 3) break;\r
sfn[i++] = c;\r
}\r
- if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;\r
- *path = p + si; /* Return pointer to the next segment */\r
+ if (!IsSeparator(c) && c > ' ') return FR_INVALID_NAME;\r
+ *path = p + si; /* Return pointer to the next segment */\r
sfn[NSFLAG] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT; /* Set last segment flag if end of the path */\r
return FR_OK;\r
}\r
for (;;) {\r
c = (BYTE)p[si++]; /* Get a byte */\r
if (c <= ' ') break; /* Break if end of the path name */\r
- if (c == '/' || c == '\\') { /* Break if a separator is found */\r
- while (p[si] == '/' || p[si] == '\\') si++; /* Skip duplicated separator if exist */\r
+ if (IsSeparator(c)) { /* Break if a separator is found */\r
+ while (IsSeparator(p[si])) si++; /* Skip duplicated separator if exist */\r
break;\r
}\r
if (c == '.' || i >= ni) { /* End of body or field overflow? */\r
sfn[i++] = c;\r
sfn[i++] = d;\r
} else { /* SBC */\r
- if (chk_chr("\"*+,:;<=>\?[]|\x7F", c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */\r
+ if (strchr("*+,:;<=>[]|\"\?\x7F", (int)c)) return FR_INVALID_NAME; /* Reject illegal chrs for SFN */\r
if (IsLower(c)) c -= 0x20; /* To upper */\r
sfn[i++] = c;\r
}\r
}\r
- *path = p + si; /* Return pointer to the next segment */\r
+ *path = &p[si]; /* Return pointer to the next segment */\r
if (i == 0) return FR_INVALID_NAME; /* Reject nul string */\r
\r
if (sfn[0] == DDEM) sfn[0] = RDDEM; /* If the first character collides with DDEM, replace it with RDDEM */\r
- sfn[NSFLAG] = (c <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */\r
+ sfn[NSFLAG] = (c <= ' ' || p[si] <= ' ') ? NS_LAST : 0; /* Set last segment flag if end of the path */\r
\r
return FR_OK;\r
#endif /* FF_USE_LFN */\r
\r
\r
#if FF_FS_RPATH != 0\r
- if (*path != '/' && *path != '\\') { /* Without heading separator */\r
- dp->obj.sclust = fs->cdir; /* Start from current directory */\r
+ if (!IsSeparator(*path) && (FF_STR_VOLUME_ID != 2 || !IsTerminator(*path))) { /* Without heading separator */\r
+ dp->obj.sclust = fs->cdir; /* Start at the current directory */\r
} else\r
#endif\r
{ /* With heading separator */\r
- while (*path == '/' || *path == '\\') path++; /* Strip heading separator */\r
- dp->obj.sclust = 0; /* Start from root directory */\r
+ while (IsSeparator(*path)) path++; /* Strip separators */\r
+ dp->obj.sclust = 0; /* Start from the root directory */\r
}\r
#if FF_FS_EXFAT\r
dp->obj.n_frag = 0; /* Invalidate last fragment counter of the object */\r
}\r
break;\r
}\r
- if (ns & NS_LAST) break; /* Last segment matched. Function completed. */\r
+ if (ns & NS_LAST) break; /* Last segment matched. Function completed. */\r
/* Get into the sub-directory */\r
- if (!(dp->obj.attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */\r
+ if (!(dp->obj.attr & AM_DIR)) { /* It is not a sub-directory and cannot follow */\r
res = FR_NO_PATH; break;\r
}\r
#if FF_FS_EXFAT\r
- if (fs->fs_type == FS_EXFAT) { /* Save containing directory information for next dir */\r
+ if (fs->fs_type == FS_EXFAT) { /* Save containing directory information for next dir */\r
dp->obj.c_scl = dp->obj.sclust;\r
dp->obj.c_size = ((DWORD)dp->obj.objsize & 0xFFFFFF00) | dp->obj.stat;\r
dp->obj.c_ofs = dp->blk_ofs;\r
const TCHAR** path /* Pointer to pointer to the path name */\r
)\r
{\r
- const TCHAR *tp, *tt;\r
+ const TCHAR *tp;\r
+ const TCHAR *tt;\r
TCHAR tc;\r
- int i, vol = -1;\r
+ int i;\r
+ int vol = -1;\r
#if FF_STR_VOLUME_ID /* Find string volume ID */\r
const char *sp;\r
char c;\r
\r
tt = tp = *path;\r
if (!tp) return vol; /* Invalid path name? */\r
- do tc = *tt++; while ((UINT)tc >= (FF_USE_LFN ? ' ' : '!') && tc != ':'); /* Find a colon in the path */\r
+ do { /* Find a colon in the path */\r
+ tc = *tt++;\r
+ } while (!IsTerminator(tc) && tc != ':');\r
\r
if (tc == ':') { /* DOS/Windows style volume ID? */\r
i = FF_VOLUMES;\r
return vol;\r
}\r
#if FF_STR_VOLUME_ID == 2 /* Unix style volume ID is enabled */\r
- if (*tp == '/') {\r
+ if (*tp == '/') { /* Is there a volume ID? */\r
+ while (*(tp + 1) == '/') tp++; /* Skip duplicated separator */\r
i = 0;\r
do {\r
- sp = VolumeStr[i]; tp = *path; /* This string volume ID and path name */\r
+ tt = tp; sp = VolumeStr[i]; /* Path name and this string volume ID */\r
do { /* Compare the volume ID with path name */\r
- c = *sp++; tc = *(++tp);\r
+ c = *sp++; tc = *(++tt);\r
if (IsLower(c)) c -= 0x20;\r
if (IsLower(tc)) tc -= 0x20;\r
} while (c && (TCHAR)c == tc);\r
- } while ((c || (tc != '/' && (UINT)tc >= (FF_USE_LFN ? ' ' : '!'))) && ++i < FF_VOLUMES); /* Repeat for each ID until pattern match */\r
+ } while ((c || (tc != '/' && !IsTerminator(tc))) && ++i < FF_VOLUMES); /* Repeat for each ID until pattern match */\r
if (i < FF_VOLUMES) { /* If a volume ID is found, get the drive number and strip it */\r
vol = i; /* Drive number */\r
- *path = tp; /* Snip the drive prefix off */\r
- return vol;\r
+ *path = tt; /* Snip the drive prefix off */\r
}\r
+ return vol;\r
}\r
#endif\r
/* No drive prefix is found */\r
\r
\r
\r
+/*-----------------------------------------------------------------------*/\r
+/* GPT support functions */\r
+/*-----------------------------------------------------------------------*/\r
+\r
+#if FF_LBA64\r
+\r
+/* Calculate CRC32 in byte-by-byte */\r
+\r
+static DWORD crc32 ( /* Returns next CRC value */\r
+ DWORD crc, /* Current CRC value */\r
+ BYTE d /* A byte to be processed */\r
+)\r
+{\r
+ BYTE b;\r
+\r
+\r
+ for (b = 1; b; b <<= 1) {\r
+ crc ^= (d & b) ? 1 : 0;\r
+ crc = (crc & 1) ? crc >> 1 ^ 0xEDB88320 : crc >> 1;\r
+ }\r
+ return crc;\r
+}\r
+\r
+\r
+/* Check validity of GPT header */\r
+\r
+static int test_gpt_header ( /* 0:Invalid, 1:Valid */\r
+ const BYTE* gpth /* Pointer to the GPT header */\r
+)\r
+{\r
+ UINT i;\r
+ DWORD bcc, hlen;\r
+\r
+\r
+ if (memcmp(gpth + GPTH_Sign, "EFI PART" "\0\0\1", 12)) return 0; /* Check signature and version (1.0) */\r
+ hlen = ld_dword(gpth + GPTH_Size); /* Check header size */\r
+ if (hlen < 92 || hlen > FF_MIN_SS) return 0;\r
+ for (i = 0, bcc = 0xFFFFFFFF; i < hlen; i++) { /* Check header BCC */\r
+ bcc = crc32(bcc, i - GPTH_Bcc < 4 ? 0 : gpth[i]);\r
+ }\r
+ if (~bcc != ld_dword(gpth + GPTH_Bcc)) return 0;\r
+ if (ld_dword(gpth + GPTH_PteSize) != SZ_GPTE) return 0; /* Table entry size (must be SZ_GPTE bytes) */\r
+ if (ld_dword(gpth + GPTH_PtNum) > 128) return 0; /* Table size (must be 128 entries or less) */\r
+\r
+ return 1;\r
+}\r
+\r
+#if !FF_FS_READONLY && FF_USE_MKFS\r
+\r
+/* Generate random value */\r
+static DWORD make_rand (\r
+ DWORD seed, /* Seed value */\r
+ BYTE *buff, /* Output buffer */\r
+ UINT n /* Data length */\r
+)\r
+{\r
+ UINT r;\r
+\r
+\r
+ if (seed == 0) seed = 1;\r
+ do {\r
+ for (r = 0; r < 8; r++) seed = seed & 1 ? seed >> 1 ^ 0xA3000000 : seed >> 1; /* Shift 8 bits the 32-bit LFSR */\r
+ *buff++ = (BYTE)seed;\r
+ } while (--n);\r
+ return seed;\r
+}\r
+\r
+#endif\r
+#endif\r
+\r
+\r
+\r
/*-----------------------------------------------------------------------*/\r
/* Load a sector and check if it is an FAT VBR */\r
/*-----------------------------------------------------------------------*/\r
\r
-static BYTE check_fs ( /* 0:FAT, 1:exFAT, 2:Valid BS but not FAT, 3:Not a BS, 4:Disk error */\r
+/* Check what the sector is */\r
+\r
+static UINT check_fs ( /* 0:FAT/FAT32 VBR, 1:exFAT VBR, 2:Not FAT and valid BS, 3:Not FAT and invalid BS, 4:Disk error */\r
FATFS* fs, /* Filesystem object */\r
- DWORD sect /* Sector# (lba) to load and check if it is an FAT-VBR or not */\r
+ LBA_t sect /* Sector to load and check if it is an FAT-VBR or not */\r
)\r
{\r
- fs->wflag = 0; fs->winsect = 0xFFFFFFFF; /* Invaidate window */\r
- if (move_window(fs, sect) != FR_OK) return 4; /* Load boot record */\r
+ WORD w, sign;\r
+ BYTE b;\r
\r
- if (ld_word(fs->win + BS_55AA) != 0xAA55) return 3; /* Check boot record signature (always here regardless of the sector size) */\r
\r
+ fs->wflag = 0; fs->winsect = (LBA_t)0 - 1; /* Invaidate window */\r
+ if (move_window(fs, sect) != FR_OK) return 4; /* Load the boot sector */\r
+ sign = ld_word(fs->win + BS_55AA);\r
#if FF_FS_EXFAT\r
- if (!mem_cmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1; /* Check if exFAT VBR */\r
+ if (sign == 0xAA55 && !memcmp(fs->win + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11)) return 1; /* It is an exFAT VBR */\r
+#endif\r
+ b = fs->win[BS_JmpBoot];\r
+ if (b == 0xEB || b == 0xE9 || b == 0xE8) { /* Valid JumpBoot code? (short jump, near jump or near call) */\r
+ if (sign == 0xAA55 && !memcmp(fs->win + BS_FilSysType32, "FAT32 ", 8)) {\r
+ return 0; /* It is an FAT32 VBR */\r
+ }\r
+ /* FAT volumes formatted with early MS-DOS lack BS_55AA and BS_FilSysType, so FAT VBR needs to be identified without them. */\r
+ w = ld_word(fs->win + BPB_BytsPerSec);\r
+ b = fs->win[BPB_SecPerClus];\r
+ if ((w & (w - 1)) == 0 && w >= FF_MIN_SS && w <= FF_MAX_SS /* Properness of sector size (512-4096 and 2^n) */\r
+ && b != 0 && (b & (b - 1)) == 0 /* Properness of cluster size (2^n) */\r
+ && ld_word(fs->win + BPB_RsvdSecCnt) != 0 /* Properness of reserved sectors (MNBZ) */\r
+ && (UINT)fs->win[BPB_NumFATs] - 1 <= 1 /* Properness of FATs (1 or 2) */\r
+ && ld_word(fs->win + BPB_RootEntCnt) != 0 /* Properness of root dir entries (MNBZ) */\r
+ && (ld_word(fs->win + BPB_TotSec16) >= 128 || ld_dword(fs->win + BPB_TotSec32) >= 0x10000) /* Properness of volume sectors (>=128) */\r
+ && ld_word(fs->win + BPB_FATSz16) != 0) { /* Properness of FAT size (MNBZ) */\r
+ return 0; /* It can be presumed an FAT VBR */\r
+ }\r
+ }\r
+ return sign == 0xAA55 ? 2 : 3; /* Not an FAT VBR (valid or invalid BS) */\r
+}\r
+\r
+\r
+/* Find an FAT volume */\r
+/* (It supports only generic partitioning rules, MBR, GPT and SFD) */\r
+\r
+static UINT find_volume ( /* Returns BS status found in the hosting drive */\r
+ FATFS* fs, /* Filesystem object */\r
+ UINT part /* Partition to fined = 0:find as SFD and partitions, >0:forced partition number */\r
+)\r
+{\r
+ UINT fmt, i;\r
+ DWORD mbr_pt[4];\r
+\r
+\r
+ fmt = check_fs(fs, 0); /* Load sector 0 and check if it is an FAT VBR as SFD format */\r
+ if (fmt != 2 && (fmt >= 3 || part == 0)) return fmt; /* Returns if it is an FAT VBR as auto scan, not a BS or disk error */\r
+\r
+ /* Sector 0 is not an FAT VBR or forced partition number wants a partition */\r
+\r
+#if FF_LBA64\r
+ if (fs->win[MBR_Table + PTE_System] == 0xEE) { /* GPT protective MBR? */\r
+ DWORD n_ent, v_ent, ofs;\r
+ QWORD pt_lba;\r
+\r
+ if (move_window(fs, 1) != FR_OK) return 4; /* Load GPT header sector (next to MBR) */\r
+ if (!test_gpt_header(fs->win)) return 3; /* Check if GPT header is valid */\r
+ n_ent = ld_dword(fs->win + GPTH_PtNum); /* Number of entries */\r
+ pt_lba = ld_qword(fs->win + GPTH_PtOfs); /* Table location */\r
+ for (v_ent = i = 0; i < n_ent; i++) { /* Find FAT partition */\r
+ if (move_window(fs, pt_lba + i * SZ_GPTE / SS(fs)) != FR_OK) return 4; /* PT sector */\r
+ ofs = i * SZ_GPTE % SS(fs); /* Offset in the sector */\r
+ if (!memcmp(fs->win + ofs + GPTE_PtGuid, GUID_MS_Basic, 16)) { /* MS basic data partition? */\r
+ v_ent++;\r
+ fmt = check_fs(fs, ld_qword(fs->win + ofs + GPTE_FstLba)); /* Load VBR and check status */\r
+ if (part == 0 && fmt <= 1) return fmt; /* Auto search (valid FAT volume found first) */\r
+ if (part != 0 && v_ent == part) return fmt; /* Forced partition order (regardless of it is valid or not) */\r
+ }\r
+ }\r
+ return 3; /* Not found */\r
+ }\r
#endif\r
- if (fs->win[BS_JmpBoot] == 0xE9 || fs->win[BS_JmpBoot] == 0xEB || fs->win[BS_JmpBoot] == 0xE8) { /* Valid JumpBoot code? */\r
- if (!mem_cmp(fs->win + BS_FilSysType, "FAT", 3)) return 0; /* Is it an FAT VBR? */\r
- if (!mem_cmp(fs->win + BS_FilSysType32, "FAT32", 5)) return 0; /* Is it an FAT32 VBR? */\r
+ if (FF_MULTI_PARTITION && part > 4) return 3; /* MBR has 4 partitions max */\r
+ for (i = 0; i < 4; i++) { /* Load partition offset in the MBR */\r
+ mbr_pt[i] = ld_dword(fs->win + MBR_Table + i * SZ_PTE + PTE_StLba);\r
}\r
- return 2; /* Valid BS but not FAT */\r
+ i = part ? part - 1 : 0; /* Table index to find first */\r
+ do { /* Find an FAT volume */\r
+ fmt = mbr_pt[i] ? check_fs(fs, mbr_pt[i]) : 3; /* Check if the partition is FAT */\r
+ } while (part == 0 && fmt >= 2 && ++i < 4);\r
+ return fmt;\r
}\r
\r
\r
/* Determine logical drive number and mount the volume if needed */\r
/*-----------------------------------------------------------------------*/\r
\r
-static FRESULT find_volume ( /* FR_OK(0): successful, !=0: an error occurred */\r
+static FRESULT mount_volume ( /* FR_OK(0): successful, !=0: an error occurred */\r
const TCHAR** path, /* Pointer to pointer to the path name (drive number) */\r
FATFS** rfs, /* Pointer to pointer to the found filesystem object */\r
- BYTE mode /* !=0: Check write protection for write access */\r
+ BYTE mode /* Desiered access mode to check write protection */\r
)\r
{\r
- BYTE fmt, *pt;\r
int vol;\r
+ FATFS *fs;\r
DSTATUS stat;\r
- DWORD bsect, fasize, tsect, sysect, nclst, szbfat, br[4];\r
+ LBA_t bsect;\r
+ DWORD tsect, sysect, fasize, nclst, szbfat;\r
WORD nrsv;\r
- FATFS *fs;\r
- UINT i;\r
+ UINT fmt;\r
\r
\r
/* Get logical drive number */\r
fs = FatFs[vol]; /* Get pointer to the filesystem object */\r
if (!fs) return FR_NOT_ENABLED; /* Is the filesystem object available? */\r
#if FF_FS_REENTRANT\r
- if (!lock_fs(fs)) return FR_TIMEOUT; /* Lock the volume */\r
+ if (!lock_volume(fs, 1)) return FR_TIMEOUT; /* Lock the volume, and system if needed */\r
#endif\r
*rfs = fs; /* Return pointer to the filesystem object */\r
\r
if (!FF_FS_READONLY && mode && (stat & STA_PROTECT)) { /* Check write protection if needed */\r
return FR_WRITE_PROTECTED;\r
}\r
- return FR_OK; /* The filesystem object is valid */\r
+ return FR_OK; /* The filesystem object is already valid */\r
}\r
}\r
\r
/* The filesystem object is not valid. */\r
- /* Following code attempts to mount the volume. (analyze BPB and initialize the filesystem object) */\r
+ /* Following code attempts to mount the volume. (find an FAT volume, analyze the BPB and initialize the filesystem object) */\r
\r
- fs->fs_type = 0; /* Clear the filesystem object */\r
- fs->pdrv = LD2PD(vol); /* Bind the logical drive and a physical drive */\r
- stat = disk_initialize(fs->pdrv); /* Initialize the physical drive */\r
+ fs->fs_type = 0; /* Invalidate the filesystem object */\r
+ stat = disk_initialize(fs->pdrv); /* Initialize the volume hosting physical drive */\r
if (stat & STA_NOINIT) { /* Check if the initialization succeeded */\r
return FR_NOT_READY; /* Failed to initialize due to no medium or hard error */\r
}\r
if (SS(fs) > FF_MAX_SS || SS(fs) < FF_MIN_SS || (SS(fs) & (SS(fs) - 1))) return FR_DISK_ERR;\r
#endif\r
\r
- /* Find an FAT partition on the drive. Supports only generic partitioning rules, FDISK and SFD. */\r
- bsect = 0;\r
- fmt = check_fs(fs, bsect); /* Load sector 0 and check if it is an FAT-VBR as SFD */\r
- if (fmt == 2 || (fmt < 2 && LD2PT(vol) != 0)) { /* Not an FAT-VBR or forced partition number */\r
- for (i = 0; i < 4; i++) { /* Get partition offset */\r
- pt = fs->win + (MBR_Table + i * SZ_PTE);\r
- br[i] = pt[PTE_System] ? ld_dword(pt + PTE_StLba) : 0;\r
- }\r
- i = LD2PT(vol); /* Partition number: 0:auto, 1-4:forced */\r
- if (i != 0) i--;\r
- do { /* Find an FAT volume */\r
- bsect = br[i];\r
- fmt = bsect ? check_fs(fs, bsect) : 3; /* Check the partition */\r
- } while (LD2PT(vol) == 0 && fmt >= 2 && ++i < 4);\r
- }\r
- if (fmt == 4) return FR_DISK_ERR; /* An error occured in the disk I/O layer */\r
+ /* Find an FAT volume on the hosting drive */\r
+ fmt = find_volume(fs, LD2PT(vol));\r
+ if (fmt == 4) return FR_DISK_ERR; /* An error occurred in the disk I/O layer */\r
if (fmt >= 2) return FR_NO_FILESYSTEM; /* No FAT volume is found */\r
+ bsect = fs->winsect; /* Volume offset in the hosting physical drive */\r
\r
/* An FAT volume is found (bsect). Following code initializes the filesystem object */\r
\r
#if FF_FS_EXFAT\r
if (fmt == 1) {\r
QWORD maxlba;\r
+ DWORD so, cv, bcl, i;\r
\r
for (i = BPB_ZeroedEx; i < BPB_ZeroedEx + 53 && fs->win[i] == 0; i++) ; /* Check zero filler */\r
if (i < BPB_ZeroedEx + 53) return FR_NO_FILESYSTEM;\r
return FR_NO_FILESYSTEM;\r
}\r
\r
- maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA + 1 of the volume */\r
- if (maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be handled in 32-bit LBA) */\r
+ maxlba = ld_qword(fs->win + BPB_TotSecEx) + bsect; /* Last LBA of the volume + 1 */\r
+ if (!FF_LBA64 && maxlba >= 0x100000000) return FR_NO_FILESYSTEM; /* (It cannot be accessed in 32-bit LBA) */\r
\r
fs->fsize = ld_dword(fs->win + BPB_FatSzEx); /* Number of sectors per FAT */\r
\r
if (fs->n_fats != 1) return FR_NO_FILESYSTEM; /* (Supports only 1 FAT) */\r
\r
fs->csize = 1 << fs->win[BPB_SecPerClusEx]; /* Cluster size */\r
- if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768) */\r
+ if (fs->csize == 0) return FR_NO_FILESYSTEM; /* (Must be 1..32768 sectors) */\r
\r
nclst = ld_dword(fs->win + BPB_NumClusEx); /* Number of clusters */\r
if (nclst > MAX_EXFAT) return FR_NO_FILESYSTEM; /* (Too many clusters) */\r
fs->volbase = bsect;\r
fs->database = bsect + ld_dword(fs->win + BPB_DataOfsEx);\r
fs->fatbase = bsect + ld_dword(fs->win + BPB_FatOfsEx);\r
- if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size requiered) */\r
+ if (maxlba < (QWORD)fs->database + nclst * fs->csize) return FR_NO_FILESYSTEM; /* (Volume size must not be smaller than the size required) */\r
fs->dirbase = ld_dword(fs->win + BPB_RootClusEx);\r
\r
- /* Check if bitmap location is in assumption (at the first cluster) */\r
- if (move_window(fs, clst2sect(fs, fs->dirbase)) != FR_OK) return FR_DISK_ERR;\r
- for (i = 0; i < SS(fs); i += SZDIRE) {\r
- if (fs->win[i] == 0x81 && ld_dword(fs->win + i + 20) == 2) break; /* 81 entry with cluster #2? */\r
+ /* Get bitmap location and check if it is contiguous (implementation assumption) */\r
+ so = i = 0;\r
+ for (;;) { /* Find the bitmap entry in the root directory (in only first cluster) */\r
+ if (i == 0) {\r
+ if (so >= fs->csize) return FR_NO_FILESYSTEM; /* Not found? */\r
+ if (move_window(fs, clst2sect(fs, (DWORD)fs->dirbase) + so) != FR_OK) return FR_DISK_ERR;\r
+ so++;\r
+ }\r
+ if (fs->win[i] == ET_BITMAP) break; /* Is it a bitmap entry? */\r
+ i = (i + SZDIRE) % SS(fs); /* Next entry */\r
+ }\r
+ bcl = ld_dword(fs->win + i + 20); /* Bitmap cluster */\r
+ if (bcl < 2 || bcl >= fs->n_fatent) return FR_NO_FILESYSTEM; /* (Wrong cluster#) */\r
+ fs->bitbase = fs->database + fs->csize * (bcl - 2); /* Bitmap sector */\r
+ for (;;) { /* Check if bitmap is contiguous */\r
+ if (move_window(fs, fs->fatbase + bcl / (SS(fs) / 4)) != FR_OK) return FR_DISK_ERR;\r
+ cv = ld_dword(fs->win + bcl % (SS(fs) / 4) * 4);\r
+ if (cv == 0xFFFFFFFF) break; /* Last link? */\r
+ if (cv != ++bcl) return FR_NO_FILESYSTEM; /* Fragmented bitmap? */\r
}\r
- if (i == SS(fs)) return FR_NO_FILESYSTEM;\r
+\r
#if !FF_FS_READONLY\r
fs->last_clst = fs->free_clst = 0xFFFFFFFF; /* Initialize cluster allocation information */\r
#endif\r
#endif /* !FF_FS_READONLY */\r
}\r
\r
- fs->fs_type = fmt; /* FAT sub-type */\r
+ fs->fs_type = (BYTE)fmt;/* FAT sub-type (the filesystem object gets valid) */\r
fs->id = ++Fsid; /* Volume mount ID */\r
#if FF_USE_LFN == 1\r
fs->lfnbuf = LfnBuf; /* Static LFN working buffer */\r
#if FF_FS_RPATH != 0\r
fs->cdir = 0; /* Initialize current directory */\r
#endif\r
-#if FF_FS_LOCK != 0 /* Clear file lock semaphores */\r
- clear_lock(fs);\r
+#if FF_FS_LOCK /* Clear file lock semaphores */\r
+ clear_share(fs);\r
#endif\r
return FR_OK;\r
}\r
/*-----------------------------------------------------------------------*/\r
\r
static FRESULT validate ( /* Returns FR_OK or FR_INVALID_OBJECT */\r
- FFOBJID* obj, /* Pointer to the FFOBJID, the 1st member in the FIL/DIR object, to check validity */\r
+ FFOBJID* obj, /* Pointer to the FFOBJID, the 1st member in the FIL/DIR structure, to check validity */\r
FATFS** rfs /* Pointer to pointer to the owner filesystem object to return */\r
)\r
{\r
\r
if (obj && obj->fs && obj->fs->fs_type && obj->id == obj->fs->id) { /* Test if the object is valid */\r
#if FF_FS_REENTRANT\r
- if (lock_fs(obj->fs)) { /* Obtain the filesystem object */\r
- if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */\r
+ if (lock_volume(obj->fs, 0)) { /* Take a grant to access the volume */\r
+ if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the hosting phsical drive is kept initialized */\r
res = FR_OK;\r
} else {\r
- unlock_fs(obj->fs, FR_OK);\r
+ unlock_volume(obj->fs, FR_OK); /* Invalidated volume, abort to access */\r
}\r
- } else {\r
+ } else { /* Could not take */\r
res = FR_TIMEOUT;\r
}\r
#else\r
- if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the phsical drive is kept initialized */\r
+ if (!(disk_status(obj->fs->pdrv) & STA_NOINIT)) { /* Test if the hosting phsical drive is kept initialized */\r
res = FR_OK;\r
}\r
#endif\r
}\r
- *rfs = (res == FR_OK) ? obj->fs : 0; /* Corresponding filesystem object */\r
+ *rfs = (res == FR_OK) ? obj->fs : 0; /* Return corresponding filesystem object if it is valid */\r
return res;\r
}\r
\r
/*-----------------------------------------------------------------------*/\r
\r
FRESULT f_mount (\r
- FATFS* fs, /* Pointer to the filesystem object (NULL:unmount)*/\r
+ FATFS* fs, /* Pointer to the filesystem object to be registered (NULL:unmount)*/\r
const TCHAR* path, /* Logical drive number to be mounted/unmounted */\r
- BYTE opt /* Mode option 0:Do not mount (delayed mount), 1:Mount immediately */\r
+ BYTE opt /* Mount option: 0=Do not mount (delayed mount), 1=Mount immediately */\r
)\r
{\r
FATFS *cfs;\r
const TCHAR *rp = path;\r
\r
\r
- /* Get logical drive number */\r
+ /* Get volume ID (logical drive number) */\r
vol = get_ldnumber(&rp);\r
if (vol < 0) return FR_INVALID_DRIVE;\r
- cfs = FatFs[vol]; /* Pointer to fs object */\r
+ cfs = FatFs[vol]; /* Pointer to the filesystem object of the volume */\r
\r
- if (cfs) {\r
-#if FF_FS_LOCK != 0\r
- clear_lock(cfs);\r
+ if (cfs) { /* Unregister current filesystem object if regsitered */\r
+ FatFs[vol] = 0;\r
+#if FF_FS_LOCK\r
+ clear_share(cfs);\r
#endif\r
-#if FF_FS_REENTRANT /* Discard sync object of the current volume */\r
- if (!ff_del_syncobj(cfs->sobj)) return FR_INT_ERR;\r
+#if FF_FS_REENTRANT /* Discard mutex of the current volume */\r
+ ff_mutex_delete(vol);\r
#endif\r
- cfs->fs_type = 0; /* Clear old fs object */\r
+ cfs->fs_type = 0; /* Invalidate the filesystem object to be unregistered */\r
}\r
\r
- if (fs) {\r
- fs->fs_type = 0; /* Clear new fs object */\r
-#if FF_FS_REENTRANT /* Create sync object for the new volume */\r
- if (!ff_cre_syncobj((BYTE)vol, &fs->sobj)) return FR_INT_ERR;\r
+ if (fs) { /* Register new filesystem object */\r
+ fs->pdrv = LD2PD(vol); /* Volume hosting physical drive */\r
+#if FF_FS_REENTRANT /* Create a volume mutex */\r
+ fs->ldrv = (BYTE)vol; /* Owner volume ID */\r
+ if (!ff_mutex_create(vol)) return FR_INT_ERR;\r
+#if FF_FS_LOCK\r
+ if (SysLock == 0) { /* Create a system mutex if needed */\r
+ if (!ff_mutex_create(FF_VOLUMES)) {\r
+ ff_mutex_delete(vol);\r
+ return FR_INT_ERR;\r
+ }\r
+ SysLock = 1; /* System mutex is ready */\r
+ }\r
+#endif\r
#endif\r
+ fs->fs_type = 0; /* Invalidate the new filesystem object */\r
+ FatFs[vol] = fs; /* Register new fs object */\r
}\r
- FatFs[vol] = fs; /* Register new fs object */\r
\r
- if (opt == 0) return FR_OK; /* Do not mount now, it will be mounted later */\r
+ if (opt == 0) return FR_OK; /* Do not mount now, it will be mounted in subsequent file functions */\r
\r
- res = find_volume(&path, &fs, 0); /* Force mounted the volume */\r
+ res = mount_volume(&path, &fs, 0); /* Force mounted the volume */\r
LEAVE_FF(fs, res);\r
}\r
\r
FRESULT f_open (\r
FIL* fp, /* Pointer to the blank file object */\r
const TCHAR* path, /* Pointer to the file name */\r
- BYTE mode /* Access mode and file open mode flags */\r
+ BYTE mode /* Access mode and open mode flags */\r
)\r
{\r
FRESULT res;\r
DIR dj;\r
FATFS *fs;\r
#if !FF_FS_READONLY\r
- DWORD dw, cl, bcs, clst, sc;\r
+ DWORD cl, bcs, clst, tm;\r
+ LBA_t sc;\r
FSIZE_t ofs;\r
#endif\r
DEF_NAMBUF\r
\r
/* Get logical drive number */\r
mode &= FF_FS_READONLY ? FA_READ : FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_CREATE_NEW | FA_OPEN_ALWAYS | FA_OPEN_APPEND;\r
- res = find_volume(&path, &fs, mode);\r
+ res = mount_volume(&path, &fs, mode);\r
if (res == FR_OK) {\r
dj.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
if (dj.fn[NSFLAG] & NS_NONAME) { /* Origin directory itself? */\r
res = FR_INVALID_NAME;\r
}\r
-#if FF_FS_LOCK != 0\r
+#if FF_FS_LOCK\r
else {\r
- res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0); /* Check if the file can be used */\r
+ res = chk_share(&dj, (mode & ~FA_READ) ? 1 : 0); /* Check if the file can be used */\r
}\r
#endif\r
}\r
if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) {\r
if (res != FR_OK) { /* No file, create new */\r
if (res == FR_NO_FILE) { /* There is no file to open, create a new entry */\r
-#if FF_FS_LOCK != 0\r
- res = enq_lock() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;\r
+#if FF_FS_LOCK\r
+ res = enq_share() ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;\r
#else\r
res = dir_register(&dj);\r
#endif\r
fp->obj.fs = fs;\r
init_alloc_info(fs, &fp->obj);\r
/* Set directory entry block initial state */\r
- mem_set(fs->dirbuf + 2, 0, 30); /* Clear 85 entry except for NumSec */\r
- mem_set(fs->dirbuf + 38, 0, 26); /* Clear C0 entry except for NumName and NameHash */\r
+ memset(fs->dirbuf + 2, 0, 30); /* Clear 85 entry except for NumSec */\r
+ memset(fs->dirbuf + 38, 0, 26); /* Clear C0 entry except for NumName and NameHash */\r
fs->dirbuf[XDIR_Attr] = AM_ARC;\r
st_dword(fs->dirbuf + XDIR_CrtTime, GET_FATTIME());\r
fs->dirbuf[XDIR_GenFlags] = 1;\r
#endif\r
{\r
/* Set directory entry initial state */\r
+ tm = GET_FATTIME(); /* Set created time */\r
+ st_dword(dj.dir + DIR_CrtTime, tm);\r
+ st_dword(dj.dir + DIR_ModTime, tm);\r
cl = ld_clust(fs, dj.dir); /* Get current cluster chain */\r
- st_dword(dj.dir + DIR_CrtTime, GET_FATTIME()); /* Set created time */\r
dj.dir[DIR_Attr] = AM_ARC; /* Reset attribute */\r
st_clust(fs, dj.dir, 0); /* Reset file allocation info */\r
st_dword(dj.dir + DIR_FileSize, 0);\r
fs->wflag = 1;\r
if (cl != 0) { /* Remove the cluster chain if exist */\r
- dw = fs->winsect;\r
+ sc = fs->winsect;\r
res = remove_chain(&dj.obj, cl, 0);\r
if (res == FR_OK) {\r
- res = move_window(fs, dw);\r
+ res = move_window(fs, sc);\r
fs->last_clst = cl - 1; /* Reuse the cluster hole */\r
}\r
}\r
if (mode & FA_CREATE_ALWAYS) mode |= FA_MODIFIED; /* Set file change flag if created or overwritten */\r
fp->dir_sect = fs->winsect; /* Pointer to the directory entry */\r
fp->dir_ptr = dj.dir;\r
-#if FF_FS_LOCK != 0\r
- fp->obj.lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0); /* Lock the file for this session */\r
+#if FF_FS_LOCK\r
+ fp->obj.lockid = inc_share(&dj, (mode & ~FA_READ) ? 1 : 0); /* Lock the file for this session */\r
if (fp->obj.lockid == 0) res = FR_INT_ERR;\r
#endif\r
}\r
fp->obj.objsize = ld_dword(dj.dir + DIR_FileSize);\r
}\r
#if FF_USE_FASTSEEK\r
- fp->cltbl = 0; /* Disable fast seek mode */\r
+ fp->cltbl = 0; /* Disable fast seek mode */\r
#endif\r
- fp->obj.fs = fs; /* Validate the file object */\r
+ fp->obj.fs = fs; /* Validate the file object */\r
fp->obj.id = fs->id;\r
- fp->flag = mode; /* Set file access mode */\r
- fp->err = 0; /* Clear error flag */\r
- fp->sect = 0; /* Invalidate current data sector */\r
- fp->fptr = 0; /* Set file pointer top of the file */\r
+ fp->flag = mode; /* Set file access mode */\r
+ fp->err = 0; /* Clear error flag */\r
+ fp->sect = 0; /* Invalidate current data sector */\r
+ fp->fptr = 0; /* Set file pointer top of the file */\r
#if !FF_FS_READONLY\r
#if !FF_FS_TINY\r
- mem_set(fp->buf, 0, FF_MAX_SS); /* Clear sector buffer */\r
+ memset(fp->buf, 0, sizeof fp->buf); /* Clear sector buffer */\r
#endif\r
if ((mode & FA_SEEKEND) && fp->obj.objsize > 0) { /* Seek to end of file if FA_OPEN_APPEND is specified */\r
fp->fptr = fp->obj.objsize; /* Offset to seek */\r
}\r
fp->clust = clst;\r
if (res == FR_OK && ofs % SS(fs)) { /* Fill sector buffer if not on the sector boundary */\r
- if ((sc = clst2sect(fs, clst)) == 0) {\r
+ sc = clst2sect(fs, clst);\r
+ if (sc == 0) {\r
res = FR_INT_ERR;\r
} else {\r
fp->sect = sc + (DWORD)(ofs / SS(fs));\r
#endif\r
}\r
}\r
+#if FF_FS_LOCK\r
+ if (res != FR_OK) dec_share(fp->obj.lockid); /* Decrement file open counter if seek failed */\r
+#endif\r
}\r
#endif\r
}\r
/*-----------------------------------------------------------------------*/\r
\r
FRESULT f_read (\r
- FIL* fp, /* Pointer to the file object */\r
- void* buff, /* Pointer to data buffer */\r
+ FIL* fp, /* Open file to be read */\r
+ void* buff, /* Data buffer to store the read data */\r
UINT btr, /* Number of bytes to read */\r
- UINT* br /* Pointer to number of bytes read */\r
+ UINT* br /* Number of bytes read */\r
)\r
{\r
FRESULT res;\r
FATFS *fs;\r
- DWORD clst, sect;\r
+ DWORD clst;\r
+ LBA_t sect;\r
FSIZE_t remain;\r
UINT rcnt, cc, csect;\r
BYTE *rbuff = (BYTE*)buff;\r
remain = fp->obj.objsize - fp->fptr;\r
if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */\r
\r
- for ( ; btr; /* Repeat until btr bytes read */\r
- btr -= rcnt, *br += rcnt, rbuff += rcnt, fp->fptr += rcnt) {\r
+ for ( ; btr > 0; btr -= rcnt, *br += rcnt, rbuff += rcnt, fp->fptr += rcnt) { /* Repeat until btr bytes read */\r
if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */\r
csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */\r
if (csect == 0) { /* On the cluster boundary? */\r
#if !FF_FS_READONLY && FF_FS_MINIMIZE <= 2 /* Replace one of the read sectors with cached data if it contains a dirty sector */\r
#if FF_FS_TINY\r
if (fs->wflag && fs->winsect - sect < cc) {\r
- mem_cpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));\r
+ memcpy(rbuff + ((fs->winsect - sect) * SS(fs)), fs->win, SS(fs));\r
}\r
#else\r
if ((fp->flag & FA_DIRTY) && fp->sect - sect < cc) {\r
- mem_cpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));\r
+ memcpy(rbuff + ((fp->sect - sect) * SS(fs)), fp->buf, SS(fs));\r
}\r
#endif\r
#endif\r
fp->flag &= (BYTE)~FA_DIRTY;\r
}\r
#endif\r
- if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */\r
+ if (disk_read(fs->pdrv, fp->buf, sect, 1) != RES_OK) ABORT(fs, FR_DISK_ERR); /* Fill sector cache */\r
}\r
#endif\r
fp->sect = sect;\r
}\r
- rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */\r
+ rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */\r
if (rcnt > btr) rcnt = btr; /* Clip it by btr if needed */\r
#if FF_FS_TINY\r
if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */\r
- mem_cpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */\r
+ memcpy(rbuff, fs->win + fp->fptr % SS(fs), rcnt); /* Extract partial sector */\r
#else\r
- mem_cpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */\r
+ memcpy(rbuff, fp->buf + fp->fptr % SS(fs), rcnt); /* Extract partial sector */\r
#endif\r
}\r
\r
/*-----------------------------------------------------------------------*/\r
\r
FRESULT f_write (\r
- FIL* fp, /* Pointer to the file object */\r
- const void* buff, /* Pointer to the data to be written */\r
+ FIL* fp, /* Open file to be written */\r
+ const void* buff, /* Data to be written */\r
UINT btw, /* Number of bytes to write */\r
- UINT* bw /* Pointer to number of bytes written */\r
+ UINT* bw /* Number of bytes written */\r
)\r
{\r
FRESULT res;\r
FATFS *fs;\r
- DWORD clst, sect;\r
+ DWORD clst;\r
+ LBA_t sect;\r
UINT wcnt, cc, csect;\r
const BYTE *wbuff = (const BYTE*)buff;\r
\r
btw = (UINT)(0xFFFFFFFF - (DWORD)fp->fptr);\r
}\r
\r
- for ( ; btw; /* Repeat until all data written */\r
- btw -= wcnt, *bw += wcnt, wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize) {\r
+ for ( ; btw > 0; btw -= wcnt, *bw += wcnt, wbuff += wcnt, fp->fptr += wcnt, fp->obj.objsize = (fp->fptr > fp->obj.objsize) ? fp->fptr : fp->obj.objsize) { /* Repeat until all data written */\r
if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */\r
csect = (UINT)(fp->fptr / SS(fs)) & (fs->csize - 1); /* Sector offset in the cluster */\r
if (csect == 0) { /* On the cluster boundary? */\r
#if FF_FS_MINIMIZE <= 2\r
#if FF_FS_TINY\r
if (fs->winsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */\r
- mem_cpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));\r
+ memcpy(fs->win, wbuff + ((fs->winsect - sect) * SS(fs)), SS(fs));\r
fs->wflag = 0;\r
}\r
#else\r
if (fp->sect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */\r
- mem_cpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));\r
+ memcpy(fp->buf, wbuff + ((fp->sect - sect) * SS(fs)), SS(fs));\r
fp->flag &= (BYTE)~FA_DIRTY;\r
}\r
#endif\r
#endif\r
fp->sect = sect;\r
}\r
- wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */\r
+ wcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */\r
if (wcnt > btw) wcnt = btw; /* Clip it by btw if needed */\r
#if FF_FS_TINY\r
if (move_window(fs, fp->sect) != FR_OK) ABORT(fs, FR_DISK_ERR); /* Move sector window */\r
- mem_cpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */\r
+ memcpy(fs->win + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */\r
fs->wflag = 1;\r
#else\r
- mem_cpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */\r
+ memcpy(fp->buf + fp->fptr % SS(fs), wbuff, wcnt); /* Fit data to the sector */\r
fp->flag |= FA_DIRTY;\r
#endif\r
}\r
/*-----------------------------------------------------------------------*/\r
\r
FRESULT f_sync (\r
- FIL* fp /* Pointer to the file object */\r
+ FIL* fp /* Open file to be synced */\r
)\r
{\r
FRESULT res;\r
if (res == FR_OK) {\r
fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute to indicate that the file has been changed */\r
fs->dirbuf[XDIR_GenFlags] = fp->obj.stat | 1; /* Update file allocation information */\r
- st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust);\r
- st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize);\r
- st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize);\r
+ st_dword(fs->dirbuf + XDIR_FstClus, fp->obj.sclust); /* Update start cluster */\r
+ st_qword(fs->dirbuf + XDIR_FileSize, fp->obj.objsize); /* Update file size */\r
+ st_qword(fs->dirbuf + XDIR_ValidFileSize, fp->obj.objsize); /* (FatFs does not support Valid File Size feature) */\r
st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Update modified time */\r
fs->dirbuf[XDIR_ModTime10] = 0;\r
st_dword(fs->dirbuf + XDIR_AccTime, 0);\r
/*-----------------------------------------------------------------------*/\r
\r
FRESULT f_close (\r
- FIL* fp /* Pointer to the file object to be closed */\r
+ FIL* fp /* Open file to be closed */\r
)\r
{\r
FRESULT res;\r
{\r
res = validate(&fp->obj, &fs); /* Lock volume */\r
if (res == FR_OK) {\r
-#if FF_FS_LOCK != 0\r
- res = dec_lock(fp->obj.lockid); /* Decrement file open counter */\r
+#if FF_FS_LOCK\r
+ res = dec_share(fp->obj.lockid); /* Decrement file open counter */\r
if (res == FR_OK) fp->obj.fs = 0; /* Invalidate file object */\r
#else\r
fp->obj.fs = 0; /* Invalidate file object */\r
#endif\r
#if FF_FS_REENTRANT\r
- unlock_fs(fs, FR_OK); /* Unlock volume */\r
+ unlock_volume(fs, FR_OK); /* Unlock volume */\r
#endif\r
}\r
}\r
\r
\r
/* Get logical drive */\r
- res = find_volume(&path, &fs, 0);\r
+ res = mount_volume(&path, &fs, 0);\r
if (res == FR_OK) {\r
dj.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
}\r
FREE_NAMBUF();\r
if (res == FR_NO_FILE) res = FR_NO_PATH;\r
-#if FF_STR_VOLUME_ID == 2 /* Also current drive is changed at Unix style volume ID */\r
+#if FF_STR_VOLUME_ID == 2 /* Also current drive is changed if in Unix style volume ID */\r
if (res == FR_OK) {\r
for (i = FF_VOLUMES - 1; i && fs != FatFs[i]; i--) ; /* Set current drive */\r
CurrVol = (BYTE)i;\r
TCHAR *tp = buff;\r
#if FF_VOLUMES >= 2\r
UINT vl;\r
-#endif\r
#if FF_STR_VOLUME_ID\r
const char *vp;\r
+#endif\r
#endif\r
FILINFO fno;\r
DEF_NAMBUF\r
\r
\r
/* Get logical drive */\r
- res = find_volume((const TCHAR**)&buff, &fs, 0); /* Get current volume */\r
+ buff[0] = 0; /* Set null string to get current volume */\r
+ res = mount_volume((const TCHAR**)&buff, &fs, 0); /* Get current volume */\r
if (res == FR_OK) {\r
dj.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
res = dir_sdi(&dj, 0);\r
if (res != FR_OK) break;\r
do { /* Find the entry links to the child directory */\r
- res = dir_read_file(&dj);\r
+ res = DIR_READ_FILE(&dj);\r
if (res != FR_OK) break;\r
if (ccl == ld_clust(fs, dj.dir)) break; /* Found the entry */\r
res = dir_next(&dj, 0);\r
#endif\r
/* Add current directory path */\r
if (res == FR_OK) {\r
- do *tp++ = buff[i++]; while (i < len); /* Copy stacked path string */\r
+ do { /* Copy stacked path string */\r
+ *tp++ = buff[i++];\r
+ } while (i < len);\r
}\r
}\r
FREE_NAMBUF();\r
{\r
FRESULT res;\r
FATFS *fs;\r
- DWORD clst, bcs, nsect;\r
+ DWORD clst, bcs;\r
+ LBA_t nsect;\r
FSIZE_t ifptr;\r
#if FF_USE_FASTSEEK\r
- DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;\r
+ DWORD cl, pcl, ncl, tcl, tlen, ulen;\r
+ DWORD *tbl;\r
+ LBA_t dsc;\r
#endif\r
\r
res = validate(&fp->obj, &fs); /* Check validity of the file object */\r
if (!dp) return FR_INVALID_OBJECT;\r
\r
/* Get logical drive */\r
- res = find_volume(&path, &fs, 0);\r
+ res = mount_volume(&path, &fs, 0);\r
if (res == FR_OK) {\r
dp->obj.fs = fs;\r
INIT_NAMBUF(fs);\r
if (dp->obj.attr & AM_DIR) { /* This object is a sub-directory */\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) {\r
- dp->obj.c_scl = dp->obj.sclust; /* Get containing directory inforamation */\r
+ dp->obj.c_scl = dp->obj.sclust; /* Get containing directory inforamation */\r
dp->obj.c_size = ((DWORD)dp->obj.objsize & 0xFFFFFF00) | dp->obj.stat;\r
dp->obj.c_ofs = dp->blk_ofs;\r
init_alloc_info(fs, &dp->obj); /* Get object allocation info */\r
if (res == FR_OK) {\r
dp->obj.id = fs->id;\r
res = dir_sdi(dp, 0); /* Rewind directory */\r
-#if FF_FS_LOCK != 0\r
+#if FF_FS_LOCK\r
if (res == FR_OK) {\r
if (dp->obj.sclust != 0) {\r
- dp->obj.lockid = inc_lock(dp, 0); /* Lock the sub directory */\r
+ dp->obj.lockid = inc_share(dp, 0); /* Lock the sub directory */\r
if (!dp->obj.lockid) res = FR_TOO_MANY_OPEN_FILES;\r
} else {\r
dp->obj.lockid = 0; /* Root directory need not to be locked */\r
FREE_NAMBUF();\r
if (res == FR_NO_FILE) res = FR_NO_PATH;\r
}\r
- if (res != FR_OK) dp->obj.fs = 0; /* Invalidate the directory object if function faild */\r
+ if (res != FR_OK) dp->obj.fs = 0; /* Invalidate the directory object if function failed */\r
\r
LEAVE_FF(fs, res);\r
}\r
\r
res = validate(&dp->obj, &fs); /* Check validity of the file object */\r
if (res == FR_OK) {\r
-#if FF_FS_LOCK != 0\r
- if (dp->obj.lockid) res = dec_lock(dp->obj.lockid); /* Decrement sub-directory open counter */\r
+#if FF_FS_LOCK\r
+ if (dp->obj.lockid) res = dec_share(dp->obj.lockid); /* Decrement sub-directory open counter */\r
if (res == FR_OK) dp->obj.fs = 0; /* Invalidate directory object */\r
#else\r
dp->obj.fs = 0; /* Invalidate directory object */\r
#endif\r
#if FF_FS_REENTRANT\r
- unlock_fs(fs, FR_OK); /* Unlock volume */\r
+ unlock_volume(fs, FR_OK); /* Unlock volume */\r
#endif\r
}\r
return res;\r
res = validate(&dp->obj, &fs); /* Check validity of the directory object */\r
if (res == FR_OK) {\r
if (!fno) {\r
- res = dir_sdi(dp, 0); /* Rewind the directory object */\r
+ res = dir_sdi(dp, 0); /* Rewind the directory object */\r
} else {\r
INIT_NAMBUF(fs);\r
- res = dir_read_file(dp); /* Read an item */\r
+ res = DIR_READ_FILE(dp); /* Read an item */\r
if (res == FR_NO_FILE) res = FR_OK; /* Ignore end of directory */\r
if (res == FR_OK) { /* A valid entry is found */\r
get_fileinfo(dp, fno); /* Get the object information */\r
for (;;) {\r
res = f_readdir(dp, fno); /* Get a directory item */\r
if (res != FR_OK || !fno || !fno->fname[0]) break; /* Terminate if any error or end of directory */\r
- if (pattern_matching(dp->pat, fno->fname, 0, 0)) break; /* Test for the file name */\r
+ if (pattern_match(dp->pat, fno->fname, 0, FIND_RECURS)) break; /* Test for the file name */\r
#if FF_USE_LFN && FF_USE_FIND == 2\r
- if (pattern_matching(dp->pat, fno->altname, 0, 0)) break; /* Test for alternative name if exist */\r
+ if (pattern_match(dp->pat, fno->altname, 0, FIND_RECURS)) break; /* Test for alternative name if exist */\r
#endif\r
}\r
return res;\r
\r
\r
/* Get logical drive */\r
- res = find_volume(&path, &dj.obj.fs, 0);\r
+ res = mount_volume(&path, &dj.obj.fs, 0);\r
if (res == FR_OK) {\r
INIT_NAMBUF(dj.obj.fs);\r
res = follow_path(&dj, path); /* Follow the file path */\r
{\r
FRESULT res;\r
FATFS *fs;\r
- DWORD nfree, clst, sect, stat;\r
+ DWORD nfree, clst, stat;\r
+ LBA_t sect;\r
UINT i;\r
FFOBJID obj;\r
\r
\r
/* Get logical drive */\r
- res = find_volume(&path, &fs, 0);\r
+ res = mount_volume(&path, &fs, 0);\r
if (res == FR_OK) {\r
*fatfs = fs; /* Return ptr to the fs object */\r
/* If free_clst is valid, return it without full FAT scan */\r
clst = 2; obj.fs = fs;\r
do {\r
stat = get_fat(&obj, clst);\r
- if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }\r
- if (stat == 1) { res = FR_INT_ERR; break; }\r
+ if (stat == 0xFFFFFFFF) {\r
+ res = FR_DISK_ERR; break;\r
+ }\r
+ if (stat == 1) {\r
+ res = FR_INT_ERR; break;\r
+ }\r
if (stat == 0) nfree++;\r
} while (++clst < fs->n_fatent);\r
} else {\r
UINT b;\r
\r
clst = fs->n_fatent - 2; /* Number of clusters */\r
- sect = fs->database; /* Assuming bitmap starts at cluster 2 */\r
+ sect = fs->bitbase; /* Bitmap sector */\r
i = 0; /* Offset in the sector */\r
do { /* Counts numbuer of bits with zero in the bitmap */\r
- if (i == 0) {\r
+ if (i == 0) { /* New sector? */\r
res = move_window(fs, sect++);\r
if (res != FR_OK) break;\r
}\r
- for (b = 8, bm = fs->win[i]; b && clst; b--, clst--) {\r
- if (!(bm & 1)) nfree++;\r
+ for (b = 8, bm = ~fs->win[i]; b && clst; b--, clst--) {\r
+ nfree += bm & 1;\r
bm >>= 1;\r
}\r
i = (i + 1) % SS(fs);\r
sect = fs->fatbase; /* Top of the FAT */\r
i = 0; /* Offset in the sector */\r
do { /* Counts numbuer of entries with zero in the FAT */\r
- if (i == 0) {\r
+ if (i == 0) { /* New sector? */\r
res = move_window(fs, sect++);\r
if (res != FR_OK) break;\r
}\r
} while (--clst);\r
}\r
}\r
- *nclst = nfree; /* Return the free clusters */\r
- fs->free_clst = nfree; /* Now free_clst is valid */\r
- fs->fsi_flag |= 1; /* FAT32: FSInfo is to be updated */\r
+ if (res == FR_OK) { /* Update parameters if succeeded */\r
+ *nclst = nfree; /* Return the free clusters */\r
+ fs->free_clst = nfree; /* Now free_clst is valid */\r
+ fs->fsi_flag |= 1; /* FAT32: FSInfo is to be updated */\r
+ }\r
}\r
}\r
\r
)\r
{\r
FRESULT res;\r
+ FATFS *fs;\r
DIR dj, sdj;\r
DWORD dclst = 0;\r
- FATFS *fs;\r
#if FF_FS_EXFAT\r
FFOBJID obj;\r
#endif\r
\r
\r
/* Get logical drive */\r
- res = find_volume(&path, &fs, FA_WRITE);\r
+ res = mount_volume(&path, &fs, FA_WRITE);\r
if (res == FR_OK) {\r
dj.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
if (FF_FS_RPATH && res == FR_OK && (dj.fn[NSFLAG] & NS_DOT)) {\r
res = FR_INVALID_NAME; /* Cannot remove dot entry */\r
}\r
-#if FF_FS_LOCK != 0\r
- if (res == FR_OK) res = chk_lock(&dj, 2); /* Check if it is an open object */\r
+#if FF_FS_LOCK\r
+ if (res == FR_OK) res = chk_share(&dj, 2); /* Check if it is an open object */\r
#endif\r
if (res == FR_OK) { /* The object is accessible */\r
if (dj.fn[NSFLAG] & NS_NONAME) {\r
}\r
if (dj.obj.attr & AM_DIR) { /* Is it a sub-directory? */\r
#if FF_FS_RPATH != 0\r
- if (dclst == fs->cdir) { /* Is it the current directory? */\r
+ if (dclst == fs->cdir) { /* Is it the current directory? */\r
res = FR_DENIED;\r
} else\r
#endif\r
{\r
- sdj.obj.fs = fs; /* Open the sub-directory */\r
+ sdj.obj.fs = fs; /* Open the sub-directory */\r
sdj.obj.sclust = dclst;\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) {\r
#endif\r
res = dir_sdi(&sdj, 0);\r
if (res == FR_OK) {\r
- res = dir_read_file(&sdj); /* Test if the directory is empty */\r
+ res = DIR_READ_FILE(&sdj); /* Test if the directory is empty */\r
if (res == FR_OK) res = FR_DENIED; /* Not empty? */\r
if (res == FR_NO_FILE) res = FR_OK; /* Empty? */\r
}\r
)\r
{\r
FRESULT res;\r
- DIR dj;\r
FATFS *fs;\r
- BYTE *dir;\r
+ DIR dj;\r
+ FFOBJID sobj;\r
DWORD dcl, pcl, tm;\r
DEF_NAMBUF\r
\r
\r
- /* Get logical drive */\r
- res = find_volume(&path, &fs, FA_WRITE);\r
+ res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */\r
if (res == FR_OK) {\r
dj.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
res = follow_path(&dj, path); /* Follow the file path */\r
- if (res == FR_OK) res = FR_EXIST; /* Any object with same name is already existing */\r
- if (FF_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) {\r
+ if (res == FR_OK) res = FR_EXIST; /* Name collision? */\r
+ if (FF_FS_RPATH && res == FR_NO_FILE && (dj.fn[NSFLAG] & NS_DOT)) { /* Invalid name? */\r
res = FR_INVALID_NAME;\r
}\r
- if (res == FR_NO_FILE) { /* Can create a new directory */\r
- dcl = create_chain(&dj.obj, 0); /* Allocate a cluster for the new directory table */\r
- dj.obj.objsize = (DWORD)fs->csize * SS(fs);\r
+ if (res == FR_NO_FILE) { /* It is clear to create a new directory */\r
+ sobj.fs = fs; /* New object id to create a new chain */\r
+ dcl = create_chain(&sobj, 0); /* Allocate a cluster for the new directory */\r
res = FR_OK;\r
- if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster */\r
- if (dcl == 1) res = FR_INT_ERR;\r
- if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;\r
- if (res == FR_OK) res = sync_window(fs); /* Flush FAT */\r
+ if (dcl == 0) res = FR_DENIED; /* No space to allocate a new cluster? */\r
+ if (dcl == 1) res = FR_INT_ERR; /* Any insanity? */\r
+ if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR; /* Disk error? */\r
tm = GET_FATTIME();\r
- if (res == FR_OK) { /* Initialize the new directory table */\r
+ if (res == FR_OK) {\r
res = dir_clear(fs, dcl); /* Clean up the new table */\r
- if (res == FR_OK && (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT)) { /* Create dot entries (FAT only) */\r
- dir = fs->win;\r
- mem_set(dir + DIR_Name, ' ', 11); /* Create "." entry */\r
- dir[DIR_Name] = '.';\r
- dir[DIR_Attr] = AM_DIR;\r
- st_dword(dir + DIR_ModTime, tm);\r
- st_clust(fs, dir, dcl);\r
- mem_cpy(dir + SZDIRE, dir, SZDIRE); /* Create ".." entry */\r
- dir[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;\r
- st_clust(fs, dir + SZDIRE, pcl);\r
- fs->wflag = 1;\r
+ if (res == FR_OK) {\r
+ if (!FF_FS_EXFAT || fs->fs_type != FS_EXFAT) { /* Create dot entries (FAT only) */\r
+ memset(fs->win + DIR_Name, ' ', 11); /* Create "." entry */\r
+ fs->win[DIR_Name] = '.';\r
+ fs->win[DIR_Attr] = AM_DIR;\r
+ st_dword(fs->win + DIR_ModTime, tm);\r
+ st_clust(fs, fs->win, dcl);\r
+ memcpy(fs->win + SZDIRE, fs->win, SZDIRE); /* Create ".." entry */\r
+ fs->win[SZDIRE + 1] = '.'; pcl = dj.obj.sclust;\r
+ st_clust(fs, fs->win + SZDIRE, pcl);\r
+ fs->wflag = 1;\r
+ }\r
+ res = dir_register(&dj); /* Register the object to the parent directoy */\r
}\r
}\r
if (res == FR_OK) {\r
- res = dir_register(&dj); /* Register the object to the directoy */\r
- }\r
- if (res == FR_OK) {\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) { /* Initialize directory entry block */\r
st_dword(fs->dirbuf + XDIR_ModTime, tm); /* Created time */\r
st_dword(fs->dirbuf + XDIR_FstClus, dcl); /* Table start cluster */\r
- st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)dj.obj.objsize); /* File size needs to be valid */\r
- st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)dj.obj.objsize);\r
+ st_dword(fs->dirbuf + XDIR_FileSize, (DWORD)fs->csize * SS(fs)); /* Directory size needs to be valid */\r
+ st_dword(fs->dirbuf + XDIR_ValidFileSize, (DWORD)fs->csize * SS(fs));\r
fs->dirbuf[XDIR_GenFlags] = 3; /* Initialize the object flag */\r
fs->dirbuf[XDIR_Attr] = AM_DIR; /* Attribute */\r
res = store_xdir(&dj);\r
} else\r
#endif\r
{\r
- dir = dj.dir;\r
- st_dword(dir + DIR_ModTime, tm); /* Created time */\r
- st_clust(fs, dir, dcl); /* Table start cluster */\r
- dir[DIR_Attr] = AM_DIR; /* Attribute */\r
+ st_dword(dj.dir + DIR_ModTime, tm); /* Created time */\r
+ st_clust(fs, dj.dir, dcl); /* Table start cluster */\r
+ dj.dir[DIR_Attr] = AM_DIR; /* Attribute */\r
fs->wflag = 1;\r
}\r
if (res == FR_OK) {\r
res = sync_fs(fs);\r
}\r
} else {\r
- remove_chain(&dj.obj, dcl, 0); /* Could not register, remove cluster chain */\r
+ remove_chain(&sobj, dcl, 0); /* Could not register, remove the allocated cluster */\r
}\r
}\r
FREE_NAMBUF();\r
)\r
{\r
FRESULT res;\r
- DIR djo, djn;\r
FATFS *fs;\r
+ DIR djo, djn;\r
BYTE buf[FF_FS_EXFAT ? SZDIRE * 2 : SZDIRE], *dir;\r
- DWORD dw;\r
+ LBA_t sect;\r
DEF_NAMBUF\r
\r
\r
get_ldnumber(&path_new); /* Snip the drive number of new name off */\r
- res = find_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */\r
+ res = mount_volume(&path_old, &fs, FA_WRITE); /* Get logical drive of the old object */\r
if (res == FR_OK) {\r
djo.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
- res = follow_path(&djo, path_old); /* Check old object */\r
+ res = follow_path(&djo, path_old); /* Check old object */\r
if (res == FR_OK && (djo.fn[NSFLAG] & (NS_DOT | NS_NONAME))) res = FR_INVALID_NAME; /* Check validity of name */\r
-#if FF_FS_LOCK != 0\r
+#if FF_FS_LOCK\r
if (res == FR_OK) {\r
- res = chk_lock(&djo, 2);\r
+ res = chk_share(&djo, 2);\r
}\r
#endif\r
- if (res == FR_OK) { /* Object to be renamed is found */\r
+ if (res == FR_OK) { /* Object to be renamed is found */\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) { /* At exFAT volume */\r
BYTE nf, nn;\r
WORD nh;\r
\r
- mem_cpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */\r
- mem_cpy(&djn, &djo, sizeof djo);\r
+ memcpy(buf, fs->dirbuf, SZDIRE * 2); /* Save 85+C0 entry of old object */\r
+ memcpy(&djn, &djo, sizeof djo);\r
res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */\r
if (res == FR_OK) { /* Is new name already in use by any other object? */\r
res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;\r
if (res == FR_OK) {\r
nf = fs->dirbuf[XDIR_NumSec]; nn = fs->dirbuf[XDIR_NumName];\r
nh = ld_word(fs->dirbuf + XDIR_NameHash);\r
- mem_cpy(fs->dirbuf, buf, SZDIRE * 2); /* Restore 85+C0 entry */\r
+ memcpy(fs->dirbuf, buf, SZDIRE * 2); /* Restore 85+C0 entry */\r
fs->dirbuf[XDIR_NumSec] = nf; fs->dirbuf[XDIR_NumName] = nn;\r
st_word(fs->dirbuf + XDIR_NameHash, nh);\r
if (!(fs->dirbuf[XDIR_Attr] & AM_DIR)) fs->dirbuf[XDIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */\r
} else\r
#endif\r
{ /* At FAT/FAT32 volume */\r
- mem_cpy(buf, djo.dir, SZDIRE); /* Save directory entry of the object */\r
- mem_cpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */\r
+ memcpy(buf, djo.dir, SZDIRE); /* Save directory entry of the object */\r
+ memcpy(&djn, &djo, sizeof (DIR)); /* Duplicate the directory object */\r
res = follow_path(&djn, path_new); /* Make sure if new object name is not in use */\r
if (res == FR_OK) { /* Is new name already in use by any other object? */\r
res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ? FR_NO_FILE : FR_EXIST;\r
res = dir_register(&djn); /* Register the new entry */\r
if (res == FR_OK) {\r
dir = djn.dir; /* Copy directory entry of the object except name */\r
- mem_cpy(dir + 13, buf + 13, SZDIRE - 13);\r
+ memcpy(dir + 13, buf + 13, SZDIRE - 13);\r
dir[DIR_Attr] = buf[DIR_Attr];\r
if (!(dir[DIR_Attr] & AM_DIR)) dir[DIR_Attr] |= AM_ARC; /* Set archive attribute if it is a file */\r
fs->wflag = 1;\r
if ((dir[DIR_Attr] & AM_DIR) && djo.obj.sclust != djn.obj.sclust) { /* Update .. entry in the sub-directory if needed */\r
- dw = clst2sect(fs, ld_clust(fs, dir));\r
- if (dw == 0) {\r
+ sect = clst2sect(fs, ld_clust(fs, dir));\r
+ if (sect == 0) {\r
res = FR_INT_ERR;\r
} else {\r
/* Start of critical section where an interruption can cause a cross-link */\r
- res = move_window(fs, dw);\r
+ res = move_window(fs, sect);\r
dir = fs->win + SZDIRE * 1; /* Ptr to .. entry */\r
if (res == FR_OK && dir[1] == '.') {\r
st_clust(fs, dir, djn.obj.sclust);\r
)\r
{\r
FRESULT res;\r
- DIR dj;\r
FATFS *fs;\r
+ DIR dj;\r
DEF_NAMBUF\r
\r
\r
- res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */\r
+ res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */\r
if (res == FR_OK) {\r
dj.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
)\r
{\r
FRESULT res;\r
- DIR dj;\r
FATFS *fs;\r
+ DIR dj;\r
DEF_NAMBUF\r
\r
\r
- res = find_volume(&path, &fs, FA_WRITE); /* Get logical drive */\r
+ res = mount_volume(&path, &fs, FA_WRITE); /* Get logical drive */\r
if (res == FR_OK) {\r
dj.obj.fs = fs;\r
INIT_NAMBUF(fs);\r
)\r
{\r
FRESULT res;\r
- DIR dj;\r
FATFS *fs;\r
+ DIR dj;\r
UINT si, di;\r
WCHAR wc;\r
\r
/* Get logical drive */\r
- res = find_volume(&path, &fs, 0);\r
+ res = mount_volume(&path, &fs, 0);\r
\r
/* Get volume label */\r
if (res == FR_OK && label) {\r
dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */\r
res = dir_sdi(&dj, 0);\r
if (res == FR_OK) {\r
- res = dir_read_label(&dj); /* Find a volume label entry */\r
+ res = DIR_READ_LABEL(&dj); /* Find a volume label entry */\r
if (res == FR_OK) {\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) {\r
WCHAR hs;\r
+ UINT nw;\r
\r
for (si = di = hs = 0; si < dj.dir[XDIR_NumLabel]; si++) { /* Extract volume label from 83 entry */\r
wc = ld_word(dj.dir + XDIR_Label + si * 2);\r
if (hs == 0 && IsSurrogate(wc)) { /* Is the code a surrogate? */\r
hs = wc; continue;\r
}\r
- wc = put_utf((DWORD)hs << 16 | wc, &label[di], 4);\r
- if (wc == 0) { di = 0; break; }\r
- di += wc;\r
+ nw = put_utf((DWORD)hs << 16 | wc, &label[di], 4); /* Store it in API encoding */\r
+ if (nw == 0) { /* Encode error? */\r
+ di = 0; break;\r
+ }\r
+ di += nw;\r
hs = 0;\r
}\r
if (hs != 0) di = 0; /* Broken surrogate pair? */\r
wc = dj.dir[si++];\r
#if FF_USE_LFN && FF_LFN_UNICODE >= 1 /* Unicode output */\r
if (dbc_1st((BYTE)wc) && si < 11) wc = wc << 8 | dj.dir[si++]; /* Is it a DBC? */\r
- wc = ff_oem2uni(wc, CODEPAGE); /* Convert it into Unicode */\r
- if (wc != 0) wc = put_utf(wc, &label[di], 4); /* Put it in Unicode */\r
- if (wc == 0) { di = 0; break; }\r
- di += wc;\r
+ wc = ff_oem2uni(wc, CODEPAGE); /* Convert it into Unicode */\r
+ if (wc == 0) { /* Invalid char in current code page? */\r
+ di = 0; break;\r
+ }\r
+ di += put_utf(wc, &label[di], 4); /* Store it in Unicode */\r
#else /* ANSI/OEM output */\r
label[di++] = (TCHAR)wc;\r
#endif\r
if (res == FR_OK) {\r
switch (fs->fs_type) {\r
case FS_EXFAT:\r
- di = BPB_VolIDEx; break;\r
+ di = BPB_VolIDEx;\r
+ break;\r
\r
case FS_FAT32:\r
- di = BS_VolID32; break;\r
+ di = BS_VolID32;\r
+ break;\r
\r
default:\r
di = BS_VolID;\r
)\r
{\r
FRESULT res;\r
- DIR dj;\r
FATFS *fs;\r
+ DIR dj;\r
BYTE dirvn[22];\r
UINT di;\r
WCHAR wc;\r
- static const char badchr[] = "+.,;=[]/\\\"*:<>\?|\x7F"; /* [0..] for FAT, [7..] for exFAT */\r
+ static const char badchr[18] = "+.,;=[]" "/*:<>|\\\"\?\x7F"; /* [0..16] for FAT, [7..16] for exFAT */\r
#if FF_USE_LFN\r
DWORD dc;\r
#endif\r
\r
/* Get logical drive */\r
- res = find_volume(&label, &fs, FA_WRITE);\r
+ res = mount_volume(&label, &fs, FA_WRITE);\r
if (res != FR_OK) LEAVE_FF(fs, res);\r
\r
#if FF_FS_EXFAT\r
if (fs->fs_type == FS_EXFAT) { /* On the exFAT volume */\r
- mem_set(dirvn, 0, 22);\r
+ memset(dirvn, 0, 22);\r
di = 0;\r
while ((UINT)*label >= ' ') { /* Create volume label */\r
dc = tchar2uni(&label); /* Get a Unicode character */\r
st_word(dirvn + di * 2, (WCHAR)(dc >> 16)); di++;\r
}\r
}\r
- if (dc == 0 || chk_chr(badchr + 7, (int)dc) || di >= 11) { /* Check validity of the volume label */\r
+ if (dc == 0 || strchr(&badchr[7], (int)dc) || di >= 11) { /* Check validity of the volume label */\r
LEAVE_FF(fs, FR_INVALID_NAME);\r
}\r
st_word(dirvn + di * 2, (WCHAR)dc); di++;\r
} else\r
#endif\r
{ /* On the FAT/FAT32 volume */\r
- mem_set(dirvn, ' ', 11);\r
+ memset(dirvn, ' ', 11);\r
di = 0;\r
while ((UINT)*label >= ' ') { /* Create volume label */\r
#if FF_USE_LFN\r
if (wc >= 0x80) wc = ExCvt[wc - 0x80]; /* To upper extended characters (SBCS cfg) */\r
#endif\r
#endif\r
- if (wc == 0 || chk_chr(badchr + 0, (int)wc) || di >= (UINT)((wc >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */\r
+ if (wc == 0 || strchr(&badchr[0], (int)wc) || di >= (UINT)((wc >= 0x100) ? 10 : 11)) { /* Reject invalid characters for volume label */\r
LEAVE_FF(fs, FR_INVALID_NAME);\r
}\r
if (wc >= 0x100) dirvn[di++] = (BYTE)(wc >> 8);\r
dj.obj.fs = fs; dj.obj.sclust = 0; /* Open root directory */\r
res = dir_sdi(&dj, 0);\r
if (res == FR_OK) {\r
- res = dir_read_label(&dj); /* Get volume label entry */\r
+ res = DIR_READ_LABEL(&dj); /* Get volume label entry */\r
if (res == FR_OK) {\r
if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {\r
dj.dir[XDIR_NumLabel] = (BYTE)di; /* Change the volume label */\r
- mem_cpy(dj.dir + XDIR_Label, dirvn, 22);\r
+ memcpy(dj.dir + XDIR_Label, dirvn, 22);\r
} else {\r
if (di != 0) {\r
- mem_cpy(dj.dir, dirvn, 11); /* Change the volume label */\r
+ memcpy(dj.dir, dirvn, 11); /* Change the volume label */\r
} else {\r
dj.dir[DIR_Name] = DDEM; /* Remove the volume label */\r
}\r
if (di != 0) { /* Create a volume label entry */\r
res = dir_alloc(&dj, 1); /* Allocate an entry */\r
if (res == FR_OK) {\r
- mem_set(dj.dir, 0, SZDIRE); /* Clean the entry */\r
+ memset(dj.dir, 0, SZDIRE); /* Clean the entry */\r
if (FF_FS_EXFAT && fs->fs_type == FS_EXFAT) {\r
- dj.dir[XDIR_Type] = 0x83; /* Create 83 entry */\r
+ dj.dir[XDIR_Type] = ET_VLABEL; /* Create volume label entry */\r
dj.dir[XDIR_NumLabel] = (BYTE)di;\r
- mem_cpy(dj.dir + XDIR_Label, dirvn, 22);\r
+ memcpy(dj.dir + XDIR_Label, dirvn, 22);\r
} else {\r
dj.dir[DIR_Attr] = AM_VOL; /* Create volume label entry */\r
- mem_cpy(dj.dir, dirvn, 11);\r
+ memcpy(dj.dir, dirvn, 11);\r
}\r
fs->wflag = 1;\r
res = sync_fs(fs);\r
for (;;) { /* Find a contiguous cluster block */\r
n = get_fat(&fp->obj, clst);\r
if (++clst >= fs->n_fatent) clst = 2;\r
- if (n == 1) { res = FR_INT_ERR; break; }\r
- if (n == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }\r
+ if (n == 1) {\r
+ res = FR_INT_ERR; break;\r
+ }\r
+ if (n == 0xFFFFFFFF) {\r
+ res = FR_DISK_ERR; break;\r
+ }\r
if (n == 0) { /* Is it a free cluster? */\r
if (++ncl == tcl) break; /* Break if a contiguous cluster block is found */\r
} else {\r
scl = clst; ncl = 0; /* Not a free cluster */\r
}\r
- if (clst == stcl) { res = FR_DENIED; break; } /* No contiguous cluster? */\r
+ if (clst == stcl) { /* No contiguous cluster? */\r
+ res = FR_DENIED; break;\r
+ }\r
}\r
if (res == FR_OK) { /* A contiguous free area is found */\r
if (opt) { /* Allocate it now */\r
{\r
FRESULT res;\r
FATFS *fs;\r
- DWORD clst, sect;\r
+ DWORD clst;\r
+ LBA_t sect;\r
FSIZE_t remain;\r
UINT rcnt, csect;\r
BYTE *dbuf;\r
remain = fp->obj.objsize - fp->fptr;\r
if (btf > remain) btf = (UINT)remain; /* Truncate btf by remaining bytes */\r
\r
- for ( ; btf && (*func)(0, 0); /* Repeat until all data transferred or stream goes busy */\r
- fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) {\r
+ for ( ; btf > 0 && (*func)(0, 0); fp->fptr += rcnt, *bf += rcnt, btf -= rcnt) { /* Repeat until all data transferred or stream goes busy */\r
csect = (UINT)(fp->fptr / SS(fs) & (fs->csize - 1)); /* Sector offset in the cluster */\r
if (fp->fptr % SS(fs) == 0) { /* On the sector boundary? */\r
if (csect == 0) { /* On the cluster boundary? */\r
dbuf = fp->buf;\r
#endif\r
fp->sect = sect;\r
- rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes left in the sector */\r
+ rcnt = SS(fs) - (UINT)fp->fptr % SS(fs); /* Number of bytes remains in the sector */\r
if (rcnt > btf) rcnt = btf; /* Clip it by btr if needed */\r
rcnt = (*func)(dbuf + ((UINT)fp->fptr % SS(fs)), rcnt); /* Forward the file data */\r
if (rcnt == 0) ABORT(fs, FR_INT_ERR);\r
\r
\r
\r
-#if FF_USE_MKFS && !FF_FS_READONLY\r
+#if !FF_FS_READONLY && FF_USE_MKFS\r
/*-----------------------------------------------------------------------*/\r
-/* Create an FAT/exFAT volume */\r
+/* Create FAT/exFAT volume (with sub-functions) */\r
/*-----------------------------------------------------------------------*/\r
\r
+#define N_SEC_TRACK 63 /* Sectors per track for determination of drive CHS */\r
+#define GPT_ALIGN 0x100000 /* Alignment of partitions in GPT [byte] (>=128KB) */\r
+#define GPT_ITEMS 128 /* Number of GPT table size (>=128, sector aligned) */\r
+\r
+\r
+/* Create partitions on the physical drive in format of MBR or GPT */\r
+\r
+static FRESULT create_partition (\r
+ BYTE drv, /* Physical drive number */\r
+ const LBA_t plst[], /* Partition list */\r
+ BYTE sys, /* System ID for each partition (for only MBR) */\r
+ BYTE *buf /* Working buffer for a sector */\r
+)\r
+{\r
+ UINT i, cy;\r
+ LBA_t sz_drv;\r
+ DWORD sz_drv32, nxt_alloc32, sz_part32;\r
+ BYTE *pte;\r
+ BYTE hd, n_hd, sc, n_sc;\r
+\r
+ /* Get physical drive size */\r
+ if (disk_ioctl(drv, GET_SECTOR_COUNT, &sz_drv) != RES_OK) return FR_DISK_ERR;\r
+\r
+#if FF_LBA64\r
+ if (sz_drv >= FF_MIN_GPT) { /* Create partitions in GPT format */\r
+ WORD ss;\r
+ UINT sz_ptbl, pi, si, ofs;\r
+ DWORD bcc, rnd, align;\r
+ QWORD nxt_alloc, sz_part, sz_pool, top_bpt;\r
+ static const BYTE gpt_mbr[16] = {0x00, 0x00, 0x02, 0x00, 0xEE, 0xFE, 0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF};\r
+\r
+#if FF_MAX_SS != FF_MIN_SS\r
+ if (disk_ioctl(drv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR; /* Get sector size */\r
+ if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;\r
+#else\r
+ ss = FF_MAX_SS;\r
+#endif\r
+ rnd = (DWORD)sz_drv + GET_FATTIME(); /* Random seed */\r
+ align = GPT_ALIGN / ss; /* Partition alignment for GPT [sector] */\r
+ sz_ptbl = GPT_ITEMS * SZ_GPTE / ss; /* Size of partition table [sector] */\r
+ top_bpt = sz_drv - sz_ptbl - 1; /* Backup partition table start sector */\r
+ nxt_alloc = 2 + sz_ptbl; /* First allocatable sector */\r
+ sz_pool = top_bpt - nxt_alloc; /* Size of allocatable area */\r
+ bcc = 0xFFFFFFFF; sz_part = 1;\r
+ pi = si = 0; /* partition table index, size table index */\r
+ do {\r
+ if (pi * SZ_GPTE % ss == 0) memset(buf, 0, ss); /* Clean the buffer if needed */\r
+ if (sz_part != 0) { /* Is the size table not termintated? */\r
+ nxt_alloc = (nxt_alloc + align - 1) & ((QWORD)0 - align); /* Align partition start */\r
+ sz_part = plst[si++]; /* Get a partition size */\r
+ if (sz_part <= 100) { /* Is the size in percentage? */\r
+ sz_part = sz_pool * sz_part / 100;\r
+ sz_part = (sz_part + align - 1) & ((QWORD)0 - align); /* Align partition end (only if in percentage) */\r
+ }\r
+ if (nxt_alloc + sz_part > top_bpt) { /* Clip the size at end of the pool */\r
+ sz_part = (nxt_alloc < top_bpt) ? top_bpt - nxt_alloc : 0;\r
+ }\r
+ }\r
+ if (sz_part != 0) { /* Add a partition? */\r
+ ofs = pi * SZ_GPTE % ss;\r
+ memcpy(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16); /* Set partition GUID (Microsoft Basic Data) */\r
+ rnd = make_rand(rnd, buf + ofs + GPTE_UpGuid, 16); /* Set unique partition GUID */\r
+ st_qword(buf + ofs + GPTE_FstLba, nxt_alloc); /* Set partition start sector */\r
+ st_qword(buf + ofs + GPTE_LstLba, nxt_alloc + sz_part - 1); /* Set partition end sector */\r
+ nxt_alloc += sz_part; /* Next allocatable sector */\r
+ }\r
+ if ((pi + 1) * SZ_GPTE % ss == 0) { /* Write the buffer if it is filled up */\r
+ for (i = 0; i < ss; bcc = crc32(bcc, buf[i++])) ; /* Calculate table check sum */\r
+ if (disk_write(drv, buf, 2 + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to primary table */\r
+ if (disk_write(drv, buf, top_bpt + pi * SZ_GPTE / ss, 1) != RES_OK) return FR_DISK_ERR; /* Write to secondary table */\r
+ }\r
+ } while (++pi < GPT_ITEMS);\r
+\r
+ /* Create primary GPT header */\r
+ memset(buf, 0, ss);\r
+ memcpy(buf + GPTH_Sign, "EFI PART" "\0\0\1\0" "\x5C\0\0", 16); /* Signature, version (1.0) and size (92) */\r
+ st_dword(buf + GPTH_PtBcc, ~bcc); /* Table check sum */\r
+ st_qword(buf + GPTH_CurLba, 1); /* LBA of this header */\r
+ st_qword(buf + GPTH_BakLba, sz_drv - 1); /* LBA of secondary header */\r
+ st_qword(buf + GPTH_FstLba, 2 + sz_ptbl); /* LBA of first allocatable sector */\r
+ st_qword(buf + GPTH_LstLba, top_bpt - 1); /* LBA of last allocatable sector */\r
+ st_dword(buf + GPTH_PteSize, SZ_GPTE); /* Size of a table entry */\r
+ st_dword(buf + GPTH_PtNum, GPT_ITEMS); /* Number of table entries */\r
+ st_dword(buf + GPTH_PtOfs, 2); /* LBA of this table */\r
+ rnd = make_rand(rnd, buf + GPTH_DskGuid, 16); /* Disk GUID */\r
+ for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */\r
+ st_dword(buf + GPTH_Bcc, ~bcc); /* Header check sum */\r
+ if (disk_write(drv, buf, 1, 1) != RES_OK) return FR_DISK_ERR;\r
+\r
+ /* Create secondary GPT header */\r
+ st_qword(buf + GPTH_CurLba, sz_drv - 1); /* LBA of this header */\r
+ st_qword(buf + GPTH_BakLba, 1); /* LBA of primary header */\r
+ st_qword(buf + GPTH_PtOfs, top_bpt); /* LBA of this table */\r
+ st_dword(buf + GPTH_Bcc, 0);\r
+ for (i = 0, bcc= 0xFFFFFFFF; i < 92; bcc = crc32(bcc, buf[i++])) ; /* Calculate header check sum */\r
+ st_dword(buf + GPTH_Bcc, ~bcc); /* Header check sum */\r
+ if (disk_write(drv, buf, sz_drv - 1, 1) != RES_OK) return FR_DISK_ERR;\r
+\r
+ /* Create protective MBR */\r
+ memset(buf, 0, ss);\r
+ memcpy(buf + MBR_Table, gpt_mbr, 16); /* Create a GPT partition */\r
+ st_word(buf + BS_55AA, 0xAA55);\r
+ if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR;\r
+\r
+ } else\r
+#endif\r
+ { /* Create partitions in MBR format */\r
+ sz_drv32 = (DWORD)sz_drv;\r
+ n_sc = N_SEC_TRACK; /* Determine drive CHS without any consideration of the drive geometry */\r
+ for (n_hd = 8; n_hd != 0 && sz_drv32 / n_hd / n_sc > 1024; n_hd *= 2) ;\r
+ if (n_hd == 0) n_hd = 255; /* Number of heads needs to be <256 */\r
+\r
+ memset(buf, 0, FF_MAX_SS); /* Clear MBR */\r
+ pte = buf + MBR_Table; /* Partition table in the MBR */\r
+ for (i = 0, nxt_alloc32 = n_sc; i < 4 && nxt_alloc32 != 0 && nxt_alloc32 < sz_drv32; i++, nxt_alloc32 += sz_part32) {\r
+ sz_part32 = (DWORD)plst[i]; /* Get partition size */\r
+ if (sz_part32 <= 100) sz_part32 = (sz_part32 == 100) ? sz_drv32 : sz_drv32 / 100 * sz_part32; /* Size in percentage? */\r
+ if (nxt_alloc32 + sz_part32 > sz_drv32 || nxt_alloc32 + sz_part32 < nxt_alloc32) sz_part32 = sz_drv32 - nxt_alloc32; /* Clip at drive size */\r
+ if (sz_part32 == 0) break; /* End of table or no sector to allocate? */\r
+\r
+ st_dword(pte + PTE_StLba, nxt_alloc32); /* Start LBA */\r
+ st_dword(pte + PTE_SizLba, sz_part32); /* Number of sectors */\r
+ pte[PTE_System] = sys; /* System type */\r
+\r
+ cy = (UINT)(nxt_alloc32 / n_sc / n_hd); /* Start cylinder */\r
+ hd = (BYTE)(nxt_alloc32 / n_sc % n_hd); /* Start head */\r
+ sc = (BYTE)(nxt_alloc32 % n_sc + 1); /* Start sector */\r
+ pte[PTE_StHead] = hd;\r
+ pte[PTE_StSec] = (BYTE)((cy >> 2 & 0xC0) | sc);\r
+ pte[PTE_StCyl] = (BYTE)cy;\r
+\r
+ cy = (UINT)((nxt_alloc32 + sz_part32 - 1) / n_sc / n_hd); /* End cylinder */\r
+ hd = (BYTE)((nxt_alloc32 + sz_part32 - 1) / n_sc % n_hd); /* End head */\r
+ sc = (BYTE)((nxt_alloc32 + sz_part32 - 1) % n_sc + 1); /* End sector */\r
+ pte[PTE_EdHead] = hd;\r
+ pte[PTE_EdSec] = (BYTE)((cy >> 2 & 0xC0) | sc);\r
+ pte[PTE_EdCyl] = (BYTE)cy;\r
+\r
+ pte += SZ_PTE; /* Next entry */\r
+ }\r
+\r
+ st_word(buf + BS_55AA, 0xAA55); /* MBR signature */\r
+ if (disk_write(drv, buf, 0, 1) != RES_OK) return FR_DISK_ERR; /* Write it to the MBR */\r
+ }\r
+\r
+ return FR_OK;\r
+}\r
+\r
+\r
+\r
FRESULT f_mkfs (\r
- const TCHAR* path, /* Logical drive number */\r
- BYTE opt, /* Format option */\r
- DWORD au, /* Size of allocation unit (cluster) [byte] */\r
- void* work, /* Pointer to working buffer (null: use heap memory) */\r
- UINT len /* Size of working buffer [byte] */\r
+ const TCHAR* path, /* Logical drive number */\r
+ const MKFS_PARM* opt, /* Format options */\r
+ void* work, /* Pointer to working buffer (null: use len bytes of heap memory) */\r
+ UINT len /* Size of working buffer [byte] */\r
)\r
{\r
- const UINT n_fats = 1; /* Number of FATs for FAT/FAT32 volume (1 or 2) */\r
- const UINT n_rootdir = 512; /* Number of root directory entries for FAT volume */\r
static const WORD cst[] = {1, 4, 16, 64, 256, 512, 0}; /* Cluster size boundary for FAT volume (4Ks unit) */\r
static const WORD cst32[] = {1, 2, 4, 8, 16, 32, 0}; /* Cluster size boundary for FAT32 volume (128Ks unit) */\r
- BYTE fmt, sys, *buf, *pte, pdrv, part;\r
+ static const MKFS_PARM defopt = {FM_ANY, 0, 0, 0, 0}; /* Default parameter */\r
+ BYTE fsopt, fsty, sys, pdrv, ipart;\r
+ BYTE *buf;\r
+ BYTE *pte;\r
WORD ss; /* Sector size */\r
- DWORD szb_buf, sz_buf, sz_blk, n_clst, pau, sect, nsect, n;\r
- DWORD b_vol, b_fat, b_data; /* Base LBA for volume, fat, data */\r
- DWORD sz_vol, sz_rsv, sz_fat, sz_dir; /* Size for volume, fat, dir, data */\r
- UINT i;\r
+ DWORD sz_buf, sz_blk, n_clst, pau, nsect, n, vsn;\r
+ LBA_t sz_vol, b_vol, b_fat, b_data; /* Size of volume, Base LBA of volume, fat, data */\r
+ LBA_t sect, lba[2];\r
+ DWORD sz_rsv, sz_fat, sz_dir, sz_au; /* Size of reserved, fat, dir, data, cluster */\r
+ UINT n_fat, n_root, i; /* Index, Number of FATs and Number of roor dir entries */\r
int vol;\r
- DSTATUS stat;\r
-#if FF_USE_TRIM || FF_FS_EXFAT\r
- DWORD tbl[3];\r
-#endif\r
+ DSTATUS ds;\r
+ FRESULT res;\r
\r
\r
/* Check mounted drive and clear work area */\r
vol = get_ldnumber(&path); /* Get target logical drive */\r
if (vol < 0) return FR_INVALID_DRIVE;\r
- if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear the volume if mounted */\r
- pdrv = LD2PD(vol); /* Physical drive */\r
- part = LD2PT(vol); /* Partition (0:create as new, 1-4:get from partition table) */\r
-\r
- /* Check physical drive status */\r
- stat = disk_initialize(pdrv);\r
- if (stat & STA_NOINIT) return FR_NOT_READY;\r
- if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;\r
- if (disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk) != RES_OK || !sz_blk || sz_blk > 32768 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Erase block to align data area */\r
-#if FF_MAX_SS != FF_MIN_SS /* Get sector size of the medium if variable sector size cfg. */\r
+ if (FatFs[vol]) FatFs[vol]->fs_type = 0; /* Clear the fs object if mounted */\r
+ pdrv = LD2PD(vol); /* Hosting physical drive */\r
+ ipart = LD2PT(vol); /* Hosting partition (0:create as new, 1..:existing partition) */\r
+\r
+ /* Initialize the hosting physical drive */\r
+ ds = disk_initialize(pdrv);\r
+ if (ds & STA_NOINIT) return FR_NOT_READY;\r
+ if (ds & STA_PROTECT) return FR_WRITE_PROTECTED;\r
+\r
+ /* Get physical drive parameters (sz_drv, sz_blk and ss) */\r
+ if (!opt) opt = &defopt; /* Use default parameter if it is not given */\r
+ sz_blk = opt->align;\r
+ if (sz_blk == 0) disk_ioctl(pdrv, GET_BLOCK_SIZE, &sz_blk); /* Block size from the paramter or lower layer */\r
+ if (sz_blk == 0 || sz_blk > 0x8000 || (sz_blk & (sz_blk - 1))) sz_blk = 1; /* Use default if the block size is invalid */\r
+#if FF_MAX_SS != FF_MIN_SS\r
if (disk_ioctl(pdrv, GET_SECTOR_SIZE, &ss) != RES_OK) return FR_DISK_ERR;\r
if (ss > FF_MAX_SS || ss < FF_MIN_SS || (ss & (ss - 1))) return FR_DISK_ERR;\r
#else\r
ss = FF_MAX_SS;\r
#endif\r
- if ((au != 0 && au < ss) || au > 0x1000000 || (au & (au - 1))) return FR_INVALID_PARAMETER; /* Check if au is valid */\r
- au /= ss; /* Cluster size in unit of sector */\r
+\r
+ /* Options for FAT sub-type and FAT parameters */\r
+ fsopt = opt->fmt & (FM_ANY | FM_SFD);\r
+ n_fat = (opt->n_fat >= 1 && opt->n_fat <= 2) ? opt->n_fat : 1;\r
+ n_root = (opt->n_root >= 1 && opt->n_root <= 32768 && (opt->n_root % (ss / SZDIRE)) == 0) ? opt->n_root : 512;\r
+ sz_au = (opt->au_size <= 0x1000000 && (opt->au_size & (opt->au_size - 1)) == 0) ? opt->au_size : 0;\r
+ sz_au /= ss; /* Byte --> Sector */\r
\r
/* Get working buffer */\r
+ sz_buf = len / ss; /* Size of working buffer [sector] */\r
+ if (sz_buf == 0) return FR_NOT_ENOUGH_CORE;\r
+ buf = (BYTE*)work; /* Working buffer */\r
#if FF_USE_LFN == 3\r
- if (!work) { /* Use heap memory for working buffer */\r
- for (szb_buf = MAX_MALLOC, buf = 0; szb_buf >= ss && (buf = ff_memalloc(szb_buf)) == 0; szb_buf /= 2) ;\r
- sz_buf = szb_buf / ss; /* Size of working buffer (sector) */\r
- } else\r
+ if (!buf) buf = ff_memalloc(sz_buf * ss); /* Use heap memory for working buffer */\r
#endif\r
- {\r
- buf = (BYTE*)work; /* Working buffer */\r
- sz_buf = len / ss; /* Size of working buffer (sector) */\r
- szb_buf = sz_buf * ss; /* Size of working buffer (byte) */\r
- }\r
- if (!buf || sz_buf == 0) return FR_NOT_ENOUGH_CORE;\r
+ if (!buf) return FR_NOT_ENOUGH_CORE;\r
\r
/* Determine where the volume to be located (b_vol, sz_vol) */\r
- if (FF_MULTI_PARTITION && part != 0) {\r
- /* Get partition information from partition table in the MBR */\r
+ b_vol = sz_vol = 0;\r
+ if (FF_MULTI_PARTITION && ipart != 0) { /* Is the volume associated with any specific partition? */\r
+ /* Get partition location from the existing partition table */\r
if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Load MBR */\r
if (ld_word(buf + BS_55AA) != 0xAA55) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if MBR is valid */\r
- pte = buf + (MBR_Table + (part - 1) * SZ_PTE);\r
- if (pte[PTE_System] == 0) LEAVE_MKFS(FR_MKFS_ABORTED); /* No partition? */\r
- b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */\r
- sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */\r
- } else {\r
- /* Create a single-partition in this function */\r
+#if FF_LBA64\r
+ if (buf[MBR_Table + PTE_System] == 0xEE) { /* GPT protective MBR? */\r
+ DWORD n_ent, ofs;\r
+ QWORD pt_lba;\r
+\r
+ /* Get the partition location from GPT */\r
+ if (disk_read(pdrv, buf, 1, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Load GPT header sector (next to MBR) */\r
+ if (!test_gpt_header(buf)) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if GPT header is valid */\r
+ n_ent = ld_dword(buf + GPTH_PtNum); /* Number of entries */\r
+ pt_lba = ld_qword(buf + GPTH_PtOfs); /* Table start sector */\r
+ ofs = i = 0;\r
+ while (n_ent) { /* Find MS Basic partition with order of ipart */\r
+ if (ofs == 0 && disk_read(pdrv, buf, pt_lba++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Get PT sector */\r
+ if (!memcmp(buf + ofs + GPTE_PtGuid, GUID_MS_Basic, 16) && ++i == ipart) { /* MS basic data partition? */\r
+ b_vol = ld_qword(buf + ofs + GPTE_FstLba);\r
+ sz_vol = ld_qword(buf + ofs + GPTE_LstLba) - b_vol + 1;\r
+ break;\r
+ }\r
+ n_ent--; ofs = (ofs + SZ_GPTE) % ss; /* Next entry */\r
+ }\r
+ if (n_ent == 0) LEAVE_MKFS(FR_MKFS_ABORTED); /* Partition not found */\r
+ fsopt |= 0x80; /* Partitioning is in GPT */\r
+ } else\r
+#endif\r
+ { /* Get the partition location from MBR partition table */\r
+ pte = buf + (MBR_Table + (ipart - 1) * SZ_PTE);\r
+ if (ipart > 4 || pte[PTE_System] == 0) LEAVE_MKFS(FR_MKFS_ABORTED); /* No partition? */\r
+ b_vol = ld_dword(pte + PTE_StLba); /* Get volume start sector */\r
+ sz_vol = ld_dword(pte + PTE_SizLba); /* Get volume size */\r
+ }\r
+ } else { /* The volume is associated with a physical drive */\r
if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_vol) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
- b_vol = (opt & FM_SFD) ? 0 : 63; /* Volume start sector */\r
- if (sz_vol < b_vol) LEAVE_MKFS(FR_MKFS_ABORTED);\r
- sz_vol -= b_vol; /* Volume size */\r
+ if (!(fsopt & FM_SFD)) { /* To be partitioned? */\r
+ /* Create a single-partition on the drive in this function */\r
+#if FF_LBA64\r
+ if (sz_vol >= FF_MIN_GPT) { /* Which partition type to create, MBR or GPT? */\r
+ fsopt |= 0x80; /* Partitioning is in GPT */\r
+ b_vol = GPT_ALIGN / ss; sz_vol -= b_vol + GPT_ITEMS * SZ_GPTE / ss + 1; /* Estimated partition offset and size */\r
+ } else\r
+#endif\r
+ { /* Partitioning is in MBR */\r
+ if (sz_vol > N_SEC_TRACK) {\r
+ b_vol = N_SEC_TRACK; sz_vol -= b_vol; /* Estimated partition offset and size */\r
+ }\r
+ }\r
+ }\r
}\r
if (sz_vol < 128) LEAVE_MKFS(FR_MKFS_ABORTED); /* Check if volume size is >=128s */\r
\r
- /* Pre-determine the FAT type */\r
- do {\r
- if (FF_FS_EXFAT && (opt & FM_EXFAT)) { /* exFAT possible? */\r
- if ((opt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || au > 128) { /* exFAT only, vol >= 64Ms or au > 128s ? */\r
- fmt = FS_EXFAT; break;\r
+ /* Now start to create an FAT volume at b_vol and sz_vol */\r
+\r
+ do { /* Pre-determine the FAT type */\r
+ if (FF_FS_EXFAT && (fsopt & FM_EXFAT)) { /* exFAT possible? */\r
+ if ((fsopt & FM_ANY) == FM_EXFAT || sz_vol >= 0x4000000 || sz_au > 128) { /* exFAT only, vol >= 64MS or sz_au > 128S ? */\r
+ fsty = FS_EXFAT; break;\r
}\r
}\r
- if (au > 128) LEAVE_MKFS(FR_INVALID_PARAMETER); /* Too large au for FAT/FAT32 */\r
- if (opt & FM_FAT32) { /* FAT32 possible? */\r
- if ((opt & FM_ANY) == FM_FAT32 || !(opt & FM_FAT)) { /* FAT32 only or no-FAT? */\r
- fmt = FS_FAT32; break;\r
+#if FF_LBA64\r
+ if (sz_vol >= 0x100000000) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too large volume for FAT/FAT32 */\r
+#endif\r
+ if (sz_au > 128) sz_au = 128; /* Invalid AU for FAT/FAT32? */\r
+ if (fsopt & FM_FAT32) { /* FAT32 possible? */\r
+ if (!(fsopt & FM_FAT)) { /* no-FAT? */\r
+ fsty = FS_FAT32; break;\r
}\r
}\r
- if (!(opt & FM_FAT)) LEAVE_MKFS(FR_INVALID_PARAMETER); /* no-FAT? */\r
- fmt = FS_FAT16;\r
+ if (!(fsopt & FM_FAT)) LEAVE_MKFS(FR_INVALID_PARAMETER); /* no-FAT? */\r
+ fsty = FS_FAT16;\r
} while (0);\r
\r
+ vsn = (DWORD)sz_vol + GET_FATTIME(); /* VSN generated from current time and partitiion size */\r
+\r
#if FF_FS_EXFAT\r
- if (fmt == FS_EXFAT) { /* Create an exFAT volume */\r
- DWORD szb_bit, szb_case, sum, nb, cl;\r
+ if (fsty == FS_EXFAT) { /* Create an exFAT volume */\r
+ DWORD szb_bit, szb_case, sum, nbit, clu, clen[3];\r
WCHAR ch, si;\r
UINT j, st;\r
- BYTE b;\r
\r
- if (sz_vol < 0x1000) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */\r
+ if (sz_vol < 0x1000) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume for exFAT? */\r
#if FF_USE_TRIM\r
- tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area may be erased */\r
- disk_ioctl(pdrv, CTRL_TRIM, tbl);\r
+ lba[0] = b_vol; lba[1] = b_vol + sz_vol - 1; /* Inform storage device that the volume area may be erased */\r
+ disk_ioctl(pdrv, CTRL_TRIM, lba);\r
#endif\r
/* Determine FAT location, data location and number of clusters */\r
- if (au == 0) { /* au auto-selection */\r
- au = 8;\r
- if (sz_vol >= 0x80000) au = 64; /* >= 512Ks */\r
- if (sz_vol >= 0x4000000) au = 256; /* >= 64Ms */\r
+ if (sz_au == 0) { /* AU auto-selection */\r
+ sz_au = 8;\r
+ if (sz_vol >= 0x80000) sz_au = 64; /* >= 512Ks */\r
+ if (sz_vol >= 0x4000000) sz_au = 256; /* >= 64Ms */\r
}\r
b_fat = b_vol + 32; /* FAT start at offset 32 */\r
- sz_fat = ((sz_vol / au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */\r
- b_data = (b_fat + sz_fat + sz_blk - 1) & ~(sz_blk - 1); /* Align data area to the erase block boundary */\r
- if (b_data >= sz_vol / 2) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */\r
- n_clst = (sz_vol - (b_data - b_vol)) / au; /* Number of clusters */\r
+ sz_fat = (DWORD)((sz_vol / sz_au + 2) * 4 + ss - 1) / ss; /* Number of FAT sectors */\r
+ b_data = (b_fat + sz_fat + sz_blk - 1) & ~((LBA_t)sz_blk - 1); /* Align data area to the erase block boundary */\r
+ if (b_data - b_vol >= sz_vol / 2) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */\r
+ n_clst = (DWORD)((sz_vol - (b_data - b_vol)) / sz_au); /* Number of clusters */\r
if (n_clst <16) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too few clusters? */\r
if (n_clst > MAX_EXFAT) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters? */\r
\r
- szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */\r
- tbl[0] = (szb_bit + au * ss - 1) / (au * ss); /* Number of allocation bitmap clusters */\r
+ szb_bit = (n_clst + 7) / 8; /* Size of allocation bitmap */\r
+ clen[0] = (szb_bit + sz_au * ss - 1) / (sz_au * ss); /* Number of allocation bitmap clusters */\r
\r
/* Create a compressed up-case table */\r
- sect = b_data + au * tbl[0]; /* Table start sector */\r
- sum = 0; /* Table checksum to be stored in the 82 entry */\r
+ sect = b_data + sz_au * clen[0]; /* Table start sector */\r
+ sum = 0; /* Table checksum to be stored in the 82 entry */\r
st = 0; si = 0; i = 0; j = 0; szb_case = 0;\r
do {\r
switch (st) {\r
}\r
for (j = 1; (WCHAR)(si + j) && (WCHAR)(si + j) == ff_wtoupper((WCHAR)(si + j)); j++) ; /* Get run length of no-case block */\r
if (j >= 128) {\r
- ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 */\r
+ ch = 0xFFFF; st = 2; break; /* Compress the no-case block if run is >= 128 chars */\r
}\r
st = 1; /* Do not compress short run */\r
- /* go to next case */\r
+ /* FALLTHROUGH */\r
case 1:\r
ch = si++; /* Fill the short run */\r
if (--j == 0) st = 0;\r
ch = (WCHAR)j; si += (WCHAR)j; /* Number of chars to skip */\r
st = 0;\r
}\r
- sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */\r
+ sum = xsum32(buf[i + 0] = (BYTE)ch, sum); /* Put it into the write buffer */\r
sum = xsum32(buf[i + 1] = (BYTE)(ch >> 8), sum);\r
i += 2; szb_case += 2;\r
- if (si == 0 || i == szb_buf) { /* Write buffered data when buffer full or end of process */\r
+ if (si == 0 || i == sz_buf * ss) { /* Write buffered data when buffer full or end of process */\r
n = (i + ss - 1) / ss;\r
if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
sect += n; i = 0;\r
}\r
} while (si);\r
- tbl[1] = (szb_case + au * ss - 1) / (au * ss); /* Number of up-case table clusters */\r
- tbl[2] = 1; /* Number of root dir clusters */\r
+ clen[1] = (szb_case + sz_au * ss - 1) / (sz_au * ss); /* Number of up-case table clusters */\r
+ clen[2] = 1; /* Number of root dir clusters */\r
\r
/* Initialize the allocation bitmap */\r
- sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of sectors */\r
- nb = tbl[0] + tbl[1] + tbl[2]; /* Number of clusters in-use by system */\r
+ sect = b_data; nsect = (szb_bit + ss - 1) / ss; /* Start of bitmap and number of bitmap sectors */\r
+ nbit = clen[0] + clen[1] + clen[2]; /* Number of clusters in-use by system (bitmap, up-case and root-dir) */\r
do {\r
- mem_set(buf, 0, szb_buf);\r
- for (i = 0; nb >= 8 && i < szb_buf; buf[i++] = 0xFF, nb -= 8) ;\r
- for (b = 1; nb != 0 && i < szb_buf; buf[i] |= b, b <<= 1, nb--) ;\r
+ memset(buf, 0, sz_buf * ss); /* Initialize bitmap buffer */\r
+ for (i = 0; nbit != 0 && i / 8 < sz_buf * ss; buf[i / 8] |= 1 << (i % 8), i++, nbit--) ; /* Mark used clusters */\r
n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */\r
if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
sect += n; nsect -= n;\r
\r
/* Initialize the FAT */\r
sect = b_fat; nsect = sz_fat; /* Start of FAT and number of FAT sectors */\r
- j = nb = cl = 0;\r
+ j = nbit = clu = 0;\r
do {\r
- mem_set(buf, 0, szb_buf); i = 0; /* Clear work area and reset write index */\r
- if (cl == 0) { /* Set entry 0 and 1 */\r
- st_dword(buf + i, 0xFFFFFFF8); i += 4; cl++;\r
- st_dword(buf + i, 0xFFFFFFFF); i += 4; cl++;\r
+ memset(buf, 0, sz_buf * ss); i = 0; /* Clear work area and reset write offset */\r
+ if (clu == 0) { /* Initialize FAT [0] and FAT[1] */\r
+ st_dword(buf + i, 0xFFFFFFF8); i += 4; clu++;\r
+ st_dword(buf + i, 0xFFFFFFFF); i += 4; clu++;\r
}\r
do { /* Create chains of bitmap, up-case and root dir */\r
- while (nb != 0 && i < szb_buf) { /* Create a chain */\r
- st_dword(buf + i, (nb > 1) ? cl + 1 : 0xFFFFFFFF);\r
- i += 4; cl++; nb--;\r
+ while (nbit != 0 && i < sz_buf * ss) { /* Create a chain */\r
+ st_dword(buf + i, (nbit > 1) ? clu + 1 : 0xFFFFFFFF);\r
+ i += 4; clu++; nbit--;\r
}\r
- if (nb == 0 && j < 3) nb = tbl[j++]; /* Next chain */\r
- } while (nb != 0 && i < szb_buf);\r
+ if (nbit == 0 && j < 3) nbit = clen[j++]; /* Get next chain length */\r
+ } while (nbit != 0 && i < sz_buf * ss);\r
n = (nsect > sz_buf) ? sz_buf : nsect; /* Write the buffered data */\r
if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
sect += n; nsect -= n;\r
} while (nsect);\r
\r
/* Initialize the root directory */\r
- mem_set(buf, 0, szb_buf);\r
- buf[SZDIRE * 0 + 0] = 0x83; /* 83 entry (volume label) */\r
- buf[SZDIRE * 1 + 0] = 0x81; /* 81 entry (allocation bitmap) */\r
- st_dword(buf + SZDIRE * 1 + 20, 2); /* cluster */\r
- st_dword(buf + SZDIRE * 1 + 24, szb_bit); /* size */\r
- buf[SZDIRE * 2 + 0] = 0x82; /* 82 entry (up-case table) */\r
- st_dword(buf + SZDIRE * 2 + 4, sum); /* sum */\r
- st_dword(buf + SZDIRE * 2 + 20, 2 + tbl[0]); /* cluster */\r
- st_dword(buf + SZDIRE * 2 + 24, szb_case); /* size */\r
- sect = b_data + au * (tbl[0] + tbl[1]); nsect = au; /* Start of the root directory and number of sectors */\r
+ memset(buf, 0, sz_buf * ss);\r
+ buf[SZDIRE * 0 + 0] = ET_VLABEL; /* Volume label entry (no label) */\r
+ buf[SZDIRE * 1 + 0] = ET_BITMAP; /* Bitmap entry */\r
+ st_dword(buf + SZDIRE * 1 + 20, 2); /* cluster */\r
+ st_dword(buf + SZDIRE * 1 + 24, szb_bit); /* size */\r
+ buf[SZDIRE * 2 + 0] = ET_UPCASE; /* Up-case table entry */\r
+ st_dword(buf + SZDIRE * 2 + 4, sum); /* sum */\r
+ st_dword(buf + SZDIRE * 2 + 20, 2 + clen[0]); /* cluster */\r
+ st_dword(buf + SZDIRE * 2 + 24, szb_case); /* size */\r
+ sect = b_data + sz_au * (clen[0] + clen[1]); nsect = sz_au; /* Start of the root directory and number of sectors */\r
do { /* Fill root directory sectors */\r
n = (nsect > sz_buf) ? sz_buf : nsect;\r
if (disk_write(pdrv, buf, sect, n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
- mem_set(buf, 0, ss);\r
+ memset(buf, 0, ss); /* Rest of entries are filled with zero */\r
sect += n; nsect -= n;\r
} while (nsect);\r
\r
sect = b_vol;\r
for (n = 0; n < 2; n++) {\r
/* Main record (+0) */\r
- mem_set(buf, 0, ss);\r
- mem_cpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */\r
- st_dword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */\r
- st_dword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */\r
- st_dword(buf + BPB_FatOfsEx, b_fat - b_vol); /* FAT offset [sector] */\r
+ memset(buf, 0, ss);\r
+ memcpy(buf + BS_JmpBoot, "\xEB\x76\x90" "EXFAT ", 11); /* Boot jump code (x86), OEM name */\r
+ st_qword(buf + BPB_VolOfsEx, b_vol); /* Volume offset in the physical drive [sector] */\r
+ st_qword(buf + BPB_TotSecEx, sz_vol); /* Volume size [sector] */\r
+ st_dword(buf + BPB_FatOfsEx, (DWORD)(b_fat - b_vol)); /* FAT offset [sector] */\r
st_dword(buf + BPB_FatSzEx, sz_fat); /* FAT size [sector] */\r
- st_dword(buf + BPB_DataOfsEx, b_data - b_vol); /* Data offset [sector] */\r
+ st_dword(buf + BPB_DataOfsEx, (DWORD)(b_data - b_vol)); /* Data offset [sector] */\r
st_dword(buf + BPB_NumClusEx, n_clst); /* Number of clusters */\r
- st_dword(buf + BPB_RootClusEx, 2 + tbl[0] + tbl[1]); /* Root dir cluster # */\r
- st_dword(buf + BPB_VolIDEx, GET_FATTIME()); /* VSN */\r
+ st_dword(buf + BPB_RootClusEx, 2 + clen[0] + clen[1]); /* Root dir cluster # */\r
+ st_dword(buf + BPB_VolIDEx, vsn); /* VSN */\r
st_word(buf + BPB_FSVerEx, 0x100); /* Filesystem version (1.00) */\r
for (buf[BPB_BytsPerSecEx] = 0, i = ss; i >>= 1; buf[BPB_BytsPerSecEx]++) ; /* Log2 of sector size [byte] */\r
- for (buf[BPB_SecPerClusEx] = 0, i = au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */\r
+ for (buf[BPB_SecPerClusEx] = 0, i = sz_au; i >>= 1; buf[BPB_SecPerClusEx]++) ; /* Log2 of cluster size [sector] */\r
buf[BPB_NumFATsEx] = 1; /* Number of FATs */\r
buf[BPB_DrvNumEx] = 0x80; /* Drive number (for int13) */\r
st_word(buf + BS_BootCodeEx, 0xFEEB); /* Boot code (x86) */\r
}\r
if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
/* Extended bootstrap record (+1..+8) */\r
- mem_set(buf, 0, ss);\r
+ memset(buf, 0, ss);\r
st_word(buf + ss - 2, 0xAA55); /* Signature (placed at end of sector) */\r
for (j = 1; j < 9; j++) {\r
for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */\r
if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
}\r
/* OEM/Reserved record (+9..+10) */\r
- mem_set(buf, 0, ss);\r
+ memset(buf, 0, ss);\r
for ( ; j < 11; j++) {\r
for (i = 0; i < ss; sum = xsum32(buf[i++], sum)) ; /* VBR checksum */\r
if (disk_write(pdrv, buf, sect++, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
#endif /* FF_FS_EXFAT */\r
{ /* Create an FAT/FAT32 volume */\r
do {\r
- pau = au;\r
+ pau = sz_au;\r
/* Pre-determine number of clusters and FAT sub-type */\r
- if (fmt == FS_FAT32) { /* FAT32 volume */\r
- if (pau == 0) { /* au auto-selection */\r
- n = sz_vol / 0x20000; /* Volume size in unit of 128KS */\r
+ if (fsty == FS_FAT32) { /* FAT32 volume */\r
+ if (pau == 0) { /* AU auto-selection */\r
+ n = (DWORD)sz_vol / 0x20000; /* Volume size in unit of 128KS */\r
for (i = 0, pau = 1; cst32[i] && cst32[i] <= n; i++, pau <<= 1) ; /* Get from table */\r
}\r
- n_clst = sz_vol / pau; /* Number of clusters */\r
+ n_clst = (DWORD)sz_vol / pau; /* Number of clusters */\r
sz_fat = (n_clst * 4 + 8 + ss - 1) / ss; /* FAT size [sector] */\r
sz_rsv = 32; /* Number of reserved sectors */\r
sz_dir = 0; /* No static directory */\r
if (n_clst <= MAX_FAT16 || n_clst > MAX_FAT32) LEAVE_MKFS(FR_MKFS_ABORTED);\r
} else { /* FAT volume */\r
if (pau == 0) { /* au auto-selection */\r
- n = sz_vol / 0x1000; /* Volume size in unit of 4KS */\r
+ n = (DWORD)sz_vol / 0x1000; /* Volume size in unit of 4KS */\r
for (i = 0, pau = 1; cst[i] && cst[i] <= n; i++, pau <<= 1) ; /* Get from table */\r
}\r
- n_clst = sz_vol / pau;\r
+ n_clst = (DWORD)sz_vol / pau;\r
if (n_clst > MAX_FAT12) {\r
n = n_clst * 2 + 4; /* FAT size [byte] */\r
} else {\r
- fmt = FS_FAT12;\r
+ fsty = FS_FAT12;\r
n = (n_clst * 3 + 1) / 2 + 3; /* FAT size [byte] */\r
}\r
sz_fat = (n + ss - 1) / ss; /* FAT size [sector] */\r
sz_rsv = 1; /* Number of reserved sectors */\r
- sz_dir = (DWORD)n_rootdir * SZDIRE / ss; /* Rootdir size [sector] */\r
+ sz_dir = (DWORD)n_root * SZDIRE / ss; /* Root dir size [sector] */\r
}\r
b_fat = b_vol + sz_rsv; /* FAT base */\r
- b_data = b_fat + sz_fat * n_fats + sz_dir; /* Data base */\r
+ b_data = b_fat + sz_fat * n_fat + sz_dir; /* Data base */\r
\r
- /* Align data base to erase block boundary (for flash memory media) */\r
- n = ((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data; /* Next nearest erase block from current data base */\r
- if (fmt == FS_FAT32) { /* FAT32: Move FAT base */\r
+ /* Align data area to erase block boundary (for flash memory media) */\r
+ n = (DWORD)(((b_data + sz_blk - 1) & ~(sz_blk - 1)) - b_data); /* Sectors to next nearest from current data base */\r
+ if (fsty == FS_FAT32) { /* FAT32: Move FAT */\r
sz_rsv += n; b_fat += n;\r
- } else { /* FAT: Expand FAT size */\r
- sz_fat += n / n_fats;\r
+ } else { /* FAT: Expand FAT */\r
+ if (n % n_fat) { /* Adjust fractional error if needed */\r
+ n--; sz_rsv++; b_fat++;\r
+ }\r
+ sz_fat += n / n_fat;\r
}\r
\r
/* Determine number of clusters and final check of validity of the FAT sub-type */\r
- if (sz_vol < b_data + pau * 16 - b_vol) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume */\r
- n_clst = (sz_vol - sz_rsv - sz_fat * n_fats - sz_dir) / pau;\r
- if (fmt == FS_FAT32) {\r
- if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32 */\r
- if (au == 0 && (au = pau / 2) != 0) continue; /* Adjust cluster size and retry */\r
+ if (sz_vol < b_data + pau * 16 - b_vol) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too small volume? */\r
+ n_clst = ((DWORD)sz_vol - sz_rsv - sz_fat * n_fat - sz_dir) / pau;\r
+ if (fsty == FS_FAT32) {\r
+ if (n_clst <= MAX_FAT16) { /* Too few clusters for FAT32? */\r
+ if (sz_au == 0 && (sz_au = pau / 2) != 0) continue; /* Adjust cluster size and retry */\r
LEAVE_MKFS(FR_MKFS_ABORTED);\r
}\r
}\r
- if (fmt == FS_FAT16) {\r
+ if (fsty == FS_FAT16) {\r
if (n_clst > MAX_FAT16) { /* Too many clusters for FAT16 */\r
- if (au == 0 && (pau * 2) <= 64) {\r
- au = pau * 2; continue; /* Adjust cluster size and retry */\r
+ if (sz_au == 0 && (pau * 2) <= 64) {\r
+ sz_au = pau * 2; continue; /* Adjust cluster size and retry */\r
}\r
- if ((opt & FM_FAT32)) {\r
- fmt = FS_FAT32; continue; /* Switch type to FAT32 and retry */\r
+ if ((fsopt & FM_FAT32)) {\r
+ fsty = FS_FAT32; continue; /* Switch type to FAT32 and retry */\r
}\r
- if (au == 0 && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */\r
+ if (sz_au == 0 && (sz_au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */\r
LEAVE_MKFS(FR_MKFS_ABORTED);\r
}\r
if (n_clst <= MAX_FAT12) { /* Too few clusters for FAT16 */\r
- if (au == 0 && (au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */\r
+ if (sz_au == 0 && (sz_au = pau * 2) <= 128) continue; /* Adjust cluster size and retry */\r
LEAVE_MKFS(FR_MKFS_ABORTED);\r
}\r
}\r
- if (fmt == FS_FAT12 && n_clst > MAX_FAT12) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters for FAT12 */\r
+ if (fsty == FS_FAT12 && n_clst > MAX_FAT12) LEAVE_MKFS(FR_MKFS_ABORTED); /* Too many clusters for FAT12 */\r
\r
/* Ok, it is the valid cluster configuration */\r
break;\r
} while (1);\r
\r
#if FF_USE_TRIM\r
- tbl[0] = b_vol; tbl[1] = b_vol + sz_vol - 1; /* Inform the device the volume area can be erased */\r
- disk_ioctl(pdrv, CTRL_TRIM, tbl);\r
+ lba[0] = b_vol; lba[1] = b_vol + sz_vol - 1; /* Inform storage device that the volume area may be erased */\r
+ disk_ioctl(pdrv, CTRL_TRIM, lba);\r
#endif\r
/* Create FAT VBR */\r
- mem_set(buf, 0, ss);\r
- mem_cpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code (x86), OEM name */\r
+ memset(buf, 0, ss);\r
+ memcpy(buf + BS_JmpBoot, "\xEB\xFE\x90" "MSDOS5.0", 11); /* Boot jump code (x86), OEM name */\r
st_word(buf + BPB_BytsPerSec, ss); /* Sector size [byte] */\r
buf[BPB_SecPerClus] = (BYTE)pau; /* Cluster size [sector] */\r
st_word(buf + BPB_RsvdSecCnt, (WORD)sz_rsv); /* Size of reserved area */\r
- buf[BPB_NumFATs] = (BYTE)n_fats; /* Number of FATs */\r
- st_word(buf + BPB_RootEntCnt, (WORD)((fmt == FS_FAT32) ? 0 : n_rootdir)); /* Number of root directory entries */\r
+ buf[BPB_NumFATs] = (BYTE)n_fat; /* Number of FATs */\r
+ st_word(buf + BPB_RootEntCnt, (WORD)((fsty == FS_FAT32) ? 0 : n_root)); /* Number of root directory entries */\r
if (sz_vol < 0x10000) {\r
st_word(buf + BPB_TotSec16, (WORD)sz_vol); /* Volume size in 16-bit LBA */\r
} else {\r
- st_dword(buf + BPB_TotSec32, sz_vol); /* Volume size in 32-bit LBA */\r
+ st_dword(buf + BPB_TotSec32, (DWORD)sz_vol); /* Volume size in 32-bit LBA */\r
}\r
buf[BPB_Media] = 0xF8; /* Media descriptor byte */\r
st_word(buf + BPB_SecPerTrk, 63); /* Number of sectors per track (for int13) */\r
st_word(buf + BPB_NumHeads, 255); /* Number of heads (for int13) */\r
- st_dword(buf + BPB_HiddSec, b_vol); /* Volume offset in the physical drive [sector] */\r
- if (fmt == FS_FAT32) {\r
- st_dword(buf + BS_VolID32, GET_FATTIME()); /* VSN */\r
+ st_dword(buf + BPB_HiddSec, (DWORD)b_vol); /* Volume offset in the physical drive [sector] */\r
+ if (fsty == FS_FAT32) {\r
+ st_dword(buf + BS_VolID32, vsn); /* VSN */\r
st_dword(buf + BPB_FATSz32, sz_fat); /* FAT size [sector] */\r
st_dword(buf + BPB_RootClus32, 2); /* Root directory cluster # (2) */\r
st_word(buf + BPB_FSInfo32, 1); /* Offset of FSINFO sector (VBR + 1) */\r
st_word(buf + BPB_BkBootSec32, 6); /* Offset of backup VBR (VBR + 6) */\r
buf[BS_DrvNum32] = 0x80; /* Drive number (for int13) */\r
buf[BS_BootSig32] = 0x29; /* Extended boot signature */\r
- mem_cpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */\r
+ memcpy(buf + BS_VolLab32, "NO NAME " "FAT32 ", 19); /* Volume label, FAT signature */\r
} else {\r
- st_dword(buf + BS_VolID, GET_FATTIME()); /* VSN */\r
+ st_dword(buf + BS_VolID, vsn); /* VSN */\r
st_word(buf + BPB_FATSz16, (WORD)sz_fat); /* FAT size [sector] */\r
buf[BS_DrvNum] = 0x80; /* Drive number (for int13) */\r
buf[BS_BootSig] = 0x29; /* Extended boot signature */\r
- mem_cpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */\r
+ memcpy(buf + BS_VolLab, "NO NAME " "FAT ", 19); /* Volume label, FAT signature */\r
}\r
st_word(buf + BS_55AA, 0xAA55); /* Signature (offset is fixed here regardless of sector size) */\r
if (disk_write(pdrv, buf, b_vol, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it to the VBR sector */\r
\r
/* Create FSINFO record if needed */\r
- if (fmt == FS_FAT32) {\r
+ if (fsty == FS_FAT32) {\r
disk_write(pdrv, buf, b_vol + 6, 1); /* Write backup VBR (VBR + 6) */\r
- mem_set(buf, 0, ss);\r
+ memset(buf, 0, ss);\r
st_dword(buf + FSI_LeadSig, 0x41615252);\r
st_dword(buf + FSI_StrucSig, 0x61417272);\r
st_dword(buf + FSI_Free_Count, n_clst - 1); /* Number of free clusters */\r
}\r
\r
/* Initialize FAT area */\r
- mem_set(buf, 0, (UINT)szb_buf);\r
+ memset(buf, 0, sz_buf * ss);\r
sect = b_fat; /* FAT start sector */\r
- for (i = 0; i < n_fats; i++) { /* Initialize FATs each */\r
- if (fmt == FS_FAT32) {\r
- st_dword(buf + 0, 0xFFFFFFF8); /* Entry 0 */\r
- st_dword(buf + 4, 0xFFFFFFFF); /* Entry 1 */\r
- st_dword(buf + 8, 0x0FFFFFFF); /* Entry 2 (root directory) */\r
+ for (i = 0; i < n_fat; i++) { /* Initialize FATs each */\r
+ if (fsty == FS_FAT32) {\r
+ st_dword(buf + 0, 0xFFFFFFF8); /* FAT[0] */\r
+ st_dword(buf + 4, 0xFFFFFFFF); /* FAT[1] */\r
+ st_dword(buf + 8, 0x0FFFFFFF); /* FAT[2] (root directory) */\r
} else {\r
- st_dword(buf + 0, (fmt == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* Entry 0 and 1 */\r
+ st_dword(buf + 0, (fsty == FS_FAT12) ? 0xFFFFF8 : 0xFFFFFFF8); /* FAT[0] and FAT[1] */\r
}\r
nsect = sz_fat; /* Number of FAT sectors */\r
do { /* Fill FAT sectors */\r
n = (nsect > sz_buf) ? sz_buf : nsect;\r
if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
- mem_set(buf, 0, ss);\r
+ memset(buf, 0, ss); /* Rest of FAT all are cleared */\r
sect += n; nsect -= n;\r
} while (nsect);\r
}\r
\r
/* Initialize root directory (fill with zero) */\r
- nsect = (fmt == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */\r
+ nsect = (fsty == FS_FAT32) ? pau : sz_dir; /* Number of root directory sectors */\r
do {\r
n = (nsect > sz_buf) ? sz_buf : nsect;\r
if (disk_write(pdrv, buf, sect, (UINT)n) != RES_OK) LEAVE_MKFS(FR_DISK_ERR);\r
} while (nsect);\r
}\r
\r
- /* Determine system ID in the partition table */\r
- if (FF_FS_EXFAT && fmt == FS_EXFAT) {\r
- sys = 0x07; /* HPFS/NTFS/exFAT */\r
+ /* A FAT volume has been created here */\r
+\r
+ /* Determine system ID in the MBR partition table */\r
+ if (FF_FS_EXFAT && fsty == FS_EXFAT) {\r
+ sys = 0x07; /* exFAT */\r
+ } else if (fsty == FS_FAT32) {\r
+ sys = 0x0C; /* FAT32X */\r
+ } else if (sz_vol >= 0x10000) {\r
+ sys = 0x06; /* FAT12/16 (large) */\r
+ } else if (fsty == FS_FAT16) {\r
+ sys = 0x04; /* FAT16 */\r
} else {\r
- if (fmt == FS_FAT32) {\r
- sys = 0x0C; /* FAT32X */\r
- } else {\r
- if (sz_vol >= 0x10000) {\r
- sys = 0x06; /* FAT12/16 (large) */\r
- } else {\r
- sys = (fmt == FS_FAT16) ? 0x04 : 0x01; /* FAT16 : FAT12 */\r
- }\r
- }\r
+ sys = 0x01; /* FAT12 */\r
}\r
\r
/* Update partition information */\r
- if (FF_MULTI_PARTITION && part != 0) { /* Created in the existing partition */\r
- /* Update system ID in the partition table */\r
- if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Read the MBR */\r
- buf[MBR_Table + (part - 1) * SZ_PTE + PTE_System] = sys; /* Set system ID */\r
- if (disk_write(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it back to the MBR */\r
- } else { /* Created as a new single partition */\r
- if (!(opt & FM_SFD)) { /* Create partition table if in FDISK format */\r
- mem_set(buf, 0, ss);\r
- st_word(buf + BS_55AA, 0xAA55); /* MBR signature */\r
- pte = buf + MBR_Table; /* Create partition table for single partition in the drive */\r
- pte[PTE_Boot] = 0; /* Boot indicator */\r
- pte[PTE_StHead] = 1; /* Start head */\r
- pte[PTE_StSec] = 1; /* Start sector */\r
- pte[PTE_StCyl] = 0; /* Start cylinder */\r
- pte[PTE_System] = sys; /* System type */\r
- n = (b_vol + sz_vol) / (63 * 255); /* (End CHS may be invalid) */\r
- pte[PTE_EdHead] = 254; /* End head */\r
- pte[PTE_EdSec] = (BYTE)(((n >> 2) & 0xC0) | 63); /* End sector */\r
- pte[PTE_EdCyl] = (BYTE)n; /* End cylinder */\r
- st_dword(pte + PTE_StLba, b_vol); /* Start offset in LBA */\r
- st_dword(pte + PTE_SizLba, sz_vol); /* Size in sectors */\r
- if (disk_write(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it to the MBR */\r
+ if (FF_MULTI_PARTITION && ipart != 0) { /* Volume is in the existing partition */\r
+ if (!FF_LBA64 || !(fsopt & 0x80)) { /* Is the partition in MBR? */\r
+ /* Update system ID in the partition table */\r
+ if (disk_read(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Read the MBR */\r
+ buf[MBR_Table + (ipart - 1) * SZ_PTE + PTE_System] = sys; /* Set system ID */\r
+ if (disk_write(pdrv, buf, 0, 1) != RES_OK) LEAVE_MKFS(FR_DISK_ERR); /* Write it back to the MBR */\r
+ }\r
+ } else { /* Volume as a new single partition */\r
+ if (!(fsopt & FM_SFD)) { /* Create partition table if not in SFD format */\r
+ lba[0] = sz_vol; lba[1] = 0;\r
+ res = create_partition(pdrv, lba, sys, buf);\r
+ if (res != FR_OK) LEAVE_MKFS(res);\r
}\r
}\r
\r
\r
\r
\r
+\r
#if FF_MULTI_PARTITION\r
/*-----------------------------------------------------------------------*/\r
/* Create Partition Table on the Physical Drive */\r
\r
FRESULT f_fdisk (\r
BYTE pdrv, /* Physical drive number */\r
- const DWORD* szt, /* Pointer to the size table for each partitions */\r
+ const LBA_t ptbl[], /* Pointer to the size table for each partitions */\r
void* work /* Pointer to the working buffer (null: use heap memory) */\r
)\r
{\r
- UINT i, n, sz_cyl, tot_cyl, b_cyl, e_cyl, p_cyl;\r
- BYTE s_hd, e_hd, *p, *buf = (BYTE*)work;\r
+ BYTE *buf = (BYTE*)work;\r
DSTATUS stat;\r
- DWORD sz_disk, sz_part, s_part;\r
FRESULT res;\r
\r
\r
+ /* Initialize the physical drive */\r
stat = disk_initialize(pdrv);\r
if (stat & STA_NOINIT) return FR_NOT_READY;\r
if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;\r
- if (disk_ioctl(pdrv, GET_SECTOR_COUNT, &sz_disk)) return FR_DISK_ERR;\r
\r
- buf = (BYTE*)work;\r
#if FF_USE_LFN == 3\r
if (!buf) buf = ff_memalloc(FF_MAX_SS); /* Use heap memory for working buffer */\r
#endif\r
if (!buf) return FR_NOT_ENOUGH_CORE;\r
\r
- /* Determine the CHS without any consideration of the drive geometry */\r
- for (n = 16; n < 256 && sz_disk / n / 63 > 1024; n *= 2) ;\r
- if (n == 256) n--;\r
- e_hd = (BYTE)(n - 1);\r
- sz_cyl = 63 * n;\r
- tot_cyl = sz_disk / sz_cyl;\r
-\r
- /* Create partition table */\r
- mem_set(buf, 0, FF_MAX_SS);\r
- p = buf + MBR_Table; b_cyl = 0;\r
- for (i = 0; i < 4; i++, p += SZ_PTE) {\r
- p_cyl = (szt[i] <= 100U) ? (DWORD)tot_cyl * szt[i] / 100 : szt[i] / sz_cyl; /* Number of cylinders */\r
- if (p_cyl == 0) continue;\r
- s_part = (DWORD)sz_cyl * b_cyl;\r
- sz_part = (DWORD)sz_cyl * p_cyl;\r
- if (i == 0) { /* Exclude first track of cylinder 0 */\r
- s_hd = 1;\r
- s_part += 63; sz_part -= 63;\r
- } else {\r
- s_hd = 0;\r
- }\r
- e_cyl = b_cyl + p_cyl - 1; /* End cylinder */\r
- if (e_cyl >= tot_cyl) LEAVE_MKFS(FR_INVALID_PARAMETER);\r
-\r
- /* Set partition table */\r
- p[1] = s_hd; /* Start head */\r
- p[2] = (BYTE)(((b_cyl >> 2) & 0xC0) | 1); /* Start sector */\r
- p[3] = (BYTE)b_cyl; /* Start cylinder */\r
- p[4] = 0x07; /* System type (temporary setting) */\r
- p[5] = e_hd; /* End head */\r
- p[6] = (BYTE)(((e_cyl >> 2) & 0xC0) | 63); /* End sector */\r
- p[7] = (BYTE)e_cyl; /* End cylinder */\r
- st_dword(p + 8, s_part); /* Start sector in LBA */\r
- st_dword(p + 12, sz_part); /* Number of sectors */\r
+ res = create_partition(pdrv, ptbl, 0x07, buf); /* Create partitions (system ID is temporary setting and determined by f_mkfs) */\r
\r
- /* Next partition */\r
- b_cyl += p_cyl;\r
- }\r
- st_word(p, 0xAA55); /* MBR signature (always at offset 510) */\r
-\r
- /* Write it to the MBR */\r
- res = (disk_write(pdrv, buf, 0, 1) == RES_OK && disk_ioctl(pdrv, CTRL_SYNC, 0) == RES_OK) ? FR_OK : FR_DISK_ERR;\r
LEAVE_MKFS(res);\r
}\r
\r
#endif /* FF_MULTI_PARTITION */\r
-#endif /* FF_USE_MKFS && !FF_FS_READONLY */\r
+#endif /* !FF_FS_READONLY && FF_USE_MKFS */\r
\r
\r
\r
/*-----------------------------------------------------------------------*/\r
\r
TCHAR* f_gets (\r
- TCHAR* buff, /* Pointer to the string buffer to read */\r
+ TCHAR* buff, /* Pointer to the buffer to store read string */\r
int len, /* Size of string buffer (items) */\r
FIL* fp /* Pointer to the file object */\r
)\r
if (FF_LFN_UNICODE == 2) len -= (FF_STRF_ENCODE == 0) ? 3 : 4;\r
if (FF_LFN_UNICODE == 3) len -= 1;\r
while (nc < len) {\r
-#if FF_STRF_ENCODE == 0 /* Read a character in ANSI/OEM */\r
- f_read(fp, s, 1, &rc);\r
- if (rc != 1) break;\r
+#if FF_STRF_ENCODE == 0 /* Read a character in ANSI/OEM */\r
+ f_read(fp, s, 1, &rc); /* Get a code unit */\r
+ if (rc != 1) break; /* EOF? */\r
wc = s[0];\r
- if (dbc_1st((BYTE)wc)) {\r
- f_read(fp, s, 1, &rc);\r
- if (rc != 1 || !dbc_2nd(s[0])) continue;\r
+ if (dbc_1st((BYTE)wc)) { /* DBC 1st byte? */\r
+ f_read(fp, s, 1, &rc); /* Get 2nd byte */\r
+ if (rc != 1 || !dbc_2nd(s[0])) continue; /* Wrong code? */\r
wc = wc << 8 | s[0];\r
}\r
- dc = ff_oem2uni(wc, CODEPAGE);\r
- if (dc == 0) continue;\r
+ dc = ff_oem2uni(wc, CODEPAGE); /* Convert ANSI/OEM into Unicode */\r
+ if (dc == 0) continue; /* Conversion error? */\r
#elif FF_STRF_ENCODE == 1 || FF_STRF_ENCODE == 2 /* Read a character in UTF-16LE/BE */\r
- f_read(fp, s, 2, &rc);\r
- if (rc != 2) break;\r
+ f_read(fp, s, 2, &rc); /* Get a code unit */\r
+ if (rc != 2) break; /* EOF? */\r
dc = (FF_STRF_ENCODE == 1) ? ld_word(s) : s[0] << 8 | s[1];\r
- if (IsSurrogateL(dc)) continue;\r
- if (IsSurrogateH(dc)) {\r
- f_read(fp, s, 2, &rc);\r
- if (rc != 2) break;\r
+ if (IsSurrogateL(dc)) continue; /* Broken surrogate pair? */\r
+ if (IsSurrogateH(dc)) { /* High surrogate? */\r
+ f_read(fp, s, 2, &rc); /* Get low surrogate */\r
+ if (rc != 2) break; /* EOF? */\r
wc = (FF_STRF_ENCODE == 1) ? ld_word(s) : s[0] << 8 | s[1];\r
- if (!IsSurrogateL(wc)) continue;\r
- dc = ((dc & 0x3FF) + 0x40) << 10 | (wc & 0x3FF);\r
+ if (!IsSurrogateL(wc)) continue; /* Broken surrogate pair? */\r
+ dc = ((dc & 0x3FF) + 0x40) << 10 | (wc & 0x3FF); /* Merge surrogate pair */\r
}\r
#else /* Read a character in UTF-8 */\r
- f_read(fp, s, 1, &rc);\r
- if (rc != 1) break;\r
+ f_read(fp, s, 1, &rc); /* Get a code unit */\r
+ if (rc != 1) break; /* EOF? */\r
dc = s[0];\r
- if (dc >= 0x80) { /* Multi-byte character? */\r
+ if (dc >= 0x80) { /* Multi-byte sequence? */\r
ct = 0;\r
- if ((dc & 0xE0) == 0xC0) { dc &= 0x1F; ct = 1; } /* 2-byte? */\r
- if ((dc & 0xF0) == 0xE0) { dc &= 0x0F; ct = 2; } /* 3-byte? */\r
- if ((dc & 0xF8) == 0xF0) { dc &= 0x07; ct = 3; } /* 4-byte? */\r
+ if ((dc & 0xE0) == 0xC0) { /* 2-byte sequence? */\r
+ dc &= 0x1F; ct = 1;\r
+ }\r
+ if ((dc & 0xF0) == 0xE0) { /* 3-byte sequence? */\r
+ dc &= 0x0F; ct = 2;\r
+ }\r
+ if ((dc & 0xF8) == 0xF0) { /* 4-byte sequence? */\r
+ dc &= 0x07; ct = 3;\r
+ }\r
if (ct == 0) continue;\r
- f_read(fp, s, ct, &rc); /* Get trailing bytes */\r
+ f_read(fp, s, ct, &rc); /* Get trailing bytes */\r
if (rc != ct) break;\r
rc = 0;\r
- do { /* Merge trailing bytes */\r
+ do { /* Merge the byte sequence */\r
if ((s[rc] & 0xC0) != 0x80) break;\r
dc = dc << 6 | (s[rc] & 0x3F);\r
} while (++rc < ct);\r
if (rc != ct || dc < 0x80 || IsSurrogate(dc) || dc >= 0x110000) continue; /* Wrong encoding? */\r
}\r
#endif\r
+ /* A code point is avaialble in dc to be output */\r
+\r
if (FF_USE_STRFUNC == 2 && dc == '\r') continue; /* Strip \r off if needed */\r
#if FF_LFN_UNICODE == 1 || FF_LFN_UNICODE == 3 /* Output it in UTF-16/32 encoding */\r
if (FF_LFN_UNICODE == 1 && dc >= 0x10000) { /* Out of BMP at UTF-16? */\r
*p++ = (TCHAR)dc; nc++;\r
if (dc == '\n') break; /* End of line? */\r
#elif FF_LFN_UNICODE == 2 /* Output it in UTF-8 encoding */\r
- if (dc < 0x80) { /* 1-byte */\r
+ if (dc < 0x80) { /* Single byte? */\r
*p++ = (TCHAR)dc;\r
nc++;\r
if (dc == '\n') break; /* End of line? */\r
- } else {\r
- if (dc < 0x800) { /* 2-byte */\r
- *p++ = (TCHAR)(0xC0 | (dc >> 6 & 0x1F));\r
- *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));\r
- nc += 2;\r
- } else {\r
- if (dc < 0x10000) { /* 3-byte */\r
- *p++ = (TCHAR)(0xE0 | (dc >> 12 & 0x0F));\r
- *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F));\r
- *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));\r
- nc += 3;\r
- } else { /* 4-byte */\r
- *p++ = (TCHAR)(0xF0 | (dc >> 18 & 0x07));\r
- *p++ = (TCHAR)(0x80 | (dc >> 12 & 0x3F));\r
- *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F));\r
- *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));\r
- nc += 4;\r
- }\r
- }\r
- }\r
-#endif\r
- }\r
-\r
-#else /* Byte-by-byte without any conversion (ANSI/OEM API) */\r
+ } else if (dc < 0x800) { /* 2-byte sequence? */\r
+ *p++ = (TCHAR)(0xC0 | (dc >> 6 & 0x1F));\r
+ *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));\r
+ nc += 2;\r
+ } else if (dc < 0x10000) { /* 3-byte sequence? */\r
+ *p++ = (TCHAR)(0xE0 | (dc >> 12 & 0x0F));\r
+ *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F));\r
+ *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));\r
+ nc += 3;\r
+ } else { /* 4-byte sequence */\r
+ *p++ = (TCHAR)(0xF0 | (dc >> 18 & 0x07));\r
+ *p++ = (TCHAR)(0x80 | (dc >> 12 & 0x3F));\r
+ *p++ = (TCHAR)(0x80 | (dc >> 6 & 0x3F));\r
+ *p++ = (TCHAR)(0x80 | (dc >> 0 & 0x3F));\r
+ nc += 4;\r
+ }\r
+#endif\r
+ }\r
+\r
+#else /* Byte-by-byte read without any conversion (ANSI/OEM API) */\r
len -= 1; /* Make a room for the terminator */\r
while (nc < len) {\r
- f_read(fp, s, 1, &rc);\r
- if (rc != 1) break;\r
+ f_read(fp, s, 1, &rc); /* Get a byte */\r
+ if (rc != 1) break; /* EOF? */\r
dc = s[0];\r
if (FF_USE_STRFUNC == 2 && dc == '\r') continue;\r
*p++ = (TCHAR)dc; nc++;\r
\r
#if !FF_FS_READONLY\r
#include <stdarg.h>\r
+#define SZ_PUTC_BUF 64\r
+#define SZ_NUM_BUF 32\r
+\r
/*-----------------------------------------------------------------------*/\r
-/* Put a Character to the File */\r
+/* Put a Character to the File (with sub-functions) */\r
/*-----------------------------------------------------------------------*/\r
\r
-typedef struct { /* Putchar output buffer and work area */\r
+/* Output buffer and work area */\r
+\r
+typedef struct {\r
FIL *fp; /* Ptr to the writing file */\r
int idx, nchr; /* Write index of buf[] (-1:error), number of encoding units written */\r
#if FF_USE_LFN && FF_LFN_UNICODE == 1\r
BYTE bs[4];\r
UINT wi, ct;\r
#endif\r
- BYTE buf[64]; /* Write buffer */\r
+ BYTE buf[SZ_PUTC_BUF]; /* Write buffer */\r
} putbuff;\r
\r
\r
-static\r
-void putc_bfd ( /* Buffered write with code conversion */\r
- putbuff* pb,\r
- TCHAR c\r
-)\r
+/* Buffered file write with code conversion */\r
+\r
+static void putc_bfd (putbuff* pb, TCHAR c)\r
{\r
UINT n;\r
int i, nc;\r
WCHAR hs, wc;\r
#if FF_LFN_UNICODE == 2\r
DWORD dc;\r
- TCHAR *tp;\r
+ const TCHAR* tp;\r
#endif\r
#endif\r
\r
}\r
\r
i = pb->idx; /* Write index of pb->buf[] */\r
- if (i < 0) return;\r
+ if (i < 0) return; /* In write error? */\r
nc = pb->nchr; /* Write unit counter */\r
\r
#if FF_USE_LFN && FF_LFN_UNICODE\r
#if FF_LFN_UNICODE == 1 /* UTF-16 input */\r
- if (IsSurrogateH(c)) {\r
- pb->hs = c; return;\r
+ if (IsSurrogateH(c)) { /* Is this a high-surrogate? */\r
+ pb->hs = c; return; /* Save it for next */\r
}\r
hs = pb->hs; pb->hs = 0;\r
- if (hs != 0) {\r
- if (!IsSurrogateL(c)) hs = 0;\r
+ if (hs != 0) { /* Is there a leading high-surrogate? */\r
+ if (!IsSurrogateL(c)) hs = 0; /* Discard high-surrogate if not a surrogate pair */\r
} else {\r
- if (IsSurrogateL(c)) return;\r
+ if (IsSurrogateL(c)) return; /* Discard stray low-surrogate */\r
}\r
wc = c;\r
#elif FF_LFN_UNICODE == 2 /* UTF-8 input */\r
for (;;) {\r
if (pb->ct == 0) { /* Out of multi-byte sequence? */\r
pb->bs[pb->wi = 0] = (BYTE)c; /* Save 1st byte */\r
- if ((BYTE)c < 0x80) break; /* 1-byte? */\r
- if (((BYTE)c & 0xE0) == 0xC0) pb->ct = 1; /* 2-byte? */\r
- if (((BYTE)c & 0xF0) == 0xE0) pb->ct = 2; /* 3-byte? */\r
- if (((BYTE)c & 0xF1) == 0xF0) pb->ct = 3; /* 4-byte? */\r
- return;\r
+ if ((BYTE)c < 0x80) break; /* Single byte code? */\r
+ if (((BYTE)c & 0xE0) == 0xC0) pb->ct = 1; /* 2-byte sequence? */\r
+ if (((BYTE)c & 0xF0) == 0xE0) pb->ct = 2; /* 3-byte sequence? */\r
+ if (((BYTE)c & 0xF8) == 0xF0) pb->ct = 3; /* 4-byte sequence? */\r
+ return; /* Wrong leading byte (discard it) */\r
} else { /* In the multi-byte sequence */\r
if (((BYTE)c & 0xC0) != 0x80) { /* Broken sequence? */\r
- pb->ct = 0; continue;\r
+ pb->ct = 0; continue; /* Discard the sequense */\r
}\r
pb->bs[++pb->wi] = (BYTE)c; /* Save the trailing byte */\r
- if (--pb->ct == 0) break; /* End of multi-byte sequence? */\r
+ if (--pb->ct == 0) break; /* End of the sequence? */\r
return;\r
}\r
}\r
- tp = (TCHAR*)pb->bs;\r
- dc = tchar2uni(&tp); /* UTF-8 ==> UTF-16 */\r
- if (dc == 0xFFFFFFFF) return;\r
- wc = (WCHAR)dc;\r
+ tp = (const TCHAR*)pb->bs;\r
+ dc = tchar2uni(&tp); /* UTF-8 ==> UTF-16 */\r
+ if (dc == 0xFFFFFFFF) return; /* Wrong code? */\r
hs = (WCHAR)(dc >> 16);\r
+ wc = (WCHAR)dc;\r
#elif FF_LFN_UNICODE == 3 /* UTF-32 input */\r
- if (IsSurrogate(c) || c >= 0x110000) return;\r
- if (c >= 0x10000) {\r
+ if (IsSurrogate(c) || c >= 0x110000) return; /* Discard invalid code */\r
+ if (c >= 0x10000) { /* Out of BMP? */\r
hs = (WCHAR)(0xD800 | ((c >> 10) - 0x40)); /* Make high surrogate */\r
wc = 0xDC00 | (c & 0x3FF); /* Make low surrogate */\r
} else {\r
wc = (WCHAR)c;\r
}\r
#endif\r
+ /* A code point in UTF-16 is available in hs and wc */\r
\r
-#if FF_STRF_ENCODE == 1 /* Write a character in UTF-16LE */\r
- if (hs != 0) {\r
+#if FF_STRF_ENCODE == 1 /* Write a code point in UTF-16LE */\r
+ if (hs != 0) { /* Surrogate pair? */\r
st_word(&pb->buf[i], hs);\r
i += 2;\r
nc++;\r
}\r
st_word(&pb->buf[i], wc);\r
i += 2;\r
-#elif FF_STRF_ENCODE == 2 /* Write a character in UTF-16BE */\r
- if (hs != 0) {\r
+#elif FF_STRF_ENCODE == 2 /* Write a code point in UTF-16BE */\r
+ if (hs != 0) { /* Surrogate pair? */\r
pb->buf[i++] = (BYTE)(hs >> 8);\r
pb->buf[i++] = (BYTE)hs;\r
nc++;\r
}\r
pb->buf[i++] = (BYTE)(wc >> 8);\r
pb->buf[i++] = (BYTE)wc;\r
-#elif FF_STRF_ENCODE == 3 /* Write it in UTF-8 */\r
- if (hs != 0) { /* 4-byte */\r
+#elif FF_STRF_ENCODE == 3 /* Write a code point in UTF-8 */\r
+ if (hs != 0) { /* 4-byte sequence? */\r
nc += 3;\r
hs = (hs & 0x3FF) + 0x40;\r
pb->buf[i++] = (BYTE)(0xF0 | hs >> 8);\r
pb->buf[i++] = (BYTE)(0x80 | (hs & 3) << 4 | (wc >> 6 & 0x0F));\r
pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));\r
} else {\r
- if (wc < 0x80) { /* 1-byte */\r
+ if (wc < 0x80) { /* Single byte? */\r
pb->buf[i++] = (BYTE)wc;\r
} else {\r
- if (wc < 0x800) { /* 2-byte */\r
+ if (wc < 0x800) { /* 2-byte sequence? */\r
nc += 1;\r
pb->buf[i++] = (BYTE)(0xC0 | wc >> 6);\r
- } else { /* 3-byte */\r
+ } else { /* 3-byte sequence */\r
nc += 2;\r
pb->buf[i++] = (BYTE)(0xE0 | wc >> 12);\r
pb->buf[i++] = (BYTE)(0x80 | (wc >> 6 & 0x3F));\r
pb->buf[i++] = (BYTE)(0x80 | (wc & 0x3F));\r
}\r
}\r
-#else /* Write it in ANSI/OEM */\r
+#else /* Write a code point in ANSI/OEM */\r
if (hs != 0) return;\r
wc = ff_uni2oem(wc, CODEPAGE); /* UTF-16 ==> ANSI/OEM */\r
- if (wc == 0) return;;\r
+ if (wc == 0) return;\r
if (wc >= 0x100) {\r
pb->buf[i++] = (BYTE)(wc >> 8); nc++;\r
}\r
pb->buf[i++] = (BYTE)wc;\r
#endif\r
\r
-#else /* ANSI/OEM input (without re-encode) */\r
+#else /* ANSI/OEM input (without re-encoding) */\r
pb->buf[i++] = (BYTE)c;\r
#endif\r
\r
}\r
\r
\r
-static\r
-int putc_flush ( /* Flush left characters in the buffer */\r
- putbuff* pb\r
-)\r
+/* Flush remaining characters in the buffer */\r
+\r
+static int putc_flush (putbuff* pb)\r
{\r
UINT nw;\r
\r
if ( pb->idx >= 0 /* Flush buffered characters to the file */\r
&& f_write(pb->fp, pb->buf, (UINT)pb->idx, &nw) == FR_OK\r
&& (UINT)pb->idx == nw) return pb->nchr;\r
- return EOF;\r
+ return -1;\r
}\r
\r
\r
-static\r
-void putc_init ( /* Initialize write buffer */\r
- putbuff* pb,\r
- FIL* fp\r
-)\r
+/* Initialize write buffer */\r
+\r
+static void putc_init (putbuff* pb, FIL* fp)\r
{\r
- mem_set(pb, 0, sizeof (putbuff));\r
+ memset(pb, 0, sizeof (putbuff));\r
pb->fp = fp;\r
}\r
\r
\r
\r
/*-----------------------------------------------------------------------*/\r
-/* Put a Formatted String to the File */\r
+/* Put a Formatted String to the File (with sub-functions) */\r
/*-----------------------------------------------------------------------*/\r
+#if FF_PRINT_FLOAT && FF_INTDEF == 2\r
+#include <math.h>\r
+\r
+static int ilog10 (double n) /* Calculate log10(n) in integer output */\r
+{\r
+ int rv = 0;\r
+\r
+ while (n >= 10) { /* Decimate digit in right shift */\r
+ if (n >= 100000) {\r
+ n /= 100000; rv += 5;\r
+ } else {\r
+ n /= 10; rv++;\r
+ }\r
+ }\r
+ while (n < 1) { /* Decimate digit in left shift */\r
+ if (n < 0.00001) {\r
+ n *= 100000; rv -= 5;\r
+ } else {\r
+ n *= 10; rv--;\r
+ }\r
+ }\r
+ return rv;\r
+}\r
+\r
+\r
+static double i10x (int n) /* Calculate 10^n in integer input */\r
+{\r
+ double rv = 1;\r
+\r
+ while (n > 0) { /* Left shift */\r
+ if (n >= 5) {\r
+ rv *= 100000; n -= 5;\r
+ } else {\r
+ rv *= 10; n--;\r
+ }\r
+ }\r
+ while (n < 0) { /* Right shift */\r
+ if (n <= -5) {\r
+ rv /= 100000; n += 5;\r
+ } else {\r
+ rv /= 10; n++;\r
+ }\r
+ }\r
+ return rv;\r
+}\r
+\r
+\r
+static void ftoa (\r
+ char* buf, /* Buffer to output the floating point string */\r
+ double val, /* Value to output */\r
+ int prec, /* Number of fractional digits */\r
+ TCHAR fmt /* Notation */\r
+)\r
+{\r
+ int d;\r
+ int e = 0, m = 0;\r
+ char sign = 0;\r
+ double w;\r
+ const char *er = 0;\r
+ const char ds = FF_PRINT_FLOAT == 2 ? ',' : '.';\r
+\r
+\r
+ if (isnan(val)) { /* Not a number? */\r
+ er = "NaN";\r
+ } else {\r
+ if (prec < 0) prec = 6; /* Default precision? (6 fractional digits) */\r
+ if (val < 0) { /* Negative? */\r
+ val = 0 - val; sign = '-';\r
+ } else {\r
+ sign = '+';\r
+ }\r
+ if (isinf(val)) { /* Infinite? */\r
+ er = "INF";\r
+ } else {\r
+ if (fmt == 'f') { /* Decimal notation? */\r
+ val += i10x(0 - prec) / 2; /* Round (nearest) */\r
+ m = ilog10(val);\r
+ if (m < 0) m = 0;\r
+ if (m + prec + 3 >= SZ_NUM_BUF) er = "OV"; /* Buffer overflow? */\r
+ } else { /* E notation */\r
+ if (val != 0) { /* Not a true zero? */\r
+ val += i10x(ilog10(val) - prec) / 2; /* Round (nearest) */\r
+ e = ilog10(val);\r
+ if (e > 99 || prec + 7 >= SZ_NUM_BUF) { /* Buffer overflow or E > +99? */\r
+ er = "OV";\r
+ } else {\r
+ if (e < -99) e = -99;\r
+ val /= i10x(e); /* Normalize */\r
+ }\r
+ }\r
+ }\r
+ }\r
+ if (!er) { /* Not error condition */\r
+ if (sign == '-') *buf++ = sign; /* Add a - if negative value */\r
+ do { /* Put decimal number */\r
+ if (m == -1) *buf++ = ds; /* Insert a decimal separator when get into fractional part */\r
+ w = i10x(m); /* Snip the highest digit d */\r
+ d = (int)(val / w); val -= d * w;\r
+ *buf++ = (char)('0' + d); /* Put the digit */\r
+ } while (--m >= -prec); /* Output all digits specified by prec */\r
+ if (fmt != 'f') { /* Put exponent if needed */\r
+ *buf++ = (char)fmt;\r
+ if (e < 0) {\r
+ e = 0 - e; *buf++ = '-';\r
+ } else {\r
+ *buf++ = '+';\r
+ }\r
+ *buf++ = (char)('0' + e / 10);\r
+ *buf++ = (char)('0' + e % 10);\r
+ }\r
+ }\r
+ }\r
+ if (er) { /* Error condition */\r
+ if (sign) *buf++ = sign; /* Add sign if needed */\r
+ do { /* Put error symbol */\r
+ *buf++ = *er++;\r
+ } while (*er);\r
+ }\r
+ *buf = 0; /* Term */\r
+}\r
+#endif /* FF_PRINT_FLOAT && FF_INTDEF == 2 */\r
+\r
+\r
\r
int f_printf (\r
FIL* fp, /* Pointer to the file object */\r
{\r
va_list arp;\r
putbuff pb;\r
- BYTE f, r;\r
- UINT i, j, w;\r
+ UINT i, j, w, f, r;\r
+ int prec;\r
+#if FF_PRINT_LLI && FF_INTDEF == 2\r
+ QWORD v;\r
+#else\r
DWORD v;\r
- TCHAR c, d, str[32], *p;\r
+#endif\r
+ TCHAR *tp;\r
+ TCHAR tc, pad;\r
+ TCHAR nul = 0;\r
+ char d, str[SZ_NUM_BUF];\r
\r
\r
putc_init(&pb, fp);\r
va_start(arp, fmt);\r
\r
for (;;) {\r
- c = *fmt++;\r
- if (c == 0) break; /* End of string */\r
- if (c != '%') { /* Non escape character */\r
- putc_bfd(&pb, c);\r
+ tc = *fmt++;\r
+ if (tc == 0) break; /* End of format string */\r
+ if (tc != '%') { /* Not an escape character (pass-through) */\r
+ putc_bfd(&pb, tc);\r
continue;\r
}\r
- w = f = 0;\r
- c = *fmt++;\r
- if (c == '0') { /* Flag: '0' padding */\r
- f = 1; c = *fmt++;\r
- } else {\r
- if (c == '-') { /* Flag: left justified */\r
- f = 2; c = *fmt++;\r
- }\r
+ f = w = 0; pad = ' '; prec = -1; /* Initialize parms */\r
+ tc = *fmt++;\r
+ if (tc == '0') { /* Flag: '0' padded */\r
+ pad = '0'; tc = *fmt++;\r
+ } else if (tc == '-') { /* Flag: Left aligned */\r
+ f = 2; tc = *fmt++;\r
}\r
- if (c == '*') { /* Minimum width by argument */\r
+ if (tc == '*') { /* Minimum width from an argument */\r
w = va_arg(arp, int);\r
- c = *fmt++;\r
+ tc = *fmt++;\r
} else {\r
- while (IsDigit(c)) { /* Minimum width */\r
- w = w * 10 + c - '0';\r
- c = *fmt++;\r
- }\r
- }\r
- if (c == 'l' || c == 'L') { /* Type prefix: Size is long int */\r
- f |= 4; c = *fmt++;\r
- }\r
- if (c == 0) break;\r
- d = c;\r
- if (IsLower(d)) d -= 0x20;\r
- switch (d) { /* Atgument type is... */\r
- case 'S' : /* String */\r
- p = va_arg(arp, TCHAR*);\r
- for (j = 0; p[j]; j++) ;\r
- if (!(f & 2)) { /* Right padded */\r
- while (j++ < w) putc_bfd(&pb, ' ') ;\r
- }\r
- while (*p) putc_bfd(&pb, *p++) ; /* String body */\r
- while (j++ < w) putc_bfd(&pb, ' ') ; /* Left padded */\r
- continue;\r
-\r
- case 'C' : /* Character */\r
- putc_bfd(&pb, (TCHAR)va_arg(arp, int)); continue;\r
-\r
- case 'B' : /* Unsigned binary */\r
+ while (IsDigit(tc)) { /* Minimum width */\r
+ w = w * 10 + tc - '0';\r
+ tc = *fmt++;\r
+ }\r
+ }\r
+ if (tc == '.') { /* Precision */\r
+ tc = *fmt++;\r
+ if (tc == '*') { /* Precision from an argument */\r
+ prec = va_arg(arp, int);\r
+ tc = *fmt++;\r
+ } else {\r
+ prec = 0;\r
+ while (IsDigit(tc)) { /* Precision */\r
+ prec = prec * 10 + tc - '0';\r
+ tc = *fmt++;\r
+ }\r
+ }\r
+ }\r
+ if (tc == 'l') { /* Size: long int */\r
+ f |= 4; tc = *fmt++;\r
+#if FF_PRINT_LLI && FF_INTDEF == 2\r
+ if (tc == 'l') { /* Size: long long int */\r
+ f |= 8; tc = *fmt++;\r
+ }\r
+#endif\r
+ }\r
+ if (tc == 0) break; /* End of format string */\r
+ switch (tc) { /* Atgument type is... */\r
+ case 'b': /* Unsigned binary */\r
r = 2; break;\r
\r
- case 'O' : /* Unsigned octal */\r
+ case 'o': /* Unsigned octal */\r
r = 8; break;\r
\r
- case 'D' : /* Signed decimal */\r
- case 'U' : /* Unsigned decimal */\r
+ case 'd': /* Signed decimal */\r
+ case 'u': /* Unsigned decimal */\r
r = 10; break;\r
\r
- case 'X' : /* Unsigned hexdecimal */\r
+ case 'x': /* Unsigned hexadecimal (lower case) */\r
+ case 'X': /* Unsigned hexadecimal (upper case) */\r
r = 16; break;\r
\r
+ case 'c': /* Character */\r
+ putc_bfd(&pb, (TCHAR)va_arg(arp, int));\r
+ continue;\r
+\r
+ case 's': /* String */\r
+ tp = va_arg(arp, TCHAR*); /* Get a pointer argument */\r
+ if (!tp) tp = &nul; /* Null ptr generates a null string */\r
+ for (j = 0; tp[j]; j++) ; /* j = tcslen(tp) */\r
+ if (prec >= 0 && j > (UINT)prec) j = prec; /* Limited length of string body */\r
+ for ( ; !(f & 2) && j < w; j++) putc_bfd(&pb, pad); /* Left pads */\r
+ while (*tp && prec--) putc_bfd(&pb, *tp++); /* Body */\r
+ while (j++ < w) putc_bfd(&pb, ' '); /* Right pads */\r
+ continue;\r
+#if FF_PRINT_FLOAT && FF_INTDEF == 2\r
+ case 'f': /* Floating point (decimal) */\r
+ case 'e': /* Floating point (e) */\r
+ case 'E': /* Floating point (E) */\r
+ ftoa(str, va_arg(arp, double), prec, tc); /* Make a floating point string */\r
+ for (j = strlen(str); !(f & 2) && j < w; j++) putc_bfd(&pb, pad); /* Left pads */\r
+ for (i = 0; str[i]; putc_bfd(&pb, str[i++])) ; /* Body */\r
+ while (j++ < w) putc_bfd(&pb, ' '); /* Right pads */\r
+ continue;\r
+#endif\r
default: /* Unknown type (pass-through) */\r
- putc_bfd(&pb, c); continue;\r
+ putc_bfd(&pb, tc); continue;\r
}\r
\r
- /* Get an argument and put it in numeral */\r
- v = (f & 4) ? (DWORD)va_arg(arp, long) : ((d == 'D') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int));\r
- if (d == 'D' && (v & 0x80000000)) {\r
- v = 0 - v;\r
- f |= 8;\r
+ /* Get an integer argument and put it in numeral */\r
+#if FF_PRINT_LLI && FF_INTDEF == 2\r
+ if (f & 8) { /* long long argument? */\r
+ v = (QWORD)va_arg(arp, long long);\r
+ } else if (f & 4) { /* long argument? */\r
+ v = (tc == 'd') ? (QWORD)(long long)va_arg(arp, long) : (QWORD)va_arg(arp, unsigned long);\r
+ } else { /* int/short/char argument */\r
+ v = (tc == 'd') ? (QWORD)(long long)va_arg(arp, int) : (QWORD)va_arg(arp, unsigned int);\r
+ }\r
+ if (tc == 'd' && (v & 0x8000000000000000)) { /* Negative value? */\r
+ v = 0 - v; f |= 1;\r
+ }\r
+#else\r
+ if (f & 4) { /* long argument? */\r
+ v = (DWORD)va_arg(arp, long);\r
+ } else { /* int/short/char argument */\r
+ v = (tc == 'd') ? (DWORD)(long)va_arg(arp, int) : (DWORD)va_arg(arp, unsigned int);\r
}\r
+ if (tc == 'd' && (v & 0x80000000)) { /* Negative value? */\r
+ v = 0 - v; f |= 1;\r
+ }\r
+#endif\r
i = 0;\r
- do {\r
- d = (TCHAR)(v % r); v /= r;\r
- if (d > 9) d += (c == 'x') ? 0x27 : 0x07;\r
+ do { /* Make an integer number string */\r
+ d = (char)(v % r); v /= r;\r
+ if (d > 9) d += (tc == 'x') ? 0x27 : 0x07;\r
str[i++] = d + '0';\r
- } while (v && i < sizeof str / sizeof *str);\r
- if (f & 8) str[i++] = '-';\r
- j = i; d = (f & 1) ? '0' : ' ';\r
- if (!(f & 2)) {\r
- while (j++ < w) putc_bfd(&pb, d); /* Right pad */\r
- }\r
- do {\r
- putc_bfd(&pb, str[--i]); /* Number body */\r
+ } while (v && i < SZ_NUM_BUF);\r
+ if (f & 1) str[i++] = '-'; /* Sign */\r
+ /* Write it */\r
+ for (j = i; !(f & 2) && j < w; j++) { /* Left pads */\r
+ putc_bfd(&pb, pad);\r
+ }\r
+ do { /* Body */\r
+ putc_bfd(&pb, (TCHAR)str[--i]);\r
} while (i);\r
- while (j++ < w) putc_bfd(&pb, d); /* Left pad */\r
+ while (j++ < w) { /* Right pads */\r
+ putc_bfd(&pb, ' ');\r
+ }\r
}\r
\r
va_end(arp);\r
WORD cp /* Value to be set as active code page */\r
)\r
{\r
- static const WORD validcp[] = { 437, 720, 737, 771, 775, 850, 852, 857, 860, 861, 862, 863, 864, 865, 866, 869, 932, 936, 949, 950, 0};\r
- static const BYTE* const tables[] = {Ct437, Ct720, Ct737, Ct771, Ct775, Ct850, Ct852, Ct857, Ct860, Ct861, Ct862, Ct863, Ct864, Ct865, Ct866, Ct869, Dc932, Dc936, Dc949, Dc950, 0};\r
+ static const WORD validcp[22] = { 437, 720, 737, 771, 775, 850, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 869, 932, 936, 949, 950, 0};\r
+ static const BYTE *const tables[22] = {Ct437, Ct720, Ct737, Ct771, Ct775, Ct850, Ct852, Ct855, Ct857, Ct860, Ct861, Ct862, Ct863, Ct864, Ct865, Ct866, Ct869, Dc932, Dc936, Dc949, Dc950, 0};\r
UINT i;\r
\r
\r
for (i = 0; validcp[i] != 0 && validcp[i] != cp; i++) ; /* Find the code page */\r
- if (validcp[i] != cp) return FR_INVALID_PARAMETER; /* Not found? */\r
+ if (validcp[i] != cp) return FR_INVALID_PARAMETER; /* Not found? */\r
\r
CodePage = cp;\r
if (cp >= 900) { /* DBCS */\r